@polkadot/rpc-core 9.14.2 → 10.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.
package/cjs/bundle.js CHANGED
@@ -1,81 +1,37 @@
1
1
  "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- var _exportNames = {
7
- RpcCore: true,
8
- packageInfo: true
9
- };
10
- exports.RpcCore = void 0;
11
- Object.defineProperty(exports, "packageInfo", {
12
- enumerable: true,
13
- get: function () {
14
- return _packageInfo.packageInfo;
15
- }
16
- });
17
- var _rxjs = require("rxjs");
18
- var _types = require("@polkadot/types");
19
- var _util = require("@polkadot/util");
20
- var _util2 = require("./util");
21
- Object.keys(_util2).forEach(function (key) {
22
- if (key === "default" || key === "__esModule") return;
23
- if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
24
- if (key in exports && exports[key] === _util2[key]) return;
25
- Object.defineProperty(exports, key, {
26
- enumerable: true,
27
- get: function () {
28
- return _util2[key];
29
- }
30
- });
31
- });
32
- var _packageInfo = require("./packageInfo");
33
- // Copyright 2017-2023 @polkadot/rpc-core authors & contributors
34
- // SPDX-License-Identifier: Apache-2.0
35
-
36
- const l = (0, _util.logger)('rpc-core');
2
+ var _RpcCore_instanceId, _RpcCore_registryDefault, _RpcCore_getBlockRegistry, _RpcCore_getBlockHash, _RpcCore_storageCache;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.RpcCore = exports.packageInfo = void 0;
5
+ const tslib_1 = require("tslib");
6
+ const rxjs_1 = require("rxjs");
7
+ const types_1 = require("@polkadot/types");
8
+ const util_1 = require("@polkadot/util");
9
+ const index_js_1 = require("./util/index.js");
10
+ var packageInfo_js_1 = require("./packageInfo.js");
11
+ Object.defineProperty(exports, "packageInfo", { enumerable: true, get: function () { return packageInfo_js_1.packageInfo; } });
12
+ tslib_1.__exportStar(require("./util/index.js"), exports);
13
+ const l = (0, util_1.logger)('rpc-core');
37
14
  const EMPTY_META = {
38
- fallback: undefined,
39
- modifier: {
40
- isOptional: true
41
- },
42
- type: {
43
- asMap: {
44
- linked: {
45
- isTrue: false
46
- }
47
- },
48
- isMap: false
49
- }
15
+ fallback: undefined,
16
+ modifier: { isOptional: true },
17
+ type: {
18
+ asMap: { linked: { isTrue: false } },
19
+ isMap: false
20
+ }
50
21
  };
51
-
52
- // utility method to create a nicely-formatted error
53
22
  /** @internal */
