UNPKG

1.33 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#L6
4import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
5import { base58Decode } from "../base58/index.js";
6import { checkAddressChecksum } from "./checksum.js";
7import { defaults } from "./defaults.js";
8export function decodeAddress(encoded, ignoreChecksum, ss58Format = -1) {
9 if (!encoded) {
10 throw new Error('Invalid empty address passed');
11 }
12
13 if (isU8a(encoded) || isHex(encoded)) {
14 return u8aToU8a(encoded);
15 }
16
17 try {
18 const decoded = base58Decode(encoded);
19
20 if (!defaults.allowedEncodedLengths.includes(decoded.length)) {
21 throw new Error('Invalid decoded address length');
22 }
23
24 const [isValid, endPos, ss58Length, ss58Decoded] = checkAddressChecksum(decoded);
25
26 if (!isValid && !ignoreChecksum) {
27 throw new Error('Invalid decoded address checksum');
28 } else if (ss58Format !== -1 && ss58Format !== ss58Decoded) {
29 throw new Error(`Expected ss58Format ${ss58Format}, received ${ss58Decoded}`);
30 }
31
32 return decoded.slice(ss58Length, endPos);
33 } catch (error) {
34 throw new Error(`Decoding ${encoded}: ${error.message}`);
35 }
36}
\No newline at end of file