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