@talismn/scale 0.0.0-pr997-20231116062730 → 0.1.0

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 (47) hide show
  1. package/dist/declarations/src/index.d.ts +1 -2
  2. package/dist/declarations/src/papito.d.ts +6 -0
  3. package/dist/declarations/src/util/compactMetadata.d.ts +20 -0
  4. package/dist/declarations/src/util/decodeMetadata.d.ts +13 -0
  5. package/dist/declarations/src/util/decodeScale.d.ts +4 -0
  6. package/dist/declarations/src/util/encodeMetadata.d.ts +8 -0
  7. package/dist/declarations/src/util/encodeStateKey.d.ts +4 -0
  8. package/dist/declarations/src/util/getMetadataVersion.d.ts +6 -0
  9. package/dist/declarations/src/util/index.d.ts +7 -0
  10. package/dist/declarations/src/util/serdePapi.d.ts +29 -0
  11. package/dist/talismn-scale.cjs.dev.js +318 -1395
  12. package/dist/talismn-scale.cjs.prod.js +318 -1395
  13. package/dist/talismn-scale.esm.js +283 -1330
  14. package/package.json +16 -20
  15. package/CHANGELOG.md +0 -13
  16. package/dist/declarations/src/capi/crypto/base58.d.ts +0 -18
  17. package/dist/declarations/src/capi/crypto/hashers.d.ts +0 -66
  18. package/dist/declarations/src/capi/crypto/index.d.ts +0 -3
  19. package/dist/declarations/src/capi/crypto/ss58.d.ts +0 -16
  20. package/dist/declarations/src/capi/crypto/util/index.d.ts +0 -4
  21. package/dist/declarations/src/capi/crypto/util/nosimd.d.ts +0 -19
  22. package/dist/declarations/src/capi/crypto/util/simd.d.ts +0 -1
  23. package/dist/declarations/src/capi/frame_metadata/Extrinsic.d.ts +0 -50
  24. package/dist/declarations/src/capi/frame_metadata/FrameMetadata.d.ts +0 -61
  25. package/dist/declarations/src/capi/frame_metadata/decodeMetadata.d.ts +0 -312
  26. package/dist/declarations/src/capi/frame_metadata/index.d.ts +0 -4
  27. package/dist/declarations/src/capi/frame_metadata/key_codecs.d.ts +0 -27
  28. package/dist/declarations/src/capi/frame_metadata/raw/v14.d.ts +0 -312
  29. package/dist/declarations/src/capi/index.d.ts +0 -4
  30. package/dist/declarations/src/capi/scale_info/index.d.ts +0 -4
  31. package/dist/declarations/src/capi/scale_info/overrides/ChainError.d.ts +0 -26
  32. package/dist/declarations/src/capi/scale_info/overrides/Era.d.ts +0 -33
  33. package/dist/declarations/src/capi/scale_info/overrides/index.d.ts +0 -1
  34. package/dist/declarations/src/capi/scale_info/overrides/overrides.d.ts +0 -23
  35. package/dist/declarations/src/capi/scale_info/raw/Ty.d.ts +0 -313
  36. package/dist/declarations/src/capi/scale_info/transformTys.d.ts +0 -34
  37. package/dist/declarations/src/capi/util/index.d.ts +0 -3
  38. package/dist/declarations/src/capi/util/key.d.ts +0 -22
  39. package/dist/declarations/src/capi/util/normalize.d.ts +0 -25
  40. package/dist/declarations/src/capi/util/state.d.ts +0 -25
  41. package/dist/declarations/src/util.d.ts +0 -9
  42. package/dist/nosimd-20b5b0ca.esm.js +0 -45
  43. package/dist/nosimd-3e5ed5a9.cjs.prod.js +0 -48
  44. package/dist/nosimd-61fc593c.cjs.dev.js +0 -48
  45. package/dist/simd-133b8f48.cjs.prod.js +0 -14
  46. package/dist/simd-2ddb8d7c.cjs.dev.js +0 -14
  47. package/dist/simd-b794dbff.esm.js +0 -1
@@ -1,1315 +1,21 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var util = require('@talismn/util');
6
- var wasmFeatureDetect = require('wasm-feature-detect');
7
- var $ = require('@talismn/subshape-fork');
3
+ var metadataBuilders = require('@polkadot-api/metadata-builders');
4
+ var utils = require('@polkadot-api/utils');
5
+ var substrateBindings = require('@polkadot-api/substrate-bindings');
8
6
  var anylogger = require('anylogger');
7
+ var scaleTs = require('scale-ts');
9
8
 
10
- function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
11
-
12
- function _interopNamespace(e) {
13
- if (e && e.__esModule) return e;
14
- var n = Object.create(null);
15
- if (e) {
16
- Object.keys(e).forEach(function (k) {
17
- if (k !== 'default') {
18
- var d = Object.getOwnPropertyDescriptor(e, k);
19
- Object.defineProperty(n, k, d.get ? d : {
20
- enumerable: true,
21
- get: function () { return e[k]; }
22
- });
23
- }
24
- });
25
- }
26
- n["default"] = e;
27
- return Object.freeze(n);
28
- }
9
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
29
10
 
30
- var $__namespace = /*#__PURE__*/_interopNamespace($);
31
11
  var anylogger__default = /*#__PURE__*/_interopDefault(anylogger);
32
12
 
