UNPKG

1.08 kBJavaScriptView Raw
1import { u8aConcat } from '@polkadot/util';
2import { base58Encode } from '../base58/index.js';
3import { decodeAddress } from './decode.js';
4import { defaults } from './defaults.js';
5import { sshash } from './sshash.js';
6export function encodeAddress(key, ss58Format = defaults.prefix) {
7 // decode it, this means we can re-encode an address
8 const u8a = decodeAddress(key);
9 if ((ss58Format < 0) || (ss58Format > 16383) || [46, 47].includes(ss58Format)) {
10 throw new Error('Out of range ss58Format specified');
11 }
12 else if (!defaults.allowedDecodedLengths.includes(u8a.length)) {
13 throw new Error(`Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
14 }
15 const input = u8aConcat(ss58Format < 64
16 ? [ss58Format]
17 : [
18 ((ss58Format & 0b0000_0000_1111_1100) >> 2) | 0b0100_0000,
19 (ss58Format >> 8) | ((ss58Format & 0b0000_0000_0000_0011) << 6)
20 ], u8a);
21 return base58Encode(u8aConcat(input, sshash(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1)));
22}