@pezkuwi/api 16.5.5 → 16.5.6

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 (204) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +12 -12
  3. package/augment.js +1 -0
  4. package/base/Decorate.js +752 -0
  5. package/base/Events.js +78 -0
  6. package/base/Getters.js +207 -0
  7. package/base/Init.js +400 -0
  8. package/base/find.js +7 -0
  9. package/{build/base → base}/index.d.ts +1 -1
  10. package/base/index.js +57 -0
  11. package/bundle-pezkuwi-api.js +26238 -0
  12. package/{src/bundle.ts → bundle.js} +0 -9
  13. package/cjs/augment.d.ts +1 -0
  14. package/cjs/augment.js +3 -0
  15. package/cjs/base/Decorate.d.ts +143 -0
  16. package/cjs/base/Decorate.js +756 -0
  17. package/cjs/base/Events.d.ts +67 -0
  18. package/cjs/base/Events.js +82 -0
  19. package/cjs/base/Getters.d.ts +163 -0
  20. package/cjs/base/Getters.js +211 -0
  21. package/cjs/base/Init.d.ts +44 -0
  22. package/cjs/base/Init.js +404 -0
  23. package/cjs/base/find.d.ts +3 -0
  24. package/cjs/base/find.js +11 -0
  25. package/cjs/base/index.d.ts +47 -0
  26. package/cjs/base/index.js +61 -0
  27. package/{src/base/types.ts → cjs/base/types.d.ts} +8 -12
  28. package/cjs/base/types.js +2 -0
  29. package/cjs/bundle.d.ts +7 -0
  30. package/cjs/bundle.js +17 -0
  31. package/cjs/index.js +5 -0
  32. package/cjs/package.json +3 -0
  33. package/cjs/packageDetect.d.ts +1 -0
  34. package/cjs/packageDetect.js +10 -0
  35. package/cjs/packageInfo.js +4 -0
  36. package/{build → cjs}/promise/Api.d.ts +2 -2
  37. package/cjs/promise/Api.js +195 -0
  38. package/cjs/promise/Combinator.js +72 -0
  39. package/cjs/promise/decorateMethod.js +75 -0
  40. package/cjs/promise/index.js +7 -0
  41. package/cjs/promise/types.js +2 -0
  42. package/{build → cjs}/rx/Api.d.ts +2 -2
  43. package/cjs/rx/Api.js +173 -0
  44. package/cjs/rx/decorateMethod.js +6 -0
  45. package/cjs/rx/index.js +7 -0
  46. package/cjs/submittable/Result.js +84 -0
  47. package/cjs/submittable/createClass.js +277 -0
  48. package/cjs/submittable/createSubmittable.js +8 -0
  49. package/cjs/submittable/index.js +7 -0
  50. package/cjs/submittable/types.js +2 -0
  51. package/cjs/types/calls.js +4 -0
  52. package/cjs/types/consts.js +4 -0
  53. package/cjs/types/errors.js +4 -0
  54. package/cjs/types/events.js +4 -0
  55. package/cjs/types/index.js +13 -0
  56. package/cjs/types/storage.js +4 -0
  57. package/cjs/types/submittable.js +4 -0
  58. package/cjs/util/augmentObject.js +84 -0
  59. package/cjs/util/decorate.js +17 -0
  60. package/cjs/util/filterEvents.js +25 -0
  61. package/cjs/util/index.js +11 -0
  62. package/cjs/util/isKeyringPair.js +7 -0
  63. package/cjs/util/logging.js +5 -0
  64. package/cjs/util/validate.js +26 -0
  65. package/index.d.ts +2 -0
  66. package/index.js +2 -0
  67. package/package.json +588 -22
  68. package/packageDetect.d.ts +1 -0
  69. package/{src/packageDetect.ts → packageDetect.js} +0 -8
  70. package/packageInfo.d.ts +6 -0
  71. package/packageInfo.js +1 -0
  72. package/promise/Api.d.ts +158 -0
  73. package/promise/Api.js +191 -0
  74. package/promise/Combinator.d.ts +12 -0
  75. package/promise/Combinator.js +68 -0
  76. package/promise/decorateMethod.d.ts +14 -0
  77. package/promise/decorateMethod.js +71 -0
  78. package/promise/index.d.ts +2 -0
  79. package/promise/index.js +2 -0
  80. package/{src/promise/types.ts → promise/types.d.ts} +0 -4
  81. package/promise/types.js +1 -0
  82. package/rx/Api.d.ts +155 -0
  83. package/{src/rx/Api.ts → rx/Api.js} +67 -84
  84. package/rx/decorateMethod.d.ts +3 -0
  85. package/rx/decorateMethod.js +3 -0
  86. package/rx/index.d.ts +2 -0
  87. package/rx/index.js +2 -0
  88. package/submittable/Result.d.ts +31 -0
  89. package/submittable/Result.js +80 -0
  90. package/submittable/createClass.d.ts +12 -0
  91. package/submittable/createClass.js +274 -0
  92. package/submittable/createSubmittable.d.ts +8 -0
  93. package/submittable/createSubmittable.js +5 -0
  94. package/{src/submittable/index.ts → submittable/index.d.ts} +0 -3
  95. package/submittable/index.js +2 -0
  96. package/{src/submittable/types.ts → submittable/types.d.ts} +0 -3
  97. package/submittable/types.js +1 -0
  98. package/types/calls.d.ts +1 -0
  99. package/types/calls.js +1 -0
  100. package/types/consts.d.ts +1 -0
  101. package/types/consts.js +1 -0
  102. package/types/errors.d.ts +1 -0
  103. package/types/errors.js +1 -0
  104. package/types/events.d.ts +1 -0
  105. package/types/events.js +1 -0
  106. package/types/index.d.ts +114 -0
  107. package/types/index.js +8 -0
  108. package/types/storage.d.ts +1 -0
  109. package/types/storage.js +1 -0
  110. package/types/submittable.d.ts +1 -0
  111. package/types/submittable.js +1 -0
  112. package/util/augmentObject.d.ts +9 -0
  113. package/util/augmentObject.js +81 -0
  114. package/util/decorate.d.ts +16 -0
  115. package/util/decorate.js +14 -0
  116. package/util/filterEvents.d.ts +6 -0
  117. package/util/filterEvents.js +22 -0
  118. package/{src/util/index.ts → util/index.d.ts} +0 -6
  119. package/util/index.js +4 -0
  120. package/util/isKeyringPair.d.ts +3 -0
  121. package/util/isKeyringPair.js +4 -0
  122. package/util/logging.d.ts +1 -0
  123. package/util/logging.js +2 -0
  124. package/util/validate.d.ts +3 -0
  125. package/util/validate.js +23 -0
  126. package/src/augment.ts +0 -4
  127. package/src/base/Decorate.ts +0 -1103
  128. package/src/base/Events.ts +0 -91
  129. package/src/base/Getters.ts +0 -245
  130. package/src/base/Init.ts +0 -525
  131. package/src/base/find.ts +0 -14
  132. package/src/base/index.ts +0 -85
  133. package/src/checkTypes.manual.ts +0 -323
  134. package/src/index.ts +0 -6
  135. package/src/mod.ts +0 -4
  136. package/src/packageInfo.ts +0 -6
  137. package/src/promise/Api.ts +0 -214
  138. package/src/promise/Combinator.ts +0 -91
  139. package/src/promise/Combinators.spec.ts +0 -109
  140. package/src/promise/decorateMethod.ts +0 -118
  141. package/src/promise/index.spec.ts +0 -167
  142. package/src/promise/index.ts +0 -5
  143. package/src/rx/decorateMethod.ts +0 -9
  144. package/src/rx/index.ts +0 -5
  145. package/src/submittable/Result.ts +0 -111
  146. package/src/submittable/createClass.ts +0 -438
  147. package/src/submittable/createSubmittable.ts +0 -19
  148. package/src/test/SingleAccountSigner.ts +0 -53
  149. package/src/test/index.ts +0 -5
  150. package/src/test/logEvents.ts +0 -24
  151. package/src/types/calls.ts +0 -4
  152. package/src/types/consts.ts +0 -4
  153. package/src/types/errors.ts +0 -4
  154. package/src/types/events.ts +0 -4
  155. package/src/types/index.ts +0 -137
  156. package/src/types/storage.ts +0 -4
  157. package/src/types/submittable.ts +0 -4
  158. package/src/util/augmentObject.spec.ts +0 -54
  159. package/src/util/augmentObject.ts +0 -112
  160. package/src/util/decorate.ts +0 -43
  161. package/src/util/filterEvents.ts +0 -34
  162. package/src/util/isKeyringPair.ts +0 -11
  163. package/src/util/logging.ts +0 -6
  164. package/src/util/validate.spec.ts +0 -72
  165. package/src/util/validate.ts +0 -36
  166. package/tsconfig.build.json +0 -25
  167. package/tsconfig.build.tsbuildinfo +0 -1
  168. package/tsconfig.spec.json +0 -26
  169. /package/{build/augment.d.ts → augment.d.ts} +0 -0
  170. /package/{build/base → base}/Decorate.d.ts +0 -0
  171. /package/{build/base → base}/Events.d.ts +0 -0
  172. /package/{build/base → base}/Getters.d.ts +0 -0
  173. /package/{build/base → base}/Init.d.ts +0 -0
  174. /package/{build/base → base}/find.d.ts +0 -0
  175. /package/{build/base → base}/types.d.ts +0 -0
  176. /package/{build/packageDetect.d.ts → base/types.js} +0 -0
  177. /package/{build/bundle.d.ts → bundle.d.ts} +0 -0
  178. /package/{build → cjs}/index.d.ts +0 -0
  179. /package/{build → cjs}/packageInfo.d.ts +0 -0
  180. /package/{build → cjs}/promise/Combinator.d.ts +0 -0
  181. /package/{build → cjs}/promise/decorateMethod.d.ts +0 -0
  182. /package/{build → cjs}/promise/index.d.ts +0 -0
  183. /package/{build → cjs}/promise/types.d.ts +0 -0
  184. /package/{build → cjs}/rx/decorateMethod.d.ts +0 -0
  185. /package/{build → cjs}/rx/index.d.ts +0 -0
  186. /package/{build → cjs}/submittable/Result.d.ts +0 -0
  187. /package/{build → cjs}/submittable/createClass.d.ts +0 -0
  188. /package/{build → cjs}/submittable/createSubmittable.d.ts +0 -0
  189. /package/{build → cjs}/submittable/index.d.ts +0 -0
  190. /package/{build → cjs}/submittable/types.d.ts +0 -0
  191. /package/{build → cjs}/types/calls.d.ts +0 -0
  192. /package/{build → cjs}/types/consts.d.ts +0 -0
  193. /package/{build → cjs}/types/errors.d.ts +0 -0
  194. /package/{build → cjs}/types/events.d.ts +0 -0
  195. /package/{build → cjs}/types/index.d.ts +0 -0
  196. /package/{build → cjs}/types/storage.d.ts +0 -0
  197. /package/{build → cjs}/types/submittable.d.ts +0 -0
  198. /package/{build → cjs}/util/augmentObject.d.ts +0 -0
  199. /package/{build → cjs}/util/decorate.d.ts +0 -0
  200. /package/{build → cjs}/util/filterEvents.d.ts +0 -0
  201. /package/{build → cjs}/util/index.d.ts +0 -0
  202. /package/{build → cjs}/util/isKeyringPair.d.ts +0 -0
  203. /package/{build → cjs}/util/logging.d.ts +0 -0
  204. /package/{build → cjs}/util/validate.d.ts +0 -0
