@polkadot/types-codec 9.14.2 → 10.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/abstract/Array.js +140 -155
  2. package/abstract/Base.js +95 -112
  3. package/abstract/Int.js +212 -220
  4. package/abstract/Object.js +34 -45
  5. package/abstract/index.js +3 -6
  6. package/base/Compact.js +149 -165
  7. package/base/DoNotConstruct.js +61 -64
  8. package/base/Enum.js +345 -382
  9. package/base/Int.js +14 -18
  10. package/base/Null.js +71 -82
  11. package/base/Option.js +217 -226
  12. package/base/Result.js +54 -67
  13. package/base/Tuple.js +96 -101
  14. package/base/UInt.js +11 -15
  15. package/base/Vec.js +84 -89
  16. package/base/VecAny.js +8 -12
  17. package/base/VecFixed.js +59 -70
  18. package/base/index.js +12 -15
  19. package/bundle.js +7 -10
  20. package/cjs/abstract/Array.js +138 -159
  21. package/cjs/abstract/Base.js +96 -117
  22. package/cjs/abstract/Int.js +215 -238
  23. package/cjs/abstract/Object.js +30 -49
  24. package/cjs/abstract/index.js +8 -25
  25. package/cjs/base/Compact.js +151 -173
  26. package/cjs/base/DoNotConstruct.js +63 -70
  27. package/cjs/base/Enum.js +350 -396
  28. package/cjs/base/Int.js +16 -24
  29. package/cjs/base/Null.js +70 -86
  30. package/cjs/base/Option.js +220 -234
  31. package/cjs/base/Result.js +56 -71
  32. package/cjs/base/Tuple.js +103 -109
  33. package/cjs/base/UInt.js +13 -19
  34. package/cjs/base/Vec.js +94 -101
  35. package/cjs/base/VecAny.js +10 -16
  36. package/cjs/base/VecFixed.js +66 -79
  37. package/cjs/base/index.js +26 -88
  38. package/cjs/bundle.js +11 -86
  39. package/cjs/detectOther.js +2 -10
  40. package/cjs/detectPackage.js +6 -11
  41. package/cjs/extended/BTreeMap.js +10 -16
  42. package/cjs/extended/BTreeSet.js +162 -178
  43. package/cjs/extended/BitVec.js +70 -77
  44. package/cjs/extended/Bytes.js +59 -62
  45. package/cjs/extended/HashMap.js +10 -16
  46. package/cjs/extended/Linkage.js +50 -60
  47. package/cjs/extended/Map.js +176 -181
  48. package/cjs/extended/OptionBool.js +65 -68
  49. package/cjs/extended/Range.js +37 -46
  50. package/cjs/extended/RangeInclusive.js +13 -21
  51. package/cjs/extended/Type.js +14 -22
  52. package/cjs/extended/U8aFixed.js +33 -43
  53. package/cjs/extended/WrapperKeepOpaque.js +99 -99
  54. package/cjs/extended/WrapperOpaque.js +19 -28
  55. package/cjs/extended/index.js +31 -108
  56. package/cjs/index.js +3 -15
  57. package/cjs/native/Bool.js +101 -116
  58. package/cjs/native/Date.js +125 -151
  59. package/cjs/native/Float.js +95 -114
  60. package/cjs/native/Json.js +102 -124
  61. package/cjs/native/Raw.js +128 -150
  62. package/cjs/native/Set.js +200 -220
  63. package/cjs/native/Struct.data.js +2 -9
  64. package/cjs/native/Struct.js +238 -251
  65. package/cjs/native/Text.js +137 -149
  66. package/cjs/native/index.js +21 -78
  67. package/cjs/packageInfo.js +2 -16
  68. package/cjs/primitive/F32.js +8 -11
  69. package/cjs/primitive/F64.js +8 -11
  70. package/cjs/primitive/I128.js +8 -11
  71. package/cjs/primitive/I16.js +8 -11
  72. package/cjs/primitive/I256.js +8 -11
  73. package/cjs/primitive/I32.js +8 -11
  74. package/cjs/primitive/I64.js +8 -11
  75. package/cjs/primitive/I8.js +8 -11
  76. package/cjs/primitive/U128.js +8 -11
  77. package/cjs/primitive/U16.js +8 -11
  78. package/cjs/primitive/U256.js +8 -11
  79. package/cjs/primitive/U32.js +8 -11
  80. package/cjs/primitive/U64.js +8 -11
  81. package/cjs/primitive/U8.js +8 -11
  82. package/cjs/primitive/USize.js +7 -13
  83. package/cjs/primitive/index.js +47 -199
  84. package/cjs/types/codec.js +2 -1
  85. package/cjs/types/helpers.js +2 -1
  86. package/cjs/types/index.js +6 -48
  87. package/cjs/types/interfaces.js +2 -1
  88. package/cjs/types/registry.js +2 -1
  89. package/cjs/utils/compareArray.js +12 -17
  90. package/cjs/utils/compareMap.js +23 -26
  91. package/cjs/utils/compareSet.js +17 -23
  92. package/cjs/utils/decodeU8a.js +63 -74
  93. package/cjs/utils/index.js +24 -91
  94. package/cjs/utils/mapToTypeMap.js +13 -18
  95. package/cjs/utils/sanitize.js +198 -204
  96. package/cjs/utils/sortValues.js +39 -49
  97. package/cjs/utils/typeToConstructor.js +8 -11
  98. package/cjs/utils/typesToMap.js +10 -16
  99. package/cjs/utils/util.js +6 -11
  100. package/detectOther.js +0 -5
  101. package/detectPackage.js +2 -7
  102. package/extended/BTreeMap.js +8 -11
  103. package/extended/BTreeSet.js +159 -171
  104. package/extended/BitVec.js +63 -70
  105. package/extended/Bytes.js +56 -57
  106. package/extended/HashMap.js +8 -11
  107. package/extended/Linkage.js +46 -51
  108. package/extended/Map.js +173 -173
  109. package/extended/OptionBool.js +62 -62
  110. package/extended/Range.js +31 -39
  111. package/extended/RangeInclusive.js +11 -16
  112. package/extended/Type.js +12 -17
  113. package/extended/U8aFixed.js +30 -36
  114. package/extended/WrapperKeepOpaque.js +92 -91
  115. package/extended/WrapperOpaque.js +17 -23
  116. package/extended/index.js +14 -17
  117. package/index.js +2 -5
  118. package/native/Bool.js +102 -111
  119. package/native/Date.js +126 -144
  120. package/native/Float.js +94 -107
  121. package/native/Json.js +104 -114
  122. package/native/Raw.js +130 -146
  123. package/native/Set.js +194 -209
  124. package/native/Struct.data.js +0 -3
  125. package/native/Struct.js +233 -241
  126. package/native/Text.js +135 -143
  127. package/native/index.js +8 -11
  128. package/package.json +8 -5
  129. package/packageInfo.js +1 -11
  130. package/primitive/F32.js +3 -7
  131. package/primitive/F64.js +3 -7
  132. package/primitive/I128.js +3 -7
  133. package/primitive/I16.js +3 -7
  134. package/primitive/I256.js +3 -7
  135. package/primitive/I32.js +3 -7
  136. package/primitive/I64.js +3 -7
  137. package/primitive/I8.js +3 -7
  138. package/primitive/U128.js +3 -7
  139. package/primitive/U16.js +3 -7
  140. package/primitive/U256.js +3 -7
  141. package/primitive/U32.js +3 -7
  142. package/primitive/U64.js +3 -7
  143. package/primitive/U8.js +3 -7
  144. package/primitive/USize.js +5 -9
  145. package/primitive/index.js +15 -18
  146. package/types/index.js +4 -7
  147. package/utils/compareArray.js +7 -11
  148. package/utils/compareMap.js +18 -19
  149. package/utils/compareSet.js +12 -16
  150. package/utils/decodeU8a.js +54 -61
  151. package/utils/index.js +9 -12
  152. package/utils/mapToTypeMap.js +9 -13
  153. package/utils/sanitize.js +182 -185
  154. package/utils/sortValues.js +32 -36
  155. package/utils/typeToConstructor.js +3 -4
  156. package/utils/typesToMap.js +5 -8
  157. package/utils/util.js +1 -4
