1 | import { u32 } from '@polkadot/types-codec';
|
2 | import { BN, bnToBn, isBigInt, isBn, isHex, isNumber, isU8a } from '@polkadot/util';
|
3 | import { decodeAddress, encodeAddress } from '@polkadot/util-crypto';
|
4 | const PREFIX_1BYTE = 0xef;
|
5 | const PREFIX_2BYTE = 0xfc;
|
6 | const PREFIX_4BYTE = 0xfd;
|
7 | const PREFIX_8BYTE = 0xfe;
|
8 | const MAX_1BYTE = new BN(PREFIX_1BYTE);
|
9 | const MAX_2BYTE = new BN(1).shln(16);
|
10 | const MAX_4BYTE = new BN(1).shln(32);
|
11 |
|
12 | function decodeAccountIndex(value) {
|
13 |
|
14 | if (value instanceof GenericAccountIndex) {
|
15 |
|
16 |
|
17 | return value.toBn();
|
18 | }
|
19 | else if (isBn(value) || isNumber(value) || isHex(value) || isU8a(value) || isBigInt(value)) {
|
20 | return value;
|
21 | }
|
22 | return decodeAccountIndex(decodeAddress(value));
|
23 | }
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | export class GenericAccountIndex extends u32 {
|
31 | constructor(registry, value = new BN(0)) {
|
32 | super(registry, decodeAccountIndex(value));
|
33 | }
|
34 | static calcLength(_value) {
|
35 | const value = bnToBn(_value);
|
36 | if (value.lte(MAX_1BYTE)) {
|
37 | return 1;
|
38 | }
|
39 | else if (value.lt(MAX_2BYTE)) {
|
40 | return 2;
|
41 | }
|
42 | else if (value.lt(MAX_4BYTE)) {
|
43 | return 4;
|
44 | }
|
45 | return 8;
|
46 | }
|
47 | static readLength(input) {
|
48 | const first = input[0];
|
49 | if (first === PREFIX_2BYTE) {
|
50 | return [1, 2];
|
51 | }
|
52 | else if (first === PREFIX_4BYTE) {
|
53 | return [1, 4];
|
54 | }
|
55 | else if (first === PREFIX_8BYTE) {
|
56 | return [1, 8];
|
57 | }
|
58 | return [0, 1];
|
59 | }
|
60 | static writeLength(input) {
|
61 | switch (input.length) {
|
62 | case 2: return new Uint8Array([PREFIX_2BYTE]);
|
63 | case 4: return new Uint8Array([PREFIX_4BYTE]);
|
64 | case 8: return new Uint8Array([PREFIX_8BYTE]);
|
65 | default: return new Uint8Array([]);
|
66 | }
|
67 | }
|
68 | |
69 |
|
70 |
|
71 | eq(other) {
|
72 |
|
73 | if (isBn(other) || isNumber(other)) {
|
74 | return super.eq(other);
|
75 | }
|
76 |
|
77 | return super.eq(this.registry.createTypeUnsafe('AccountIndex', [other]));
|
78 | }
|
79 | |
80 |
|
81 |
|
82 | toHuman() {
|
83 | return this.toJSON();
|
84 | }
|
85 | |
86 |
|
87 |
|
88 | toJSON() {
|
89 | return this.toString();
|
90 | }
|
91 | |
92 |
|
93 |
|
94 | toPrimitive() {
|
95 | return this.toJSON();
|
96 | }
|
97 | |
98 |
|
99 |
|
100 | toString() {
|
101 | const length = GenericAccountIndex.calcLength(this);
|
102 | return encodeAddress(this.toU8a().subarray(0, length), this.registry.chainSS58);
|
103 | }
|
104 | |
105 |
|
106 |
|
107 | toRawType() {
|
108 | return 'AccountIndex';
|
109 | }
|
110 | }
|