33
- //
34
- // The simd variants of these hash fns are faster, but some devices don't support them.
35
- //
36
- // This file re-exports the faster fns from `./simd` for devices which support them,
37
- // and falls back to `./nosimd` re-exports for devices which do not.
38
- //
39
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- let Blake2b;
41
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
- let Xxhash;
43
- let readyPromise = null;
44
- const watCryptoWaitReady = async () => {
45
- // if this is the second/third/etc time we've called watCryptoWaitReady,
46
- // then get a reference to the existing promise and wait for it to resolve/reject
47
- if (readyPromise !== null) return await readyPromise;
48
-
49
- // if this is the first time we've called watCryptoWaitReady,
50
- // then create and return a new promise
51
- const deferred = util.Deferred();
52
- readyPromise = deferred.promise
53
-
54
- // spawn a task to initialize the fns and resolve the readyPromise
55
- ;
56
- (async () => {
57
- try {
58
- // initialize simd or nosimd, based on wasm feature detection
59
- if (await wasmFeatureDetect.simd()) {
60
- // system supports wasm simd
61
- const imported = await Promise.resolve().then(function () { return require('./simd-133b8f48.cjs.prod.js'); });
62
- Blake2b = imported.Blake2b;
63
- Xxhash = imported.Xxhash;
64
- } else {
65
- // system does not support wasm simd
66
- const imported = await Promise.resolve().then(function () { return require('./nosimd-3e5ed5a9.cjs.prod.js'); });
67
- Blake2b = imported.Blake2b;
68
- Xxhash = imported.Xxhash;
69
- }
70
-
71
- // feature detection and loading complete
72
- deferred.resolve();
73
- } catch (error) {
74
- // feature detection and loading failed
75
- deferred.reject(error);
76
- }
77
- })();
78
-
79
- // wait for the promise to resolve/reject
80
- return await readyPromise;
81
- };
82
-
83
- // Copyright 2018-2023 the Deno authors. All rights reserved. MIT license.
84
- // This module is browser compatible.
85
-
86
- /**
87
- * {@linkcode encode} and {@linkcode decode} for
88
- * [base58](https://en.wikipedia.org/wiki/Binary-to-text_encoding#Base58) encoding.
89
- *
90
- * This module is browser compatible.
91
- *
92
- * @module
93
- */
94
-
95
- // deno-fmt-ignore
96
- const mapBase58 = {
97
- "1": 0,
98
- "2": 1,
99
- "3": 2,
100
- "4": 3,
101
- "5": 4,
102
- "6": 5,
103
- "7": 6,
104
- "8": 7,
105
- "9": 8,
106
- "A": 9,
107
- "B": 10,
108
- "C": 11,
109
- "D": 12,
110
- "E": 13,
111
- "F": 14,
112
- "G": 15,
113
- "H": 16,
114
- "J": 17,
115
- "K": 18,
116
- "L": 19,
117
- "M": 20,
118
- "N": 21,
119
- "P": 22,
120
- "Q": 23,
121
- "R": 24,
122
- "S": 25,
123
- "T": 26,
124
- "U": 27,
125
- "V": 28,
126
- "W": 29,
127
- "X": 30,
128
- "Y": 31,
129
- "Z": 32,
130
- "a": 33,
131
- "b": 34,
132
- "c": 35,
133
- "d": 36,
134
- "e": 37,
135
- "f": 38,
136
- "g": 39,
137
- "h": 40,
138
- "i": 41,
139
- "j": 42,
140
- "k": 43,
141
- "m": 44,
142
- "n": 45,
143
- "o": 46,
144
- "p": 47,
145
- "q": 48,
146
- "r": 49,
147
- "s": 50,
148
- "t": 51,
149
- "u": 52,
150
- "v": 53,
151
- "w": 54,
152
- "x": 55,
153
- "y": 56,
154
- "z": 57
155
- };
156
- const base58alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split("");
157
-
158
- /**
159
- * Encodes a given Uint8Array, ArrayBuffer or string into draft-mspotny-base58-03 RFC base58 representation:
160
- * https://tools.ietf.org/id/draft-msporny-base58-01.html#rfc.section.1
161
- *
162
- * @param data
163
- *
164
- * @returns Encoded value
165
- */
166
- function encode$1(data) {
167
- const uint8tData = typeof data === "string" ? new TextEncoder().encode(data) : data instanceof Uint8Array ? data : new Uint8Array(data);
168
- let length = 0;
169
- let zeroes = 0;
170
-
171
- // Counting leading zeroes
172
- let index = 0;
173
- while (uint8tData[index] === 0) {
174
- zeroes++;
175
- index++;
176
- }
177
- const notZeroUint8Data = uint8tData.slice(index);
178
- const size = Math.round(uint8tData.length * 138 / 100 + 1);
179
- const b58Encoding = [];
180
- notZeroUint8Data.forEach(byte => {
181
- let i = 0;
182
- let carry = byte;
183
- for (let reverse_iterator = size - 1; (carry > 0 || i < length) && reverse_iterator !== -1; reverse_iterator--, i++) {
184
- carry += (b58Encoding[reverse_iterator] || 0) * 256;
185
- b58Encoding[reverse_iterator] = Math.round(carry % 58);
186
- carry = Math.floor(carry / 58);
187
- }
188
- length = i;
189
- });
190
- const strResult = Array.from({
191
- length: b58Encoding.length + zeroes
192
- });
193
- if (zeroes > 0) {
194
- strResult.fill("1", 0, zeroes);
195
- }
196
- b58Encoding.forEach(byteValue => strResult.push(base58alphabet[byteValue]));
197
- return strResult.join("");
198
- }
199
-
200
- /**
201
- * Decodes a given b58 string according to draft-mspotny-base58-03 RFC base58 representation:
202
- * https://tools.ietf.org/id/draft-msporny-base58-01.html#rfc.section.1
203
- *
204
- * @param b58
205
- *
206
- * @returns Decoded value
207
- */
208
- function decode$1(b58) {
209
- const splitInput = b58.trim().split("");
210
- let length = 0;
211
- let ones = 0;
212
-
213
- // Counting leading ones
214
- let index = 0;
215
- while (splitInput[index] === "1") {
216
- ones++;
217
- index++;
218
- }
219
- const notZeroData = splitInput.slice(index);
220
- const size = Math.round(b58.length * 733 / 1000 + 1);
221
- const output = [];
222
- notZeroData.forEach((char, idx) => {
223
- let carry = mapBase58[char];
224
- let i = 0;
225
- if (carry === undefined) {
226
- throw new Error(`Invalid base58 char at index ${idx} with value ${char}`);
227
- }
228
- for (let reverse_iterator = size - 1; (carry > 0 || i < length) && reverse_iterator !== -1; reverse_iterator--, i++) {
229
- carry += 58 * (output[reverse_iterator] || 0);
230
- output[reverse_iterator] = Math.round(carry % 256);
231
- carry = Math.floor(carry / 256);
232
- }
233
- length = i;
234
- });
235
- const validOutput = output.filter(item => item !== undefined);
236
- if (ones > 0) {
237
- const onesResult = Array.from({
238
- length: ones
239
- }).fill(0, 0, ones);
240
- return new Uint8Array([...onesResult, ...validOutput]);
241
- }
242
- return new Uint8Array(validOutput);
243
- }
244
-
245
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
246
- function encode(prefix, payload, checksumLength) {
247
- return encode$1(encodeRaw(prefix, payload, checksumLength));
248
- }
249
- function encodeRaw(prefix, payload, checksumLength) {
250
- checksumLength ??= DEFAULT_PAYLOAD_CHECKSUM_LENGTHS[payload.length];
251
- if (!checksumLength) throw new InvalidPayloadLengthError();
252
- const prefixBytes = prefix < 64 ? Uint8Array.of(prefix) : Uint8Array.of((prefix & 0b0000_0000_1111_1100) >> 2 | 0b0100_0000, prefix >> 8 | (prefix & 0b0000_0000_0000_0011) << 6);
253
- const hasher = new Blake2b();
254
- hasher.update(SS58PRE);
255
- hasher.update(prefixBytes);
256
- hasher.update(payload);
257
- const digest = hasher.digest();
258
- const checksum = digest.subarray(0, checksumLength);
259
- hasher.dispose();
260
- const address = new Uint8Array(prefixBytes.length + payload.length + checksumLength);
261
- address.set(prefixBytes, 0);
262
- address.set(payload, prefixBytes.length);
263
- address.set(checksum, prefixBytes.length + payload.length);
264
- return address;
265
- }
266
- class InvalidPayloadLengthError extends Error {
267
- name = "InvalidPayloadLengthError";
268
- }
269
- function decode(address) {
270
- return decodeRaw(decode$1(address));
271
- }
272
- function decodeRaw(address) {
273
- const checksumLength = VALID_ADDRESS_CHECKSUM_LENGTHS[address.length];
274
- if (!checksumLength) throw new InvalidAddressLengthError();
275
- const prefixLength = address[0] & 0b0100_0000 ? 2 : 1;
276
- const prefix = prefixLength === 1 ? address[0] : (address[0] & 0b0011_1111) << 2 | address[1] >> 6 | (address[1] & 0b0011_1111) << 8;
277
- const hasher = new Blake2b();
278
- hasher.update(SS58PRE);
279
- hasher.update(address.subarray(0, address.length - checksumLength));
280
- const digest = hasher.digest();
281
- const checksum = address.subarray(address.length - checksumLength);
282
- hasher.dispose();
283
- if (!isValidChecksum(digest, checksum, checksumLength)) {
284
- throw new InvalidAddressChecksumError();
285
- }
286
- const pubKey = address.subarray(prefixLength, address.length - checksumLength);
287
- return [prefix, pubKey];
288
- }
289
- class InvalidAddressLengthError extends Error {
290
- name = "InvalidAddressError";
291
- }
292
- class InvalidAddressChecksumError extends Error {
293
- name = "InvalidAddressChecksumError";
294
- }
295
-
296
- // SS58PRE string (0x53533538505245 hex) encoded as Uint8Array
297
- const SS58PRE = Uint8Array.of(83, 83, 53, 56, 80, 82, 69);
298
- const VALID_ADDRESS_CHECKSUM_LENGTHS = {
299
- 3: 1,
300
- 4: 1,
301
- 5: 2,
302
- 6: 1,
303
- 7: 2,
304
- 8: 3,
305
- 9: 4,
306
- 10: 1,
307
- 11: 2,
308
- 12: 3,
309
- 13: 4,
310
- 14: 5,
311
- 15: 6,
312
- 16: 7,
313
- 17: 8,
314
- 35: 2,
315
- 36: 2,
316
- 37: 2
317
- };
318
- const DEFAULT_PAYLOAD_CHECKSUM_LENGTHS = {
319
- 1: 1,
320
- 2: 1,
321
- 4: 1,
322
- 8: 1,
323
- 32: 2,
324
- 33: 2
325
- };
326
- function isValidChecksum(digest, checksum, checksumLength) {
327
- for (let i = 0; i < checksumLength; i++) {
328
- if (digest[i] !== checksum[i]) {
329
- return false;
330
- }
331
- }
332
- return true;
333
- }
334
-
335
- var ss58 = /*#__PURE__*/Object.freeze({
336
- __proto__: null,
337
- encode: encode,
338
- encodeRaw: encodeRaw,
339
- InvalidPayloadLengthError: InvalidPayloadLengthError,
340
- decode: decode,
341
- decodeRaw: decodeRaw,
342
- InvalidAddressLengthError: InvalidAddressLengthError,
343
- InvalidAddressChecksumError: InvalidAddressChecksumError
344
- });
345
-
346
- /**
347
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
348
- * Changes August 19th 2023 :
349
- * - updated to use subshape for scale decoding
350
- * - adapted from deno to typescript
351
- *
352
- Copyright 2023 Parity Technologies
353
-
354
- Licensed under the Apache License, Version 2.0 (the "License");
355
- you may not use this file except in compliance with the License.
356
- You may obtain a copy of the License at
357
-
358
- http://www.apache.org/licenses/LICENSE-2.0
359
-
360
- Unless required by applicable law or agreed to in writing, software
361
- distributed under the License is distributed on an "AS IS" BASIS,
362
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
363
- See the License for the specific language governing permissions and
364
- limitations under the License.
365
- */
366
- class Hasher {
367
- $hash($inner) {
368
- return $hash(this, $inner);
369
- }
370
- hash(data) {
371
- const output = new Uint8Array(this.digestLength + (this.concat ? data.length : 0));
372
- const hashing = this.create();
373
- hashing.update(data);
374
- hashing.digestInto(output);
375
- hashing.dispose?.();
376
- if (this.concat) {
377
- output.set(data, this.digestLength);
378
- }
379
- return output;
380
- }
381
- }
382
- function $hash(hasher, $inner) {
383
- return $__namespace.createShape({
384
- metadata: $__namespace.metadata("$hash", $hash, hasher, $inner),
385
- staticSize: hasher.digestLength + $inner.staticSize,
386
- subEncode(buffer, value) {
387
- const hashArray = buffer.array.subarray(buffer.index, buffer.index += hasher.digestLength);
388
- const cursor = hasher.concat ? buffer.createCursor($inner.staticSize) : new $.EncodeBuffer(buffer.stealAlloc($inner.staticSize));
389
- $inner.subEncode(cursor, value);
390
- buffer.waitForBuffer(cursor, () => {
391
- if (hasher.concat) cursor.close();else cursor._commitWritten();
392
- const hashing = hasher.create();
393
- updateHashing(hashing, cursor);
394
- hashing.digestInto(hashArray);
395
- hashing.dispose?.();
396
- });
397
- },
398
- subDecode(buffer) {
399
- if (!hasher.concat) throw new DecodeNonTransparentKeyError();
400
- buffer.index += hasher.digestLength;
401
- return $inner.subDecode(buffer);
402
- },
403
- subAssert(assert) {
404
- $inner.subAssert(assert);
405
- }
406
- });
407
- }
408
- class Blake2Hasher extends Hasher {
409
- constructor(size, concat) {
410
- super();
411
- this.concat = concat;
412
- this.digestLength = size / 8;
413
- }
414
- create() {
415
- return new Blake2b(this.digestLength);
416
- }
417
- }
418
- class IdentityHasher extends Hasher {
419
- digestLength = 0;
420
- concat = true;
421
- create() {
422
- return {
423
- update() {},
424
- digestInto() {}
425
- };
426
- }
427
- $hash($inner) {
428
- return $inner;
429
- }
430
- hash(data) {
431
- return data.slice();
432
- }
433
- }
434
- class TwoxHasher extends Hasher {
435
- constructor(size, concat) {
436
- super();
437
- this.concat = concat;
438
- this.digestLength = size / 8;
439
- this.rounds = size / 64;
440
- }
441
- create() {
442
- return new Xxhash(this.rounds);
443
- }
444
- }
445
- const blake2_64 = new Blake2Hasher(64, false);
446
- const blake2_128 = new Blake2Hasher(128, false);
447
- const blake2_128Concat = new Blake2Hasher(128, true);
448
- const blake2_256 = new Blake2Hasher(256, false);
449
- const blake2_512 = new Blake2Hasher(512, false);
450
- const identity = new IdentityHasher();
451
- const twox128 = new TwoxHasher(128, false);
452
- const twox256 = new TwoxHasher(256, false);
453
- const twox64Concat = new TwoxHasher(64, true);
454
- function updateHashing(hashing, data) {
455
- for (const array of data.finishedArrays) {
456
- if (array instanceof $.EncodeBuffer) {
457
- updateHashing(hashing, array);
458
- } else {
459
- hashing.update(array);
460
- }
461
- }
462
- }
463
- class DecodeNonTransparentKeyError extends Error {
464
- name = "DecodeNonTransparentKeyError";
465
- }
466
-
467
- /**
468
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
469
- * Changes August 19th 2023 :
470
- * - updated to use subshape for scale decoding
471
- * - adapted from deno to typescript
472
- *
473
- Copyright 2023 Parity Technologies
474
-
475
- Licensed under the Apache License, Version 2.0 (the "License");
476
- you may not use this file except in compliance with the License.
477
- You may obtain a copy of the License at
478
-
479
- http://www.apache.org/licenses/LICENSE-2.0
480
-
481
- Unless required by applicable law or agreed to in writing, software
482
- distributed under the License is distributed on an "AS IS" BASIS,
483
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
484
- See the License for the specific language governing permissions and
485
- limitations under the License.
486
- */
487
- const $tyId = $__namespace.compact($__namespace.u32);
488
- const $field = $__namespace.object($__namespace.optionalField("name", $__namespace.str), $__namespace.field("ty", $tyId), $__namespace.optionalField("typeName", $__namespace.str), $__namespace.field("docs", $__namespace.array($__namespace.str)));
489
- const $primitiveKind = $__namespace.literalUnion(["bool", "char", "str", "u8", "u16", "u32", "u64", "u128", "u256", "i8", "i16", "i32", "i64", "i128", "i256"]);
490
- const $tyDef = $__namespace.taggedUnion("type", [$__namespace.variant("Struct", $__namespace.field("fields", $__namespace.array($field))), $__namespace.variant("Union", $__namespace.field("members", $__namespace.array($__namespace.object($__namespace.field("name", $__namespace.str), $__namespace.field("fields", $__namespace.array($field)), $__namespace.field("index", $__namespace.u8), $__namespace.field("docs", $__namespace.array($__namespace.str)))))), $__namespace.variant("Sequence", $__namespace.field("typeParam", $tyId)), $__namespace.variant("SizedArray", $__namespace.field("len", $__namespace.u32), $__namespace.field("typeParam", $tyId)), $__namespace.variant("Tuple", $__namespace.field("fields", $__namespace.array($tyId))), $__namespace.variant("Primitive", $__namespace.field("kind", $primitiveKind)), $__namespace.variant("Compact", $__namespace.field("typeParam", $tyId)), $__namespace.variant("BitSequence", $__namespace.field("bitOrderType", $tyId), $__namespace.field("bitStoreType", $tyId))]);
491
- const $ty = $__namespace.object($__namespace.field("id", $__namespace.compact($__namespace.u32)), $__namespace.field("path", $__namespace.array($__namespace.str)), $__namespace.field("params", $__namespace.array($__namespace.object($__namespace.field("name", $__namespace.str), $__namespace.optionalField("ty", $tyId)))), $tyDef, $__namespace.field("docs", $__namespace.array($__namespace.str)));
492
-
493
- /**
494
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
495
- * Changes August 19th 2023 :
496
- * - updated to use subshape for scale decoding
497
- * - adapted from deno to typescript
498
- *
499
- Copyright 2023 Parity Technologies
500
-
501
- Licensed under the Apache License, Version 2.0 (the "License");
502
- you may not use this file except in compliance with the License.
503
- You may obtain a copy of the License at
504
-
505
- http://www.apache.org/licenses/LICENSE-2.0
506
-
507
- Unless required by applicable law or agreed to in writing, software
508
- distributed under the License is distributed on an "AS IS" BASIS,
509
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
510
- See the License for the specific language governing permissions and
511
- limitations under the License.
512
- */
513
-
514
- const unquotedKey = /^(?!__proto__$)[$_\p{ID_Start}][$\p{ID_Continue}]+$|^\d+$/u;
515
- function stringifyKey(key) {
516
- return unquotedKey.test(key) ? key : JSON.stringify(key);
517
- }
518
- function stringifyPropertyAccess(key) {
519
- return unquotedKey.test(key) ? `.${key}` : `[${JSON.stringify(key)}]`;
520
- }
521
-
522
- /**
523
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
524
- * Changes August 19th 2023 :
525
- * - updated to use subshape for scale decoding
526
- * - adapted from deno to typescript
527
- *
528
- Copyright 2023 Parity Technologies
529
-
530
- Licensed under the Apache License, Version 2.0 (the "License");
531
- you may not use this file except in compliance with the License.
532
- You may obtain a copy of the License at
533
-
534
- http://www.apache.org/licenses/LICENSE-2.0
535
-
536
- Unless required by applicable law or agreed to in writing, software
537
- distributed under the License is distributed on an "AS IS" BASIS,
538
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
539
- See the License for the specific language governing permissions and
540
- limitations under the License.
541
- */
542
-
543
- function normalizeIdent(ident) {
544
- if (ident.startsWith("r#")) ident = ident.slice(2);
545
- return normalizeKeyword(ident.replace(/(?:[^\p{ID_Continue}]|_)+(.)/gu, (_, $1) => $1.toUpperCase()));
546
- }
547
- function normalizeDocs(docs) {
548
- let str = docs?.join("\n") ?? "";
549
- str = str.replace(/[^\S\n]+$/gm, "") // strip trailing whitespace
550
- .replace(/^\n+|\n+$/g, ""); // strip leading and trailing newlines
551
- const match = /^([^\S\n]+).*(?:\n\1.*)*$/.exec(str); // find a common indent
552
- if (match) {
553
- const {
554
- 1: prefix
555
- } = match;
556
- str = str.replace(new RegExp(`^${prefix}`, "gm"), ""); // strip the common indent
557
- // this `new RegExp` is safe because `prefix` must be whitespace
558
- }
559
-
560
- return str;
561
- }
562
- function normalizePackageName(name) {
563
- return name.replace(/[A-Z]/g, x => `-` + x.toLowerCase());
564
- }
565
- function normalizeTypeName(name) {
566
- return normalizeIdent(name).replace(/^./, x => x.toUpperCase());
567
- }
568
- function normalizeVariableName(name) {
569
- return normalizeIdent(name).replace(/^./, x => x.toLowerCase());
570
- }
571
-
572
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
573
- const keywords = ["break", "case", "catch", "class", "const", "continue", "debugger", "delete", "do", "else", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "new", "null", "return", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "let", "static", "yield", "await", "enum", "implements", "interface", "package", "private", "protected", "public"];
574
- function normalizeKeyword(ident) {
575
- return keywords.includes(ident) ? ident + "_" : ident;
576
- }
577
-
578
- /**
579
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
580
- * Changes August 19th 2023 :
581
- * - updated to use subshape for scale decoding
582
- * - adapted from deno to typescript
583
- *
584
- Copyright 2023 Parity Technologies
585
-
586
- Licensed under the Apache License, Version 2.0 (the "License");
587
- you may not use this file except in compliance with the License.
588
- You may obtain a copy of the License at
589
-
590
- http://www.apache.org/licenses/LICENSE-2.0
591
-
592
- Unless required by applicable law or agreed to in writing, software
593
- distributed under the License is distributed on an "AS IS" BASIS,
594
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
595
- See the License for the specific language governing permissions and
596
- limitations under the License.
597
- */
598
-
599
- function getOrInit(container, key, init) {
600
- let value = container.get(key);
601
- if (value === undefined) {
602
- value = init();
603
- container.set(key, value);
604
- }
605
- return value;
606
- }
607
-
608
- // export class WeakRefMap<K, V extends object> {
609
- // map = new Map<K, WeakRef<V>>()
610
- // finReg = new FinalizationRegistry<K>((key) => this.map.delete(key))
611
- // get(key: K) {
612
- // return this.map.get(key)?.deref()
613
- // }
614
- // set(key: K, value: V) {
615
- // this.map.set(key, new WeakRef(value))
616
- // this.finReg.register(value, key, value)
617
- // }
618
- // delete(key: K) {
619
- // const value = this.get(key)
620
- // if (!value) return false
621
- // this.map.delete(key)
622
- // this.finReg.unregister(value)
623
- // return true
624
- // }
625
- // }
626
-
627
- /**
628
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
629
- * Changes August 19th 2023 :
630
- * - updated to use subshape for scale decoding
631
- * - adapted from deno to typescript
632
- *
633
- Copyright 2023 Parity Technologies
634
-
635
- Licensed under the Apache License, Version 2.0 (the "License");
636
- you may not use this file except in compliance with the License.
637
- You may obtain a copy of the License at
638
-
639
- http://www.apache.org/licenses/LICENSE-2.0
640
-
641
- Unless required by applicable law or agreed to in writing, software
642
- distributed under the License is distributed on an "AS IS" BASIS,
643
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
644
- See the License for the specific language governing permissions and
645
- limitations under the License.
646
- */
647
-
648
- class ChainError extends Error {
649
- name = "ChainError";
650
- constructor(value) {
651
- super();
652
- this.value = value;
653
- this.stack = "ChainError: see error.value\n [error occurred on chain]";
654
- }
655
- static toArgs = x => [x.value];
656
- }
657
-
658
- /**
659
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
660
- * Changes August 19th 2023 :
661
- * - updated to use subshape for scale decoding
662
- * - adapted from deno to typescript
663
- *
664
- Copyright 2023 Parity Technologies
665
-
666
- Licensed under the Apache License, Version 2.0 (the "License");
667
- you may not use this file except in compliance with the License.
668
- You may obtain a copy of the License at
669
-
670
- http://www.apache.org/licenses/LICENSE-2.0
671
-
672
- Unless required by applicable law or agreed to in writing, software
673
- distributed under the License is distributed on an "AS IS" BASIS,
674
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
675
- See the License for the specific language governing permissions and
676
- limitations under the License.
677
- */
678
- // eslint-disable-next-line @typescript-eslint/no-namespace
679
- exports.Era = void 0;
680
- (function (_Era) {
681
- _Era.Immortal = {
682
- type: "Immortal"
683
- };
684
- function Mortal(period, current) {
685
- const adjustedPeriod = minN(maxN(nextPowerOfTwo(period), 4n), 1n << 16n);
686
- const phase = current % adjustedPeriod;
687
- const quantizeFactor = maxN(adjustedPeriod >> 12n, 1n);
688
- const quantizedPhase = phase / quantizeFactor * quantizeFactor;
689
- return {
690
- type: "Mortal",
691
- period: adjustedPeriod,
692
- phase: quantizedPhase
693
- };
694
- }
695
- _Era.Mortal = Mortal;
696
- })(exports.Era || (exports.Era = {}));
697
- const $era = $__namespace.createShape({
698
- metadata: $__namespace.metadata("$era"),
699
- staticSize: 2,
700
- subEncode(buffer, value) {
701
- if (value.type === "Immortal") {
702
- buffer.array[buffer.index++] = 0;
703
- } else {
704
- const quantizeFactor = maxN(value.period >> 12n, 1n);
705
- const encoded = minN(maxN(trailingZeroes(value.period) - 1n, 1n), 15n) | value.phase / quantizeFactor << 4n;
706
- $__namespace.u16.subEncode(buffer, Number(encoded));
707
- }
708
- },
709
- subDecode(buffer) {
710
- if (buffer.array[buffer.index] === 0) {
711
- buffer.index++;
712
- return {
713
- type: "Immortal"
714
- };
715
- } else {
716
- const encoded = BigInt($__namespace.u16.subDecode(buffer));
717
- const period = 2n << encoded % (1n << 4n);
718
- const quantizeFactor = maxN(period >> 12n, 1n);
719
- const phase = (encoded >> 4n) * quantizeFactor;
720
- if (period >= 4n && phase <= period) {
721
- return {
722
- type: "Mortal",
723
- period,
724
- phase
725
- };
726
- } else {
727
- throw new Error("Invalid period and phase");
728
- }
729
- }
730
- },
731
- subAssert: $__namespace.taggedUnion("type", [$__namespace.variant("Immortal"), $__namespace.variant("Mortal", $__namespace.field("period", $__namespace.u64), $__namespace.field("phase", $__namespace.u64))]).subAssert
732
- });
733
- function maxN(a, b) {
734
- return a > b ? a : b;
735
- }
736
- function minN(a, b) {
737
- return a < b ? a : b;
738
- }
739
- function trailingZeroes(n) {
740
- let i = 0n;
741
- while (!(n & 1n)) {
742
- i++;
743
- n >>= 1n;
744
- }
745
- return i;
746
- }
747
- function nextPowerOfTwo(n) {
748
- n--;
749
- let p = 1n;
750
- while (n > 0n) {
751
- p <<= 1n;
752
- n >>= 1n;
753
- }
754
- return p;
755
- }
756
-
757
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
758
- const isResult = new $__namespace.ShapeVisitor().add($__namespace.result, () => true).fallback(() => false);
759
- const isOption = new $__namespace.ShapeVisitor().add($__namespace.option, () => true).fallback(() => false);
760
- const overrides = {
761
- "Option": (ty, visit) => {
762
- let $some = visit(ty.params[0].ty);
763
- if (isOption.visit($some)) {
764
- $some = $__namespace.tuple($some);
765
- }
766
- return $__namespace.option($some);
767
- },
768
- "Result": (ty, visit) => {
769
- let $ok = visit(ty.params[0].ty);
770
- if (isResult.visit($ok)) {
771
- $ok = $__namespace.tuple($ok);
772
- }
773
- return $__namespace.result($ok, $__namespace.instance(ChainError, $__namespace.tuple(visit(ty.params[1].ty)), ChainError.toArgs));
774
- },
775
- "BTreeMap": (ty, visit) => {
776
- return $__namespace.map(visit(ty.params[0].ty), visit(ty.params[1].ty));
777
- },
778
- "BTreeSet": (ty, visit) => {
779
- return $__namespace.set(visit(ty.params[0].ty));
780
- },
781
- "frame_support::traits::misc::WrapperOpaque": (ty, visit) => {
782
- return $__namespace.lenPrefixed(visit(ty.params[0].ty));
783
- },
784
- "frame_support::traits::misc::WrapperKeepOpaque": (ty, visit) => {
785
- return $__namespace.lenPrefixed(visit(ty.params[0].ty));
786
- },
787
- "sp_runtime::generic::era::Era": () => {
788
- return $era;
789
- }
790
- };
791
-
792
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
793
- /**
794
- * All derived codecs for ZSTs will use this exact codec,
795
- * so `derivedCodec === $null` is true iff the type is a ZST.
796
- */
797
- const $null = $__namespace.withMetadata($__namespace.metadata("$null"), $__namespace.constant(null));
798
- function transformTys(tys) {
799
- const tysMap = new Map(tys.map(ty => [ty.id, ty]));
800
- const memo = new Map();
801
- const types = {};
802
- const paths = {};
803
- const seenPaths = new Map();
804
- const includePaths = new Set();
805
- const names = new Map();
806
- const nameCounts = new Map();
807
- for (const ty of tys) {
808
- const path = ty.path.join("::");
809
- if (!path) continue;
810
- const last = seenPaths.get(path);
811
- if (last !== undefined) {
812
- if (last === null || !eqTy(tysMap, last.id, ty.id)) {
813
- seenPaths.set(path, null);
814
- includePaths.delete(path);
815
- }
816
- continue;
817
- }
818
- seenPaths.set(path, ty);
819
- includePaths.add(path);
820
- }
821
- for (const path of includePaths) {
822
- const parts = path.split("::");
823
- const name = parts.at(-1);
824
- const map = getOrInit(nameCounts, name, () => new Map());
825
- for (let i = 0; i < parts.length; i++) {
826
- const pathPart = parts.slice(0, i).join("::");
827
- map.set(pathPart, (map.get(pathPart) ?? 0) + 1);
828
- }
829
- }
830
- for (const path of includePaths) {
831
- const parts = path.split("::");
832
- const name = parts.at(-1);
833
- const map = nameCounts.get(name);
834
- const pathLength = parts.findIndex((_, i) => map.get(parts.slice(0, i).join("::")) === 1);
835
- const newPath = [...parts.slice(0, pathLength), name].join("::");
836
- const newName = normalizeTypeName(newPath);
837
- names.set(path, newName);
838
- }
839
- return {
840
- ids: tys.map(ty => visit(ty.id)),
841
- types,
842
- paths
843
- };
844
- function visit(i) {
845
- return getOrInit(memo, i, () => {
846
- memo.set(i, $__namespace.deferred(() => memo.get(i)));
847
- const ty = tysMap.get(i);
848
- const path = ty.path.join("::");
849
- const usePath = includePaths.has(path);
850
- const name = names.get(path);
851
- if (usePath && types[name]) return types[name];
852
- const codec = withDocs(ty.docs, _visit(ty));
853
- if (usePath) return types[name] ??= paths[path] = codec;
854
- return codec;
855
- });
856
- }
857
- function _visit(ty) {
858
- const overrideFn = overrides[ty.path.join("::")];
859
- if (overrideFn) return overrideFn(ty, visit);
860
- if (ty.type === "Struct") {
861
- if (ty.fields.length === 0) {
862
- return $null;
863
- } else if (ty.fields[0].name === undefined) {
864
- if (ty.fields.length === 1) {
865
- // wrapper
866
- return visit(ty.fields[0].ty);
867
- } else {
868
- return $__namespace.tuple(...ty.fields.map(x => visit(x.ty)));
869
- }
870
- } else {
871
- return $__namespace.object(...ty.fields.map(x => withDocs(x.docs, maybeOptionalField(normalizeIdent(x.name), visit(x.ty)))));
872
- }
873
- } else if (ty.type === "Tuple") {
874
- if (ty.fields.length === 0) {
875
- return $null;
876
- } else if (ty.fields.length === 1) {
877
- // wrapper
878
- return visit(ty.fields[0]);
879
- } else {
880
- return $__namespace.tuple(...ty.fields.map(x => visit(x)));
881
- }
882
- } else if (ty.type === "Union") {
883
- if (ty.members.length === 0) {
884
- return $__namespace.never;
885
- } else if (ty.members.every(x => x.fields.length === 0)) {
886
- const members = {};
887
- for (const {
888
- index,
889
- name
890
- } of ty.members) {
891
- members[index] = normalizeIdent(name);
892
- }
893
- return $__namespace.literalUnion(members);
894
- } else {
895
- const members = {};
896
- for (const {
897
- fields,
898
- name,
899
- index
900
- } of ty.members) {
901
- let member;
902
- const type = normalizeIdent(name);
903
- if (fields.length === 0) {
904
- member = $__namespace.variant(type);
905
- } else if (fields[0].name === undefined) {
906
- // Tuple variant
907
- const $value = fields.length === 1 ? visit(fields[0].ty) : $__namespace.tuple(...fields.map(f => visit(f.ty)));
908
- member = $__namespace.variant(type, maybeOptionalField("value", $value));
909
- } else {
910
- // Object variant
911
- const memberFields = fields.map(field => {
912
- return withDocs(field.docs, maybeOptionalField(normalizeIdent(field.name), visit(field.ty)));
913
- });
914
- member = $__namespace.variant(type, ...memberFields);
915
- }
916
- members[index] = member;
917
- }
918
- return $__namespace.taggedUnion("type", members);
919
- }
920
- } else if (ty.type === "Sequence") {
921
- const $inner = visit(ty.typeParam);
922
- if ($inner === $__namespace.u8) {
923
- return $__namespace.uint8Array;
924
- } else {
925
- return $__namespace.array($inner);
926
- }
927
- } else if (ty.type === "SizedArray") {
928
- const $inner = visit(ty.typeParam);
929
- if ($inner === $__namespace.u8) {
930
- return $__namespace.sizedUint8Array(ty.len);
931
- } else {
932
- return $__namespace.sizedArray($inner, ty.len);
933
- }
934
- } else if (ty.type === "Primitive") {
935
- if (ty.kind === "char") return $__namespace.str;
936
- return $__namespace[ty.kind];
937
- } else if (ty.type === "Compact") {
938
- return $__namespace.compact(visit(ty.typeParam));
939
- } else if (ty.type === "BitSequence") {
940
- return $__namespace.bitSequence;
941
- } else {
942
- throw new Error("unreachable");
943
- }
944
- }
945
- }
946
- function withDocs(_docs, codec) {
947
- const docs = normalizeDocs(_docs);
948
- if (docs) return $__namespace.documented(docs, codec);
949
- return codec;
950
- }
951
- function eqTy(tysMap, a, b) {
952
- const seen = new Set();
953
- return eqTy(a, b);
954
- function eqTy(ai, bi) {
955
- const key = `${ai}=${bi}`;
956
- if (seen.has(key)) return true;
957
- seen.add(key);
958
- const a = tysMap.get(ai);
959
- const b = tysMap.get(bi);
960
- if (a.id === b.id) return true;
961
- if (a.type !== b.type) return false;
962
- if (a.path.join("::") !== b.path.join("::")) return false;
963
- if (normalizeDocs(a.docs) !== normalizeDocs(b.docs)) return false;
964
- if (!eqArray(a.params, b.params, (a, b) => a.name === b.name && a.ty == null === (b.ty == null) && (a.ty == null || eqTy(a.ty, b.ty)))) {
965
- return false;
966
- }
967
- if (a.type === "BitSequence") {
968
- return true;
969
- }
970
- if (a.type === "Primitive" && b.type === "Primitive") {
971
- return a.kind === b.kind;
972
- }
973
- if (a.type === "Compact" && b.type === "Compact" || a.type === "Sequence" && b.type === "Sequence") {
974
- return eqTy(a.typeParam, b.typeParam);
975
- }
976
- if (a.type === "SizedArray" && b.type === "SizedArray") {
977
- return a.len === b.len && eqTy(a.typeParam, b.typeParam);
978
- }
979
- if (a.type === "Struct" && b.type === "Struct") {
980
- return eqArray(a.fields, b.fields, eqField);
981
- }
982
- if (a.type === "Tuple" && b.type === "Tuple") {
983
- return eqArray(a.fields, b.fields, eqTy);
984
- }
985
- if (a.type === "Union" && b.type === "Union") {
986
- return eqArray(a.members, b.members, (a, b) => a.index === b.index && a.name === b.name && normalizeDocs(a.docs) === normalizeDocs(b.docs) && eqArray(a.fields, b.fields, eqField));
987
- }
988
- return false;
989
- }
990
- function eqField(a, b) {
991
- return a.name === b.name && a.typeName === b.typeName && eqDocs(a.docs, b.docs) && eqTy(a.ty, b.ty);
992
- }
993
- function eqDocs(a, b) {
994
- return normalizeDocs(a) === normalizeDocs(b);
995
- }
996
- function eqArray(a, b, eqVal) {
997
- return a.length === b.length && a.every((x, i) => eqVal(x, b[i]));
998
- }
999
- }
1000
- const optionInnerVisitor = new $__namespace.ShapeVisitor().add($__namespace.option, (_codec, $some) => $some).fallback(() => null);
1001
- function maybeOptionalField(key, $value) {
1002
- const $inner = optionInnerVisitor.visit($value);
1003
- return $inner ? $__namespace.optionalField(key, $inner) : $__namespace.field(key, $value);
1004
- }
1005
-
1006
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
1007
- function $storageKey(palletName, entryName, $key) {
1008
- const palletHash = twox128.hash(new TextEncoder().encode(palletName));
1009
- const entryHash = twox128.hash(new TextEncoder().encode(entryName));
1010
- return $__namespace.createShape({
1011
- metadata: $__namespace.metadata("$storageKey", $storageKey, palletName, entryName, $key),
1012
- staticSize: $key.staticSize + 32,
1013
- subEncode(buffer, key) {
1014
- buffer.insertArray(palletHash);
1015
- buffer.insertArray(entryHash);
1016
- $key.subEncode(buffer, key);
1017
- },
1018
- subDecode(buffer) {
1019
- // Ignore initial hashes
1020
- buffer.index += 32;
1021
- return $key.subDecode(buffer);
1022
- },
1023
- subAssert(assert) {
1024
- $key.subAssert(assert);
1025
- }
1026
- });
1027
- }
1028
- const $emptyKey = $__namespace.withMetadata($__namespace.metadata("$emptyKey"), $__namespace.constant(undefined));
1029
- const $partialEmptyKey = $__namespace.createShape({
1030
- metadata: $__namespace.metadata("$partialEmptyKey"),
1031
- staticSize: 0,
1032
- subEncode() {},
1033
- subDecode() {
1034
- throw new Error("Cannot decode partial key");
1035
- },
1036
- subAssert(assert) {
1037
- if (assert.value != null) {
1038
- throw new $__namespace.ShapeAssertError(this, assert.value, `${assert.path} != null`);
1039
- }
1040
- }
1041
- });
1042
- function $partialSingleKey($inner) {
1043
- return $__namespace.createShape({
1044
- metadata: $__namespace.metadata("$partialSingleKey", $partialSingleKey, $inner),
1045
- staticSize: $inner.staticSize,
1046
- subEncode(buffer, key) {
1047
- if (key !== null) $inner.subEncode(buffer, key);
1048
- },
1049
- subDecode() {
1050
- throw new Error("Cannot decode partial key");
1051
- },
1052
- subAssert(assert) {
1053
- if (assert.value === null) return;
1054
- $inner.subAssert(assert);
1055
- }
1056
- });
1057
- }
1058
-
1059
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1060
-
1061
- function $partialMultiKey(...codecs) {
1062
- return $__namespace.createShape({
1063
- metadata: $__namespace.metadata("$partialMultiKey", $partialMultiKey, ...codecs),
1064
- staticSize: $__namespace.tuple(...codecs).staticSize,
1065
- subEncode(buffer, key) {
1066
- if (!key) return;
1067
- for (let i = 0; i < key.length; i++) {
1068
- codecs[i].subEncode(buffer, key[i]);
1069
- }
1070
- },
1071
- subDecode() {
1072
- throw new Error("Cannot decode partial key");
1073
- },
1074
- subAssert(assert) {
1075
- if (assert.value === null) return;
1076
- assert.instanceof(this, Array);
1077
- const assertLength = assert.key(this, "length");
1078
- assertLength.typeof(this, "number");
1079
- const length = assertLength.value;
1080
- $__namespace.tuple(...codecs.slice(0, length)).subAssert(assert);
1081
- }
1082
- });
1083
- }
1084
-
1085
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
1086
- const hashers = {
1087
- blake2_128,
1088
- blake2_256,
1089
- blake2_128Concat,
1090
- twox128,
1091
- twox256,
1092
- twox64Concat,
1093
- identity
1094
- };
1095
- const $hasher = $__namespace.literalUnion(["blake2_128", "blake2_256", "blake2_128Concat", "twox128", "twox256", "twox64Concat", "identity"]);
1096
- const $storageEntry = $__namespace.object($__namespace.field("name", $__namespace.str), $__namespace.field("modifier", $__namespace.literalUnion(["Optional", "Default"])), $__namespace.taggedUnion("type", [$__namespace.variant("Plain", $__namespace.field("value", $tyId)), $__namespace.variant("Map", $__namespace.field("hashers", $__namespace.array($hasher)), $__namespace.field("key", $tyId), $__namespace.field("value", $tyId))]), $__namespace.field("default", $__namespace.uint8Array), $__namespace.field("docs", $__namespace.array($__namespace.str)));
1097
- const $constant = $__namespace.object($__namespace.field("name", $__namespace.str), $__namespace.field("ty", $tyId), $__namespace.field("value", $__namespace.uint8Array), $__namespace.field("docs", $__namespace.array($__namespace.str)));
1098
- const $pallet = $__namespace.object($__namespace.field("name", $__namespace.str), $__namespace.optionalField("storage", $__namespace.object($__namespace.field("prefix", $__namespace.str), $__namespace.field("entries", $__namespace.array($storageEntry)))), $__namespace.optionalField("calls", $tyId), $__namespace.optionalField("event", $tyId), $__namespace.field("constants", $__namespace.array($constant)), $__namespace.optionalField("error", $tyId), $__namespace.field("id", $__namespace.u8));
1099
- const $extrinsicDef = $__namespace.object($__namespace.field("ty", $tyId), $__namespace.field("version", $__namespace.u8), $__namespace.field("signedExtensions", $__namespace.array($__namespace.object($__namespace.field("ident", $__namespace.str), $__namespace.field("ty", $tyId), $__namespace.field("additionalSigned", $tyId)))));
1100
-
1101
- // https://docs.substrate.io/build/application-development/#metadata-system
13
+ /** Constant: https://docs.substrate.io/build/application-development/#metadata-format */
1102
14
  const magicNumber = 1635018093;
