on bb22285 help sign in
bridge/src/lib/utils/address.ts
41 lines 1.3 kB history raw
1import { reduce } from 'lodash';
2import { isAddress, keccak256 } from 'web3-utils';
3import { pubToAddress } from 'ethereumjs-util';
4import { ETH_ZERO_ADDR, ETH_ZERO_ADDR_SHORT } from 'lib/constants';
6export const stripHexPrefix = (hex: string) => {
7 return hex.startsWith('0x') ? hex.slice(2) : hex;
8};
10export const addHexPrefix = (hex: string) => {
11 return hex.startsWith('0x') ? hex : `0x${hex}`;
12};
14export const isValidAddress = (a: string) => '0x0' === a || isAddress(a);
16export const abbreviateAddress = (address: string) =>
17 `${address.slice(0, 6)}…${address.slice(-4)}`;
19export const isZeroAddress = (a: string) =>
20 a === ETH_ZERO_ADDR || a === ETH_ZERO_ADDR_SHORT;
22export const toChecksumAddress = (address: string) => {
23 const addr = stripHexPrefix(address).toLowerCase();
24 const hash = keccak256(addr).toString('hex');
26 return reduce(
27 addr,
28 (acc, char, idx) =>
29 parseInt(hash[idx], 16) >= 8 ? acc + char.toUpperCase() : acc + char,
30 '0x'
31 );
32};
34export const eqAddr = (addr0: string, addr1: string) =>
35 !addr0 || !addr1
36 ? false
37 : toChecksumAddress(addr0) === toChecksumAddress(addr1);
39export const publicToAddress = (publicKey: Buffer): string => {
40 return '0x' + pubToAddress(Buffer.from(publicKey), true).toString('hex');
41};