package/base/Enum.js CHANGED
@@ -1,137 +1,124 @@
1
- // Copyright 2017-2023 @polkadot/types-codec authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
1
  import { isHex, isNumber, isObject, isString, isU8a, objectProperties, stringCamelCase, stringify, stringPascalCase, u8aConcatStrict, u8aToHex, u8aToU8a } from '@polkadot/util';
5
- import { mapToTypeMap, typesToMap } from "../utils/index.js";
6
- import { Null } from "./Null.js";
7
-
8
- // export interface, this is used in Enum.with, so required as public by TS
9
-
2
+ import { mapToTypeMap, typesToMap } from '../utils/index.js';
3
+ import { Null } from './Null.js';
10
4
  function noopSetDefinition(d) {
11
- return d;
5
+ return d;
12
6
  }
13
7
  function isRustEnum(def) {
14
- const defValues = Object.values(def);
15
- if (defValues.some(v => isNumber(v))) {
16
- if (!defValues.every(v => isNumber(v) && v >= 0 && v <= 255)) {
17
- throw new Error('Invalid number-indexed enum definition');
18
- }
19
- return false;
20
- }
21
- return true;
8
+ const defValues = Object.values(def);
9
+ if (defValues.some((v) => isNumber(v))) {
10
+ if (!defValues.every((v) => isNumber(v) && v >= 0 && v <= 255)) {
11
+ throw new Error('Invalid number-indexed enum definition');
12
+ }
13
+ return false;
14
+ }
15
+ return true;
22
16
  }