1103
- const $metadata = $__namespace.object($__namespace.field("magicNumber", $__namespace.constant(magicNumber, $__namespace.u32)), $__namespace.field("version", $__namespace.constant(14, $__namespace.u8)), $__namespace.field("tys", $__namespace.array($ty)), $__namespace.field("pallets", $__namespace.array($pallet)), $__namespace.field("extrinsic", $extrinsicDef),
1104
- // TODO: is this useful?
1105
- $__namespace.field("runtime", $tyId));
1106
- function transformMetadata(metadata) {
1107
- const {
1108
- ids,
1109
- types,
1110
- paths
1111
- } = transformTys(metadata.tys);
1112
- return {
1113
- types,
1114
- paths,
1115
- pallets: Object.fromEntries(metadata.pallets.map(pallet => [pallet.name, {
1116
- id: pallet.id,
1117
- name: pallet.name,
1118
- storagePrefix: pallet.storage?.prefix ?? pallet.name,
1119
- storage: Object.fromEntries(pallet.storage?.entries.map(storage => {
1120
- let key, partialKey;
1121
- if (storage.type === "Plain") {
1122
- key = $emptyKey;
1123
- partialKey = $partialEmptyKey;
1124
- } else if (storage.hashers.length === 1) {
1125
- key = hashers[storage.hashers[0]].$hash(ids[storage.key]);
1126
- partialKey = $partialSingleKey(key);
1127
- } else {
1128
- const codecs = extractTupleMembersVisitor.visit(ids[storage.key]).map((codec, i) => hashers[storage.hashers[i]].$hash(codec));
1129
- key = $__namespace.tuple(...codecs);
1130
- partialKey = $partialMultiKey(...codecs);
1131
- }
1132
- return [storage.name, {
1133
- singular: storage.type === "Plain",
1134
- name: storage.name,
1135
- key: $storageKey(pallet.name, storage.name, key),
1136
- partialKey: $storageKey(pallet.name, storage.name, partialKey),
1137
- value: ids[storage.value],
1138
- docs: normalizeDocs(storage.docs),
1139
- default: storage.modifier === "Default" ? storage.default : undefined
1140
- }];
1141
- }) ?? []),
1142
- constants: Object.fromEntries(pallet.constants.map(constant => [constant.name, {
1143
- name: constant.name,
1144
- codec: ids[constant.ty],
1145
- value: constant.value,
1146
- docs: normalizeDocs(constant.docs)
1147
- }])),
1148
- types: {
1149
- call: ids[pallet.calls],
1150
- error: ids[pallet.error],
1151
- event: ids[pallet.event]
1152
- },
1153
- docs: ""
1154
- }])),
1155
- extrinsic: {
1156
- call: getExtrinsicParameter("call"),
1157
- signature: getExtrinsicParameter("signature"),
1158
- address: getExtrinsicParameter("address"),
1159
- extra: getExtensionsCodec("ty"),
1160
- additional: getExtensionsCodec("additionalSigned")
1161
- }
1162
- };
1163
- function getExtrinsicParameter(key) {
1164
- const extrinsicTy = metadata.tys[metadata.extrinsic.ty];
1165
- if (!extrinsicTy) return $__namespace.never;
1166
- return ids[extrinsicTy.params.find(x => x.name.toLowerCase() === key).ty];
1167
- }
1168
- function getExtensionsCodec(key) {
1169
- return $__namespace.object(...metadata.extrinsic.signedExtensions.flatMap(ext => {
1170
- const codec = ids[ext[key]];
1171
- if (codec === $null) return [];
1172
- return [$__namespace.field(normalizeIdent(ext.ident), codec)];
1173
- }) // eslint-disable-line @typescript-eslint/no-explicit-any
1174
- );
1175
- }
1176
- }
1177
-
1178
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1179
- const extractTupleMembersVisitor = new $__namespace.ShapeVisitor().add(
1180
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1181
- $__namespace.tuple, (_codec, ...members) => members);
1182
-
1183
- /**
1184
- * Adapted from https://github.com/paritytech/capi-old copyright Parity Technologies (APACHE License 2.0)
1185
- * Changes August 19th 2023 :
1186
- * - updated to use subshape for scale decoding
1187
- * - adapted from deno to typescript
1188
- *
1189
- Copyright 2023 Parity Technologies
1190
-
1191
- Licensed under the Apache License, Version 2.0 (the "License");
1192
- you may not use this file except in compliance with the License.
1193
- You may obtain a copy of the License at
1194
-
1195
- http://www.apache.org/licenses/LICENSE-2.0
1196
-
1197
- Unless required by applicable law or agreed to in writing, software
1198
- distributed under the License is distributed on an "AS IS" BASIS,
1199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1200
- See the License for the specific language governing permissions and
1201
- limitations under the License.
1202
- */
1203
- function decodeMetadata(encoded) {
1204
- return transformMetadata($metadata.decode(encoded));
1205
- }
1206
- const $metadataV14 = $metadata;
1207
-
1208
- /* eslint-disable @typescript-eslint/no-non-null-assertion */
1209
- function $extrinsic(metadata) {
1210
- const $sig = metadata.extrinsic.signature;
1211
- const $sigPromise = $__namespace.promise($sig);
1212
- const $call = metadata.extrinsic.call;
1213
- const $address = metadata.extrinsic.address;
1214
- const $extra = metadata.extrinsic.extra;
1215
- const $additional = metadata.extrinsic.additional;
1216
- const toSignSize = $call.staticSize + $extra.staticSize + $additional.staticSize;
1217
- const totalSize = 1 + $address.staticSize + $sig.staticSize + toSignSize;
1218
- const $baseExtrinsic = $__namespace.createShape({
1219
- metadata: [],
1220
- staticSize: totalSize,
1221
- subEncode(buffer, extrinsic) {
1222
- const firstByte = +!!extrinsic.signature << 7 | extrinsic.protocolVersion;
1223
- buffer.array[buffer.index++] = firstByte;
1224
- const {
1225
- signature,
1226
- call
1227
- } = extrinsic;
1228
- if (signature) {
1229
- $address.subEncode(buffer, signature.sender.address);
1230
- if (signature.additional) {
1231
- const toSignBuffer = new $__namespace.EncodeBuffer(buffer.stealAlloc(toSignSize));
1232
- $call.subEncode(toSignBuffer, call);
1233
- const callEnd = toSignBuffer.finishedSize + toSignBuffer.index;
1234
- $extra.subEncode(toSignBuffer, signature.extra);
1235
- const extraEnd = toSignBuffer.finishedSize + toSignBuffer.index;
1236
- $additional.subEncode(toSignBuffer, signature.additional);
1237
- const toSignEncoded = toSignBuffer.finish();
1238
- const callEncoded = toSignEncoded.subarray(0, callEnd);
1239
- const extraEncoded = toSignEncoded.subarray(callEnd, extraEnd);
1240
- const toSign = toSignEncoded.length > 256 ? blake2_256.hash(toSignEncoded) : toSignEncoded;
1241
- const sig = signature.sender.sign(toSign, toSignEncoded);
1242
- if (sig instanceof Promise) {
1243
- $sigPromise.subEncode(buffer, sig);
1244
- } else {
1245
- $sig.subEncode(buffer, sig);
1246
- }
1247
- buffer.insertArray(extraEncoded);
1248
- buffer.insertArray(callEncoded);
1249
- } else {
1250
- $sig.subEncode(buffer, signature.sig);
1251
- $extra.subEncode(buffer, signature.extra);
1252
- $call.subEncode(buffer, call);
1253
- }
1254
- } else {
1255
- $call.subEncode(buffer, call);
1256
- }
1257
- },
1258
- subDecode(buffer) {
1259
- const firstByte = buffer.array[buffer.index++];
1260
- const hasSignature = firstByte & 1 << 7;
1261
- const protocolVersion = firstByte & ~(1 << 7);
1262
- let signature;
1263
- if (hasSignature) {
1264
- const address = $address.subDecode(buffer);
1265
- const sig = $sig.subDecode(buffer);
1266
- const extra = $extra.subDecode(buffer);
1267
- signature = {
1268
- sender: {
1269
- address
1270
- },
1271
- sig,
1272
- extra
1273
- };
1274
- }
1275
- const call = $call.subDecode(buffer);
1276
- return {
1277
- protocolVersion,
1278
- signature,
1279
- call
1280
- };
1281
- },
1282
- subAssert(assert) {
1283
- assert.typeof(this, "object");
1284
- assert.key(this, "protocolVersion").equals($__namespace.u8, 4);
1285
- const value_ = assert.value;
1286
- $call.subAssert(assert.key(this, "call"));
1287
- if (value_.signature) {
1288
- const signatureAssertState = assert.key(this, "signature");
1289
- $address.subAssert(signatureAssertState.key(this, "sender").key(this, "address"));
1290
- $extra.subAssert(signatureAssertState.key(this, "extra"));
1291
- if ("additional" in value_.signature) {
1292
- $additional.subAssert(signatureAssertState.key(this, "additional"));
1293
- signatureAssertState.key(this, "sender").key(this, "sign").typeof(this, "function");
1294
- } else {
1295
- $sig.subAssert(signatureAssertState.key(this, "sig"));
1296
- }
1297
- }
1298
- }
1299
- });
1300
- return $__namespace.withMetadata($__namespace.metadata("$extrinsic", $extrinsic, metadata), $__namespace.lenPrefixed($baseExtrinsic));
1301
- }
1302
- class SignerError extends Error {
1303
- name = "SignerError";
1304
- constructor(inner) {
1305
- super();
1306
- this.inner = inner;
1307
- }
1308
- }
1309
15
 
