1 | import { u8aToHex, u8aToU8a } from '@polkadot/util';
|
2 | import { keccakAsU8a } from '../keccak/index.js';
|
3 | import { secp256k1Expand } from '../secp256k1/index.js';
|
4 | function getH160(u8a) {
|
5 | if ([33, 65].includes(u8a.length)) {
|
6 | u8a = keccakAsU8a(secp256k1Expand(u8a));
|
7 | }
|
8 | return u8a.slice(-20);
|
9 | }
|
10 | export function ethereumEncode(addressOrPublic) {
|
11 | if (!addressOrPublic) {
|
12 | return '0x';
|
13 | }
|
14 | const u8aAddress = u8aToU8a(addressOrPublic);
|
15 | if (![20, 32, 33, 65].includes(u8aAddress.length)) {
|
16 | throw new Error(`Invalid address or publicKey provided, received ${u8aAddress.length} bytes input`);
|
17 | }
|
18 | const address = u8aToHex(getH160(u8aAddress), -1, false);
|
19 | const hash = u8aToHex(keccakAsU8a(address), -1, false);
|
20 | let result = '';
|
21 | for (let i = 0; i < 40; i++) {
|
22 | result = `${result}${parseInt(hash[i], 16) > 7 ? address[i].toUpperCase() : address[i]}`;
|
23 | }
|
24 | return `0x${result}`;
|
25 | }
|