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