1310
16
  var packageJson = {
1311
17
  name: "@talismn/scale",
1312
- version: "0.0.0-pr997-20231116062730",
18
+ version: "0.1.0",
1313
19
  author: "Talisman",
1314
20
  homepage: "https://talisman.xyz",
1315
21
  license: "GPL-3.0-or-later",
@@ -1332,27 +38,23 @@ var packageJson = {
1332
38
  scripts: {
1333
39
  test: "jest",
1334
40
  lint: "eslint src --max-warnings 0",
1335
- clean: "rm -rf dist && rm -rf .turbo rm -rf node_modules"
41
+ clean: "rm -rf dist .turbo node_modules"
1336
42
  },
1337
43
  dependencies: {
1338
- "@talismn/subshape-fork": "^0.0.1",
1339
- "@talismn/util": "workspace:*",
44
+ "@polkadot-api/metadata-builders": "0.9.1",
45
+ "@polkadot-api/substrate-bindings": "0.9.3",
46
+ "@polkadot-api/utils": "0.1.2",
1340
47
  anylogger: "^1.0.11",
1341
- "wasm-feature-detect": "^1.6.0",
1342
- "wat-the-crypto": "^0.0.3"
48
+ "scale-ts": "^1.6.1"
1343
49
  },
1344
50
  devDependencies: {
1345
- "@polkadot/util-crypto": "^11.1.1",
1346
51
  "@talismn/eslint-config": "workspace:*",
1347
52
  "@talismn/tsconfig": "workspace:*",
1348
- "@types/jest": "^27.5.1",
1349
- eslint: "^8.52.0",
53
+ "@types/jest": "^29.5.14",
54
+ eslint: "^8.57.1",
1350
55
  jest: "^29.7",
1351
- "ts-jest": "^29.1.1",
1352
- typescript: "^5.2.2"
1353
- },
1354
- peerDependencies: {
1355
- "@polkadot/util-crypto": "^11.x"
56
+ "ts-jest": "^29.2.5",
57
+ typescript: "^5.6.3"
1356
58
  },
1357
59
  eslintConfig: {
1358
60
  root: true,
@@ -1362,39 +64,51 @@ var packageJson = {
1362
64
  }
1363
65
  };
1364
66
 
1365
- var log = anylogger__default["default"](packageJson.name);
67
+ var log = anylogger__default.default(packageJson.name);
1366
68
 
1367
- const filterMetadataPalletsAndItems = (metadata, palletsAndItems, extraKeepTypes) => {
69
+ /**
70
+ * Converts a `Metadata` into a `MiniMetadata`.
71
+ *
72
+ * A `MiniMetadata` only contains the types inside of its `lookup` which are relevant for
73
+ * the storage queries specified in `palletsAndItems`.
74
+ *
75
+ * E.g. if `palletsAndItems` is `{ pallet: "System", items: ["Account"] }`, then only the
76
+ * types used in the `System.Account` storage query will remain inside of metadata.lookups.
77
+ */
78
+ const compactMetadata = (metadata, palletsAndItems, extraKeepTypes) => {
1368
79
  // remove pallets we don't care about
1369
80
  metadata.pallets = metadata.pallets.filter(pallet =>
1370
81
  // keep this pallet if it's listed in `palletsAndItems`
1371
82
  palletsAndItems.some(({
1372
- pallet: palletFilter
1373
- }) => palletFilter(pallet)));
83
+ pallet: palletName
84
+ }) => pallet.name === palletName));
1374
85
 