@@ -1,1103 +0,0 @@
1
- // Copyright 2017-2025 @polkadot/api authors & contributors
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- import type { Observable } from 'rxjs';
5
- import type { AugmentedCall, DeriveCustom, QueryableCalls } from '@pezkuwi/api-base/types';
6
- import type { RpcInterface } from '@pezkuwi/rpc-core/types';
7
- import type { Metadata, StorageKey, Text, u64, Vec } from '@pezkuwi/types';
8
- import type { Call, Hash, RuntimeApiMethodMetadataV16, RuntimeVersion } from '@pezkuwi/types/interfaces';
9
- import type { DecoratedMeta } from '@pezkuwi/types/metadata/decorate/types';
10
- import type { StorageEntry } from '@pezkuwi/types/primitive/types';
11
- import type { AnyFunction, AnyJson, AnyTuple, CallFunction, Codec, DefinitionCall, DefinitionCallNamed, DefinitionRpc, DefinitionRpcSub, DefinitionsCall, DefinitionsCallEntry, DetectCodec, IMethod, IStorageKey, Registry, RegistryError, RegistryTypes } from '@pezkuwi/types/types';
12
- import type { HexString } from '@pezkuwi/util/types';
13
- import type { SubmittableExtrinsic } from '../submittable/types.js';
14
- import type { ApiDecoration, ApiInterfaceRx, ApiOptions, ApiTypes, AugmentedQuery, DecoratedErrors, DecoratedEvents, DecoratedRpc, DecorateMethod, GenericStorageEntryFunction, PaginationOptions, QueryableConsts, QueryableStorage, QueryableStorageEntry, QueryableStorageEntryAt, QueryableStorageMulti, QueryableStorageMultiArg, SubmittableExtrinsicFunction, SubmittableExtrinsics } from '../types/index.js';
15
- import type { AllDerives } from '../util/decorate.js';
16
- import type { VersionedRegistry } from './types.js';
17
-
18
- import { BehaviorSubject, combineLatest, from, map, of, switchMap, tap, toArray } from 'rxjs';
19
-
20
- import { getAvailableDerives } from '@pezkuwi/api-derive';
21
- import { memo, RpcCore } from '@pezkuwi/rpc-core';
22
- import { WsProvider } from '@pezkuwi/rpc-provider';
23
- import { expandMetadata, GenericExtrinsic, typeDefinitions, TypeRegistry } from '@pezkuwi/types';
24
- import { getSpecRuntime } from '@pezkuwi/types-known';
25
- import { arrayChunk, arrayFlatten, assertReturn, BN, compactStripLength, lazyMethod, lazyMethods, logger, nextTick, objectSpread, stringCamelCase, stringUpperFirst, u8aConcatStrict, u8aToHex } from '@pezkuwi/util';
26
- import { blake2AsHex } from '@pezkuwi/util-crypto';
27
-
28
- import { createSubmittable } from '../submittable/index.js';
29
- import { augmentObject } from '../util/augmentObject.js';
30
- import { decorateDeriveSections } from '../util/decorate.js';
31
- import { extractStorageArgs } from '../util/validate.js';
32
- import { Events } from './Events.js';
33
- import { findCall, findError } from './find.js';
34
-
35
- interface MetaDecoration {
36
- callIndex?: Uint8Array;
37
- meta: Record<string, unknown>;
38
- method: string;
39
- section: string;
40
- toJSON: () => any;
41
- }
42
-
43
- interface FullDecoration<ApiType extends ApiTypes> {
44
- createdAt?: Uint8Array | undefined;
45
- decoratedApi: ApiDecoration<ApiType>;
46
- decoratedMeta: DecoratedMeta;
47
- }
48
-
49
- // the max amount of keys/values that we will retrieve at once
50
- const PAGE_SIZE_K = 1000; // limit aligned with the 1k on the node (trie lookups are heavy)
51
- const PAGE_SIZE_V = 250; // limited since the data may be > 16MB (e.g. misfiring elections)
52
- const PAGE_SIZE_Q = 50; // queue of pending storage queries (mapped together, next tick)
53
-
54
- const l = logger('api/init');
55
-
56
- let instanceCounter = 0;
57
-
58
- function getAtQueryFn<ApiType extends ApiTypes> (api: ApiDecoration<ApiType>, { method, section }: StorageEntry): AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple> {
59
- return assertReturn(api.rx.query[section] && api.rx.query[section][method], () => `query.${section}.${method} is not available in this version of the metadata`);
60
- }
61
-
62
- export abstract class Decorate<ApiType extends ApiTypes> extends Events {
63
- readonly #instanceId: string;
64
- readonly #runtimeLog: Record<string, boolean> = {};
65
-
66
- #registry: Registry;
67
- #storageGetQ: [Observable<Codec[]>, [StorageEntry, unknown[]][]][] = [];
68
- #storageSubQ: [Observable<Codec[]>, [StorageEntry, unknown[]][]][] = [];
69
-
70
- // HACK Use BN import so decorateDerive works... yes, wtf.
71
- protected __phantom = new BN(0);
72
-
73
- protected _type: ApiTypes;
74
- protected _call: QueryableCalls<ApiType> = {} as QueryableCalls<ApiType>;
75
- protected _consts: QueryableConsts<ApiType> = {} as QueryableConsts<ApiType>;
76
- protected _derive?: ReturnType<Decorate<ApiType>['_decorateDerive']>;
77
- protected _errors: DecoratedErrors<ApiType> = {} as DecoratedErrors<ApiType>;
78
- protected _events: DecoratedEvents<ApiType> = {} as DecoratedEvents<ApiType>;
79
- protected _extrinsics?: SubmittableExtrinsics<ApiType>;
80
- protected _extrinsicType = GenericExtrinsic.LATEST_EXTRINSIC_VERSION;
81
- protected _genesisHash?: Hash;
82
- protected _isConnected: BehaviorSubject<boolean>;
83
- protected _isReady = false;
84
- protected _query: QueryableStorage<ApiType> = {} as QueryableStorage<ApiType>;
85
- protected _queryMulti?: QueryableStorageMulti<ApiType>;
86
- protected _rpc?: DecoratedRpc<ApiType, RpcInterface>;
87
- protected _rpcCore: RpcCore & RpcInterface;
88
- protected _runtimeMap: Record<HexString, string> = {};
89
- protected _runtimeChain?: Text;
90
- protected _runtimeMetadata?: Metadata;
91
- protected _runtimeVersion?: RuntimeVersion;
92
- protected _rx: ApiInterfaceRx = { call: {} as QueryableCalls<'rxjs'>, consts: {} as QueryableConsts<'rxjs'>, query: {} as QueryableStorage<'rxjs'>, tx: {} as SubmittableExtrinsics<'rxjs'> } as ApiInterfaceRx;
93
-
94
- protected readonly _options: ApiOptions;
95
-
96
- /**
97
- * This is the one and only method concrete children classes need to implement.
98
- * It's a higher-order function, which takes one argument
99
- * `method: Method extends (...args: any[]) => Observable<any>`
100
- * (and one optional `options`), and should return the user facing method.
101
- * For example:
102
- * - For ApiRx, `decorateMethod` should just be identity, because the input
103
- * function is already an Observable
104
- * - For ApiPromise, `decorateMethod` should return a function that takes all
105
- * the parameters from `method`, adds an optional `callback` argument, and
106
- * returns a Promise.
107
- *
108
- * We could easily imagine other user-facing interfaces, which are simply
109
- * implemented by transforming the Observable to Stream/Iterator/Kefir/Bacon
110
- * via `decorateMethod`.
111
- */
112
- protected _decorateMethod: DecorateMethod<ApiType>;
113
-
114
- /**
115
- * @description Create an instance of the class
116
- *
117
- * @param options Options object to create API instance or a Provider instance
118
- *
119
- * @example
120
- * <BR>
121
- *
122
- * ```javascript
123
- * import Api from '@pezkuwi/api/promise';
124
- *
125
- * const api = new Api().isReady();
126
- *
127
- * api.rpc.subscribeNewHeads((header) => {
128
- * console.log(`new block #${header.number.toNumber()}`);
129
- * });
130
- * ```
131
- */
132
- constructor (options: ApiOptions, type: ApiTypes, decorateMethod: DecorateMethod<ApiType>) {
133
- super();
134
-
135
- this.#instanceId = `${++instanceCounter}`;
136
- this.#registry = options.source?.registry || options.registry || new TypeRegistry();
137
- this._rx.callAt = (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) =>
138
- from(this.at(blockHash, knownVersion)).pipe(map((a) => a.rx.call));
139
- this._rx.queryAt = (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion) =>
140
- from(this.at(blockHash, knownVersion)).pipe(map((a) => a.rx.query));
141
- this._rx.registry = this.#registry;
142
- this._decorateMethod = decorateMethod;
143
- this._options = options;
144
- this._type = type;
145
-
146
- const provider = options.source
147
- ? options.source._rpcCore.provider.isClonable
148
- ? options.source._rpcCore.provider.clone()
149
- : options.source._rpcCore.provider
150
- : (options.provider || new WsProvider());
151
-
152
- // The RPC interface decorates the known interfaces on init
153
- this._rpcCore = new RpcCore(this.#instanceId, this.#registry, {
154
- isPedantic: this._options.isPedantic,
155
- provider,
156
- rpcCacheCapacity: this._options.rpcCacheCapacity,
157
- ttl: this._options.provider?.ttl,
158
- userRpc: this._options.rpc
159
- }) as (RpcCore & RpcInterface);
160
- this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected);
161
- this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
162
- }
163
-
164
- public abstract at (blockHash: Uint8Array | string, knownVersion?: RuntimeVersion): Promise<ApiDecoration<ApiType>>;
165
-
166
- /**
167
- * @description Return the current used registry
168
- */
169
- public get registry (): Registry {
170
- return this.#registry;
171
- }
172
-
173
- /**
174
- * @description Creates an instance of a type as registered
175
- */
176
- public createType <T extends Codec = Codec, K extends string = string> (type: K, ...params: unknown[]): DetectCodec<T, K> {
177
- return this.#registry.createType(type, ...params);
178
- }
179
-
180
- /**
181
- * @description Register additional user-defined of chain-specific types in the type registry
182
- */
183
- public registerTypes (types?: RegistryTypes): void {
184
- types && this.#registry.register(types);
185
- }
186
-
187
- /**
188
- * @returns `true` if the API operates with subscriptions
189
- */
190
- get hasSubscriptions (): boolean {
191
- return this._rpcCore.provider.hasSubscriptions;
192
- }
193
-
194
- /**
195
- * @returns `true` if the API decorate multi-key queries
196
- */
197
- get supportMulti (): boolean {
198
- return this._rpcCore.provider.hasSubscriptions || !!this._rpcCore.state.queryStorageAt;
199
- }
200
-
201
- protected _emptyDecorated (registry: Registry, blockHash?: Uint8Array): ApiDecoration<ApiType> {
202
- return {
203
- call: {},
204
- consts: {},
205
- errors: {},
206
- events: {},
207
- query: {},
208
- registry,
209
- rx: {
210
- call: {},
211
- query: {}
212
- },
213
- tx: createSubmittable(this._type, this._rx, this._decorateMethod, registry, blockHash)
214
- } as ApiDecoration<ApiType>;
215
- }
216
-
217
- protected _createDecorated (registry: VersionedRegistry<ApiType>, fromEmpty: boolean, decoratedApi: ApiDecoration<ApiType> | null, blockHash?: Uint8Array): FullDecoration<ApiType> {
218
- if (!decoratedApi) {
219
- decoratedApi = this._emptyDecorated(registry.registry, blockHash);
220
- }
221
-
222
- if (fromEmpty || !registry.decoratedMeta) {
223
- registry.decoratedMeta = expandMetadata(registry.registry, registry.metadata);
224
- }
225
-
226
- const runtime = this._decorateCalls(registry, this._decorateMethod, blockHash);
227
- const runtimeRx = this._decorateCalls<'rxjs'>(registry, this._rxDecorateMethod, blockHash);
228
- const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash);
229
- const storageRx = this._decorateStorage<'rxjs'>(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
230
-
231
- augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
232
- augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
233
- augmentObject('events', registry.decoratedMeta.events, decoratedApi.events, fromEmpty);
234
- augmentObject('query', storage, decoratedApi.query, fromEmpty);
235
- augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty);
236
- augmentObject('call', runtime, decoratedApi.call, fromEmpty);
237
- augmentObject('call', runtimeRx, decoratedApi.rx.call, fromEmpty);
238
-
239
- decoratedApi.findCall = (callIndex: Uint8Array | string): CallFunction =>
240
- findCall(registry.registry, callIndex);
241
- decoratedApi.findError = (errorIndex: Uint8Array | string): RegistryError =>
242
- findError(registry.registry, errorIndex);
243
- decoratedApi.queryMulti = blockHash
244
- ? this._decorateMultiAt(decoratedApi, this._decorateMethod, blockHash)
245
- : this._decorateMulti(this._decorateMethod);
246
- decoratedApi.runtimeVersion = registry.runtimeVersion;
247
-
248
- return {
249
- createdAt: blockHash,
250
- decoratedApi,
251
- decoratedMeta: registry.decoratedMeta
252
- };
253
- }
254
-
255
- protected _injectMetadata (registry: VersionedRegistry<ApiType>, fromEmpty = false): void {
256
- // clear the decoration, we are redoing it here
257
- if (fromEmpty || !registry.decoratedApi) {
258
- registry.decoratedApi = this._emptyDecorated(registry.registry);
259
- }
260
-
261
- const { decoratedApi, decoratedMeta } = this._createDecorated(registry, fromEmpty, registry.decoratedApi);
262
-
263
- this._call = decoratedApi.call;
264
- this._consts = decoratedApi.consts;
265
- this._errors = decoratedApi.errors;
266
- this._events = decoratedApi.events;
267
- this._query = decoratedApi.query;
268
-
269
- this._rx.call = decoratedApi.rx.call;
270
- this._rx.query = decoratedApi.rx.query;
271
-
272
- const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
273
- const rxtx = this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod);
274
-
275
- if (fromEmpty || !this._extrinsics) {
276
- this._extrinsics = tx;
277
- this._rx.tx = rxtx;
278
- } else {
279
- augmentObject('tx', tx, this._extrinsics, false);
280
- augmentObject(null, rxtx, this._rx.tx, false);
281
- }
282
-
283
- augmentObject(null, decoratedMeta.consts, this._rx.consts, fromEmpty);
284
-
285
- this.emit('decorated');
286
- }
287
-
288
- /**
289
- * @deprecated
290
- * backwards compatible endpoint for metadata injection, may be removed in the future (However, it is still useful for testing injection)
291
- */
292
- public injectMetadata (metadata: Metadata, fromEmpty?: boolean, registry?: Registry): void {
293
- this._injectMetadata({ counter: 0, metadata, registry: registry || this.#registry, runtimeVersion: this.#registry.createType('RuntimeVersionPartial') }, fromEmpty);
294
- }
295
-
296
- private _decorateFunctionMeta (input: MetaDecoration, output: MetaDecoration): MetaDecoration {
297
- output.meta = input.meta;
298
- output.method = input.method;
299
- output.section = input.section;
300
- output.toJSON = input.toJSON;
301
-
302
- if (input.callIndex) {
303
- output.callIndex = input.callIndex;
304
- }
305
-
306
- return output;
307
- }
308
-
309
- // Filter all RPC methods based on the results of the rpc_methods call. We do this in the following
310
- // manner to cater for both old and new:
311
- // - when the number of entries are 0, only remove the ones with isOptional (account & contracts)
312
- // - when non-zero, remove anything that is not in the array (we don't do this)
313
- protected _filterRpc (methods: string[], additional: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>): void {
314
- // add any specific user-base RPCs
315
- if (Object.keys(additional).length !== 0) {
316
- this._rpcCore.addUserInterfaces(additional);
317
-
318
- // re-decorate, only adding any new additional interfaces
319
- this._decorateRpc(this._rpcCore, this._decorateMethod, this._rpc);
320
- this._decorateRpc(this._rpcCore, this._rxDecorateMethod, this._rx.rpc);
321
- }
322
-
323
- // extract the actual sections from the methods (this is useful when
324
- // we try and create mappings to runtime names via a hash mapping)
325
- const sectionMap: Record<string, boolean> = {};
326
-
327
- for (let i = 0, count = methods.length; i < count; i++) {
328
- const [section] = methods[i].split('_');
329
-
330
- sectionMap[section] = true;
331
- }
332
-
333
- // convert the actual section names into an easy name lookup
334
- const sections = Object.keys(sectionMap);
335
-
336
- for (let i = 0, count = sections.length; i < count; i++) {
337
- const nameA = stringUpperFirst(sections[i]);
338
- const nameB = `${nameA}Api`;
339
-
340
- this._runtimeMap[blake2AsHex(nameA, 64)] = nameA;
341
- this._runtimeMap[blake2AsHex(nameB, 64)] = nameB;
342
- }
343
-
344
- // finally we filter the actual methods to expose
345
- this._filterRpcMethods(methods);
346
- }
347
-
348
- protected _filterRpcMethods (exposed: string[]): void {
349
- const hasResults = exposed.length !== 0;
350
- const allKnown = [...this._rpcCore.mapping.entries()];
351
- const allKeys: string[] = [];
352
- const count = allKnown.length;
353
-
354
- for (let i = 0; i < count; i++) {
355
- const [, { alias, endpoint, method, pubsub, section }] = allKnown[i];
356
-
357
- allKeys.push(`${section}_${method}`);
358
-
359
- if (pubsub) {
360
- allKeys.push(`${section}_${pubsub[1]}`);
361
- allKeys.push(`${section}_${pubsub[2]}`);
362
- }
363
-
364
- if (alias) {
365
- allKeys.push(...alias);
366
- }
367
-
368
- if (endpoint) {
369
- allKeys.push(endpoint);
370
- }
371
- }
372
-
373
- const unknown = exposed.filter((k: string) =>
374
- !allKeys.includes(k) &&
375
- !k.includes('_unstable_')
376
- );
377
-
378
- if (unknown.length && !this._options.noInitWarn) {
379
- l.warn(`RPC methods not decorated: ${unknown.join(', ')}`);
380
- }
381
-
382
- // loop through all entries we have (populated in decorate) and filter as required
383
- // only remove when we have results and method missing, or with no results if optional
384
- for (let i = 0; i < count; i++) {
385
- const [k, { method, section }] = allKnown[i];
386
-
387
- if (hasResults && !exposed.includes(k) && k !== 'rpc_methods') {
388
- if ((this._rpc as unknown as Record<string, Record<string, unknown>>)[section]) {
389
- delete (this._rpc as unknown as Record<string, Record<string, unknown>>)[section][method];
390
- delete (this._rx.rpc as unknown as Record<string, Record<string, unknown>>)[section][method];
391
- }
392
- }
393
- }
394
- }
395
-
396
- private _rpcSubmitter<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): DecoratedRpc<ApiType, RpcInterface> {
397
- const method = (method: string, ...params: any[]) => {
398
- return from(this._rpcCore.provider.send<AnyJson>(method, params));
399
- };
400
-
401
- return decorateMethod(method) as DecoratedRpc<ApiType, RpcInterface>;
402
- }
403
-
404
- protected _decorateRpc<ApiType extends ApiTypes> (rpc: RpcCore & RpcInterface, decorateMethod: DecorateMethod<ApiType>, input: Partial<DecoratedRpc<ApiType, RpcInterface>> = this._rpcSubmitter(decorateMethod)): DecoratedRpc<ApiType, RpcInterface> {
405
- const out: Record<string, Record<string, unknown>> = input;
406
-
407
- const decorateFn = (section: string, method: string): unknown => {
408
- const source = rpc[section as 'chain'][method as 'getHeader'];
409
- const fn = decorateMethod(source, { methodName: method }) as {
410
- meta: unknown;
411
- raw: unknown;
412
- };
413
-
414
- fn.meta = source.meta;
415
- fn.raw = decorateMethod(source.raw, { methodName: method }) as unknown;
416
-
417
- return fn;
418
- };
419
-
420
- for (let s = 0, scount = rpc.sections.length; s < scount; s++) {
421
- const section = rpc.sections[s];
422
-
423
- if (!Object.prototype.hasOwnProperty.call(out, section)) {
424
- const methods = Object.keys(rpc[section as 'chain']);
425
-
426
- const decorateInternal = (method: string) =>
427
- decorateFn(section, method);
428
-
429
- for (let m = 0, mcount = methods.length; m < mcount; m++) {
430
- const method = methods[m];
431
-
432
- // skip subscriptions where we have a non-subscribe interface
433
- if (this.hasSubscriptions || !(method.startsWith('subscribe') || method.startsWith('unsubscribe'))) {
434
- if (!Object.prototype.hasOwnProperty.call(out, section)) {
435
- out[section] = {};
436
- }
437
-
438
- lazyMethod(out[section], method, decorateInternal);
439
- }
440
- }
441
- }
442
- }
443
-
444
- return out as unknown as DecoratedRpc<ApiType, RpcInterface>;
445
- }
446
-
447
- // add all definition entries
448
- protected _addRuntimeDef (result: DefinitionsCall, additional?: DefinitionsCall): void {
449
- if (!additional) {
450
- return;
451
- }
452
-
453
- const entries = Object.entries(additional);
454
-
455
- for (let j = 0, ecount = entries.length; j < ecount; j++) {
456
- const [key, defs] = entries[j];
457
-
458
- if (result[key]) {
459
- // we have this one already, step through for new versions or
460
- // new methods and add those as applicable
461
- for (let k = 0, dcount = defs.length; k < dcount; k++) {
462
- const def = defs[k];
463
- const prev = result[key].find(({ version }) => def.version === version);
464
-
465
- if (prev) {
466
- // interleave the new methods with the old - last definition wins
467
- objectSpread(prev.methods, def.methods);
468
- } else {
469
- // we don't have this specific version, add it
470
- result[key].push(def);
471
- }
472
- }
473
- } else {
474
- // we don't have this runtime definition, add it as-is
475
- result[key] = defs;
476
- }
477
- }
478
- }
479
-
480
- // extract all runtime definitions
481
- protected _getRuntimeDefs (registry: Registry, specName: Text, chain: Text | string = ''): [string, DefinitionsCallEntry[]][] {
482
- const result: DefinitionsCall = {};
483
- const defValues = Object.values(typeDefinitions);
484
-
485
- // options > chain/spec > built-in, apply in reverse order with
486
- // methods overriding previous definitions (or interleave missing)
487
- for (let i = 0, count = defValues.length; i < count; i++) {
488
- this._addRuntimeDef(result, defValues[i].runtime);
489
- }
490
-
491
- this._addRuntimeDef(result, getSpecRuntime(registry, chain, specName));
492
- this._addRuntimeDef(result, this._options.runtime);
493
-
494
- return Object.entries(result);
495
- }
496
-
497
- // Helper for _getRuntimeDefsViaMetadata
498
- protected _getMethods (registry: Registry, methods: Vec<RuntimeApiMethodMetadataV16>) {
499
- const result: Record<string, DefinitionCall> = {};
500
-
501
- methods.forEach((m) => {
502
- const { docs, inputs, name, output } = m;
503
-
504
- result[name.toString()] = {
505
- description: docs.map((d) => d.toString()).join(),
506
- params: inputs.map(({ name, type }) => {
507
- return { name: name.toString(), type: registry.lookup.getName(type) || registry.lookup.getTypeDef(type).type };
508
- }),
509
- type: registry.lookup.getName(output) || registry.lookup.getTypeDef(output).type
510
- };
511
- });
512
-
513
- return result;
514
- }
515
-
516
- // Maintains the same structure as `_getRuntimeDefs` in order to make conversion easier.
517
- protected _getRuntimeDefsViaMetadata (registry: Registry): [string, DefinitionsCallEntry[]][] {
518
- const result: DefinitionsCall = {};
519
- const { apis } = registry.metadata;
520
-
521
- for (let i = 0, count = apis.length; i < count; i++) {
522
- const { methods, name } = apis[i];
523
-
524
- result[name.toString()] = [{
525
- methods: this._getMethods(registry, methods),
526
- // We set the version to 0 here since it will not be relevant when we are grabbing the runtime apis
527
- // from the Metadata.
528
- version: 0
529
- }];
530
- }
531
-
532
- return Object.entries(result);
533
- }
534
-
535
- // When the calls are available in the metadata, it will generate them based off of the metadata.
536
- // When they are not available it will use the hardcoded calls generated in the static types.
537
- protected _decorateCalls<ApiType extends ApiTypes> ({ registry, runtimeVersion: { apis, specName, specVersion } }: VersionedRegistry<any>, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array | string | null): QueryableCalls<ApiType> {
538
- const result = {} as QueryableCalls<ApiType>;
539
- const named: Record<string, Record<string, DefinitionCallNamed>> = {};
540
- const hashes: Record<HexString, boolean> = {};
541
- const isApiInMetadata = registry.metadata.apis.length > 0;
542
- const sections = isApiInMetadata ? this._getRuntimeDefsViaMetadata(registry) : this._getRuntimeDefs(registry, specName, this._runtimeChain);
543
- const older: string[] = [];
544
- const implName = `${specName.toString()}/${specVersion.toString()}`;
545
- const hasLogged = this.#runtimeLog[implName] || false;
546
-
547
- this.#runtimeLog[implName] = true;
548
-
549
- if (isApiInMetadata) {
550
- for (let i = 0, scount = sections.length; i < scount; i++) {
551
- const [_section, secs] = sections[i];
552
- const sec = secs[0];
553
- const sectionHash = blake2AsHex(_section, 64);
554
-
555
- const section = stringCamelCase(_section);
556
- const methods = Object.entries(sec.methods);
557
-
558
- if (!named[section]) {
559
- named[section] = {};
560
- }
561
-
562
- for (let m = 0, mcount = methods.length; m < mcount; m++) {
563
- const [_method, def] = methods[m];
564
- const method = stringCamelCase(_method);
565
-
566
- named[section][method] = objectSpread({ method, name: `${_section}_${_method}`, section, sectionHash }, def);
567
- }
568
- }
569
- } else {
570
- for (let i = 0, scount = sections.length; i < scount; i++) {
571
- const [_section, secs] = sections[i];
572
- const sectionHash = blake2AsHex(_section, 64);
573
- const rtApi = apis.find(([a]) => a.eq(sectionHash));
574
-
575
- hashes[sectionHash] = true;
576
-
577
- if (rtApi) {
578
- const all = secs.map(({ version }) => version).sort();
579
- const sec = secs.find(({ version }) => rtApi[1].eq(version));
580
-
581
- if (sec) {
582
- const section = stringCamelCase(_section);
583
- const methods = Object.entries(sec.methods);
584
-
585
- if (methods.length) {
586
- if (!named[section]) {
587
- named[section] = {};
588
- }
589
-
590
- for (let m = 0, mcount = methods.length; m < mcount; m++) {
591
- const [_method, def] = methods[m];
592
- const method = stringCamelCase(_method);
593
-
594
- named[section][method] = objectSpread({ method, name: `${_section}_${_method}`, section, sectionHash }, def);
595
- }
596
- }
597
- } else {
598
- older.push(`${_section}/${rtApi[1].toString()} (${all.join('/')} known)`);
599
- }
600
- }
601
- }
602
-
603
- // find the runtimes that we don't have hashes for
604
- const notFound = apis
605
- .map(([a, v]): [HexString, string] => [a.toHex(), v.toString()])
606
- .filter(([a]) => !hashes[a])
607
- .map(([a, v]) => `${this._runtimeMap[a] || a}/${v}`);
608
-
609
- if (!this._options.noInitWarn && !hasLogged) {
610
- if (older.length) {
611
- l.warn(`${implName}: Not decorating runtime apis without matching versions: ${older.join(', ')}`);
612
- }
613
-
614
- if (notFound.length) {
615
- l.warn(`${implName}: Not decorating unknown runtime apis: ${notFound.join(', ')}`);
616
- }
617
- }
618
- }
619
-
620
- const stateCall = blockHash
621
- ? (name: string, bytes: Uint8Array) => this._rpcCore.state.call(name, bytes, blockHash)
622
- : (name: string, bytes: Uint8Array) => this._rpcCore.state.call(name, bytes);
623
-
624
- const lazySection = (section: string) =>
625
- lazyMethods({}, Object.keys(named[section]), (method: string) =>
626
- this._decorateCall(registry, named[section][method], stateCall, decorateMethod)
627
- );
628
-
629
- const modules = Object.keys(named);
630
-
631
- for (let i = 0, count = modules.length; i < count; i++) {
632
- lazyMethod(result, modules[i], lazySection);
633
- }
634
-
635
- return result;
636
- }
637
-
638
- protected _decorateCall<ApiType extends ApiTypes> (registry: Registry, def: DefinitionCallNamed, stateCall: (method: string, bytes: Uint8Array) => Observable<Codec>, decorateMethod: DecorateMethod<ApiType>): AugmentedCall<ApiType> {
639
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
640
- const decorated = decorateMethod((...args: unknown[]): Observable<Codec> => {
641
- if (args.length !== def.params.length) {
642
- throw new Error(`${def.name}:: Expected ${def.params.length} arguments, found ${args.length}`);
643
- }
644
-
645
- const bytes = registry.createType('Raw', u8aConcatStrict(
646
- args.map((a, i) => registry.createTypeUnsafe(def.params[i].type, [a]).toU8a())
647
- ));
648
-
649
- return stateCall(def.name, bytes).pipe(
650
- map((r) => registry.createTypeUnsafe(def.type, [r]))
651
- );
652
- });
653
-
654
- (decorated as AugmentedCall<ApiType>).meta = def;
655
-
656
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
657
- return decorated;
658
- }
659
-
660
- // only be called if supportMulti is true
661
- protected _decorateMulti<ApiType extends ApiTypes> (decorateMethod: DecorateMethod<ApiType>): QueryableStorageMulti<ApiType> {
662
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
663
- return decorateMethod((keys: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
664
- keys.length
665
- ? (this.hasSubscriptions
666
- ? this._rpcCore.state.subscribeStorage
667
- : this._rpcCore.state.queryStorageAt
668
- )(keys.map((args: QueryableStorageMultiArg<ApiType>): [StorageEntry, ...unknown[]] =>
669
- Array.isArray(args)
670
- ? args[0].creator.meta.type.isPlain
671
- ? [args[0].creator]
672
- : args[0].creator.meta.type.asMap.hashers.length === 1
673
- ? [args[0].creator, args.slice(1)]
674
- : [args[0].creator, ...args.slice(1)]
675
- : [args.creator]
676
- ))
677
- : of([])
678
- );
679
- }
680
-
681
- protected _decorateMultiAt<ApiType extends ApiTypes> (atApi: ApiDecoration<ApiType>, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array | string): QueryableStorageMulti<ApiType> {
682
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
683
- return decorateMethod((calls: QueryableStorageMultiArg<ApiType>[]): Observable<Codec[]> =>
684
- calls.length
685
- ? this._rpcCore.state.queryStorageAt(
686
- calls.map((args: QueryableStorageMultiArg<ApiType>) => {
687
- if (Array.isArray(args)) {
688
- const { creator } = getAtQueryFn(atApi, args[0].creator);
689
-
690
- return creator.meta.type.isPlain
691
- ? [creator]
692
- : creator.meta.type.asMap.hashers.length === 1
693
- ? [creator, args.slice(1)]
694
- : [creator, ...args.slice(1)];
695
- }
696
-
697
- return [getAtQueryFn(atApi, args.creator).creator];
698
- }),
699
- blockHash)
700
- : of([])
701
- );
702
- }
703
-
704
- protected _decorateExtrinsics<ApiType extends ApiTypes> ({ tx }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>): SubmittableExtrinsics<ApiType> {
705
- const result = createSubmittable(this._type, this._rx, decorateMethod) as SubmittableExtrinsics<ApiType>;
706
-
707
- const lazySection = (section: string) =>
708
- lazyMethods({}, Object.keys(tx[section]), (method: string) =>
709
- method.startsWith('$')
710
- ? tx[section][method]
711
- : this._decorateExtrinsicEntry(tx[section][method], result)
712
- );
713
-
714
- const sections = Object.keys(tx);
715
-
716
- for (let i = 0, count = sections.length; i < count; i++) {
717
- lazyMethod(result, sections[i], lazySection);
718
- }
719
-
720
- return result;
721
- }
722
-
723
- private _decorateExtrinsicEntry<ApiType extends ApiTypes> (method: CallFunction, creator: (value: Call | Uint8Array | string) => SubmittableExtrinsic<ApiType>): SubmittableExtrinsicFunction<ApiType> {
724
- const decorated = (...params: unknown[]): SubmittableExtrinsic<ApiType> =>
725
- creator(method(...params));
726
-
727
- // pass through the `.is`
728
- decorated.is = (other: IMethod<AnyTuple>) =>
729
- method.is(other);
730
-
731
- // eslint-disable-next-line @typescript-eslint/no-unsafe-return
732
- return this._decorateFunctionMeta(method as unknown as MetaDecoration, decorated as unknown as MetaDecoration) as unknown as SubmittableExtrinsicFunction<ApiType>;
733
- }
734
-
735
- protected _decorateStorage<ApiType extends ApiTypes> ({ query, registry }: DecoratedMeta, decorateMethod: DecorateMethod<ApiType>, blockHash?: Uint8Array): QueryableStorage<ApiType> {
736
- const result = {} as QueryableStorage<ApiType>;
737
-
738
- const lazySection = (section: string) =>
739
- lazyMethods({}, Object.keys(query[section]), (method: string) =>
740
- blockHash
741
- ? this._decorateStorageEntryAt(registry, query[section][method], decorateMethod, blockHash)
742
- : this._decorateStorageEntry(query[section][method], decorateMethod)
743
- );
744
-
745
- const sections = Object.keys(query);
746
-
747
- for (let i = 0, count = sections.length; i < count; i++) {
748
- lazyMethod(result, sections[i], lazySection);
749
- }
750
-
751
- return result;
752
- }
753
-
754
- private _decorateStorageEntry<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): QueryableStorageEntry<ApiType> {
755
- const getArgs = (args: unknown[], registry?: Registry) =>
756
- extractStorageArgs(registry || this.#registry, creator, args);
757
-
758
- const getQueryAt = (blockHash: Hash | Uint8Array | string): Observable<AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple>> =>
759
- from(this.at(blockHash)).pipe(
760
- map((api) => getAtQueryFn(api, creator)));
761
-
762
- // Disable this where it occurs for each field we are decorating
763
- /* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
764
-
765
- const decorated: AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple> & MetaDecoration = this._decorateStorageCall(creator, decorateMethod);
766
-
767
- decorated.creator = creator;
768
-
769
- // eslint-disable-next-line deprecation/deprecation
770
- decorated.at = decorateMethod((blockHash: Hash, ...args: unknown[]): Observable<Codec> =>
771
- getQueryAt(blockHash).pipe(
772
- switchMap((q) => q(...args))));
773
-
774
- decorated.hash = decorateMethod((...args: unknown[]): Observable<Hash> =>
775
- this._rpcCore.state.getStorageHash(getArgs(args)));
776
-
777
- decorated.is = <A extends AnyTuple> (key: IStorageKey<AnyTuple>): key is IStorageKey<A> =>
778
- key.section === creator.section &&
779
- key.method === creator.method;
780
-
781
- decorated.key = (...args: unknown[]): string =>
782
- u8aToHex(compactStripLength(creator(...args))[1]);
783
-
784
- decorated.keyPrefix = (...args: unknown[]): string =>
785
- u8aToHex(creator.keyPrefix(...args));
786
-
787
- decorated.size = decorateMethod((...args: unknown[]): Observable<u64> =>
788
- this._rpcCore.state.getStorageSize(getArgs(args)));
789
-
790
- // eslint-disable-next-line deprecation/deprecation
791
- decorated.sizeAt = decorateMethod((blockHash: Hash | Uint8Array | string, ...args: unknown[]): Observable<u64> =>
792
- getQueryAt(blockHash).pipe(
793
- switchMap((q) =>
794
- this._rpcCore.state.getStorageSize(getArgs(args, q.creator.meta.registry), blockHash))));
795
-
796
- // .keys() & .entries() only available on map types
797
- if (creator.iterKey && creator.meta.type.isMap) {
798
- decorated.entries = decorateMethod(
799
- memo(this.#instanceId, (...args: unknown[]): Observable<[StorageKey, Codec][]> =>
800
- this._retrieveMapEntries(creator, null, args)));
801
-
802
- // eslint-disable-next-line deprecation/deprecation
803
- decorated.entriesAt = decorateMethod(
804
- memo(this.#instanceId, (blockHash: Hash | Uint8Array | string, ...args: unknown[]): Observable<[StorageKey, Codec][]> =>
805
- getQueryAt(blockHash).pipe(
806
- switchMap((q) => this._retrieveMapEntries(q.creator, blockHash, args)))));
807
-
808
- decorated.entriesPaged = decorateMethod(
809
- memo(this.#instanceId, (opts: PaginationOptions): Observable<[StorageKey, Codec][]> =>
810
- this._retrieveMapEntriesPaged(creator, undefined, opts)));
811
-
812
- decorated.keys = decorateMethod(
813
- memo(this.#instanceId, (...args: unknown[]): Observable<StorageKey[]> =>
814
- this._retrieveMapKeys(creator, null, args)));
815
-
816
- // eslint-disable-next-line deprecation/deprecation
817
- decorated.keysAt = decorateMethod(
818
- memo(this.#instanceId, (blockHash: Hash | Uint8Array | string, ...args: unknown[]): Observable<StorageKey[]> =>
819
- getQueryAt(blockHash).pipe(
820
- switchMap((q) => this._retrieveMapKeys(q.creator, blockHash, args)))));
821
-
822
- decorated.keysPaged = decorateMethod(
823
- memo(this.#instanceId, (opts: PaginationOptions): Observable<StorageKey[]> =>
824
- this._retrieveMapKeysPaged(creator, undefined, opts)));
825
- }
826
-
827
- if (this.supportMulti && creator.meta.type.isMap) {
828
- // When using double map storage function, user need to pass double map key as an array
829
- decorated.multi = decorateMethod((args: unknown[]): Observable<Codec[]> =>
830
- creator.meta.type.asMap.hashers.length === 1
831
- ? this._retrieveMulti(args.map((a) => [creator, [a]]))
832
- : this._retrieveMulti(args.map((a) => [creator, a as unknown[]]))
833
- );
834
- }
835
-
836
- /* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
837
-
838
- return this._decorateFunctionMeta(creator as unknown as MetaDecoration, decorated) as unknown as QueryableStorageEntry<ApiType>;
839
- }
840
-
841
- private _decorateStorageEntryAt<ApiType extends ApiTypes> (registry: Registry, creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>, blockHash: Uint8Array): QueryableStorageEntryAt<ApiType> {
842
- const getArgs = (args: unknown[]): unknown[] => extractStorageArgs(registry, creator, args);
843
-
844
- // Disable this where it occurs for each field we are decorating
845
- /* eslint-disable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
846
-
847
- const decorated: AugmentedQuery<'rxjs', GenericStorageEntryFunction, AnyTuple> & MetaDecoration = decorateMethod((...args: unknown[]): Observable<Codec> =>
848
- this._rpcCore.state.getStorage(getArgs(args), blockHash));
849
-
850
- decorated.creator = creator;
851
-
852
- decorated.hash = decorateMethod((...args: unknown[]): Observable<Hash> =>
853
- this._rpcCore.state.getStorageHash(getArgs(args), blockHash));
854
-
855
- decorated.is = <A extends AnyTuple> (key: IStorageKey<AnyTuple>): key is IStorageKey<A> =>
856
- key.section === creator.section &&
857
- key.method === creator.method;
858
-
859
- decorated.key = (...args: unknown[]): string =>
860
- u8aToHex(compactStripLength(creator(...args))[1]);
861
-
862
- decorated.keyPrefix = (...keys: unknown[]): string =>
863
- u8aToHex(creator.keyPrefix(...keys));
864
-
865
- decorated.size = decorateMethod((...args: unknown[]): Observable<u64> =>
866
- this._rpcCore.state.getStorageSize(getArgs(args), blockHash));
867
-
868
- // .keys() & .entries() only available on map types
869
- if (creator.iterKey && creator.meta.type.isMap) {
870
- decorated.entries = decorateMethod(
871
- memo(this.#instanceId, (...args: unknown[]): Observable<[StorageKey, Codec][]> =>
872
- this._retrieveMapEntries(creator, blockHash, args)));
873
-
874
- decorated.entriesPaged = decorateMethod(
875
- memo(this.#instanceId, (opts: PaginationOptions): Observable<[StorageKey, Codec][]> =>
876
- this._retrieveMapEntriesPaged(creator, blockHash, opts)));
877
-
878
- decorated.keys = decorateMethod(
879
- memo(this.#instanceId, (...args: unknown[]): Observable<StorageKey[]> =>
880
- this._retrieveMapKeys(creator, blockHash, args)));
881
-
882
- decorated.keysPaged = decorateMethod(
883
- memo(this.#instanceId, (opts: PaginationOptions): Observable<StorageKey[]> =>
884
- this._retrieveMapKeysPaged(creator, blockHash, opts)));
885
- }
886
-
887
- if (this.supportMulti && creator.meta.type.isMap) {
888
- // When using double map storage function, user need to pass double map key as an array
889
- decorated.multi = decorateMethod((args: unknown[]): Observable<Codec[]> =>
890
- creator.meta.type.asMap.hashers.length === 1
891
- ? this._retrieveMulti(args.map((a) => [creator, [a]]), blockHash)
892
- : this._retrieveMulti(args.map((a) => [creator, a as unknown[]]), blockHash)
893
- );
894
- }
895
-
896
- /* eslint-enable @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-assignment */
897
-
898
- return this._decorateFunctionMeta(creator as unknown as MetaDecoration, decorated) as unknown as QueryableStorageEntry<ApiType>;
899
- }
900
-
901
- private _queueStorage (call: [StorageEntry, unknown[]], queue: [Observable<Codec[]>, [StorageEntry, unknown[]][]][]): Observable<Codec> {
902
- const query = queue === this.#storageSubQ
903
- ? this._rpcCore.state.subscribeStorage
904
- : this._rpcCore.state.queryStorageAt;
905
- let queueIdx = queue.length - 1;
906
- let valueIdx = 0;
907
- let valueObs: Observable<Codec[]>;
908
-
909
- // if we don't have queue entries yet,
910
- // or the current queue has fired (see from below),
911
- // or the current queue has the max entries,
912
- // then we create a new queue
913
- if (queueIdx === -1 || !queue[queueIdx] || queue[queueIdx][1].length === PAGE_SIZE_Q) {
914
- queueIdx++;
915
-
916
- valueObs = from(
917
- // we delay the execution until the next tick, this allows
918
- // any queries made in this timeframe to be added to the same
919
- // queue for a single query
920
- new Promise<[StorageEntry, unknown[]][]>((resolve): void => {
921
- nextTick((): void => {
922
- // get all the calls in this instance, resolve with it
923
- // and then clear the queue so we don't add more
924
- // (anything after this will be added to a new queue)
925
- const calls = queue[queueIdx][1];
926
-
927
- delete queue[queueIdx];
928
-
929
- resolve(calls);
930
- });
931
- })
932
- ).pipe(
933
- switchMap((calls) => query(calls))
934
- );
935
-
936
- queue.push([valueObs, [call]]);
937
- } else {
938
- valueObs = queue[queueIdx][0];
939
- valueIdx = queue[queueIdx][1].length;
940
-
941
- queue[queueIdx][1].push(call);
942
- }
943
-
944
- return valueObs.pipe(
945
- // return the single value at this index
946
- map((values) => values[valueIdx])
947
- );
948
- }
949
-
950
- // Decorate the base storage call. In the case or rxjs or promise-without-callback (await)
951
- // we make a subscription, alternatively we push this through a single-shot query
952
- private _decorateStorageCall<ApiType extends ApiTypes> (creator: StorageEntry, decorateMethod: DecorateMethod<ApiType>): ReturnType<DecorateMethod<ApiType>> {
953
- const memoed = memo(this.#instanceId, (...args: unknown[]): Observable<Codec> => {
954
- const call = extractStorageArgs(this.#registry, creator, args);
955
-
956
- if (!this.hasSubscriptions) {
957
- return this._rpcCore.state.getStorage(call);
958
- }
959
-
960
- return this._queueStorage(call, this.#storageSubQ);
961
- });
962
-
963
- return decorateMethod(memoed, {
964
- methodName: creator.method,
965
- overrideNoSub: (...args: unknown[]) =>
966
- this._queueStorage(extractStorageArgs(this.#registry, creator, args), this.#storageGetQ)
967
- });
968
- }
969
-
970
- // retrieve a set of values for a specific set of keys - here we chunk the keys into PAGE_SIZE sizes
971
- private _retrieveMulti (keys: [StorageEntry, unknown[]][], blockHash?: Uint8Array): Observable<Codec[]> {
972
- if (!keys.length) {
973
- return of([]);
974
- }
975
-
976
- const query = this.hasSubscriptions && !blockHash
977
- ? this._rpcCore.state.subscribeStorage
978
- : this._rpcCore.state.queryStorageAt;
979
-
980
- if (keys.length <= PAGE_SIZE_V) {
981
- return blockHash
982
- ? query(keys, blockHash)
983
- : query(keys);
984
- }
985
-
986
- return combineLatest(
987
- arrayChunk(keys, PAGE_SIZE_V).map((k) =>
988
- blockHash
989
- ? query(k, blockHash)
990
- : query(k)
991
- )
992
- ).pipe(
993
- map(arrayFlatten)
994
- );
995
- }
996
-
997
- private _retrieveMapKeys ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | null, args: unknown[]): Observable<StorageKey[]> {
998
- if (!iterKey || !meta.type.isMap) {
999
- throw new Error('keys can only be retrieved on maps');
1000
- }
1001
-
1002
- const headKey = iterKey(...args).toHex();
1003
- const startSubject = new BehaviorSubject<string>(headKey);
1004
- const query = at
1005
- ? (startKey: string) =>
1006
- this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey, at)
1007
- : (startKey: string) =>
1008
- this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey);
1009
- const setMeta = (key: StorageKey) => key.setMeta(meta, section, method);
1010
-
1011
- return startSubject.pipe(
1012
- switchMap(query),
1013
- map((keys) => keys.map(setMeta)),
1014
- tap((keys) =>
1015
- nextTick((): void => {
1016
- keys.length === PAGE_SIZE_K
1017
- ? startSubject.next(keys[PAGE_SIZE_K - 1].toHex())
1018
- : startSubject.complete();
1019
- })
1020
- ),
1021
- toArray(), // toArray since we want to startSubject to be completed
1022
- map(arrayFlatten)
1023
- );
1024
- }
1025
-
1026
- private _retrieveMapKeysPaged ({ iterKey, meta, method, section }: StorageEntry, at: Hash | Uint8Array | string | undefined, opts: PaginationOptions): Observable<StorageKey[]> {
1027
- if (!iterKey || !meta.type.isMap) {
1028
- throw new Error('keys can only be retrieved on maps');
1029
- }
1030
-
1031
- const setMeta = (key: StorageKey) => key.setMeta(meta, section, method);
1032
- const query = at
1033
- ? (headKey: string) =>
1034
- this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey, at)
1035
- : (headKey: string) =>
1036
- this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey);
1037
-
1038
- return query(iterKey(...opts.args).toHex()).pipe(
1039
- map((keys) => keys.map(setMeta))
1040
- );
1041
- }
1042
-
1043
- private _retrieveMapEntries (entry: StorageEntry, at: Hash | Uint8Array | string | null, args: unknown[]): Observable<[StorageKey, Codec][]> {
1044
- const query = at
1045
- ? (keys: StorageKey[]) =>
1046
- this._rpcCore.state.queryStorageAt(keys, at)
1047
- : (keys: StorageKey[]) =>
1048
- this._rpcCore.state.queryStorageAt(keys);
1049
-
1050
- return this._retrieveMapKeys(entry, at, args).pipe(
1051
- switchMap((keys) =>
1052
- keys.length
1053
- ? combineLatest(arrayChunk(keys, PAGE_SIZE_V).map(query)).pipe(
1054
- map((valsArr) =>
1055
- arrayFlatten(valsArr).map((value, index): [StorageKey, Codec] => [keys[index], value])
1056
- )
1057
- )
1058
- : of([])
1059
- )
1060
- );
1061
- }
1062
-
1063
- private _retrieveMapEntriesPaged (entry: StorageEntry, at: Hash | Uint8Array | string | undefined, opts: PaginationOptions): Observable<[StorageKey, Codec][]> {
1064
- const query = at
1065
- ? (keys: StorageKey[]) =>
1066
- this._rpcCore.state.queryStorageAt(keys, at)
1067
- : (keys: StorageKey[]) =>
1068
- this._rpcCore.state.queryStorageAt(keys);
1069
-
1070
- return this._retrieveMapKeysPaged(entry, at, opts).pipe(
1071
- switchMap((keys) =>
1072
- keys.length
1073
- ? query(keys).pipe(
1074
- map((valsArr) =>
1075
- valsArr.map((value, index): [StorageKey, Codec] => [keys[index], value])
1076
- )
1077
- )
1078
- : of([])
1079
- )
1080
- );
1081
- }
1082
-
1083
- protected _decorateDeriveRx (decorateMethod: DecorateMethod<ApiType>): AllDerives<'rxjs'> {
1084
- const specName = this._runtimeVersion?.specName.toString();
1085
-
1086
- // Pull in derive from api-derive
1087
- const available = getAvailableDerives(this.#instanceId, this._rx, objectSpread<DeriveCustom>({}, this._options.derives, this._options.typesBundle?.spec?.[specName || '']?.derives));
1088
-
1089
- return decorateDeriveSections<'rxjs'>(decorateMethod, available);
1090
- }
1091
-
1092
- protected _decorateDerive (decorateMethod: DecorateMethod<ApiType>): AllDerives<ApiType> {
1093
- return decorateDeriveSections<ApiType>(decorateMethod, this._rx.derive);
1094
- }
1095
-
1096
- /**
1097
- * Put the `this.onCall` function of ApiRx here, because it is needed by
1098
- * `api._rx`.
1099
- */
1100
- protected _rxDecorateMethod = <Method extends AnyFunction>(method: Method): Method => {
1101
- return method;
1102
- };
1103
- }