54
- function logErrorMessage(method, _ref, error) {
55
- let {
56
- noErrorLog,
57
- params,
58
- type
59
- } = _ref;
60
- if (noErrorLog) {
61
- return;
62
- }
63
- const inputs = params.map(_ref2 => {
64
- let {
65
- isOptional,
66
- name,
67
- type
68
- } = _ref2;
69
- return `${name}${isOptional ? '?' : ''}: ${type}`;
70
- }).join(', ');
71
- l.error(`${method}(${inputs}): ${type}:: ${error.message}`);
23
+ function logErrorMessage(method, { noErrorLog, params, type }, error) {
24
+ if (noErrorLog) {
25
+ return;
26
+ }
27
+ const inputs = params.map(({ isOptional, name, type }) => `${name}${isOptional ? '?' : ''}: ${type}`).join(', ');
28
+ l.error(`${method}(${inputs}): ${type}:: ${error.message}`);
72
29
  }
73
30
  function isTreatAsHex(key) {
74
- // :code is problematic - it does not have the length attached, which is
75
- // unlike all other storage entries where it is indeed properly encoded
76
- return ['0x3a636f6465'].includes(key.toHex());
31
+ // :code is problematic - it does not have the length attached, which is
32
+ // unlike all other storage entries where it is indeed properly encoded
33
+ return ['0x3a636f6465'].includes(key.toHex());
77
34
  }
78
-
79
35
  /**
80
36
  * @name Rpc
81
37
  * @summary The API may use a HTTP or WebSockets provider.
@@ -100,363 +56,333 @@ function isTreatAsHex(key) {
100
56
  * ```
101
57
  */
102
58
  class RpcCore {
103
- #instanceId;
104
- #registryDefault;
105
- #getBlockRegistry;
106
- #getBlockHash;
107
- #storageCache = new Map();
108
- mapping = new Map();
109
- sections = [];
110
-
111
- /**
112
- * @constructor
113
- * Default constructor for the Api Object
114
- * @param {ProviderInterface} provider An API provider using HTTP or WebSocket
115
- */
116
- constructor(instanceId, registry, provider) {
117
- let userRpc = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
118
- // eslint-disable-next-line @typescript-eslint/unbound-method
119
- if (!provider || !(0, _util.isFunction)(provider.send)) {
120
- throw new Error('Expected Provider to API create');
59
+ /**
60
+ * @constructor
61
+ * Default constructor for the Api Object
62
+ * @param {ProviderInterface} provider An API provider using HTTP or WebSocket
63
+ */
64
+ constructor(instanceId, registry, provider, userRpc = {}) {
65
+ _RpcCore_instanceId.set(this, void 0);
66
+ _RpcCore_registryDefault.set(this, void 0);
67
+ _RpcCore_getBlockRegistry.set(this, void 0);
68
+ _RpcCore_getBlockHash.set(this, void 0);
69
+ _RpcCore_storageCache.set(this, new Map());
70
+ this.mapping = new Map();
71
+ this.sections = [];
72
+ // eslint-disable-next-line @typescript-eslint/unbound-method
73
+ if (!provider || !(0, util_1.isFunction)(provider.send)) {
74
+ throw new Error('Expected Provider to API create');
75
+ }
76
+ tslib_1.__classPrivateFieldSet(this, _RpcCore_instanceId, instanceId, "f");
77
+ tslib_1.__classPrivateFieldSet(this, _RpcCore_registryDefault, registry, "f");
78
+ this.provider = provider;
79
+ const sectionNames = Object.keys(types_1.rpcDefinitions);
80
+ // these are the base keys (i.e. part of jsonrpc)
81
+ this.sections.push(...sectionNames);
82
+ // decorate all interfaces, defined and user on this instance
83
+ this.addUserInterfaces(userRpc);
84
+ }
85
+ /**
86
+ * @description Returns the connected status of a provider
87
+ */
88
+ get isConnected() {
89
+ return this.provider.isConnected;
90
+ }
91
+ /**
92
+ * @description Manually connect from the attached provider
93
+ */
94
+ connect() {
95
+ return this.provider.connect();
96
+ }
97
+ /**
98
+ * @description Manually disconnect from the attached provider
99
+ */
100
+ disconnect() {
101
+ return this.provider.disconnect();
102
+ }
103
+ /**
104
+ * @description Sets a registry swap (typically from Api)
105
+ */
106
+ setRegistrySwap(registrySwap) {
107
+ tslib_1.__classPrivateFieldSet(this, _RpcCore_getBlockRegistry, (0, util_1.memoize)(registrySwap, {
108
+ getInstanceId: () => tslib_1.__classPrivateFieldGet(this, _RpcCore_instanceId, "f")
109
+ }), "f");
121
110
  }
122
- this.#instanceId = instanceId;
123
- this.#registryDefault = registry;
124
- this.provider = provider;
125
- const sectionNames = Object.keys(_types.rpcDefinitions);
126
-
127
- // these are the base keys (i.e. part of jsonrpc)
128
- this.sections.push(...sectionNames);
129
-
130
- // decorate all interfaces, defined and user on this instance
131
- this.addUserInterfaces(userRpc);
132
- }
133
-
134
- /**
135
- * @description Returns the connected status of a provider
136
- */
137
- get isConnected() {
138
- return this.provider.isConnected;
139
- }
140
-
141
- /**
142
- * @description Manually connect from the attached provider
143
- */
144
- connect() {
145
- return this.provider.connect();
146
- }
147
-
148
- /**
149
- * @description Manually disconnect from the attached provider
150
- */
151
- disconnect() {
152
- return this.provider.disconnect();
153
- }
154
-
155
- /**
156
- * @description Sets a registry swap (typically from Api)
157
- */
158
- setRegistrySwap(registrySwap) {
159
- this.#getBlockRegistry = (0, _util.memoize)(registrySwap, {
160
- getInstanceId: () => this.#instanceId
161
- });
162
- }
163
-
164
- /**
165
- * @description Sets a function to resolve block hash from block number
166
- */
167
- setResolveBlockHash(resolveBlockHash) {
168
- this.#getBlockHash = (0, _util.memoize)(resolveBlockHash, {
169
- getInstanceId: () => this.#instanceId
170
- });
171
- }
172
- addUserInterfaces(userRpc) {
173
- // add any extra user-defined sections
174
- this.sections.push(...Object.keys(userRpc).filter(k => !this.sections.includes(k)));
175
- for (let s = 0; s < this.sections.length; s++) {
176
- const section = this.sections[s];
177
- const defs = (0, _util.objectSpread)({}, _types.rpcDefinitions[section], userRpc[section]);
178
- const methods = Object.keys(defs);
179
- for (let m = 0; m < methods.length; m++) {
180
- const method = methods[m];
181
- const def = defs[method];
182
- const jsonrpc = def.endpoint || `${section}_${method}`;
183
- if (!this.mapping.has(jsonrpc)) {
184
- const isSubscription = !!def.pubsub;
185
- if (!this[section]) {
186
- this[section] = {};
187
- }
188
- this.mapping.set(jsonrpc, (0, _util.objectSpread)({}, def, {
189
- isSubscription,
190
- jsonrpc,
191
- method,
192
- section
193
- }));
194
- (0, _util.lazyMethod)(this[section], method, () => isSubscription ? this._createMethodSubscribe(section, method, def) : this._createMethodSend(section, method, def));
111
+ /**
112
+ * @description Sets a function to resolve block hash from block number
113
+ */
114
+ setResolveBlockHash(resolveBlockHash) {
115
+ tslib_1.__classPrivateFieldSet(this, _RpcCore_getBlockHash, (0, util_1.memoize)(resolveBlockHash, {
116
+ getInstanceId: () => tslib_1.__classPrivateFieldGet(this, _RpcCore_instanceId, "f")
117
+ }), "f");
118
+ }
119
+ addUserInterfaces(userRpc) {
120
+ // add any extra user-defined sections
121
+ this.sections.push(...Object.keys(userRpc).filter((k) => !this.sections.includes(k)));
122
+ for (let s = 0; s < this.sections.length; s++) {
123
+ const section = this.sections[s];
124
+ const defs = (0, util_1.objectSpread)({}, types_1.rpcDefinitions[section], userRpc[section]);
125
+ const methods = Object.keys(defs);
126
+ for (let m = 0; m < methods.length; m++) {
127
+ const method = methods[m];
128
+ const def = defs[method];
129
+ const jsonrpc = def.endpoint || `${section}_${method}`;
130
+ if (!this.mapping.has(jsonrpc)) {
131
+ const isSubscription = !!def.pubsub;
132
+ if (!this[section]) {
133
+ this[section] = {};
134
+ }
135
+ this.mapping.set(jsonrpc, (0, util_1.objectSpread)({}, def, { isSubscription, jsonrpc, method, section }));
136
+ (0, util_1.lazyMethod)(this[section], method, () => isSubscription
137
+ ? this._createMethodSubscribe(section, method, def)
138
+ : this._createMethodSend(section, method, def));
139
+ }
140
+ }
195
141
  }
196
- }
197
142
  }
198
- }
199
- _memomize(creator, def) {
200
- const memoOpts = {
201
- getInstanceId: () => this.#instanceId
202
- };
203
- const memoized = (0, _util.memoize)(creator(true), memoOpts);
204
- memoized.raw = (0, _util.memoize)(creator(false), memoOpts);
205
- memoized.meta = def;
206
- return memoized;
207
- }
208
- _formatResult(isScale, registry, blockHash, method, def, params, result) {
209
- return isScale ? this._formatOutput(registry, blockHash, method, def, params, result) : result;
210
- }
211
- _createMethodSend(section, method, def) {
212
- const rpcName = def.endpoint || `${section}_${method}`;
213
- const hashIndex = def.params.findIndex(_ref3 => {
214
- let {
215
- isHistoric
216
- } = _ref3;
217
- return isHistoric;
218
- });
219
- let memoized = null;
220
-
221
- // execute the RPC call, doing a registry swap for historic as applicable
222
- const callWithRegistry = async (isScale, values) => {
223
- var _this$getBlockHash;
224
- const blockId = hashIndex === -1 ? null : values[hashIndex];
225
- const blockHash = blockId && def.params[hashIndex].type === 'BlockNumber' ? await ((_this$getBlockHash = this.#getBlockHash) == null ? void 0 : _this$getBlockHash.call(this, blockId)) : blockId;
226
- const {
227
- registry
228
- } = isScale && blockHash && this.#getBlockRegistry ? await this.#getBlockRegistry((0, _util.u8aToU8a)(blockHash)) : {
229
- registry: this.#registryDefault
230
- };
231
- const params = this._formatInputs(registry, null, def, values);
232
-
233
- // only cache .at(<blockHash>) queries, e.g. where valid blockHash was supplied
234
- const result = await this.provider.send(rpcName, params.map(p => p.toJSON()), !!blockHash);
235
- return this._formatResult(isScale, registry, blockHash, method, def, params, result);
236
- };
237
- const creator = isScale => function () {
238
- for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) {
239
- values[_key] = arguments[_key];
240
- }
241
- const isDelayed = isScale && hashIndex !== -1 && !!values[hashIndex];
242
- return new _rxjs.Observable(observer => {
243
- callWithRegistry(isScale, values).then(value => {
244
- observer.next(value);
245
- observer.complete();
246
- }).catch(error => {
247
- logErrorMessage(method, def, error);
248
- observer.error(error);
249
- observer.complete();
250
- });
251
- return () => {
252
- // delete old results from cache
253
- if (isScale) {
254
- var _memoized;
255
- (_memoized = memoized) == null ? void 0 : _memoized.unmemoize(...values);
256
- } else {
257
- var _memoized2;
258
- (_memoized2 = memoized) == null ? void 0 : _memoized2.raw.unmemoize(...values);
259
- }
143
+ _memomize(creator, def) {
144
+ const memoOpts = { getInstanceId: () => tslib_1.__classPrivateFieldGet(this, _RpcCore_instanceId, "f") };
145
+ const memoized = (0, util_1.memoize)(creator(true), memoOpts);
146
+ memoized.raw = (0, util_1.memoize)(creator(false), memoOpts);
147
+ memoized.meta = def;
148
+ return memoized;
149
+ }
150
+ _formatResult(isScale, registry, blockHash, method, def, params, result) {
151
+ return isScale
152
+ ? this._formatOutput(registry, blockHash, method, def, params, result)
153
+ : result;
154
+ }
155
+ _createMethodSend(section, method, def) {
156
+ const rpcName = def.endpoint || `${section}_${method}`;
157
+ const hashIndex = def.params.findIndex(({ isHistoric }) => isHistoric);
158
+ let memoized = null;
159
+ // execute the RPC call, doing a registry swap for historic as applicable
160
+ const callWithRegistry = async (isScale, values) => {
161
+ const blockId = hashIndex === -1
162
+ ? null
163
+ : values[hashIndex];
164
+ const blockHash = blockId && def.params[hashIndex].type === 'BlockNumber'
165
+ ? await tslib_1.__classPrivateFieldGet(this, _RpcCore_getBlockHash, "f")?.call(this, blockId)
166
+ : blockId;
167
+ const { registry } = isScale && blockHash && tslib_1.__classPrivateFieldGet(this, _RpcCore_getBlockRegistry, "f")
168
+ ? await tslib_1.__classPrivateFieldGet(this, _RpcCore_getBlockRegistry, "f").call(this, (0, util_1.u8aToU8a)(blockHash))
169
+ : { registry: tslib_1.__classPrivateFieldGet(this, _RpcCore_registryDefault, "f") };
170
+ const params = this._formatInputs(registry, null, def, values);
171
+ // only cache .at(<blockHash>) queries, e.g. where valid blockHash was supplied
172
+ const result = await this.provider.send(rpcName, params.map((p) => p.toJSON()), !!blockHash);
173
+ return this._formatResult(isScale, registry, blockHash, method, def, params, result);
260
174
  };
261
- }).pipe(
262
- // eslint-disable-next-line deprecation/deprecation
263
- (0, _rxjs.publishReplay)(1),
264
- // create a Replay(1)
265
- isDelayed ? (0, _util2.refCountDelay)() // Unsubscribe after delay
266
- // eslint-disable-next-line deprecation/deprecation
267
- : (0, _rxjs.refCount)());
268
- };
269
- memoized = this._memomize(creator, def);
270
- return memoized;
271
- }
272
-
273
- // create a subscriptor, it subscribes once and resolves with the id as subscribe
274
- _createSubscriber(_ref4, errorHandler) {
275
- let {
276
- paramsJson,
277
- subName,
278
- subType,
279
- update
280
- } = _ref4;
281
- return new Promise((resolve, reject) => {
282
- this.provider.subscribe(subType, subName, paramsJson, update).then(resolve).catch(error => {
283
- errorHandler(error);
284
- reject(error);
285
- });
286
- });
287
- }
288
- _createMethodSubscribe(section, method, def) {
289
- var _this = this;
290
- const [updateType, subMethod, unsubMethod] = def.pubsub;
291
- const subName = `${section}_${subMethod}`;
292
- const unsubName = `${section}_${unsubMethod}`;
293
- const subType = `${section}_${updateType}`;
294
- let memoized = null;
295
- const creator = isScale => function () {
296
- for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
297
- values[_key2] = arguments[_key2];
298
- }
299
- return new _rxjs.Observable(observer => {
300
- // Have at least an empty promise, as used in the unsubscribe
301
- let subscriptionPromise = Promise.resolve(null);
302
- const registry = _this.#registryDefault;
303
- const errorHandler = error => {
304
- logErrorMessage(method, def, error);
305
- observer.error(error);
175
+ const creator = (isScale) => (...values) => {
176
+ const isDelayed = isScale && hashIndex !== -1 && !!values[hashIndex];
177
+ return new rxjs_1.Observable((observer) => {
178
+ callWithRegistry(isScale, values)
179
+ .then((value) => {
180
+ observer.next(value);
181
+ observer.complete();
182
+ })
183
+ .catch((error) => {
184
+ logErrorMessage(method, def, error);
185
+ observer.error(error);
186
+ observer.complete();
187
+ });
188
+ return () => {
189
+ // delete old results from cache
190
+ if (isScale) {
191
+ memoized?.unmemoize(...values);
192
+ }
193
+ else {
194
+ memoized?.raw.unmemoize(...values);
195
+ }
196
+ };
197
+ }).pipe(
198
+ // eslint-disable-next-line deprecation/deprecation
199
+ (0, rxjs_1.publishReplay)(1), // create a Replay(1)
200
+ isDelayed
201
+ ? (0, index_js_1.refCountDelay)() // Unsubscribe after delay
202
+ // eslint-disable-next-line deprecation/deprecation
203
+ : (0, rxjs_1.refCount)());
306
204
  };
307
- try {
308
- const params = _this._formatInputs(registry, null, def, values);
309
- const paramsJson = params.map(p => p.toJSON());
310
- const update = (error, result) => {
311
- if (error) {
312
- logErrorMessage(method, def, error);
313
- return;
314
- }
315
- try {
316
- observer.next(_this._formatResult(isScale, registry, null, method, def, params, result));
317
- } catch (error) {
318
- observer.error(error);
319
- }
320
- };
321
- subscriptionPromise = _this._createSubscriber({
322
- paramsJson,
323
- subName,
324
- subType,
325
- update
326
- }, errorHandler);
327
- } catch (error) {
328
- errorHandler(error);
329
- }
330
-
331
- // Teardown logic
332
- return () => {
333
- // Delete from cache, so old results don't hang around
334
- if (isScale) {
335
- var _memoized3;
336
- (_memoized3 = memoized) == null ? void 0 : _memoized3.unmemoize(...values);
337
- } else {
338
- var _memoized4;
339
- (_memoized4 = memoized) == null ? void 0 : _memoized4.raw.unmemoize(...values);
340
- }
341
-
342
- // Unsubscribe from provider
343
- subscriptionPromise.then(subscriptionId => (0, _util.isNull)(subscriptionId) ? Promise.resolve(false) : _this.provider.unsubscribe(subType, unsubName, subscriptionId)).catch(error => logErrorMessage(method, def, error));
205
+ memoized = this._memomize(creator, def);
206
+ return memoized;
207
+ }
208
+ // create a subscriptor, it subscribes once and resolves with the id as subscribe
209
+ _createSubscriber({ paramsJson, subName, subType, update }, errorHandler) {
210
+ return new Promise((resolve, reject) => {
211
+ this.provider
212
+ .subscribe(subType, subName, paramsJson, update)
213
+ .then(resolve)
214
+ .catch((error) => {
215
+ errorHandler(error);
216
+ reject(error);
217
+ });
218
+ });
219
+ }
220
+ _createMethodSubscribe(section, method, def) {
221
+ const [updateType, subMethod, unsubMethod] = def.pubsub;
222
+ const subName = `${section}_${subMethod}`;
223
+ const unsubName = `${section}_${unsubMethod}`;
224
+ const subType = `${section}_${updateType}`;
225
+ let memoized = null;
226
+ const creator = (isScale) => (...values) => {
227
+ return new rxjs_1.Observable((observer) => {
228
+ // Have at least an empty promise, as used in the unsubscribe
229
+ let subscriptionPromise = Promise.resolve(null);
230
+ const registry = tslib_1.__classPrivateFieldGet(this, _RpcCore_registryDefault, "f");
231
+ const errorHandler = (error) => {
232
+ logErrorMessage(method, def, error);
233
+ observer.error(error);
234
+ };
235
+ try {
236
+ const params = this._formatInputs(registry, null, def, values);
237
+ const paramsJson = params.map((p) => p.toJSON());
238
+ const update = (error, result) => {
239
+ if (error) {
240
+ logErrorMessage(method, def, error);
241
+ return;
242
+ }
243
+ try {
244
+ observer.next(this._formatResult(isScale, registry, null, method, def, params, result));
245
+ }
246
+ catch (error) {
247
+ observer.error(error);
248
+ }
249
+ };
250
+ subscriptionPromise = this._createSubscriber({ paramsJson, subName, subType, update }, errorHandler);
251
+ }
252
+ catch (error) {
253
+ errorHandler(error);
254
+ }
255
+ // Teardown logic
256
+ return () => {
257
+ // Delete from cache, so old results don't hang around
258
+ if (isScale) {
259
+ memoized?.unmemoize(...values);
260
+ }
261
+ else {
262
+ memoized?.raw.unmemoize(...values);
263
+ }
264
+ // Unsubscribe from provider
265
+ subscriptionPromise
266
+ .then((subscriptionId) => (0, util_1.isNull)(subscriptionId)
267
+ ? Promise.resolve(false)
268
+ : this.provider.unsubscribe(subType, unsubName, subscriptionId))
269
+ .catch((error) => logErrorMessage(method, def, error));
270
+ };
271
+ }).pipe((0, index_js_1.drr)());
344
272
  };
345
- }).pipe((0, _util2.drr)());
346
- };
347
- memoized = this._memomize(creator, def);
348
- return memoized;
349
- }
350
- _formatInputs(registry, blockHash, def, inputs) {
351
- const reqArgCount = def.params.filter(_ref5 => {
352
- let {
353
- isOptional
354
- } = _ref5;
355
- return !isOptional;
356
- }).length;
357
- const optText = reqArgCount === def.params.length ? '' : ` (${def.params.length - reqArgCount} optional)`;
358
- if (inputs.length < reqArgCount || inputs.length > def.params.length) {
359
- throw new Error(`Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
273
+ memoized = this._memomize(creator, def);
274
+ return memoized;
275
+ }
276
+ _formatInputs(registry, blockHash, def, inputs) {
277
+ const reqArgCount = def.params.filter(({ isOptional }) => !isOptional).length;
278
+ const optText = reqArgCount === def.params.length
279
+ ? ''
280
+ : ` (${def.params.length - reqArgCount} optional)`;
281
+ if (inputs.length < reqArgCount || inputs.length > def.params.length) {
282
+ throw new Error(`Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
283
+ }
284
+ return inputs.map((input, index) => registry.createTypeUnsafe(def.params[index].type, [input], { blockHash }));
285
+ }
286
+ _formatOutput(registry, blockHash, method, rpc, params, result) {
287
+ if (rpc.type === 'StorageData') {
288
+ const key = params[0];
289
+ return this._formatStorageData(registry, blockHash, key, result);
290
+ }
291
+ else if (rpc.type === 'StorageChangeSet') {
292
+ const keys = params[0];
293
+ return keys
294
+ ? this._formatStorageSet(registry, result.block, keys, result.changes)
295
+ : registry.createType('StorageChangeSet', result);
296
+ }
297
+ else if (rpc.type === 'Vec<StorageChangeSet>') {
298
+ const mapped = result.map(({ block, changes }) => [
299
+ registry.createType('Hash', block),
300
+ this._formatStorageSet(registry, block, params[0], changes)
301
+ ]);
302
+ // we only query at a specific block, not a range - flatten
303
+ return method === 'queryStorageAt'
304
+ ? mapped[0][1]
305
+ : mapped;
306
+ }
307
+ return registry.createTypeUnsafe(rpc.type, [result], { blockHash });
360
308
  }
361
- return inputs.map((input, index) => registry.createTypeUnsafe(def.params[index].type, [input], {
362
- blockHash
363
- }));
364
- }
365
- _formatOutput(registry, blockHash, method, rpc, params, result) {
366
- if (rpc.type === 'StorageData') {
367
- const key = params[0];
368
- return this._formatStorageData(registry, blockHash, key, result);
369
- } else if (rpc.type === 'StorageChangeSet') {
370
- const keys = params[0];
371
- return keys ? this._formatStorageSet(registry, result.block, keys, result.changes) : registry.createType('StorageChangeSet', result);
372
- } else if (rpc.type === 'Vec<StorageChangeSet>') {
373
- const mapped = result.map(_ref6 => {
374
- let {
375
- block,
376
- changes
377
- } = _ref6;
378
- return [registry.createType('Hash', block), this._formatStorageSet(registry, block, params[0], changes)];
379
- });
380
-
381
- // we only query at a specific block, not a range - flatten
382
- return method === 'queryStorageAt' ? mapped[0][1] : mapped;
309
+ _formatStorageData(registry, blockHash, key, value) {
310
+ const isEmpty = (0, util_1.isNull)(value);
311
+ // we convert to Uint8Array since it maps to the raw encoding, all
312
+ // data will be correctly encoded (incl. numbers, excl. :code)
313
+ const input = isEmpty
314
+ ? null
315
+ : isTreatAsHex(key)
316
+ ? value
317
+ : (0, util_1.u8aToU8a)(value);
318
+ return this._newType(registry, blockHash, key, input, isEmpty);
383
319
  }
384
- return registry.createTypeUnsafe(rpc.type, [result], {
385
- blockHash
386
- });
387
- }
388
- _formatStorageData(registry, blockHash, key, value) {
389
- const isEmpty = (0, _util.isNull)(value);
390
-
391
- // we convert to Uint8Array since it maps to the raw encoding, all
392
- // data will be correctly encoded (incl. numbers, excl. :code)
393
- const input = isEmpty ? null : isTreatAsHex(key) ? value : (0, _util.u8aToU8a)(value);
394
- return this._newType(registry, blockHash, key, input, isEmpty);
395
- }
396
- _formatStorageSet(registry, blockHash, keys, changes) {
397
- // For StorageChangeSet, the changes has the [key, value] mappings
398
- const withCache = keys.length !== 1;
399
-
400
- // multiple return values (via state.storage subscription), decode the values
401
- // one at a time, all based on the query types. Three values can be returned -
402
- // - Codec - There is a valid value, non-empty
403
- // - null - The storage key is empty
404
- return keys.reduce((results, key, index) => {
405
- results.push(this._formatStorageSetEntry(registry, blockHash, key, changes, withCache, index));
406
- return results;
407
- }, []);
408
- }
409
- _formatStorageSetEntry(registry, blockHash, key, changes, withCache, entryIndex) {
410
- const hexKey = key.toHex();
411
- const found = changes.find(_ref7 => {
412
- let [key] = _ref7;
413
- return key === hexKey;
414
- });
415
- const isNotFound = (0, _util.isUndefined)(found);
416
-
417
- // if we don't find the value, this is our fallback
418
- // - in the case of an array of values, fill the hole from the cache
419
- // - if a single result value, don't fill - it is not an update hole
420
- // - fallback to an empty option in all cases
421
- if (isNotFound && withCache) {
422
- const cached = this.#storageCache.get(hexKey);
423
- if (cached) {
424
- return cached;
425
- }
320
+ _formatStorageSet(registry, blockHash, keys, changes) {
321
+ // For StorageChangeSet, the changes has the [key, value] mappings
322
+ const withCache = keys.length !== 1;
323
+ // multiple return values (via state.storage subscription), decode the values
324
+ // one at a time, all based on the query types. Three values can be returned -
325
+ // - Codec - There is a valid value, non-empty
326
+ // - null - The storage key is empty
327
+ return keys.reduce((results, key, index) => {
328
+ results.push(this._formatStorageSetEntry(registry, blockHash, key, changes, withCache, index));
329
+ return results;
330
+ }, []);
331
+ }
332
+ _formatStorageSetEntry(registry, blockHash, key, changes, withCache, entryIndex) {
333
+ const hexKey = key.toHex();
334
+ const found = changes.find(([key]) => key === hexKey);
335
+ const isNotFound = (0, util_1.isUndefined)(found);
336
+ // if we don't find the value, this is our fallback
337
+ // - in the case of an array of values, fill the hole from the cache
338
+ // - if a single result value, don't fill - it is not an update hole
339
+ // - fallback to an empty option in all cases
340
+ if (isNotFound && withCache) {
341
+ const cached = tslib_1.__classPrivateFieldGet(this, _RpcCore_storageCache, "f").get(hexKey);
342
+ if (cached) {
343
+ return cached;
344
+ }
345
+ }
346
+ const value = isNotFound
347
+ ? null
348
+ : found[1];
349
+ const isEmpty = (0, util_1.isNull)(value);
350
+ const input = isEmpty || isTreatAsHex(key)
351
+ ? value
352
+ : (0, util_1.u8aToU8a)(value);
353
+ const codec = this._newType(registry, blockHash, key, input, isEmpty, entryIndex);
354
+ // store the retrieved result - the only issue with this cache is that there is no
355
+ // clearing of it, so very long running processes (not just a couple of hours, longer)
356
+ // will increase memory beyond what is allowed.
357
+ tslib_1.__classPrivateFieldGet(this, _RpcCore_storageCache, "f").set(hexKey, codec);
358
+ return codec;
426
359
  }
427
- const value = isNotFound ? null : found[1];
428
- const isEmpty = (0, _util.isNull)(value);
429
- const input = isEmpty || isTreatAsHex(key) ? value : (0, _util.u8aToU8a)(value);
430
- const codec = this._newType(registry, blockHash, key, input, isEmpty, entryIndex);
431
-
432
- // store the retrieved result - the only issue with this cache is that there is no
433
- // clearing of it, so very long running processes (not just a couple of hours, longer)
434
- // will increase memory beyond what is allowed.
435
- this.#storageCache.set(hexKey, codec);
436
- return codec;
437
- }
438
- _newType(registry, blockHash, key, input, isEmpty) {
439
- let entryIndex = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : -1;
440
- // single return value (via state.getStorage), decode the value based on the
441
- // outputType that we have specified. Fallback to Raw on nothing
442
- const type = key.outputType || 'Raw';
443
- const meta = key.meta || EMPTY_META;
444
- const entryNum = entryIndex === -1 ? '' : ` entry ${entryIndex}:`;
445
- try {
446
- return registry.createTypeUnsafe(type, [isEmpty ? meta.fallback
447
- // For old-style Linkage, we add an empty linkage at the end
448
- ? type.includes('Linkage<') ? (0, _util.u8aConcat)((0, _util.hexToU8a)(meta.fallback.toHex()), new Uint8Array(2)) : (0, _util.hexToU8a)(meta.fallback.toHex()) : undefined : meta.modifier.isOptional ? registry.createTypeUnsafe(type, [input], {
449
- blockHash,
450
- isPedantic: true
451
- }) : input], {
452
- blockHash,
453
- isFallback: isEmpty && !!meta.fallback,
454
- isOptional: meta.modifier.isOptional,
455
- isPedantic: !meta.modifier.isOptional
456
- });
457
- } catch (error) {
458
- throw new Error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}: ${error.message}`);
360
+ _newType(registry, blockHash, key, input, isEmpty, entryIndex = -1) {
361
+ // single return value (via state.getStorage), decode the value based on the
362
+ // outputType that we have specified. Fallback to Raw on nothing
363
+ const type = key.outputType || 'Raw';
364
+ const meta = key.meta || EMPTY_META;
365
+ const entryNum = entryIndex === -1
366
+ ? ''
367
+ : ` entry ${entryIndex}:`;
368
+ try {
369
+ return registry.createTypeUnsafe(type, [
370
+ isEmpty
371
+ ? meta.fallback
372
+ // For old-style Linkage, we add an empty linkage at the end
373
+ ? type.includes('Linkage<')
374
+ ? (0, util_1.u8aConcat)((0, util_1.hexToU8a)(meta.fallback.toHex()), new Uint8Array(2))
375
+ : (0, util_1.hexToU8a)(meta.fallback.toHex())
376
+ : undefined
377
+ : meta.modifier.isOptional
378
+ ? registry.createTypeUnsafe(type, [input], { blockHash, isPedantic: true })
379
+ : input
380
+ ], { blockHash, isFallback: isEmpty && !!meta.fallback, isOptional: meta.modifier.isOptional, isPedantic: !meta.modifier.isOptional });
381
+ }
382
+ catch (error) {
383
+ throw new Error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}: ${error.message}`);
384
+ }
459
385
  }
460
- }
461
386
  }
462
- exports.RpcCore = RpcCore;
387
+ exports.RpcCore = RpcCore;
388
+ _RpcCore_instanceId = new WeakMap(), _RpcCore_registryDefault = new WeakMap(), _RpcCore_getBlockRegistry = new WeakMap(), _RpcCore_getBlockHash = new WeakMap(), _RpcCore_storageCache = new WeakMap();