1375
86
  // remove fields we don't care about from each pallet, and extract types for each storage item we care about
1376
87
  const items = palletsAndItems.flatMap(({
1377
- pallet: palletFilter,
1378
- items
88
+ pallet: palletName,
89
+ items: itemNames
1379
90
  }) => {
1380
- const pallet = metadata.pallets.find(palletFilter);
1381
- if (!pallet || !pallet.storage) {
1382
- log.warn("Failed to find pallet", palletFilter);
91
+ const pallet = metadata.pallets.find(pallet => pallet.name === palletName);
92
+ if (!pallet) {
93
+ log.debug("Failed to find pallet", palletName);
1383
94
  return [];
1384
95
  }
1385
96
 
1386
- // remove fields we don't care about
97
+ // remove pallet fields we don't care about
1387
98
  pallet.calls = undefined;
1388
99
  pallet.constants = [];
1389
- pallet.error = undefined;
1390
- pallet.event = undefined;
100
+ // v15 (NOT v14) has docs
101
+ if ("docs" in pallet) pallet.docs = [];
102
+ pallet.errors = undefined;
103
+ pallet.events = undefined;
104
+ if (!pallet.storage) return [];
1391
105
 
1392
106
  // filter and extract storage items we care about
1393
- pallet.storage.entries = pallet.storage.entries.filter(item => items.some(itemFilter => itemFilter(item)));
1394
- return pallet.storage.entries;
107
+ pallet.storage.items = pallet.storage.items.filter(item => itemNames.some(itemName => item.name === itemName));
108
+ return pallet.storage.items;
1395
109
  });
1396
110
 
1397
- // this is a set of type ids which we plan to keep in our mutated metadata
111
+ // this is a set of type ids which we plan to keep in our compacted metadata
1398
112
  // anything not in this set will be deleted
1399
113
  // we start off with just the types of the state calls we plan to make,
1400
114
  // then we run those types through a function (addDependentTypes) which will also include
@@ -1403,15 +117,45 @@ const filterMetadataPalletsAndItems = (metadata, palletsAndItems, extraKeepTypes
1403
117
  // each type can be either "Plain" or "Map"
1404
118
  // if it's "Plain" we only need to get the value type
1405
119
  // if it's a "Map" we want to keep both the key AND the value types
1406
- item.type === "Map" && item.key, item.value]).filter(type => typeof type === "number"));
120
+ item.type.tag === "plain" && item.type.value, item.type.tag === "map" && item.type.value.key, item.type.tag === "map" && item.type.value.value]).filter(type => typeof type === "number"));
1407
121
  extraKeepTypes?.forEach(type => keepTypes.add(type));