23
17
  function extractDef(registry, _def) {
24
- const def = {};
25
- let isBasic;
26
- let isIndexed;
27
- if (Array.isArray(_def)) {
28
- for (let i = 0; i < _def.length; i++) {
29
- def[_def[i]] = {
30
- Type: Null,
31
- index: i
32
- };
33
- }
34
- isBasic = true;
35
- isIndexed = false;
36
- } else if (isRustEnum(_def)) {
37
- const [Types, keys] = mapToTypeMap(registry, _def);
38
- for (let i = 0; i < keys.length; i++) {
39
- def[keys[i]] = {
40
- Type: Types[i],
41
- index: i
42
- };
43
- }
44
- isBasic = !Object.values(def).some(({
45
- Type
46
- }) => Type !== Null);
47
- isIndexed = false;
48
- } else {
49
- const entries = Object.entries(_def);
50
- for (let i = 0; i < entries.length; i++) {
51
- const [key, index] = entries[i];
52
- def[key] = {
53
- Type: Null,
54
- index
55
- };
56
- }
57
- isBasic = true;
58
- isIndexed = true;
59
- }
60
- return {
61
- def,
62
- isBasic,
63
- isIndexed
64
- };
18
+ const def = {};
19
+ let isBasic;
20
+ let isIndexed;
21
+ if (Array.isArray(_def)) {
22
+ for (let i = 0; i < _def.length; i++) {
23
+ def[_def[i]] = { Type: Null, index: i };
24
+ }
25
+ isBasic = true;
26
+ isIndexed = false;
27
+ }
28
+ else if (isRustEnum(_def)) {
29
+ const [Types, keys] = mapToTypeMap(registry, _def);
30
+ for (let i = 0; i < keys.length; i++) {
31
+ def[keys[i]] = { Type: Types[i], index: i };
32
+ }
33
+ isBasic = !Object.values(def).some(({ Type }) => Type !== Null);
34
+ isIndexed = false;
35
+ }
36
+ else {
37
+ const entries = Object.entries(_def);
38
+ for (let i = 0; i < entries.length; i++) {
39
+ const [key, index] = entries[i];
40
+ def[key] = { Type: Null, index };
41
+ }
42
+ isBasic = true;
43
+ isIndexed = true;
44
+ }
45
+ return {
46
+ def,
47
+ isBasic,
48
+ isIndexed
49
+ };
65
50
  }
66
51
  function getEntryType(def, checkIdx) {
67
- const values = Object.values(def);
68
- for (let i = 0; i < values.length; i++) {
69
- const {
70
- Type,
71
- index
72
- } = values[i];
73
- if (index === checkIdx) {
74
- return Type;
75
- }
76
- }
77
- throw new Error(`Unable to create Enum via index ${checkIdx}, in ${Object.keys(def).join(', ')}`);
52
+ const values = Object.values(def);
53
+ for (let i = 0; i < values.length; i++) {
54
+ const { Type, index } = values[i];
55
+ if (index === checkIdx) {
56
+ return Type;
57
+ }
58
+ }
59
+ throw new Error(`Unable to create Enum via index ${checkIdx}, in ${Object.keys(def).join(', ')}`);
78
60
  }
