1 |
|
2 |
|
3 |
|
4 | import { isHex, isU8a, u8aToU8a } from '@polkadot/util';
|
5 | import { base58Decode } from "../base58/index.js";
|
6 | import { checkAddressChecksum } from "./checksum.js";
|
7 | import { defaults } from "./defaults.js";
|
8 | export 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 |