UNPKG

2.09 kBJavaScriptView Raw
1import { Enum } from '@polkadot/types-codec';
2import { isBn, isNumber, isString, isU8a } from '@polkadot/util';
3import { decodeAddress } from '@polkadot/util-crypto';
4import { GenericAccountId } from './AccountId.js';
5import { GenericAccountIndex } from './AccountIndex.js';
6function decodeU8a(registry, u8a) {
7 if ([0, 32].includes(u8a.length)) {
8 return { Id: u8a };
9 }
10 else if (u8a.length === 20) {
11 return { Address20: u8a };
12 }
13 else if (u8a.length <= 8) {
14 return { Index: registry.createTypeUnsafe('AccountIndex', [u8a]).toNumber() };
15 }
16 return u8a;
17}
18function decodeMultiAny(registry, value) {
19 if (value instanceof GenericAccountId) {
20 return { Id: value };
21 }
22 else if (isU8a(value)) {
23 // NOTE This is after the AccountId check (which is U8a)
24 return decodeU8a(registry, value);
25 }
26 else if (value instanceof GenericMultiAddress) {
27 return value;
28 }
29 else if (value instanceof GenericAccountIndex || isBn(value) || isNumber(value)) {
30 return { Index: isNumber(value) ? value : value.toNumber() };
31 }
32 else if (isString(value)) {
33 return decodeU8a(registry, decodeAddress(value.toString()));
34 }
35 return value;
36}
37export class GenericMultiAddress extends Enum {
38 constructor(registry, value) {
39 super(registry, {
40 Id: 'AccountId',
41 Index: 'Compact<AccountIndex>',
42 Raw: 'Bytes',
43 // eslint-disable-next-line sort-keys
44 Address32: 'H256',
45 // eslint-disable-next-line sort-keys
46 Address20: 'H160'
47 }, decodeMultiAny(registry, value));
48 }
49 /**
50 * @description Returns a breakdown of the hex encoding for this Codec
51 */
52 inspect() {
53 const { inner, outer = [] } = this.inner.inspect();
54 return {
55 inner,
56 outer: [new Uint8Array([this.index]), ...outer]
57 };
58 }
59 /**
60 * @description Returns the string representation of the value
61 */
62 toString() {
63 return this.value.toString();
64 }
65}