1 | import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
2 | import { base58Decode } from '../base58/index.js';
|
3 | import { checkAddressChecksum } from './checksum.js';
|
4 | import { defaults } from './defaults.js';
|
5 | export function decodeAddress(encoded, ignoreChecksum, ss58Format = -1) {
|
6 | if (!encoded) {
|
7 | throw new Error('Invalid empty address passed');
|
8 | }
|
9 | if (isU8a(encoded) || isHex(encoded)) {
|
10 | return u8aToU8a(encoded);
|
11 | }
|
12 | try {
|
13 | const decoded = base58Decode(encoded);
|
14 | if (!defaults.allowedEncodedLengths.includes(decoded.length)) {
|
15 | throw new Error('Invalid decoded address length');
|
16 | }
|
17 | const [isValid, endPos, ss58Length, ss58Decoded] = checkAddressChecksum(decoded);
|
18 | if (!isValid && !ignoreChecksum) {
|
19 | throw new Error('Invalid decoded address checksum');
|
20 | }
|
21 | else if (ss58Format !== -1 && ss58Format !== ss58Decoded) {
|
22 | throw new Error(`Expected ss58Format ${ss58Format}, received ${ss58Decoded}`);
|
23 | }
|
24 | return decoded.slice(ss58Length, endPos);
|
25 | }
|
26 | catch (error) {
|
27 | throw new Error(`Decoding ${encoded}: ${error.message}`);
|
28 | }
|
29 | }
|