UNPKG

953 BJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3import { assert, u8aToHex, u8aToU8a } from '@polkadot/util';
4import { keccakAsU8a } from "../keccak/index.js";
5import { secp256k1Expand } from "../secp256k1/index.js";
6
7function getH160(u8a) {
8 if ([33, 65].includes(u8a.length)) {
9 u8a = keccakAsU8a(secp256k1Expand(u8a));
10 }
11
12 return u8a.slice(-20);
13}
14
15export function ethereumEncode(addressOrPublic) {
16 if (!addressOrPublic) {
17 return '0x';
18 }
19
20 const u8aAddress = u8aToU8a(addressOrPublic);
21 assert([20, 32, 33, 65].includes(u8aAddress.length), 'Invalid address or publicKey passed');
22 const address = u8aToHex(getH160(u8aAddress), -1, false);
23 const hash = u8aToHex(keccakAsU8a(address), -1, false);
24 let result = '';
25
26 for (let i = 0; i < 40; i++) {
27 result = `${result}${parseInt(hash[i], 16) > 7 ? address[i].toUpperCase() : address[i]}`;
28 }
29
30 return `0x${result}`;
31}
\No newline at end of file