UNPKG

1.23 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util-crypto authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3// Original implementation: https://github.com/paritytech/polka-ui/blob/4858c094684769080f5811f32b081dd7780b0880/src/polkadot.js#L34
4import { u8aConcat } from '@polkadot/util';
5import { base58Encode } from "../base58/index.js";
6import { decodeAddress } from "./decode.js";
7import { defaults } from "./defaults.js";
8import { sshash } from "./sshash.js";
9export function encodeAddress(key, ss58Format = defaults.prefix) {
10 // decode it, this means we can re-encode an address
11 const u8a = decodeAddress(key);
12
13 if (ss58Format < 0 || ss58Format > 16383 || [46, 47].includes(ss58Format)) {
14 throw new Error('Out of range ss58Format specified');
15 } else if (!defaults.allowedDecodedLengths.includes(u8a.length)) {
16 throw new Error(`Expected a valid key to convert, with length ${defaults.allowedDecodedLengths.join(', ')}`);
17 }
18
19 const input = u8aConcat(ss58Format < 64 ? [ss58Format] : [(ss58Format & 0b0000000011111100) >> 2 | 0b01000000, ss58Format >> 8 | (ss58Format & 0b0000000000000011) << 6], u8a);
20 return base58Encode(u8aConcat(input, sshash(input).subarray(0, [32, 33].includes(u8a.length) ? 2 : 1)));
21}
\No newline at end of file