1408
122
 
1409
123
  // recursively find all the types which our keepTypes depend on and add them to the keepTypes set
1410
- const metadataTysMap = new Map(metadata.tys.map(ty => [ty.id, ty]));
124
+ const metadataTysMap = new Map(metadata.lookup.map(ty => [ty.id, ty]));
1411
125
  addDependentTypes(metadataTysMap, keepTypes, [...keepTypes]);
1412
126
 
1413
127
  // ditch the types we aren't keeping
1414
- metadata.tys = metadata.tys.filter(type => keepTypes.has(type.id));
128
+ metadata.lookup = metadata.lookup.filter(type => keepTypes.has(type.id));
129
+
130
+ // update all type ids to be sequential (fill the gaps left by the deleted types)
131
+ const newTypeIds = new Map();
132
+ metadata.lookup.forEach((type, index) => newTypeIds.set(type.id, index));
133
+ const getNewTypeId = oldTypeId => {
134
+ const newTypeId = newTypeIds.get(oldTypeId);
135
+ if (typeof newTypeId !== "number") log.error(`Failed to find newTypeId for type ${oldTypeId}`);
136
+ return newTypeId ?? 0;
137
+ };
138
+ remapTypeIds(metadata, getNewTypeId);
139
+
140
+ // ditch the remaining data we don't need to keep in a miniMetata
141
+ if ("apis" in metadata) {
142
+ // metadata is v15 (NOT v14)
143
+ metadata.apis = [];
144
+ }
145
+ if ("address" in metadata.extrinsic) {
146
+ // metadata is v15 (NOT v14)
147
+ metadata.extrinsic.address = 0;
148
+ metadata.extrinsic.call = 0;
149
+ metadata.extrinsic.extra = 0;
150
+ metadata.extrinsic.signature = 0;
151
+ }
152
+ metadata.extrinsic.signedExtensions = [];
153
+ if ("outerEnums" in metadata) {
154
+ // metadata is v15 (NOT v14)
155
+ metadata.outerEnums.call = 0;
156
+ metadata.outerEnums.error = 0;
157
+ metadata.outerEnums.event = 0;
158
+ }
1415
159
  };