79
61
  function createFromU8a(registry, def, index, value) {
80
- const Type = getEntryType(def, index);
81
- return {
82
- index,
83
- value: new Type(registry, value)
84
- };
62
+ const Type = getEntryType(def, index);
63
+ return {
64
+ index,
65
+ value: new Type(registry, value)
66
+ };
85
67
  }
86
68
  function createFromValue(registry, def, index = 0, value) {
87
- const Type = getEntryType(def, index);
88
- return {
89
- index,
90
- value: value instanceof Type ? value : new Type(registry, value)
91
- };
69
+ const Type = getEntryType(def, index);
70
+ return {
71
+ index,
72
+ value: value instanceof Type
73
+ ? value
74
+ : new Type(registry, value)
75
+ };
92
76
  }
93
77
  function decodeFromJSON(registry, def, key, value) {
94
- // JSON comes in the form of { "<type (camelCase)>": "<value for type>" }, here we
95
- // additionally force to lower to ensure forward compat
96
- const keys = Object.keys(def).map(k => k.toLowerCase());
97
- const keyLower = key.toLowerCase();
98
- const index = keys.indexOf(keyLower);
99
- if (index === -1) {
100
- throw new Error(`Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`);
101
- }
102
- try {
103
- return createFromValue(registry, def, Object.values(def)[index].index, value);
104
- } catch (error) {
105
- throw new Error(`Enum(${key}):: ${error.message}`);
106
- }
78
+ // JSON comes in the form of { "<type (camelCase)>": "<value for type>" }, here we
79
+ // additionally force to lower to ensure forward compat
80
+ const keys = Object.keys(def).map((k) => k.toLowerCase());
81
+ const keyLower = key.toLowerCase();
82
+ const index = keys.indexOf(keyLower);
83
+ if (index === -1) {
84
+ throw new Error(`Cannot map Enum JSON, unable to find '${key}' in ${keys.join(', ')}`);
85
+ }
86
+ try {
87
+ return createFromValue(registry, def, Object.values(def)[index].index, value);
88
+ }
89
+ catch (error) {
90
+ throw new Error(`Enum(${key}):: ${error.message}`);
91
+ }
107
92
  }
108
93
  function decodeEnum(registry, def, value, index) {
109
- // NOTE We check the index path first, before looking at values - this allows treating
110
- // the optional indexes before anything else, more-specific > less-specific
111
- if (isNumber(index)) {
112
- return createFromValue(registry, def, index, value);
113
- } else if (isU8a(value) || isHex(value)) {
114
- const u8a = u8aToU8a(value);
115
-
116
- // nested, we don't want to match isObject below
117
- if (u8a.length) {
118
- return createFromU8a(registry, def, u8a[0], u8a.subarray(1));
119
- }
120
- } else if (value instanceof Enum) {
121
- return createFromValue(registry, def, value.index, value.value);
122
- } else if (isNumber(value)) {
123
- return createFromValue(registry, def, value);
124
- } else if (isString(value)) {
125
- return decodeFromJSON(registry, def, value.toString());
126
- } else if (isObject(value)) {
127
- const key = Object.keys(value)[0];
128
- return decodeFromJSON(registry, def, key, value[key]);
129
- }
130
-
131
- // Worst-case scenario, return the first with default
132
- return createFromValue(registry, def, Object.values(def)[0].index);
94
+ // NOTE We check the index path first, before looking at values - this allows treating
95
+ // the optional indexes before anything else, more-specific > less-specific
96
+ if (isNumber(index)) {
97
+ return createFromValue(registry, def, index, value);
98
+ }
99
+ else if (isU8a(value) || isHex(value)) {
100
+ const u8a = u8aToU8a(value);
101
+ // nested, we don't want to match isObject below
102
+ if (u8a.length) {
103
+ return createFromU8a(registry, def, u8a[0], u8a.subarray(1));
104
+ }
105
+ }
106
+ else if (value instanceof Enum) {
107
+ return createFromValue(registry, def, value.index, value.value);
108
+ }
109
+ else if (isNumber(value)) {
110
+ return createFromValue(registry, def, value);
111
+ }
112
+ else if (isString(value)) {
113
+ return decodeFromJSON(registry, def, value.toString());
114
+ }
115
+ else if (isObject(value)) {
116
+ const key = Object.keys(value)[0];
117
+ return decodeFromJSON(registry, def, key, value[key]);
118
+ }
119
+ // Worst-case scenario, return the first with default
120
+ return createFromValue(registry, def, Object.values(def)[0].index);
133
121
  }
