1 | import _classPrivateFieldLooseBase from "@babel/runtime/helpers/esm/classPrivateFieldLooseBase";
|
2 | import _classPrivateFieldLooseKey from "@babel/runtime/helpers/esm/classPrivateFieldLooseKey";
|
3 |
|
4 |
|
5 | import { firstValueFrom, map, of, switchMap } from 'rxjs';
|
6 | import { Metadata, TypeRegistry } from '@polkadot/types';
|
7 | import { getSpecAlias, getSpecExtensions, getSpecHasher, getSpecRpc, getSpecTypes, getUpgradeVersion } from '@polkadot/types-known';
|
8 | import { assert, assertReturn, BN_ZERO, isUndefined, logger, objectSpread, u8aEq, u8aToHex, u8aToU8a } from '@polkadot/util';
|
9 | import { cryptoWaitReady } from '@polkadot/util-crypto';
|
10 | import { Decorate } from "./Decorate.js";
|
11 | const KEEPALIVE_INTERVAL = 10000;
|
12 | const l = logger('api/init');
|
13 |
|
14 | function textToString(t) {
|
15 | return t.toString();
|
16 | }
|
17 |
|
18 | var _healthTimer = _classPrivateFieldLooseKey("healthTimer");
|
19 |
|
20 | var _registries = _classPrivateFieldLooseKey("registries");
|
21 |
|
22 | var _updateSub = _classPrivateFieldLooseKey("updateSub");
|
23 |
|
24 | var _waitingRegistries = _classPrivateFieldLooseKey("waitingRegistries");
|
25 |
|
26 | var _onProviderConnect = _classPrivateFieldLooseKey("onProviderConnect");
|
27 |
|
28 | var _onProviderDisconnect = _classPrivateFieldLooseKey("onProviderDisconnect");
|
29 |
|
30 | var _onProviderError = _classPrivateFieldLooseKey("onProviderError");
|
31 |
|
32 | export class Init extends Decorate {
|
33 | constructor(options, type, decorateMethod) {
|
34 | super(options, type, decorateMethod);
|
35 |
|
36 | Object.defineProperty(this, _onProviderError, {
|
37 | value: _onProviderError2
|
38 | });
|
39 | Object.defineProperty(this, _onProviderDisconnect, {
|
40 | value: _onProviderDisconnect2
|
41 | });
|
42 | Object.defineProperty(this, _onProviderConnect, {
|
43 | value: _onProviderConnect2
|
44 | });
|
45 | Object.defineProperty(this, _healthTimer, {
|
46 | writable: true,
|
47 | value: null
|
48 | });
|
49 | Object.defineProperty(this, _registries, {
|
50 | writable: true,
|
51 | value: []
|
52 | });
|
53 | Object.defineProperty(this, _updateSub, {
|
54 | writable: true,
|
55 | value: null
|
56 | });
|
57 | Object.defineProperty(this, _waitingRegistries, {
|
58 | writable: true,
|
59 | value: {}
|
60 | });
|
61 | this.registry.setKnownTypes(options);
|
62 |
|
63 |
|
64 |
|
65 | if (!options.source) {
|
66 | this.registerTypes(options.types);
|
67 | } else {
|
68 | _classPrivateFieldLooseBase(this, _registries)[_registries] = _classPrivateFieldLooseBase(options.source, _registries)[_registries];
|
69 | }
|
70 |
|
71 | this._rpc = this._decorateRpc(this._rpcCore, this._decorateMethod);
|
72 | this._rx.rpc = this._decorateRpc(this._rpcCore, this._rxDecorateMethod);
|
73 |
|
74 | if (this.supportMulti) {
|
75 | this._queryMulti = this._decorateMulti(this._decorateMethod);
|
76 | this._rx.queryMulti = this._decorateMulti(this._rxDecorateMethod);
|
77 | }
|
78 |
|
79 | this._rx.signer = options.signer;
|
80 |
|
81 | this._rpcCore.setRegistrySwap(blockHash => this.getBlockRegistry(blockHash));
|
82 |
|
83 | this._rpcCore.setResolveBlockHash(blockNumber => firstValueFrom(this._rpcCore.chain.getBlockHash(blockNumber)));
|
84 |
|
85 | if (this.hasSubscriptions) {
|
86 | this._rpcCore.provider.on('disconnected', () => _classPrivateFieldLooseBase(this, _onProviderDisconnect)[_onProviderDisconnect]());
|
87 |
|
88 | this._rpcCore.provider.on('error', e => _classPrivateFieldLooseBase(this, _onProviderError)[_onProviderError](e));
|
89 |
|
90 | this._rpcCore.provider.on('connected', () => _classPrivateFieldLooseBase(this, _onProviderConnect)[_onProviderConnect]());
|
91 | } else {
|
92 | l.warn('Api will be available in a limited mode since the provider does not support subscriptions');
|
93 | }
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | if (this._rpcCore.provider.isConnected) {
|
99 |
|
100 | _classPrivateFieldLooseBase(this, _onProviderConnect)[_onProviderConnect]();
|
101 | }
|
102 | }
|
103 | |
104 |
|
105 |
|
106 |
|
107 |
|
108 | _initRegistry(registry, chain, version, metadata, chainProps) {
|
109 | registry.clearCache();
|
110 | registry.setChainProperties(chainProps || this.registry.getChainProperties());
|
111 | registry.setKnownTypes(this._options);
|
112 | registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
|
113 | registry.setHasher(getSpecHasher(registry, chain, version.specName));
|
114 |
|
115 | if (registry.knownTypes.typesBundle) {
|
116 | registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
|
117 | }
|
118 |
|
119 | registry.setMetadata(metadata, undefined, objectSpread({}, getSpecExtensions(registry, chain, version.specName), this._options.signedExtensions));
|
120 | }
|
121 | |
122 |
|
123 |
|
124 |
|
125 |
|
126 | _getDefaultRegistry() {
|
127 | return assertReturn(_classPrivateFieldLooseBase(this, _registries)[_registries].find(({
|
128 | isDefault
|
129 | }) => isDefault), 'Initialization error, cannot find the default registry');
|
130 | }
|
131 | |
132 |
|
133 |
|
134 |
|
135 |
|
136 | async at(blockHash, knownVersion) {
|
137 | const u8aHash = u8aToU8a(blockHash);
|
138 | const registry = await this.getBlockRegistry(u8aHash, knownVersion);
|
139 |
|
140 |
|
141 | return this._createDecorated(registry, true, null, u8aHash).decoratedApi;
|
142 | }
|
143 |
|
144 | async _createBlockRegistry(blockHash, header, version) {
|
145 | const registry = new TypeRegistry(blockHash);
|
146 | const metadata = new Metadata(registry, await firstValueFrom(this._rpcCore.state.getMetadata.raw(header.parentHash)));
|
147 |
|
148 | this._initRegistry(registry, this._runtimeChain, version, metadata);
|
149 |
|
150 |
|
151 | const result = {
|
152 | lastBlockHash: blockHash,
|
153 | metadata,
|
154 | registry,
|
155 | specName: version.specName,
|
156 | specVersion: version.specVersion
|
157 | };
|
158 |
|
159 | _classPrivateFieldLooseBase(this, _registries)[_registries].push(result);
|
160 |
|
161 | return result;
|
162 | }
|
163 |
|
164 | _cacheBlockRegistryProgress(key, creator) {
|
165 |
|
166 | let waiting = _classPrivateFieldLooseBase(this, _waitingRegistries)[_waitingRegistries][key];
|
167 |
|
168 | if (isUndefined(waiting)) {
|
169 |
|
170 | waiting = _classPrivateFieldLooseBase(this, _waitingRegistries)[_waitingRegistries][key] = new Promise((resolve, reject) => {
|
171 | creator().then(registry => {
|
172 | delete _classPrivateFieldLooseBase(this, _waitingRegistries)[_waitingRegistries][key];
|
173 | resolve(registry);
|
174 | }).catch(error => {
|
175 | delete _classPrivateFieldLooseBase(this, _waitingRegistries)[_waitingRegistries][key];
|
176 | reject(error);
|
177 | });
|
178 | });
|
179 | }
|
180 |
|
181 | return waiting;
|
182 | }
|
183 |
|
184 | _getBlockRegistryViaVersion(blockHash, version) {
|
185 | if (version) {
|
186 |
|
187 |
|
188 | const existingViaVersion = _classPrivateFieldLooseBase(this, _registries)[_registries].find(({
|
189 | specName,
|
190 | specVersion
|
191 | }) => specName.eq(version.specName) && specVersion.eq(version.specVersion));
|
192 |
|
193 | if (existingViaVersion) {
|
194 | existingViaVersion.lastBlockHash = blockHash;
|
195 | return existingViaVersion;
|
196 | }
|
197 | }
|
198 |
|
199 | return null;
|
200 | }
|
201 |
|
202 | async _getBlockRegistryViaHash(blockHash) {
|
203 |
|
204 | assert(this._genesisHash && this._runtimeVersion, 'Cannot retrieve data on an uninitialized chain');
|
205 |
|
206 |
|
207 | const header = this.registry.createType('HeaderPartial', this._genesisHash.eq(blockHash) ? {
|
208 | number: BN_ZERO,
|
209 | parentHash: this._genesisHash
|
210 | } : await firstValueFrom(this._rpcCore.chain.getHeader.raw(blockHash)));
|
211 | assert(!header.parentHash.isEmpty, 'Unable to retrieve header and parent from supplied hash');
|
212 |
|
213 | const [firstVersion, lastVersion] = getUpgradeVersion(this._genesisHash, header.number);
|
214 | const version = this.registry.createType('RuntimeVersionPartial', firstVersion && (lastVersion || firstVersion.specVersion.eq(this._runtimeVersion.specVersion)) ? {
|
215 | specName: this._runtimeVersion.specName,
|
216 | specVersion: firstVersion.specVersion
|
217 | } : await firstValueFrom(this._rpcCore.state.getRuntimeVersion.raw(header.parentHash)));
|
218 | return (
|
219 | this._getBlockRegistryViaVersion(blockHash, version) || (
|
220 | await this._cacheBlockRegistryProgress(version.toHex(), () => this._createBlockRegistry(blockHash, header, version)))
|
221 | );
|
222 | }
|
223 | |
224 |
|
225 |
|
226 |
|
227 |
|
228 | async getBlockRegistry(blockHash, knownVersion) {
|
229 | return (
|
230 | _classPrivateFieldLooseBase(this, _registries)[_registries].find(({
|
231 | lastBlockHash
|
232 | }) => lastBlockHash && u8aEq(lastBlockHash, blockHash)) ||
|
233 | this._getBlockRegistryViaVersion(blockHash, knownVersion) || (
|
234 | await this._cacheBlockRegistryProgress(u8aToHex(blockHash), () => this._getBlockRegistryViaHash(blockHash)))
|
235 | );
|
236 | }
|
237 |
|
238 | async _loadMeta() {
|
239 | var _this$_options$source;
|
240 |
|
241 |
|
242 | if (this._isReady) {
|
243 | return true;
|
244 | }
|
245 |
|
246 | this._unsubscribeUpdates();
|
247 |
|
248 |
|
249 |
|
250 | [this._genesisHash, this._runtimeMetadata] = (_this$_options$source = this._options.source) !== null && _this$_options$source !== void 0 && _this$_options$source._isReady ? await this._metaFromSource(this._options.source) : await this._metaFromChain(this._options.metadata);
|
251 | return this._initFromMeta(this._runtimeMetadata);
|
252 | }
|
253 |
|
254 |
|
255 | async _metaFromSource(source) {
|
256 | this._extrinsicType = source.extrinsicVersion;
|
257 | this._runtimeChain = source.runtimeChain;
|
258 | this._runtimeVersion = source.runtimeVersion;
|
259 |
|
260 |
|
261 | const sections = Object.keys(source.rpc);
|
262 | const rpcs = [];
|
263 |
|
264 | for (let s = 0; s < sections.length; s++) {
|
265 | const section = sections[s];
|
266 | const methods = Object.keys(source.rpc[section]);
|
267 |
|
268 | for (let m = 0; m < methods.length; m++) {
|
269 | rpcs.push(`${section}_${methods[m]}`);
|
270 | }
|
271 | }
|
272 |
|
273 | this._filterRpc(rpcs, getSpecRpc(this.registry, source.runtimeChain, source.runtimeVersion.specName));
|
274 |
|
275 | return [source.genesisHash, source.runtimeMetadata];
|
276 | }
|
277 |
|
278 |
|
279 | _subscribeUpdates() {
|
280 | if (_classPrivateFieldLooseBase(this, _updateSub)[_updateSub] || !this.hasSubscriptions) {
|
281 | return;
|
282 | }
|
283 |
|
284 | _classPrivateFieldLooseBase(this, _updateSub)[_updateSub] = this._rpcCore.state.subscribeRuntimeVersion().pipe(switchMap(version => {
|
285 | var _this$_runtimeVersion;
|
286 |
|
287 | return (
|
288 | (_this$_runtimeVersion = this._runtimeVersion) !== null && _this$_runtimeVersion !== void 0 && _this$_runtimeVersion.specVersion.eq(version.specVersion) ? of(false) : this._rpcCore.state.getMetadata().pipe(map(metadata => {
|
289 | l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
|
290 | this._runtimeMetadata = metadata;
|
291 | this._runtimeVersion = version;
|
292 | this._rx.runtimeVersion = version;
|
293 |
|
294 | const thisRegistry = this._getDefaultRegistry();
|
295 |
|
296 |
|
297 | thisRegistry.metadata = metadata;
|
298 | thisRegistry.specVersion = version.specVersion;
|
299 |
|
300 | this._initRegistry(this.registry, this._runtimeChain, version, metadata);
|
301 |
|
302 | this._injectMetadata(thisRegistry, true);
|
303 |
|
304 | return true;
|
305 | }))
|
306 | );
|
307 | })).subscribe();
|
308 | }
|
309 |
|
310 | async _metaFromChain(optMetadata) {
|
311 | const [genesisHash, runtimeVersion, chain, chainProps, rpcMethods, chainMetadata] = await Promise.all([firstValueFrom(this._rpcCore.chain.getBlockHash(0)), firstValueFrom(this._rpcCore.state.getRuntimeVersion()), firstValueFrom(this._rpcCore.system.chain()), firstValueFrom(this._rpcCore.system.properties()), firstValueFrom(this._rpcCore.rpc.methods()), optMetadata ? Promise.resolve(null) : firstValueFrom(this._rpcCore.state.getMetadata())]);
|
312 |
|
313 | this._runtimeChain = chain;
|
314 | this._runtimeVersion = runtimeVersion;
|
315 | this._rx.runtimeVersion = runtimeVersion;
|
316 |
|
317 | const metadataKey = `${genesisHash.toHex() || '0x'}-${runtimeVersion.specVersion.toString()}`;
|
318 | const metadata = chainMetadata || (optMetadata && optMetadata[metadataKey] ? new Metadata(this.registry, optMetadata[metadataKey]) : await firstValueFrom(this._rpcCore.state.getMetadata()));
|
319 |
|
320 | this._initRegistry(this.registry, chain, runtimeVersion, metadata, chainProps);
|
321 |
|
322 | this._filterRpc(rpcMethods.methods.map(textToString), getSpecRpc(this.registry, chain, runtimeVersion.specName));
|
323 |
|
324 | this._subscribeUpdates();
|
325 |
|
326 |
|
327 | if (!_classPrivateFieldLooseBase(this, _registries)[_registries].length) {
|
328 | _classPrivateFieldLooseBase(this, _registries)[_registries].push({
|
329 | isDefault: true,
|
330 | metadata,
|
331 | registry: this.registry,
|
332 | specName: runtimeVersion.specName,
|
333 | specVersion: runtimeVersion.specVersion
|
334 | });
|
335 | }
|
336 |
|
337 |
|
338 | metadata.getUniqTypes(this._options.throwOnUnknown || false);
|
339 | return [genesisHash, metadata];
|
340 | }
|
341 |
|
342 | _initFromMeta(metadata) {
|
343 | this._extrinsicType = metadata.asLatest.extrinsic.version.toNumber();
|
344 | this._rx.extrinsicType = this._extrinsicType;
|
345 | this._rx.genesisHash = this._genesisHash;
|
346 | this._rx.runtimeVersion = this._runtimeVersion;
|
347 |
|
348 |
|
349 | this._injectMetadata(this._getDefaultRegistry(), true);
|
350 |
|
351 |
|
352 | this._rx.derive = this._decorateDeriveRx(this._rxDecorateMethod);
|
353 | this._derive = this._decorateDerive(this._decorateMethod);
|
354 | return true;
|
355 | }
|
356 |
|
357 | _subscribeHealth() {
|
358 |
|
359 | _classPrivateFieldLooseBase(this, _healthTimer)[_healthTimer] = this.hasSubscriptions ? setInterval(() => {
|
360 | firstValueFrom(this._rpcCore.system.health()).catch(() => undefined);
|
361 | }, KEEPALIVE_INTERVAL) : null;
|
362 | }
|
363 |
|
364 | _unsubscribeHealth() {
|
365 | if (_classPrivateFieldLooseBase(this, _healthTimer)[_healthTimer]) {
|
366 | clearInterval(_classPrivateFieldLooseBase(this, _healthTimer)[_healthTimer]);
|
367 | _classPrivateFieldLooseBase(this, _healthTimer)[_healthTimer] = null;
|
368 | }
|
369 | }
|
370 |
|
371 | _unsubscribeUpdates() {
|
372 | if (_classPrivateFieldLooseBase(this, _updateSub)[_updateSub]) {
|
373 | _classPrivateFieldLooseBase(this, _updateSub)[_updateSub].unsubscribe();
|
374 |
|
375 | _classPrivateFieldLooseBase(this, _updateSub)[_updateSub] = null;
|
376 | }
|
377 | }
|
378 |
|
379 | _unsubscribe() {
|
380 | this._unsubscribeHealth();
|
381 |
|
382 | this._unsubscribeUpdates();
|
383 | }
|
384 |
|
385 | }
|
386 |
|
387 | async function _onProviderConnect2() {
|
388 | this._isConnected.next(true);
|
389 |
|
390 | this.emit('connected');
|
391 |
|
392 | try {
|
393 | const cryptoReady = this._options.initWasm === false ? true : await cryptoWaitReady();
|
394 | const hasMeta = await this._loadMeta();
|
395 |
|
396 | this._subscribeHealth();
|
397 |
|
398 | if (hasMeta && !this._isReady && cryptoReady) {
|
399 | this._isReady = true;
|
400 | this.emit('ready', this);
|
401 | }
|
402 | } catch (_error) {
|
403 | const error = new Error(`FATAL: Unable to initialize the API: ${_error.message}`);
|
404 | l.error(error);
|
405 | this.emit('error', error);
|
406 | }
|
407 | }
|
408 |
|
409 | function _onProviderDisconnect2() {
|
410 | this._isConnected.next(false);
|
411 |
|
412 | this._unsubscribeHealth();
|
413 |
|
414 | this.emit('disconnected');
|
415 | }
|
416 |
|
417 | function _onProviderError2(error) {
|
418 | this.emit('error', error);
|
419 | } |
\ | No newline at end of file |