1416
160
  const addDependentTypes = (metadataTysMap, keepTypes, types,
1417
161
  // Prevent stack overflow when a type references itself
@@ -1426,83 +170,262 @@ addedTypes = new Set()) => {
1426
170
  if (addedTypes.has(type.id)) continue;
1427
171
  keepTypes.add(type.id);
1428
172
  addedTypes.add(type.id);
1429
- switch (type.type) {
1430
- case "Struct":
1431
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), ...type.fields.map(field => field.ty).filter(ty => typeof ty === "number")]);
173
+ const paramTypes = type.params.map(param => param.type).filter(type => typeof type === "number");
174
+ addDependentSubTypes(paramTypes);
175
+ switch (type.def.tag) {
176
+ case "array":
177
+ addDependentSubTypes([type.def.value.type]);
178
+ break;
179
+ case "bitSequence":
180
+ addDependentSubTypes([type.def.value.bitOrderType, type.def.value.bitStoreType]);
181
+ break;
182
+ case "compact":
183
+ addDependentSubTypes([type.def.value]);
184
+ break;
185
+ case "composite":
186
+ addDependentSubTypes(type.def.value.map(field => field.type).filter(type => typeof type === "number"));
187
+ break;
188
+ case "primitive":
189
+ break;
190
+ case "sequence":
191
+ addDependentSubTypes([type.def.value]);
192
+ break;
193
+ case "tuple":
194
+ addDependentSubTypes(type.def.value.filter(type => typeof type === "number"));
195
+ break;
196
+ case "variant":
197
+ addDependentSubTypes(type.def.value.flatMap(member => member.fields.map(field => field.type)).filter(type => typeof type === "number"));
198
+ break;
199
+ default:
200
+ {
201
+ // force compilation error if any types don't have a case
202
+ const exhaustiveCheck = type.def;
203
+ log.error(`Unhandled V15Type type ${exhaustiveCheck}`);
204
+ }
205
+ }
206
+ }
207
+ };
208
+ const remapTypeIds = (metadata, getNewTypeId) => {
209
+ remapLookupTypeIds(metadata, getNewTypeId);
210
+ remapStorageTypeIds(metadata, getNewTypeId);
211
+ };
212
+ const remapLookupTypeIds = (metadata, getNewTypeId) => {
213
+ for (const type of metadata.lookup) {
214
+ type.id = getNewTypeId(type.id);
215
+ for (const param of type.params) {
216
+ if (typeof param.type !== "number") continue;
217
+ param.type = getNewTypeId(param.type);
218
+ }
219
+ switch (type.def.tag) {
220
+ case "array":
221
+ type.def.value.type = getNewTypeId(type.def.value.type);
1432
222
  break;
1433
- case "Union":
1434
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), ...type.members.flatMap(member => member.fields.map(field => field.ty)).filter(ty => typeof ty === "number")]);
223
+ case "bitSequence":
224
+ type.def.value.bitOrderType = getNewTypeId(type.def.value.bitOrderType);
225
+ type.def.value.bitStoreType = getNewTypeId(type.def.value.bitStoreType);
1435
226
  break;
1436
- case "Sequence":
1437
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), type.typeParam]);
227
+ case "compact":
228
+ type.def.value = getNewTypeId(type.def.value);
1438
229
  break;
1439
- case "SizedArray":
1440
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), type.typeParam]);
230
+ case "composite":
231
+ for (const field of type.def.value) {
232
+ if (typeof field.type !== "number") continue;
233
+ field.type = getNewTypeId(field.type);
234
+ }
1441
235
  break;
1442
- case "Tuple":
1443
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), ...type.fields.filter(ty => typeof ty === "number")]);
236
+ case "primitive":
1444
237
  break;
1445
- case "Primitive":
1446
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number")]);
238
+ case "sequence":
239
+ type.def.value = getNewTypeId(type.def.value);
1447
240
  break;
1448
- case "Compact":
1449
- addDependentSubTypes([...type.params.map(param => param.ty).filter(ty => typeof ty === "number"), type.typeParam]);
241
+ case "tuple":
242
+ type.def.value = type.def.value.map(type => {
243
+ if (typeof type !== "number") return type;
244
+ return getNewTypeId(type);
245
+ });
1450
246
  break;
1451
- case "BitSequence":
1452
- addDependentSubTypes([type.bitOrderType, type.bitStoreType]);
247
+ case "variant":
248
+ for (const member of type.def.value) {
249
+ for (const field of member.fields) {
250
+ if (typeof field.type !== "number") continue;
251
+ field.type = getNewTypeId(field.type);
252
+ }
253
+ }
1453
254
  break;
1454
255
  default:
1455
256
  {
1456
257
  // force compilation error if any types don't have a case
1457
- const exhaustiveCheck = type;
1458
- log.error(`Unhandled TyMV14 type ${exhaustiveCheck}`);
258
+ const exhaustiveCheck = type.def;
259
+ log.error(`Unhandled V15Type type ${exhaustiveCheck}`);
1459
260
  }
1460
261
  }
1461
262
  }
1462
263
  };
264
+ const remapStorageTypeIds = (metadata, getNewTypeId) => {
265
+ for (const pallet of metadata.pallets) {
266
+ for (const item of pallet.storage?.items ?? []) {
267
+ if (item.type.tag === "plain") item.type.value = getNewTypeId(item.type.value);
268
+ if (item.type.tag === "map") {
269
+ item.type.value.key = getNewTypeId(item.type.value.key);
270
+ item.type.value.value = getNewTypeId(item.type.value.value);
271
+ }
272
+ }
273
+ }
274
+ };
1463
275
 
1464
- exports.$emptyKey = $emptyKey;
1465
- exports.$era = $era;
1466
- exports.$extrinsic = $extrinsic;
1467
- exports.$field = $field;
1468
- exports.$hash = $hash;
1469
- exports.$metadataV14 = $metadataV14;
1470
- exports.$null = $null;
1471
- exports.$partialEmptyKey = $partialEmptyKey;
1472
- exports.$partialMultiKey = $partialMultiKey;
1473
- exports.$partialSingleKey = $partialSingleKey;
1474
- exports.$primitiveKind = $primitiveKind;
1475
- exports.$storageKey = $storageKey;
1476
- exports.$ty = $ty;
1477
- exports.$tyDef = $tyDef;
1478
- exports.$tyId = $tyId;
1479
- exports.Blake2Hasher = Blake2Hasher;
1480
- exports.DecodeNonTransparentKeyError = DecodeNonTransparentKeyError;
1481
- exports.Hasher = Hasher;
1482
- exports.IdentityHasher = IdentityHasher;
1483
- exports.SignerError = SignerError;
1484
- exports.TwoxHasher = TwoxHasher;
1485
- exports.addDependentTypes = addDependentTypes;
1486
- exports.blake2_128 = blake2_128;
1487
- exports.blake2_128Concat = blake2_128Concat;
1488
- exports.blake2_256 = blake2_256;
1489
- exports.blake2_512 = blake2_512;
1490
- exports.blake2_64 = blake2_64;
276
+ /**
277
+ * Extracts the `version` u8 from a SCALE-encoded metadata blob and returns it as a `number`.
278
+ *
279
+ * Only reads the first 40 bytes of the blob.
280
+ */
281
+ const getMetadataVersion = metadataRpc => {
282
+ try {
283
+ return scaleTs.Struct({
284
+ magicNumber: scaleTs.u32,
285
+ version: scaleTs.u8
286
+ }).dec(metadataRpc).version;
287
+ } catch {
288
+ return 0;
289
+ }
290
+ };
291
+
292
+ const decodeMetadata = metadataRpc => {
293
+ const metadataVersion = getMetadataVersion(metadataRpc);
294
+ if (metadataVersion !== 15 && metadataVersion !== 14) return {
295
+ metadataVersion
296
+ };
297
+ const decoded = substrateBindings.metadata.dec(metadataRpc);
298
+ if (decoded.metadata.tag === "v15") return {
299
+ metadataVersion,
300
+ metadata: decoded.metadata.value,
301
+ tag: decoded.metadata.tag
302
+ };
303
+ if (decoded.metadata.tag === "v14") return {
304
+ metadataVersion,
305
+ metadata: decoded.metadata.value,
306
+ tag: decoded.metadata.tag
307
+ };
308
+ return {
309
+ metadataVersion
310
+ };
311
+ };
312
+
313
+ const decodeScale = (scaleCoder, change, error) => {
314
+ if (change === null) return null;
315
+ try {
316
+ return scaleCoder?.dec(change) ?? null;
317
+ } catch (cause) {
318
+ log.warn(error ?? `Failed to decode ${change}`, cause);
319
+ return null;
320
+ }
321
+ };
322
+
323
+ const encodeMetadata = ({
324
+ metadata,
325
+ tag
326
+ }) => utils.toHex(substrateBindings.metadata.enc({
327
+ magicNumber,
328
+ metadata: tag === "v15" ? {
329
+ tag,
330
+ value: metadata
331
+ } : {
332
+ tag,
333
+ value: metadata
334
+ }
335
+ }));
336
+
337
+ const encodeStateKey = (scaleCoder, error, ...args) => {
338
+ try {
339
+ return scaleCoder?.enc(...args);
340
+ } catch (cause) {
341
+ log.warn(error ?? `Failed to encode stateKey ${JSON.stringify(args)}`, cause);
342
+ return;
343
+ }
344
+ };
345
+
346
+ /**
347
+ * For the substrate-tokens (and other) modules, we configure the `onChainId` field in chaindata to tell the module how to query each token.
348
+ * These queries are made to the tokens pallet.
349
+ * E.g. api.query.Tokens.Account(accountAddress, papiParse(onChainId))
350
+ *
351
+ * The `onChainId` field on chaindata must be a JSON-parseable string, but for some SCALE types (especially the Binary type) we must
352
+ * use specific `polkadot-api` classes to handle SCALE-encoding the statekey.
353
+ *
354
+ * Some examples:
355
+ * Input: `5`
356
+ * Output: `5`
357
+ *
358
+ * Input: `{ type: "DexShare", value: [ { type: "Token", value: { type: "ACA" } }, { type: "Token", value: { type: "AUSD" } } ] }`
359
+ * Output: `Enum("DexShare", [Enum("Token", Enum("ACA")), Enum("Token", Enum("AUSD"))])`
360
+ *
361
+ * Input: `{ type: "LiquidCrowdloan", value: 13 }`
362
+ * Output: `Enum("LiquidCrowdloan", 13)`
363
+ *
364
+ * Input: `{ type: "NativeToken", value: "bigint:2" }`
365
+ * Output: `Enum("NativeToken", 2n)`
366
+ *
367
+ * Input: `{ type: "Erc20", value: "hex:0x07df96d1341a7d16ba1ad431e2c847d978bc2bce" }`
368
+ * Output: `Enum("Erc20", Binary.fromHex("0x07df96d1341a7d16ba1ad431e2c847d978bc2bce"))`
369
+ *
370
+ * Input: `{ type: "Stellar", value: { code: "bin:TZS", issuer: "hex:0x34c94b2a4ba9e8b57b22547dcbb30f443c4cb02da3829a89aa1bd4780e4466ba" } }`
371
+ * Output: `Enum("Stellar", { code: Binary.fromText("TZS"), issuer: Binary.fromHex("0x34c94b2a4ba9e8b57b22547dcbb30f443c4cb02da3829a89aa1bd4780e4466ba") })`
372
+ */
373
+ const papiParse = text => {
374
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
375
+ const reviver = (_key, value) => {
376
+ if (typeof value !== "string") return value;
377
+ if (value.startsWith("bigint:")) return BigInt(value.slice("bigint:".length));
378
+ if (value.startsWith("hex:")) return substrateBindings.Binary.fromHex(value.slice("hex:".length));
379
+ if (value.startsWith("bin:")) return substrateBindings.Binary.fromText(value.slice("bin:".length));
380
+ return value;
381
+ };
382
+ if (typeof text !== "string") return text;
383
+ return JSON.parse(text, reviver);
384
+ };
385
+ const papiStringify = (value, space) => {
386
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
387
+ const replacer = (_key, value) => {
388
+ if (typeof value === "bigint") return `bigint:${String(value)}`;
389
+ if (value instanceof substrateBindings.Binary) return `hex:${value.asHex()}`;
390
+ return value;
391
+ };
392
+ return JSON.stringify(value, replacer, space);
393
+ };
394
+
395
+ Object.defineProperty(exports, "getDynamicBuilder", {
396
+ enumerable: true,
397
+ get: function () { return metadataBuilders.getDynamicBuilder; }
398
+ });
399
+ Object.defineProperty(exports, "getLookupFn", {
400
+ enumerable: true,
401
+ get: function () { return metadataBuilders.getLookupFn; }
402
+ });
403
+ Object.defineProperty(exports, "fromHex", {
404
+ enumerable: true,
405
+ get: function () { return utils.fromHex; }
406
+ });
407
+ Object.defineProperty(exports, "toHex", {
408
+ enumerable: true,
409
+ get: function () { return utils.toHex; }
410
+ });
411
+ Object.defineProperty(exports, "metadata", {
412
+ enumerable: true,
413
+ get: function () { return substrateBindings.metadata; }
414
+ });
415
+ Object.defineProperty(exports, "v14", {
416
+ enumerable: true,
417
+ get: function () { return substrateBindings.v14; }
418
+ });
419
+ Object.defineProperty(exports, "v15", {
420
+ enumerable: true,
421
+ get: function () { return substrateBindings.v15; }
422
+ });
423
+ exports.compactMetadata = compactMetadata;
1491
424
  exports.decodeMetadata = decodeMetadata;
1492
- exports.filterMetadataPalletsAndItems = filterMetadataPalletsAndItems;
1493
- exports.getOrInit = getOrInit;
1494
- exports.identity = identity;
1495
- exports.normalizeDocs = normalizeDocs;
1496
- exports.normalizeIdent = normalizeIdent;
1497
- exports.normalizePackageName = normalizePackageName;
1498
- exports.normalizeTypeName = normalizeTypeName;
1499
- exports.normalizeVariableName = normalizeVariableName;
1500
- exports.ss58 = ss58;
1501
- exports.stringifyKey = stringifyKey;
1502
- exports.stringifyPropertyAccess = stringifyPropertyAccess;
1503
- exports.transformMetadataV14 = transformMetadata;
1504
- exports.transformTys = transformTys;
1505
- exports.twox128 = twox128;
1506
- exports.twox256 = twox256;
1507
- exports.twox64Concat = twox64Concat;
1508
- exports.watCryptoWaitReady = watCryptoWaitReady;
425
+ exports.decodeScale = decodeScale;
426
+ exports.encodeMetadata = encodeMetadata;
427
+ exports.encodeStateKey = encodeStateKey;
428
+ exports.getMetadataVersion = getMetadataVersion;
429
+ exports.magicNumber = magicNumber;
430
+ exports.papiParse = papiParse;
431
+ exports.papiStringify = papiStringify;