134
-
135
122
  /**
136
123
  * @name Enum
137
124
  * @description
@@ -139,270 +126,246 @@ function decodeEnum(registry, def, value, index) {
139
126
  * an extension to enum where the value type is determined by the actual index.
140
127
  */
141
128
  export class Enum {
142
- #def;
143
- #entryIndex;
144
- #indexes;
145
- #isBasic;
146
- #isIndexed;
147
- #raw;
148
- constructor(registry, Types, value, index, {
149
- definition,
150
- setDefinition = noopSetDefinition
151
- } = {}) {
152
- const {
153
- def,
154
- isBasic,
155
- isIndexed
156
- } = definition || setDefinition(extractDef(registry, Types));
157
-
158
- // shortcut isU8a as used in SCALE decoding
159
- const decoded = isU8a(value) && value.length && !isNumber(index) ? createFromU8a(registry, def, value[0], value.subarray(1)) : decodeEnum(registry, def, value, index);
160
- this.registry = registry;
161
- this.#def = def;
162
- this.#isBasic = isBasic;
163
- this.#isIndexed = isIndexed;
164
- this.#indexes = Object.values(def).map(({
165
- index
166
- }) => index);
167
- this.#entryIndex = this.#indexes.indexOf(decoded.index);
168
- this.#raw = decoded.value;
169
- if (this.#raw.initialU8aLength) {
170
- this.initialU8aLength = 1 + this.#raw.initialU8aLength;
171
- }
172
- }
173
- static with(Types) {
174
- var _class;
175
- let definition;
176
-
177
- // eslint-disable-next-line no-return-assign
178
- const setDefinition = d => definition = d;
179
- return _class = class extends Enum {
180
- constructor(registry, value, index) {
181
- super(registry, Types, value, index, {
182
- definition,
183
- setDefinition
184
- });
185
- }
186
- }, (() => {
187
- const keys = Array.isArray(Types) ? Types : Object.keys(Types);
188
- const asKeys = new Array(keys.length);
189
- const isKeys = new Array(keys.length);
190
- for (let i = 0; i < keys.length; i++) {
191
- const name = stringPascalCase(keys[i]);
192
- asKeys[i] = `as${name}`;
193
- isKeys[i] = `is${name}`;
194
- }
195
- objectProperties(_class.prototype, isKeys, (_, i, self) => self.type === keys[i]);
196
- objectProperties(_class.prototype, asKeys, (k, i, self) => {
197
- if (self.type !== keys[i]) {
198
- throw new Error(`Cannot convert '${self.type}' via ${k}`);
129
+ registry;
130
+ createdAtHash;
131
+ initialU8aLength;
132
+ isStorageFallback;
133
+ #def;
134
+ #entryIndex;
135
+ #indexes;
136
+ #isBasic;
137
+ #isIndexed;
138
+ #raw;
139
+ constructor(registry, Types, value, index, { definition, setDefinition = noopSetDefinition } = {}) {
140
+ const { def, isBasic, isIndexed } = definition || setDefinition(extractDef(registry, Types));
141
+ // shortcut isU8a as used in SCALE decoding
142
+ const decoded = isU8a(value) && value.length && !isNumber(index)
143
+ ? createFromU8a(registry, def, value[0], value.subarray(1))
144
+ : decodeEnum(registry, def, value, index);
145
+ this.registry = registry;
146
+ this.#def = def;
147
+ this.#isBasic = isBasic;
148
+ this.#isIndexed = isIndexed;
149
+ this.#indexes = Object.values(def).map(({ index }) => index);
150
+ this.#entryIndex = this.#indexes.indexOf(decoded.index);
151
+ this.#raw = decoded.value;
152
+ if (this.#raw.initialU8aLength) {
153
+ this.initialU8aLength = 1 + this.#raw.initialU8aLength;
199
154
  }
200
- return self.value;
201
- });
202
- })(), _class;
203
- }
204
-
205
- /**
206
- * @description The length of the value when encoded as a Uint8Array
207
- */
208
- get encodedLength() {
209
- return 1 + this.#raw.encodedLength;
210
- }
211
-
212
- /**
213
- * @description returns a hash of the contents
214
- */
215
- get hash() {
216
- return this.registry.hash(this.toU8a());
217
- }
218
-
219
- /**
220
- * @description The index of the enum value
221
- */
222
- get index() {
223
- return this.#indexes[this.#entryIndex];
224
- }
225
-
226
- /**
227
- * @description The value of the enum
228
- */
229
- get inner() {
230
- return this.#raw;
231
- }
232
-
233
- /**
234
- * @description true if this is a basic enum (no values)
235
- */
236
- get isBasic() {
237
- return this.#isBasic;
238
- }
239
-
240
- /**
241
- * @description Checks if the value is an empty value
242
- */
243
- get isEmpty() {
244
- return this.#raw.isEmpty;
245
- }
246
-
247
- /**
248
- * @description Checks if the Enum points to a [[Null]] type
249
- */
250
- get isNone() {
251
- return this.#raw instanceof Null;
252
- }
253
-
254
- /**
255
- * @description The available keys for this enum
256
- */
257
- get defIndexes() {
258
- return this.#indexes;
259
- }
260
-
261
- /**
262
- * @description The available keys for this enum
263
- */
264
- get defKeys() {
265
- return Object.keys(this.#def);
266
- }
267
-
268
- /**
269
- * @description The name of the type this enum value represents
270
- */
271
- get type() {
272
- return this.defKeys[this.#entryIndex];
273
- }
274
-
275
- /**
276
- * @description The value of the enum
277
- */
278
- get value() {
279
- return this.#raw;
280
- }
281
-
282
- /**
283
- * @description Compares the value of the input to see if there is a match
284
- */
285
- eq(other) {
286
- // cater for the case where we only pass the enum index
287
- if (isU8a(other)) {
288
- return !this.toU8a().some((entry, index) => entry !== other[index]);
289
- } else if (isNumber(other)) {
290
- return this.toNumber() === other;
291
- } else if (this.#isBasic && isString(other)) {
292
- return this.type === other;
293
- } else if (isHex(other)) {
294
- return this.toHex() === other;
295
- } else if (other instanceof Enum) {
296
- return this.index === other.index && this.value.eq(other.value);
297
- } else if (isObject(other)) {
298
- return this.value.eq(other[this.type]);
299
- }
300
-
301
- // compare the actual wrapper value
302
- return this.value.eq(other);
303
- }
304
-
305
- /**
306
- * @description Returns a breakdown of the hex encoding for this Codec
307
- */
308
- inspect() {
309
- if (this.#isBasic) {
310
- return {
311
- outer: [new Uint8Array([this.index])]
312
- };
313
- }
314
- const {
315
- inner,
316
- outer = []
317
- } = this.#raw.inspect();
318
- return {
319
- inner,
320
- outer: [new Uint8Array([this.index]), ...outer]
321
- };
322
- }
323
-
324
- /**
325
- * @description Returns a hex string representation of the value
326
- */
327
- toHex() {
328
- return u8aToHex(this.toU8a());
329
- }
330
-
331
- /**
332
- * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
333
- */
334
- toHuman(isExtended) {
335
- return this.#isBasic || this.isNone ? this.type : {
336
- [this.type]: this.#raw.toHuman(isExtended)
337
- };
338
- }
339
-
340
- /**
341
- * @description Converts the Object to JSON, typically used for RPC transfers
342
- */
343
- toJSON() {
344
- return this.#isBasic ? this.type : {
345
- [stringCamelCase(this.type)]: this.#raw.toJSON()
346
- };
347
- }
348
-
349
- /**
350
- * @description Returns the number representation for the value
351
- */
352
- toNumber() {
353
- return this.index;
354
- }
355
-
356
- /**
357
- * @description Converts the value in a best-fit primitive form
358
- */
359
- toPrimitive() {
360
- return this.#isBasic ? this.type : {
361
- [stringCamelCase(this.type)]: this.#raw.toPrimitive()
362
- };
363
- }
364
-
365
- /**
366
- * @description Returns a raw struct representation of the enum types
367
- */
368
- _toRawStruct() {
369
- if (this.#isBasic) {
370
- return this.#isIndexed ? this.defKeys.reduce((out, key, index) => {
371
- out[key] = this.#indexes[index];
372
- return out;
373
- }, {}) : this.defKeys;
374
- }
375
- const entries = Object.entries(this.#def);
376
- return typesToMap(this.registry, entries.reduce((out, [key, {
377
- Type
378
- }], i) => {
379
- out[0][i] = Type;
380
- out[1][i] = key;
381
- return out;
382
- }, [new Array(entries.length), new Array(entries.length)]));
383
- }
384
-
385
- /**
386
- * @description Returns the base runtime type name for this instance
387
- */
388
- toRawType() {
389
- return stringify({
390
- _enum: this._toRawStruct()
391
- });
392
- }
393
-
394
- /**
395
- * @description Returns the string representation of the value
396
- */
397
- toString() {
398
- return this.isNone ? this.type : stringify(this.toJSON());
399
- }
400
-
401
- /**
402
- * @description Encodes the value as a Uint8Array as per the SCALE specifications
403
- * @param isBare true when the value has none of the type-specific prefixes (internal)
404
- */
405
- toU8a(isBare) {
406
- return isBare ? this.#raw.toU8a(isBare) : u8aConcatStrict([new Uint8Array([this.index]), this.#raw.toU8a(isBare)]);
407
- }
155
+ }
156
+ static with(Types) {
157
+ let definition;
158
+ // eslint-disable-next-line no-return-assign
159
+ const setDefinition = (d) => definition = d;
160
+ return class extends Enum {
161
+ static {
162
+ const keys = Array.isArray(Types)
163
+ ? Types
164
+ : Object.keys(Types);
165
+ const asKeys = new Array(keys.length);
166
+ const isKeys = new Array(keys.length);
167
+ for (let i = 0; i < keys.length; i++) {
168
+ const name = stringPascalCase(keys[i]);
169
+ asKeys[i] = `as${name}`;
170
+ isKeys[i] = `is${name}`;
171
+ }
172
+ objectProperties(this.prototype, isKeys, (_, i, self) => self.type === keys[i]);
173
+ objectProperties(this.prototype, asKeys, (k, i, self) => {
174
+ if (self.type !== keys[i]) {
175
+ throw new Error(`Cannot convert '${self.type}' via ${k}`);
176
+ }
177
+ return self.value;
178
+ });
179
+ }
180
+ constructor(registry, value, index) {
181
+ super(registry, Types, value, index, { definition, setDefinition });
182
+ }
183
+ };
184
+ }
185
+ /**
186
+ * @description The length of the value when encoded as a Uint8Array
187
+ */
188
+ get encodedLength() {
189
+ return 1 + this.#raw.encodedLength;
190
+ }
191
+ /**
192
+ * @description returns a hash of the contents
193
+ */
194
+ get hash() {
195
+ return this.registry.hash(this.toU8a());
196
+ }
197
+ /**
198
+ * @description The index of the enum value
199
+ */
200
+ get index() {
201
+ return this.#indexes[this.#entryIndex];
202
+ }
203
+ /**
204
+ * @description The value of the enum
205
+ */
206
+ get inner() {
207
+ return this.#raw;
208
+ }
209
+ /**
210
+ * @description true if this is a basic enum (no values)
211
+ */
212
+ get isBasic() {
213
+ return this.#isBasic;
214
+ }
215
+ /**
216
+ * @description Checks if the value is an empty value
217
+ */
218
+ get isEmpty() {
219
+ return this.#raw.isEmpty;
220
+ }
221
+ /**
222
+ * @description Checks if the Enum points to a [[Null]] type
223
+ */
224
+ get isNone() {
225
+ return this.#raw instanceof Null;
226
+ }
227
+ /**
228
+ * @description The available keys for this enum
229
+ */
230
+ get defIndexes() {
231
+ return this.#indexes;
232
+ }
233
+ /**
234
+ * @description The available keys for this enum
235
+ */
236
+ get defKeys() {
237
+ return Object.keys(this.#def);
238
+ }
239
+ /**
240
+ * @description The name of the type this enum value represents
241
+ */
242
+ get type() {
243
+ return this.defKeys[this.#entryIndex];
244
+ }
245
+ /**
246
+ * @description The value of the enum
247
+ */
248
+ get value() {
249
+ return this.#raw;
250
+ }
251
+ /**
252
+ * @description Compares the value of the input to see if there is a match
253
+ */
254
+ eq(other) {
255
+ // cater for the case where we only pass the enum index
256
+ if (isU8a(other)) {
257
+ return !this.toU8a().some((entry, index) => entry !== other[index]);
258
+ }
259
+ else if (isNumber(other)) {
260
+ return this.toNumber() === other;
261
+ }
262
+ else if (this.#isBasic && isString(other)) {
263
+ return this.type === other;
264
+ }
265
+ else if (isHex(other)) {
266
+ return this.toHex() === other;
267
+ }
268
+ else if (other instanceof Enum) {
269
+ return this.index === other.index && this.value.eq(other.value);
270
+ }
271
+ else if (isObject(other)) {
272
+ return this.value.eq(other[this.type]);
273
+ }
274
+ // compare the actual wrapper value
275
+ return this.value.eq(other);
276
+ }
277
+ /**
278
+ * @description Returns a breakdown of the hex encoding for this Codec
279
+ */
280
+ inspect() {
281
+ if (this.#isBasic) {
282
+ return { outer: [new Uint8Array([this.index])] };
283
+ }
284
+ const { inner, outer = [] } = this.#raw.inspect();
285
+ return {
286
+ inner,
287
+ outer: [new Uint8Array([this.index]), ...outer]
288
+ };
289
+ }
290
+ /**
291
+ * @description Returns a hex string representation of the value
292
+ */
293
+ toHex() {
294
+ return u8aToHex(this.toU8a());
295
+ }
296
+ /**
297
+ * @description Converts the Object to to a human-friendly JSON, with additional fields, expansion and formatting of information
298
+ */
299
+ toHuman(isExtended) {
300
+ return this.#isBasic || this.isNone
301
+ ? this.type
302
+ : { [this.type]: this.#raw.toHuman(isExtended) };
303
+ }
304
+ /**
305
+ * @description Converts the Object to JSON, typically used for RPC transfers
306
+ */
307
+ toJSON() {
308
+ return this.#isBasic
309
+ ? this.type
310
+ : { [stringCamelCase(this.type)]: this.#raw.toJSON() };
311
+ }
312
+ /**
313
+ * @description Returns the number representation for the value
314
+ */
315
+ toNumber() {
316
+ return this.index;
317
+ }
318
+ /**
319
+ * @description Converts the value in a best-fit primitive form
320
+ */
321
+ toPrimitive() {
322
+ return this.#isBasic
323
+ ? this.type
324
+ : { [stringCamelCase(this.type)]: this.#raw.toPrimitive() };
325
+ }
326
+ /**
327
+ * @description Returns a raw struct representation of the enum types
328
+ */
329
+ _toRawStruct() {
330
+ if (this.#isBasic) {
331
+ return this.#isIndexed
332
+ ? this.defKeys.reduce((out, key, index) => {
333
+ out[key] = this.#indexes[index];
334
+ return out;
335
+ }, {})
336
+ : this.defKeys;
337
+ }
338
+ const entries = Object.entries(this.#def);
339
+ return typesToMap(this.registry, entries.reduce((out, [key, { Type }], i) => {
340
+ out[0][i] = Type;
341
+ out[1][i] = key;
342
+ return out;
343
+ }, [new Array(entries.length), new Array(entries.length)]));
344
+ }
345
+ /**
346
+ * @description Returns the base runtime type name for this instance
347
+ */
348
+ toRawType() {
349
+ return stringify({ _enum: this._toRawStruct() });
350
+ }
351
+ /**
352
+ * @description Returns the string representation of the value
353
+ */
354
+ toString() {
355
+ return this.isNone
356
+ ? this.type
357
+ : stringify(this.toJSON());
358
+ }
359
+ /**
360
+ * @description Encodes the value as a Uint8Array as per the SCALE specifications
361
+ * @param isBare true when the value has none of the type-specific prefixes (internal)
362
+ */
363
+ toU8a(isBare) {
364
+ return isBare
365
+ ? this.#raw.toU8a(isBare)
366
+ : u8aConcatStrict([
367
+ new Uint8Array([this.index]),
368
+ this.#raw.toU8a(isBare)
369
+ ]);
370
+ }
408
371
  }