UNPKG

345 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@polkadot/keyring'), require('@polkadot/util'), require('@polkadot/types'), require('@polkadot/util-crypto')) :
3 typeof define === 'function' && define.amd ? define(['exports', '@polkadot/keyring', '@polkadot/util', '@polkadot/types', '@polkadot/util-crypto'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.polkadotApi = {}, global.polkadotKeyring, global.polkadotUtil, global.polkadotTypes, global.polkadotUtilCrypto));
5})(this, (function (exports, keyring, util, types, utilCrypto) { 'use strict';
6
7 const global = window;
8
9 function _classPrivateFieldBase(receiver, privateKey) {
10 if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
11 throw new TypeError("attempted to use private field on non-instance");
12 }
13 return receiver;
14 }
15
16 var id = 0;
17 function _classPrivateFieldKey(name) {
18 return "__private_" + id++ + "_" + name;
19 }
20
21 ({
22 name: '@polkadot/x-global',
23 path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto',
24 type: 'esm',
25 version: '9.6.2'
26 });
27
28 function evaluateThis(fn) {
29 return fn('return this');
30 }
31 const xglobal = typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : evaluateThis(Function);
32
33 ({
34 name: '@polkadot/x-fetch',
35 path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto',
36 type: 'esm',
37 version: '9.6.2'
38 });
39
40 const fetch = xglobal.fetch;
41
42 function isFunction$1(value) {
43 return typeof value === 'function';
44 }
45
46 const UNKNOWN = -99999;
47 function extend(that, name, value) {
48 Object.defineProperty(that, name, {
49 configurable: true,
50 enumerable: false,
51 value
52 });
53 }
54 class RpcError extends Error {
55 constructor(message = '', code = UNKNOWN, data) {
56 super();
57 extend(this, 'message', String(message));
58 extend(this, 'name', this.constructor.name);
59 extend(this, 'data', data);
60 extend(this, 'code', code);
61 if (isFunction$1(Error.captureStackTrace)) {
62 Error.captureStackTrace(this, this.constructor);
63 } else {
64 const {
65 stack
66 } = new Error(message);
67 stack && extend(this, 'stack', stack);
68 }
69 }
70 static CODES = {
71 ASSERT: -90009,
72 INVALID_JSONRPC: -99998,
73 METHOD_NOT_FOUND: -32601,
74 UNKNOWN
75 };
76 }
77
78 function formatErrorData(data) {
79 if (util.isUndefined(data)) {
80 return '';
81 }
82 const formatted = `: ${util.isString(data) ? data.replace(/Error\("/g, '').replace(/\("/g, '(').replace(/"\)/g, ')').replace(/\(/g, ', ').replace(/\)/g, '') : util.stringify(data)}`;
83 return formatted.length <= 256 ? formatted : `${formatted.substring(0, 255)}…`;
84 }
85 function checkError(error) {
86 if (error) {
87 const {
88 code,
89 data,
90 message
91 } = error;
92 throw new RpcError(`${code}: ${message}${formatErrorData(data)}`, code, data);
93 }
94 }
95 class RpcCoder {
96 #id = 0;
97 decodeResponse(response) {
98 if (!response || response.jsonrpc !== '2.0') {
99 throw new Error('Invalid jsonrpc field in decoded object');
100 }
101 const isSubscription = !util.isUndefined(response.params) && !util.isUndefined(response.method);
102 if (!util.isNumber(response.id) && (!isSubscription || !util.isNumber(response.params.subscription) && !util.isString(response.params.subscription))) {
103 throw new Error('Invalid id field in decoded object');
104 }
105 checkError(response.error);
106 if (response.result === undefined && !isSubscription) {
107 throw new Error('No result found in jsonrpc response');
108 }
109 if (isSubscription) {
110 checkError(response.params.error);
111 return response.params.result;
112 }
113 return response.result;
114 }
115 encodeJson(method, params) {
116 const [id, data] = this.encodeObject(method, params);
117 return [id, util.stringify(data)];
118 }
119 encodeObject(method, params) {
120 const id = ++this.#id;
121 return [id, {
122 id,
123 jsonrpc: '2.0',
124 method,
125 params
126 }];
127 }
128 }
129
130 const HTTP_URL = 'http://127.0.0.1:9933';
131 const WS_URL = 'ws://127.0.0.1:9944';
132 const defaults = {
133 HTTP_URL,
134 WS_URL
135 };
136
137 const DEFAULT_CAPACITY = 128;
138 class LRUNode {
139 constructor(key) {
140 this.key = key;
141 this.next = this.prev = this;
142 }
143 }
144 var _data = _classPrivateFieldKey("data");
145 var _refs = _classPrivateFieldKey("refs");
146 var _length = _classPrivateFieldKey("length");
147 var _head = _classPrivateFieldKey("head");
148 var _tail = _classPrivateFieldKey("tail");
149 var _toHead = _classPrivateFieldKey("toHead");
150 class LRUCache {
151 constructor(capacity = DEFAULT_CAPACITY) {
152 Object.defineProperty(this, _toHead, {
153 value: _toHead2
154 });
155 this.capacity = void 0;
156 Object.defineProperty(this, _data, {
157 writable: true,
158 value: new Map()
159 });
160 Object.defineProperty(this, _refs, {
161 writable: true,
162 value: new Map()
163 });
164 Object.defineProperty(this, _length, {
165 writable: true,
166 value: 0
167 });
168 Object.defineProperty(this, _head, {
169 writable: true,
170 value: void 0
171 });
172 Object.defineProperty(this, _tail, {
173 writable: true,
174 value: void 0
175 });
176 this.capacity = capacity;
177 _classPrivateFieldBase(this, _head)[_head] = _classPrivateFieldBase(this, _tail)[_tail] = new LRUNode('<empty>');
178 }
179 get length() {
180 return _classPrivateFieldBase(this, _length)[_length];
181 }
182 get lengthData() {
183 return _classPrivateFieldBase(this, _data)[_data].size;
184 }
185 get lengthRefs() {
186 return _classPrivateFieldBase(this, _refs)[_refs].size;
187 }
188 entries() {
189 const keys = this.keys();
190 const entries = new Array(keys.length);
191 for (let i = 0; i < keys.length; i++) {
192 const key = keys[i];
193 entries[i] = [key, _classPrivateFieldBase(this, _data)[_data].get(key)];
194 }
195 return entries;
196 }
197 keys() {
198 const keys = [];
199 if (_classPrivateFieldBase(this, _length)[_length]) {
200 let curr = _classPrivateFieldBase(this, _head)[_head];
201 while (curr !== _classPrivateFieldBase(this, _tail)[_tail]) {
202 keys.push(curr.key);
203 curr = curr.next;
204 }
205 keys.push(curr.key);
206 }
207 return keys;
208 }
209 get(key) {
210 const data = _classPrivateFieldBase(this, _data)[_data].get(key);
211 if (data) {
212 _classPrivateFieldBase(this, _toHead)[_toHead](key);
213 return data;
214 }
215 return null;
216 }
217 set(key, value) {
218 if (_classPrivateFieldBase(this, _data)[_data].has(key)) {
219 _classPrivateFieldBase(this, _toHead)[_toHead](key);
220 } else {
221 const node = new LRUNode(key);
222 _classPrivateFieldBase(this, _refs)[_refs].set(node.key, node);
223 if (this.length === 0) {
224 _classPrivateFieldBase(this, _head)[_head] = _classPrivateFieldBase(this, _tail)[_tail] = node;
225 } else {
226 _classPrivateFieldBase(this, _head)[_head].prev = node;
227 node.next = _classPrivateFieldBase(this, _head)[_head];
228 _classPrivateFieldBase(this, _head)[_head] = node;
229 }
230 if (_classPrivateFieldBase(this, _length)[_length] === this.capacity) {
231 _classPrivateFieldBase(this, _data)[_data].delete(_classPrivateFieldBase(this, _tail)[_tail].key);
232 _classPrivateFieldBase(this, _refs)[_refs].delete(_classPrivateFieldBase(this, _tail)[_tail].key);
233 _classPrivateFieldBase(this, _tail)[_tail] = _classPrivateFieldBase(this, _tail)[_tail].prev;
234 _classPrivateFieldBase(this, _tail)[_tail].next = _classPrivateFieldBase(this, _head)[_head];
235 } else {
236 _classPrivateFieldBase(this, _length)[_length] += 1;
237 }
238 }
239 _classPrivateFieldBase(this, _data)[_data].set(key, value);
240 }
241 }
242 function _toHead2(key) {
243 const ref = _classPrivateFieldBase(this, _refs)[_refs].get(key);
244 if (ref && ref !== _classPrivateFieldBase(this, _head)[_head]) {
245 ref.prev.next = ref.next;
246 ref.next.prev = ref.prev;
247 ref.next = _classPrivateFieldBase(this, _head)[_head];
248 _classPrivateFieldBase(this, _head)[_head].prev = ref;
249 _classPrivateFieldBase(this, _head)[_head] = ref;
250 }
251 }
252
253 const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
254 const l$7 = util.logger('api-http');
255 var _callCache$1 = _classPrivateFieldKey("callCache");
256 var _coder$1 = _classPrivateFieldKey("coder");
257 var _endpoint = _classPrivateFieldKey("endpoint");
258 var _headers$1 = _classPrivateFieldKey("headers");
259 var _stats$1 = _classPrivateFieldKey("stats");
260 var _send$1 = _classPrivateFieldKey("send");
261 class HttpProvider {
262 constructor(endpoint = defaults.HTTP_URL, headers = {}) {
263 Object.defineProperty(this, _send$1, {
264 value: _send2$1
265 });
266 Object.defineProperty(this, _callCache$1, {
267 writable: true,
268 value: new LRUCache()
269 });
270 Object.defineProperty(this, _coder$1, {
271 writable: true,
272 value: void 0
273 });
274 Object.defineProperty(this, _endpoint, {
275 writable: true,
276 value: void 0
277 });
278 Object.defineProperty(this, _headers$1, {
279 writable: true,
280 value: void 0
281 });
282 Object.defineProperty(this, _stats$1, {
283 writable: true,
284 value: void 0
285 });
286 if (!/^(https|http):\/\//.test(endpoint)) {
287 throw new Error(`Endpoint should start with 'http://' or 'https://', received '${endpoint}'`);
288 }
289 _classPrivateFieldBase(this, _coder$1)[_coder$1] = new RpcCoder();
290 _classPrivateFieldBase(this, _endpoint)[_endpoint] = endpoint;
291 _classPrivateFieldBase(this, _headers$1)[_headers$1] = headers;
292 _classPrivateFieldBase(this, _stats$1)[_stats$1] = {
293 active: {
294 requests: 0,
295 subscriptions: 0
296 },
297 total: {
298 bytesRecv: 0,
299 bytesSent: 0,
300 cached: 0,
301 errors: 0,
302 requests: 0,
303 subscriptions: 0,
304 timeout: 0
305 }
306 };
307 }
308 get hasSubscriptions() {
309 return false;
310 }
311 clone() {
312 return new HttpProvider(_classPrivateFieldBase(this, _endpoint)[_endpoint], _classPrivateFieldBase(this, _headers$1)[_headers$1]);
313 }
314 async connect() {
315 }
316 async disconnect() {
317 }
318 get stats() {
319 return _classPrivateFieldBase(this, _stats$1)[_stats$1];
320 }
321 get isConnected() {
322 return true;
323 }
324 on(type, sub) {
325 l$7.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
326 return () => {
327 };
328 }
329 async send(method, params, isCacheable) {
330 _classPrivateFieldBase(this, _stats$1)[_stats$1].total.requests++;
331 const [, body] = _classPrivateFieldBase(this, _coder$1)[_coder$1].encodeJson(method, params);
332 let resultPromise = isCacheable ? _classPrivateFieldBase(this, _callCache$1)[_callCache$1].get(body) : null;
333 if (!resultPromise) {
334 resultPromise = _classPrivateFieldBase(this, _send$1)[_send$1](body);
335 if (isCacheable) {
336 _classPrivateFieldBase(this, _callCache$1)[_callCache$1].set(body, resultPromise);
337 }
338 } else {
339 _classPrivateFieldBase(this, _stats$1)[_stats$1].total.cached++;
340 }
341 return resultPromise;
342 }
343 async subscribe(types, method, params, cb) {
344 l$7.error(ERROR_SUBSCRIBE);
345 throw new Error(ERROR_SUBSCRIBE);
346 }
347 async unsubscribe(type, method, id) {
348 l$7.error(ERROR_SUBSCRIBE);
349 throw new Error(ERROR_SUBSCRIBE);
350 }
351 }
352 async function _send2$1(body) {
353 _classPrivateFieldBase(this, _stats$1)[_stats$1].active.requests++;
354 _classPrivateFieldBase(this, _stats$1)[_stats$1].total.bytesSent += body.length;
355 try {
356 const response = await fetch(_classPrivateFieldBase(this, _endpoint)[_endpoint], {
357 body,
358 headers: {
359 Accept: 'application/json',
360 'Content-Length': `${body.length}`,
361 'Content-Type': 'application/json',
362 ..._classPrivateFieldBase(this, _headers$1)[_headers$1]
363 },
364 method: 'POST'
365 });
366 if (!response.ok) {
367 throw new Error(`[${response.status}]: ${response.statusText}`);
368 }
369 const result = await response.text();
370 _classPrivateFieldBase(this, _stats$1)[_stats$1].total.bytesRecv += result.length;
371 const decoded = _classPrivateFieldBase(this, _coder$1)[_coder$1].decodeResponse(JSON.parse(result));
372 _classPrivateFieldBase(this, _stats$1)[_stats$1].active.requests--;
373 return decoded;
374 } catch (e) {
375 _classPrivateFieldBase(this, _stats$1)[_stats$1].active.requests--;
376 _classPrivateFieldBase(this, _stats$1)[_stats$1].total.errors++;
377 throw e;
378 }
379 }
380
381 var eventemitter3 = {exports: {}};
382
383 (function (module) {
384 var has = Object.prototype.hasOwnProperty
385 , prefix = '~';
386 function Events() {}
387 if (Object.create) {
388 Events.prototype = Object.create(null);
389 if (!new Events().__proto__) prefix = false;
390 }
391 function EE(fn, context, once) {
392 this.fn = fn;
393 this.context = context;
394 this.once = once || false;
395 }
396 function addListener(emitter, event, fn, context, once) {
397 if (typeof fn !== 'function') {
398 throw new TypeError('The listener must be a function');
399 }
400 var listener = new EE(fn, context || emitter, once)
401 , evt = prefix ? prefix + event : event;
402 if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
403 else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
404 else emitter._events[evt] = [emitter._events[evt], listener];
405 return emitter;
406 }
407 function clearEvent(emitter, evt) {
408 if (--emitter._eventsCount === 0) emitter._events = new Events();
409 else delete emitter._events[evt];
410 }
411 function EventEmitter() {
412 this._events = new Events();
413 this._eventsCount = 0;
414 }
415 EventEmitter.prototype.eventNames = function eventNames() {
416 var names = []
417 , events
418 , name;
419 if (this._eventsCount === 0) return names;
420 for (name in (events = this._events)) {
421 if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
422 }
423 if (Object.getOwnPropertySymbols) {
424 return names.concat(Object.getOwnPropertySymbols(events));
425 }
426 return names;
427 };
428 EventEmitter.prototype.listeners = function listeners(event) {
429 var evt = prefix ? prefix + event : event
430 , handlers = this._events[evt];
431 if (!handlers) return [];
432 if (handlers.fn) return [handlers.fn];
433 for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
434 ee[i] = handlers[i].fn;
435 }
436 return ee;
437 };
438 EventEmitter.prototype.listenerCount = function listenerCount(event) {
439 var evt = prefix ? prefix + event : event
440 , listeners = this._events[evt];
441 if (!listeners) return 0;
442 if (listeners.fn) return 1;
443 return listeners.length;
444 };
445 EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
446 var evt = prefix ? prefix + event : event;
447 if (!this._events[evt]) return false;
448 var listeners = this._events[evt]
449 , len = arguments.length
450 , args
451 , i;
452 if (listeners.fn) {
453 if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
454 switch (len) {
455 case 1: return listeners.fn.call(listeners.context), true;
456 case 2: return listeners.fn.call(listeners.context, a1), true;
457 case 3: return listeners.fn.call(listeners.context, a1, a2), true;
458 case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
459 case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
460 case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
461 }
462 for (i = 1, args = new Array(len -1); i < len; i++) {
463 args[i - 1] = arguments[i];
464 }
465 listeners.fn.apply(listeners.context, args);
466 } else {
467 var length = listeners.length
468 , j;
469 for (i = 0; i < length; i++) {
470 if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
471 switch (len) {
472 case 1: listeners[i].fn.call(listeners[i].context); break;
473 case 2: listeners[i].fn.call(listeners[i].context, a1); break;
474 case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
475 case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
476 default:
477 if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
478 args[j - 1] = arguments[j];
479 }
480 listeners[i].fn.apply(listeners[i].context, args);
481 }
482 }
483 }
484 return true;
485 };
486 EventEmitter.prototype.on = function on(event, fn, context) {
487 return addListener(this, event, fn, context, false);
488 };
489 EventEmitter.prototype.once = function once(event, fn, context) {
490 return addListener(this, event, fn, context, true);
491 };
492 EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
493 var evt = prefix ? prefix + event : event;
494 if (!this._events[evt]) return this;
495 if (!fn) {
496 clearEvent(this, evt);
497 return this;
498 }
499 var listeners = this._events[evt];
500 if (listeners.fn) {
501 if (
502 listeners.fn === fn &&
503 (!once || listeners.once) &&
504 (!context || listeners.context === context)
505 ) {
506 clearEvent(this, evt);
507 }
508 } else {
509 for (var i = 0, events = [], length = listeners.length; i < length; i++) {
510 if (
511 listeners[i].fn !== fn ||
512 (once && !listeners[i].once) ||
513 (context && listeners[i].context !== context)
514 ) {
515 events.push(listeners[i]);
516 }
517 }
518 if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
519 else clearEvent(this, evt);
520 }
521 return this;
522 };
523 EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
524 var evt;
525 if (event) {
526 evt = prefix ? prefix + event : event;
527 if (this._events[evt]) clearEvent(this, evt);
528 } else {
529 this._events = new Events();
530 this._eventsCount = 0;
531 }
532 return this;
533 };
534 EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
535 EventEmitter.prototype.addListener = EventEmitter.prototype.on;
536 EventEmitter.prefixed = prefix;
537 EventEmitter.EventEmitter = EventEmitter;
538 {
539 module.exports = EventEmitter;
540 }
541 } (eventemitter3));
542 const EventEmitter = eventemitter3.exports;
543
544 ({
545 name: '@polkadot/x-ws',
546 path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto',
547 type: 'esm',
548 version: '9.6.2'
549 });
550
551 const WebSocket = xglobal.WebSocket;
552
553 const known = {
554 1000: 'Normal Closure',
555 1001: 'Going Away',
556 1002: 'Protocol Error',
557 1003: 'Unsupported Data',
558 1004: '(For future)',
559 1005: 'No Status Received',
560 1006: 'Abnormal Closure',
561 1007: 'Invalid frame payload data',
562 1008: 'Policy Violation',
563 1009: 'Message too big',
564 1010: 'Missing Extension',
565 1011: 'Internal Error',
566 1012: 'Service Restart',
567 1013: 'Try Again Later',
568 1014: 'Bad Gateway',
569 1015: 'TLS Handshake'
570 };
571 function getUnmapped(code) {
572 if (code <= 1999) {
573 return '(For WebSocket standard)';
574 } else if (code <= 2999) {
575 return '(For WebSocket extensions)';
576 } else if (code <= 3999) {
577 return '(For libraries and frameworks)';
578 } else if (code <= 4999) {
579 return '(For applications)';
580 }
581 }
582 function getWSErrorString(code) {
583 if (code >= 0 && code <= 999) {
584 return '(Unused)';
585 }
586 return known[code] || getUnmapped(code) || '(Unknown)';
587 }
588
589 const ALIASES = {
590 chain_finalisedHead: 'chain_finalizedHead',
591 chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
592 chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
593 };
594 const RETRY_DELAY = 2500;
595 const DEFAULT_TIMEOUT_MS = 60 * 1000;
596 const TIMEOUT_INTERVAL = 5000;
597 const MEGABYTE = 1024 * 1024;
598 const l$6 = util.logger('api-ws');
599 function eraseRecord(record, cb) {
600 Object.keys(record).forEach(key => {
601 if (cb) {
602 cb(record[key]);
603 }
604 delete record[key];
605 });
606 }
607 var _callCache = _classPrivateFieldKey("callCache");
608 var _coder = _classPrivateFieldKey("coder");
609 var _endpoints = _classPrivateFieldKey("endpoints");
610 var _headers = _classPrivateFieldKey("headers");
611 var _eventemitter = _classPrivateFieldKey("eventemitter");
612 var _handlers = _classPrivateFieldKey("handlers");
613 var _isReadyPromise = _classPrivateFieldKey("isReadyPromise");
614 var _stats = _classPrivateFieldKey("stats");
615 var _waitingForId = _classPrivateFieldKey("waitingForId");
616 var _autoConnectMs = _classPrivateFieldKey("autoConnectMs");
617 var _endpointIndex = _classPrivateFieldKey("endpointIndex");
618 var _isConnected = _classPrivateFieldKey("isConnected");
619 var _subscriptions = _classPrivateFieldKey("subscriptions");
620 var _timeoutId = _classPrivateFieldKey("timeoutId");
621 var _websocket = _classPrivateFieldKey("websocket");
622 var _timeout = _classPrivateFieldKey("timeout");
623 var _send = _classPrivateFieldKey("send");
624 var _emit = _classPrivateFieldKey("emit");
625 var _onSocketClose = _classPrivateFieldKey("onSocketClose");
626 var _onSocketError = _classPrivateFieldKey("onSocketError");
627 var _onSocketMessage = _classPrivateFieldKey("onSocketMessage");
628 var _onSocketMessageResult = _classPrivateFieldKey("onSocketMessageResult");
629 var _onSocketMessageSubscribe = _classPrivateFieldKey("onSocketMessageSubscribe");
630 var _onSocketOpen = _classPrivateFieldKey("onSocketOpen");
631 var _resubscribe = _classPrivateFieldKey("resubscribe");
632 var _timeoutHandlers = _classPrivateFieldKey("timeoutHandlers");
633 class WsProvider {
634 constructor(endpoint = defaults.WS_URL, autoConnectMs = RETRY_DELAY, headers = {}, timeout) {
635 Object.defineProperty(this, _send, {
636 value: _send2
637 });
638 Object.defineProperty(this, _callCache, {
639 writable: true,
640 value: new LRUCache()
641 });
642 Object.defineProperty(this, _coder, {
643 writable: true,
644 value: void 0
645 });
646 Object.defineProperty(this, _endpoints, {
647 writable: true,
648 value: void 0
649 });
650 Object.defineProperty(this, _headers, {
651 writable: true,
652 value: void 0
653 });
654 Object.defineProperty(this, _eventemitter, {
655 writable: true,
656 value: void 0
657 });
658 Object.defineProperty(this, _handlers, {
659 writable: true,
660 value: {}
661 });
662 Object.defineProperty(this, _isReadyPromise, {
663 writable: true,
664 value: void 0
665 });
666 Object.defineProperty(this, _stats, {
667 writable: true,
668 value: void 0
669 });
670 Object.defineProperty(this, _waitingForId, {
671 writable: true,
672 value: {}
673 });
674 Object.defineProperty(this, _autoConnectMs, {
675 writable: true,
676 value: void 0
677 });
678 Object.defineProperty(this, _endpointIndex, {
679 writable: true,
680 value: void 0
681 });
682 Object.defineProperty(this, _isConnected, {
683 writable: true,
684 value: false
685 });
686 Object.defineProperty(this, _subscriptions, {
687 writable: true,
688 value: {}
689 });
690 Object.defineProperty(this, _timeoutId, {
691 writable: true,
692 value: null
693 });
694 Object.defineProperty(this, _websocket, {
695 writable: true,
696 value: void 0
697 });
698 Object.defineProperty(this, _timeout, {
699 writable: true,
700 value: void 0
701 });
702 Object.defineProperty(this, _emit, {
703 writable: true,
704 value: (type, ...args) => {
705 _classPrivateFieldBase(this, _eventemitter)[_eventemitter].emit(type, ...args);
706 }
707 });
708 Object.defineProperty(this, _onSocketClose, {
709 writable: true,
710 value: event => {
711 const error = new Error(`disconnected from ${_classPrivateFieldBase(this, _endpoints)[_endpoints][_classPrivateFieldBase(this, _endpointIndex)[_endpointIndex]]}: ${event.code}:: ${event.reason || getWSErrorString(event.code)}`);
712 if (_classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs] > 0) {
713 l$6.error(error.message);
714 }
715 _classPrivateFieldBase(this, _isConnected)[_isConnected] = false;
716 if (_classPrivateFieldBase(this, _websocket)[_websocket]) {
717 _classPrivateFieldBase(this, _websocket)[_websocket].onclose = null;
718 _classPrivateFieldBase(this, _websocket)[_websocket].onerror = null;
719 _classPrivateFieldBase(this, _websocket)[_websocket].onmessage = null;
720 _classPrivateFieldBase(this, _websocket)[_websocket].onopen = null;
721 _classPrivateFieldBase(this, _websocket)[_websocket] = null;
722 }
723 if (_classPrivateFieldBase(this, _timeoutId)[_timeoutId]) {
724 clearInterval(_classPrivateFieldBase(this, _timeoutId)[_timeoutId]);
725 _classPrivateFieldBase(this, _timeoutId)[_timeoutId] = null;
726 }
727 _classPrivateFieldBase(this, _emit)[_emit]('disconnected');
728 eraseRecord(_classPrivateFieldBase(this, _handlers)[_handlers], h => {
729 try {
730 h.callback(error, undefined);
731 } catch (err) {
732 l$6.error(err);
733 }
734 });
735 eraseRecord(_classPrivateFieldBase(this, _waitingForId)[_waitingForId]);
736 if (_classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs] > 0) {
737 setTimeout(() => {
738 this.connectWithRetry().catch(() => {
739 });
740 }, _classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs]);
741 }
742 }
743 });
744 Object.defineProperty(this, _onSocketError, {
745 writable: true,
746 value: error => {
747 l$6.debug(() => ['socket error', error]);
748 _classPrivateFieldBase(this, _emit)[_emit]('error', error);
749 }
750 });
751 Object.defineProperty(this, _onSocketMessage, {
752 writable: true,
753 value: message => {
754 l$6.debug(() => ['received', message.data]);
755 _classPrivateFieldBase(this, _stats)[_stats].total.bytesRecv += message.data.length;
756 const response = JSON.parse(message.data);
757 return util.isUndefined(response.method) ? _classPrivateFieldBase(this, _onSocketMessageResult)[_onSocketMessageResult](response) : _classPrivateFieldBase(this, _onSocketMessageSubscribe)[_onSocketMessageSubscribe](response);
758 }
759 });
760 Object.defineProperty(this, _onSocketMessageResult, {
761 writable: true,
762 value: response => {
763 const handler = _classPrivateFieldBase(this, _handlers)[_handlers][response.id];
764 if (!handler) {
765 l$6.debug(() => `Unable to find handler for id=${response.id}`);
766 return;
767 }
768 try {
769 const {
770 method,
771 params,
772 subscription
773 } = handler;
774 const result = _classPrivateFieldBase(this, _coder)[_coder].decodeResponse(response);
775 handler.callback(null, result);
776 if (subscription) {
777 const subId = `${subscription.type}::${result}`;
778 _classPrivateFieldBase(this, _subscriptions)[_subscriptions][subId] = util.objectSpread({}, subscription, {
779 method,
780 params
781 });
782 if (_classPrivateFieldBase(this, _waitingForId)[_waitingForId][subId]) {
783 _classPrivateFieldBase(this, _onSocketMessageSubscribe)[_onSocketMessageSubscribe](_classPrivateFieldBase(this, _waitingForId)[_waitingForId][subId]);
784 }
785 }
786 } catch (error) {
787 _classPrivateFieldBase(this, _stats)[_stats].total.errors++;
788 handler.callback(error, undefined);
789 }
790 delete _classPrivateFieldBase(this, _handlers)[_handlers][response.id];
791 }
792 });
793 Object.defineProperty(this, _onSocketMessageSubscribe, {
794 writable: true,
795 value: response => {
796 const method = ALIASES[response.method] || response.method || 'invalid';
797 const subId = `${method}::${response.params.subscription}`;
798 const handler = _classPrivateFieldBase(this, _subscriptions)[_subscriptions][subId];
799 if (!handler) {
800 _classPrivateFieldBase(this, _waitingForId)[_waitingForId][subId] = response;
801 l$6.debug(() => `Unable to find handler for subscription=${subId}`);
802 return;
803 }
804 delete _classPrivateFieldBase(this, _waitingForId)[_waitingForId][subId];
805 try {
806 const result = _classPrivateFieldBase(this, _coder)[_coder].decodeResponse(response);
807 handler.callback(null, result);
808 } catch (error) {
809 _classPrivateFieldBase(this, _stats)[_stats].total.errors++;
810 handler.callback(error, undefined);
811 }
812 }
813 });
814 Object.defineProperty(this, _onSocketOpen, {
815 writable: true,
816 value: () => {
817 if (_classPrivateFieldBase(this, _websocket)[_websocket] === null) {
818 throw new Error('WebSocket cannot be null in onOpen');
819 }
820 l$6.debug(() => ['connected to', _classPrivateFieldBase(this, _endpoints)[_endpoints][_classPrivateFieldBase(this, _endpointIndex)[_endpointIndex]]]);
821 _classPrivateFieldBase(this, _isConnected)[_isConnected] = true;
822 _classPrivateFieldBase(this, _emit)[_emit]('connected');
823 _classPrivateFieldBase(this, _resubscribe)[_resubscribe]();
824 return true;
825 }
826 });
827 Object.defineProperty(this, _resubscribe, {
828 writable: true,
829 value: () => {
830 const subscriptions = _classPrivateFieldBase(this, _subscriptions)[_subscriptions];
831 _classPrivateFieldBase(this, _subscriptions)[_subscriptions] = {};
832 Promise.all(Object.keys(subscriptions).map(async id => {
833 const {
834 callback,
835 method,
836 params,
837 type
838 } = subscriptions[id];
839 if (type.startsWith('author_')) {
840 return;
841 }
842 try {
843 await this.subscribe(type, method, params, callback);
844 } catch (error) {
845 l$6.error(error);
846 }
847 })).catch(l$6.error);
848 }
849 });
850 Object.defineProperty(this, _timeoutHandlers, {
851 writable: true,
852 value: () => {
853 const now = Date.now();
854 const ids = Object.keys(_classPrivateFieldBase(this, _handlers)[_handlers]);
855 for (let i = 0; i < ids.length; i++) {
856 const handler = _classPrivateFieldBase(this, _handlers)[_handlers][ids[i]];
857 if (now - handler.start > _classPrivateFieldBase(this, _timeout)[_timeout]) {
858 try {
859 handler.callback(new Error(`No response received from RPC endpoint in ${_classPrivateFieldBase(this, _timeout)[_timeout] / 1000}s`), undefined);
860 } catch {
861 }
862 _classPrivateFieldBase(this, _stats)[_stats].total.timeout++;
863 delete _classPrivateFieldBase(this, _handlers)[_handlers][ids[i]];
864 }
865 }
866 }
867 });
868 const endpoints = Array.isArray(endpoint) ? endpoint : [endpoint];
869 if (endpoints.length === 0) {
870 throw new Error('WsProvider requires at least one Endpoint');
871 }
872 endpoints.forEach(endpoint => {
873 if (!/^(wss|ws):\/\//.test(endpoint)) {
874 throw new Error(`Endpoint should start with 'ws://', received '${endpoint}'`);
875 }
876 });
877 _classPrivateFieldBase(this, _eventemitter)[_eventemitter] = new EventEmitter();
878 _classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs] = autoConnectMs || 0;
879 _classPrivateFieldBase(this, _coder)[_coder] = new RpcCoder();
880 _classPrivateFieldBase(this, _endpointIndex)[_endpointIndex] = -1;
881 _classPrivateFieldBase(this, _endpoints)[_endpoints] = endpoints;
882 _classPrivateFieldBase(this, _headers)[_headers] = headers;
883 _classPrivateFieldBase(this, _websocket)[_websocket] = null;
884 _classPrivateFieldBase(this, _stats)[_stats] = {
885 active: {
886 requests: 0,
887 subscriptions: 0
888 },
889 total: {
890 bytesRecv: 0,
891 bytesSent: 0,
892 cached: 0,
893 errors: 0,
894 requests: 0,
895 subscriptions: 0,
896 timeout: 0
897 }
898 };
899 _classPrivateFieldBase(this, _timeout)[_timeout] = timeout || DEFAULT_TIMEOUT_MS;
900 if (autoConnectMs > 0) {
901 this.connectWithRetry().catch(() => {
902 });
903 }
904 _classPrivateFieldBase(this, _isReadyPromise)[_isReadyPromise] = new Promise(resolve => {
905 _classPrivateFieldBase(this, _eventemitter)[_eventemitter].once('connected', () => {
906 resolve(this);
907 });
908 });
909 }
910 get hasSubscriptions() {
911 return true;
912 }
913 get isConnected() {
914 return _classPrivateFieldBase(this, _isConnected)[_isConnected];
915 }
916 get isReady() {
917 return _classPrivateFieldBase(this, _isReadyPromise)[_isReadyPromise];
918 }
919 clone() {
920 return new WsProvider(_classPrivateFieldBase(this, _endpoints)[_endpoints]);
921 }
922 async connect() {
923 try {
924 _classPrivateFieldBase(this, _endpointIndex)[_endpointIndex] = (_classPrivateFieldBase(this, _endpointIndex)[_endpointIndex] + 1) % _classPrivateFieldBase(this, _endpoints)[_endpoints].length;
925 _classPrivateFieldBase(this, _websocket)[_websocket] = typeof xglobal.WebSocket !== 'undefined' && util.isChildClass(xglobal.WebSocket, WebSocket) ? new WebSocket(_classPrivateFieldBase(this, _endpoints)[_endpoints][_classPrivateFieldBase(this, _endpointIndex)[_endpointIndex]])
926 : new WebSocket(_classPrivateFieldBase(this, _endpoints)[_endpoints][_classPrivateFieldBase(this, _endpointIndex)[_endpointIndex]], undefined, undefined, _classPrivateFieldBase(this, _headers)[_headers], undefined, {
927 fragmentOutgoingMessages: true,
928 fragmentationThreshold: 1 * MEGABYTE,
929 maxReceivedFrameSize: 24 * MEGABYTE,
930 maxReceivedMessageSize: 24 * MEGABYTE
931 });
932 _classPrivateFieldBase(this, _websocket)[_websocket].onclose = _classPrivateFieldBase(this, _onSocketClose)[_onSocketClose];
933 _classPrivateFieldBase(this, _websocket)[_websocket].onerror = _classPrivateFieldBase(this, _onSocketError)[_onSocketError];
934 _classPrivateFieldBase(this, _websocket)[_websocket].onmessage = _classPrivateFieldBase(this, _onSocketMessage)[_onSocketMessage];
935 _classPrivateFieldBase(this, _websocket)[_websocket].onopen = _classPrivateFieldBase(this, _onSocketOpen)[_onSocketOpen];
936 _classPrivateFieldBase(this, _timeoutId)[_timeoutId] = setInterval(() => _classPrivateFieldBase(this, _timeoutHandlers)[_timeoutHandlers](), TIMEOUT_INTERVAL);
937 } catch (error) {
938 l$6.error(error);
939 _classPrivateFieldBase(this, _emit)[_emit]('error', error);
940 throw error;
941 }
942 }
943 async connectWithRetry() {
944 if (_classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs] > 0) {
945 try {
946 await this.connect();
947 } catch (error) {
948 setTimeout(() => {
949 this.connectWithRetry().catch(() => {
950 });
951 }, _classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs]);
952 }
953 }
954 }
955 async disconnect() {
956 _classPrivateFieldBase(this, _autoConnectMs)[_autoConnectMs] = 0;
957 try {
958 if (_classPrivateFieldBase(this, _websocket)[_websocket]) {
959 _classPrivateFieldBase(this, _websocket)[_websocket].close(1000);
960 }
961 } catch (error) {
962 l$6.error(error);
963 _classPrivateFieldBase(this, _emit)[_emit]('error', error);
964 throw error;
965 }
966 }
967 get stats() {
968 return {
969 active: {
970 requests: Object.keys(_classPrivateFieldBase(this, _handlers)[_handlers]).length,
971 subscriptions: Object.keys(_classPrivateFieldBase(this, _subscriptions)[_subscriptions]).length
972 },
973 total: _classPrivateFieldBase(this, _stats)[_stats].total
974 };
975 }
976 on(type, sub) {
977 _classPrivateFieldBase(this, _eventemitter)[_eventemitter].on(type, sub);
978 return () => {
979 _classPrivateFieldBase(this, _eventemitter)[_eventemitter].removeListener(type, sub);
980 };
981 }
982 send(method, params, isCacheable, subscription) {
983 _classPrivateFieldBase(this, _stats)[_stats].total.requests++;
984 const [id, body] = _classPrivateFieldBase(this, _coder)[_coder].encodeJson(method, params);
985 let resultPromise = isCacheable ? _classPrivateFieldBase(this, _callCache)[_callCache].get(body) : null;
986 if (!resultPromise) {
987 resultPromise = _classPrivateFieldBase(this, _send)[_send](id, body, method, params, subscription);
988 if (isCacheable) {
989 _classPrivateFieldBase(this, _callCache)[_callCache].set(body, resultPromise);
990 }
991 } else {
992 _classPrivateFieldBase(this, _stats)[_stats].total.cached++;
993 }
994 return resultPromise;
995 }
996 subscribe(type, method, params, callback) {
997 _classPrivateFieldBase(this, _stats)[_stats].total.subscriptions++;
998 return this.send(method, params, false, {
999 callback,
1000 type
1001 });
1002 }
1003 async unsubscribe(type, method, id) {
1004 const subscription = `${type}::${id}`;
1005 if (util.isUndefined(_classPrivateFieldBase(this, _subscriptions)[_subscriptions][subscription])) {
1006 l$6.debug(() => `Unable to find active subscription=${subscription}`);
1007 return false;
1008 }
1009 delete _classPrivateFieldBase(this, _subscriptions)[_subscriptions][subscription];
1010 try {
1011 return this.isConnected && !util.isNull(_classPrivateFieldBase(this, _websocket)[_websocket]) ? this.send(method, [id]) : true;
1012 } catch (error) {
1013 return false;
1014 }
1015 }
1016 }
1017 async function _send2(id, body, method, params, subscription) {
1018 return new Promise((resolve, reject) => {
1019 try {
1020 if (!this.isConnected || _classPrivateFieldBase(this, _websocket)[_websocket] === null) {
1021 throw new Error('WebSocket is not connected');
1022 }
1023 const callback = (error, result) => {
1024 error ? reject(error) : resolve(result);
1025 };
1026 l$6.debug(() => ['calling', method, body]);
1027 _classPrivateFieldBase(this, _handlers)[_handlers][id] = {
1028 callback,
1029 method,
1030 params,
1031 start: Date.now(),
1032 subscription
1033 };
1034 _classPrivateFieldBase(this, _stats)[_stats].total.bytesSent += body.length;
1035 _classPrivateFieldBase(this, _websocket)[_websocket].send(body);
1036 } catch (error) {
1037 _classPrivateFieldBase(this, _stats)[_stats].total.errors++;
1038 reject(error);
1039 }
1040 });
1041 }
1042
1043 const packageInfo = {
1044 name: '@polkadot/api',
1045 path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto',
1046 type: 'esm',
1047 version: '8.10.1'
1048 };
1049
1050 /*! *****************************************************************************
1051 Copyright (c) Microsoft Corporation.
1052 Permission to use, copy, modify, and/or distribute this software for any
1053 purpose with or without fee is hereby granted.
1054 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1055 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1056 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1057 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1058 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1059 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1060 PERFORMANCE OF THIS SOFTWARE.
1061 ***************************************************************************** */
1062 var extendStatics = function(d, b) {
1063 extendStatics = Object.setPrototypeOf ||
1064 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
1065 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
1066 return extendStatics(d, b);
1067 };
1068 function __extends(d, b) {
1069 if (typeof b !== "function" && b !== null)
1070 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
1071 extendStatics(d, b);
1072 function __() { this.constructor = d; }
1073 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
1074 }
1075 function __awaiter(thisArg, _arguments, P, generator) {
1076 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1077 return new (P || (P = Promise))(function (resolve, reject) {
1078 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1079 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1080 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1081 step((generator = generator.apply(thisArg, _arguments || [])).next());
1082 });
1083 }
1084 function __generator(thisArg, body) {
1085 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1086 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1087 function verb(n) { return function (v) { return step([n, v]); }; }
1088 function step(op) {
1089 if (f) throw new TypeError("Generator is already executing.");
1090 while (_) try {
1091 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1092 if (y = 0, t) op = [op[0] & 2, t.value];
1093 switch (op[0]) {
1094 case 0: case 1: t = op; break;
1095 case 4: _.label++; return { value: op[1], done: false };
1096 case 5: _.label++; y = op[1]; op = [0]; continue;
1097 case 7: op = _.ops.pop(); _.trys.pop(); continue;
1098 default:
1099 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1100 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1101 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1102 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1103 if (t[2]) _.ops.pop();
1104 _.trys.pop(); continue;
1105 }
1106 op = body.call(thisArg, _);
1107 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1108 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1109 }
1110 }
1111 function __values(o) {
1112 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1113 if (m) return m.call(o);
1114 if (o && typeof o.length === "number") return {
1115 next: function () {
1116 if (o && i >= o.length) o = void 0;
1117 return { value: o && o[i++], done: !o };
1118 }
1119 };
1120 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1121 }
1122 function __read(o, n) {
1123 var m = typeof Symbol === "function" && o[Symbol.iterator];
1124 if (!m) return o;
1125 var i = m.call(o), r, ar = [], e;
1126 try {
1127 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1128 }
1129 catch (error) { e = { error: error }; }
1130 finally {
1131 try {
1132 if (r && !r.done && (m = i["return"])) m.call(i);
1133 }
1134 finally { if (e) throw e.error; }
1135 }
1136 return ar;
1137 }
1138 function __spreadArray(to, from, pack) {
1139 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1140 if (ar || !(i in from)) {
1141 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1142 ar[i] = from[i];
1143 }
1144 }
1145 return to.concat(ar || Array.prototype.slice.call(from));
1146 }
1147 function __await(v) {
1148 return this instanceof __await ? (this.v = v, this) : new __await(v);
1149 }
1150 function __asyncGenerator(thisArg, _arguments, generator) {
1151 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1152 var g = generator.apply(thisArg, _arguments || []), i, q = [];
1153 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
1154 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
1155 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
1156 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
1157 function fulfill(value) { resume("next", value); }
1158 function reject(value) { resume("throw", value); }
1159 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
1160 }
1161 function __asyncValues(o) {
1162 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1163 var m = o[Symbol.asyncIterator], i;
1164 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
1165 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
1166 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
1167 }
1168
1169 function isFunction(value) {
1170 return typeof value === 'function';
1171 }
1172
1173 function createErrorClass(createImpl) {
1174 var _super = function (instance) {
1175 Error.call(instance);
1176 instance.stack = new Error().stack;
1177 };
1178 var ctorFunc = createImpl(_super);
1179 ctorFunc.prototype = Object.create(Error.prototype);
1180 ctorFunc.prototype.constructor = ctorFunc;
1181 return ctorFunc;
1182 }
1183
1184 var UnsubscriptionError = createErrorClass(function (_super) {
1185 return function UnsubscriptionErrorImpl(errors) {
1186 _super(this);
1187 this.message = errors
1188 ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
1189 : '';
1190 this.name = 'UnsubscriptionError';
1191 this.errors = errors;
1192 };
1193 });
1194
1195 function arrRemove(arr, item) {
1196 if (arr) {
1197 var index = arr.indexOf(item);
1198 0 <= index && arr.splice(index, 1);
1199 }
1200 }
1201
1202 var Subscription = (function () {
1203 function Subscription(initialTeardown) {
1204 this.initialTeardown = initialTeardown;
1205 this.closed = false;
1206 this._parentage = null;
1207 this._finalizers = null;
1208 }
1209 Subscription.prototype.unsubscribe = function () {
1210 var e_1, _a, e_2, _b;
1211 var errors;
1212 if (!this.closed) {
1213 this.closed = true;
1214 var _parentage = this._parentage;
1215 if (_parentage) {
1216 this._parentage = null;
1217 if (Array.isArray(_parentage)) {
1218 try {
1219 for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
1220 var parent_1 = _parentage_1_1.value;
1221 parent_1.remove(this);
1222 }
1223 }
1224 catch (e_1_1) { e_1 = { error: e_1_1 }; }
1225 finally {
1226 try {
1227 if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
1228 }
1229 finally { if (e_1) throw e_1.error; }
1230 }
1231 }
1232 else {
1233 _parentage.remove(this);
1234 }
1235 }
1236 var initialFinalizer = this.initialTeardown;
1237 if (isFunction(initialFinalizer)) {
1238 try {
1239 initialFinalizer();
1240 }
1241 catch (e) {
1242 errors = e instanceof UnsubscriptionError ? e.errors : [e];
1243 }
1244 }
1245 var _finalizers = this._finalizers;
1246 if (_finalizers) {
1247 this._finalizers = null;
1248 try {
1249 for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
1250 var finalizer = _finalizers_1_1.value;
1251 try {
1252 execFinalizer(finalizer);
1253 }
1254 catch (err) {
1255 errors = errors !== null && errors !== void 0 ? errors : [];
1256 if (err instanceof UnsubscriptionError) {
1257 errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
1258 }
1259 else {
1260 errors.push(err);
1261 }
1262 }
1263 }
1264 }
1265 catch (e_2_1) { e_2 = { error: e_2_1 }; }
1266 finally {
1267 try {
1268 if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
1269 }
1270 finally { if (e_2) throw e_2.error; }
1271 }
1272 }
1273 if (errors) {
1274 throw new UnsubscriptionError(errors);
1275 }
1276 }
1277 };
1278 Subscription.prototype.add = function (teardown) {
1279 var _a;
1280 if (teardown && teardown !== this) {
1281 if (this.closed) {
1282 execFinalizer(teardown);
1283 }
1284 else {
1285 if (teardown instanceof Subscription) {
1286 if (teardown.closed || teardown._hasParent(this)) {
1287 return;
1288 }
1289 teardown._addParent(this);
1290 }
1291 (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
1292 }
1293 }
1294 };
1295 Subscription.prototype._hasParent = function (parent) {
1296 var _parentage = this._parentage;
1297 return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
1298 };
1299 Subscription.prototype._addParent = function (parent) {
1300 var _parentage = this._parentage;
1301 this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
1302 };
1303 Subscription.prototype._removeParent = function (parent) {
1304 var _parentage = this._parentage;
1305 if (_parentage === parent) {
1306 this._parentage = null;
1307 }
1308 else if (Array.isArray(_parentage)) {
1309 arrRemove(_parentage, parent);
1310 }
1311 };
1312 Subscription.prototype.remove = function (teardown) {
1313 var _finalizers = this._finalizers;
1314 _finalizers && arrRemove(_finalizers, teardown);
1315 if (teardown instanceof Subscription) {
1316 teardown._removeParent(this);
1317 }
1318 };
1319 Subscription.EMPTY = (function () {
1320 var empty = new Subscription();
1321 empty.closed = true;
1322 return empty;
1323 })();
1324 return Subscription;
1325 }());
1326 var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
1327 function isSubscription(value) {
1328 return (value instanceof Subscription ||
1329 (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
1330 }
1331 function execFinalizer(finalizer) {
1332 if (isFunction(finalizer)) {
1333 finalizer();
1334 }
1335 else {
1336 finalizer.unsubscribe();
1337 }
1338 }
1339
1340 var config = {
1341 onUnhandledError: null,
1342 onStoppedNotification: null,
1343 Promise: undefined,
1344 useDeprecatedSynchronousErrorHandling: false,
1345 useDeprecatedNextContext: false,
1346 };
1347
1348 var timeoutProvider = {
1349 setTimeout: function (handler, timeout) {
1350 var args = [];
1351 for (var _i = 2; _i < arguments.length; _i++) {
1352 args[_i - 2] = arguments[_i];
1353 }
1354 return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1355 },
1356 clearTimeout: function (handle) {
1357 return (clearTimeout)(handle);
1358 },
1359 delegate: undefined,
1360 };
1361
1362 function reportUnhandledError(err) {
1363 timeoutProvider.setTimeout(function () {
1364 {
1365 throw err;
1366 }
1367 });
1368 }
1369
1370 function noop() { }
1371
1372 function errorContext(cb) {
1373 {
1374 cb();
1375 }
1376 }
1377
1378 var Subscriber = (function (_super) {
1379 __extends(Subscriber, _super);
1380 function Subscriber(destination) {
1381 var _this = _super.call(this) || this;
1382 _this.isStopped = false;
1383 if (destination) {
1384 _this.destination = destination;
1385 if (isSubscription(destination)) {
1386 destination.add(_this);
1387 }
1388 }
1389 else {
1390 _this.destination = EMPTY_OBSERVER;
1391 }
1392 return _this;
1393 }
1394 Subscriber.create = function (next, error, complete) {
1395 return new SafeSubscriber(next, error, complete);
1396 };
1397 Subscriber.prototype.next = function (value) {
1398 if (this.isStopped) ;
1399 else {
1400 this._next(value);
1401 }
1402 };
1403 Subscriber.prototype.error = function (err) {
1404 if (this.isStopped) ;
1405 else {
1406 this.isStopped = true;
1407 this._error(err);
1408 }
1409 };
1410 Subscriber.prototype.complete = function () {
1411 if (this.isStopped) ;
1412 else {
1413 this.isStopped = true;
1414 this._complete();
1415 }
1416 };
1417 Subscriber.prototype.unsubscribe = function () {
1418 if (!this.closed) {
1419 this.isStopped = true;
1420 _super.prototype.unsubscribe.call(this);
1421 this.destination = null;
1422 }
1423 };
1424 Subscriber.prototype._next = function (value) {
1425 this.destination.next(value);
1426 };
1427 Subscriber.prototype._error = function (err) {
1428 try {
1429 this.destination.error(err);
1430 }
1431 finally {
1432 this.unsubscribe();
1433 }
1434 };
1435 Subscriber.prototype._complete = function () {
1436 try {
1437 this.destination.complete();
1438 }
1439 finally {
1440 this.unsubscribe();
1441 }
1442 };
1443 return Subscriber;
1444 }(Subscription));
1445 var _bind = Function.prototype.bind;
1446 function bind(fn, thisArg) {
1447 return _bind.call(fn, thisArg);
1448 }
1449 var ConsumerObserver = (function () {
1450 function ConsumerObserver(partialObserver) {
1451 this.partialObserver = partialObserver;
1452 }
1453 ConsumerObserver.prototype.next = function (value) {
1454 var partialObserver = this.partialObserver;
1455 if (partialObserver.next) {
1456 try {
1457 partialObserver.next(value);
1458 }
1459 catch (error) {
1460 handleUnhandledError(error);
1461 }
1462 }
1463 };
1464 ConsumerObserver.prototype.error = function (err) {
1465 var partialObserver = this.partialObserver;
1466 if (partialObserver.error) {
1467 try {
1468 partialObserver.error(err);
1469 }
1470 catch (error) {
1471 handleUnhandledError(error);
1472 }
1473 }
1474 else {
1475 handleUnhandledError(err);
1476 }
1477 };
1478 ConsumerObserver.prototype.complete = function () {
1479 var partialObserver = this.partialObserver;
1480 if (partialObserver.complete) {
1481 try {
1482 partialObserver.complete();
1483 }
1484 catch (error) {
1485 handleUnhandledError(error);
1486 }
1487 }
1488 };
1489 return ConsumerObserver;
1490 }());
1491 var SafeSubscriber = (function (_super) {
1492 __extends(SafeSubscriber, _super);
1493 function SafeSubscriber(observerOrNext, error, complete) {
1494 var _this = _super.call(this) || this;
1495 var partialObserver;
1496 if (isFunction(observerOrNext) || !observerOrNext) {
1497 partialObserver = {
1498 next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
1499 error: error !== null && error !== void 0 ? error : undefined,
1500 complete: complete !== null && complete !== void 0 ? complete : undefined,
1501 };
1502 }
1503 else {
1504 var context_1;
1505 if (_this && config.useDeprecatedNextContext) {
1506 context_1 = Object.create(observerOrNext);
1507 context_1.unsubscribe = function () { return _this.unsubscribe(); };
1508 partialObserver = {
1509 next: observerOrNext.next && bind(observerOrNext.next, context_1),
1510 error: observerOrNext.error && bind(observerOrNext.error, context_1),
1511 complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
1512 };
1513 }
1514 else {
1515 partialObserver = observerOrNext;
1516 }
1517 }
1518 _this.destination = new ConsumerObserver(partialObserver);
1519 return _this;
1520 }
1521 return SafeSubscriber;
1522 }(Subscriber));
1523 function handleUnhandledError(error) {
1524 {
1525 reportUnhandledError(error);
1526 }
1527 }
1528 function defaultErrorHandler(err) {
1529 throw err;
1530 }
1531 var EMPTY_OBSERVER = {
1532 closed: true,
1533 next: noop,
1534 error: defaultErrorHandler,
1535 complete: noop,
1536 };
1537
1538 var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
1539
1540 function identity$2(x) {
1541 return x;
1542 }
1543
1544 function pipeFromArray(fns) {
1545 if (fns.length === 0) {
1546 return identity$2;
1547 }
1548 if (fns.length === 1) {
1549 return fns[0];
1550 }
1551 return function piped(input) {
1552 return fns.reduce(function (prev, fn) { return fn(prev); }, input);
1553 };
1554 }
1555
1556 var Observable = (function () {
1557 function Observable(subscribe) {
1558 if (subscribe) {
1559 this._subscribe = subscribe;
1560 }
1561 }
1562 Observable.prototype.lift = function (operator) {
1563 var observable = new Observable();
1564 observable.source = this;
1565 observable.operator = operator;
1566 return observable;
1567 };
1568 Observable.prototype.subscribe = function (observerOrNext, error, complete) {
1569 var _this = this;
1570 var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
1571 errorContext(function () {
1572 var _a = _this, operator = _a.operator, source = _a.source;
1573 subscriber.add(operator
1574 ?
1575 operator.call(subscriber, source)
1576 : source
1577 ?
1578 _this._subscribe(subscriber)
1579 :
1580 _this._trySubscribe(subscriber));
1581 });
1582 return subscriber;
1583 };
1584 Observable.prototype._trySubscribe = function (sink) {
1585 try {
1586 return this._subscribe(sink);
1587 }
1588 catch (err) {
1589 sink.error(err);
1590 }
1591 };
1592 Observable.prototype.forEach = function (next, promiseCtor) {
1593 var _this = this;
1594 promiseCtor = getPromiseCtor(promiseCtor);
1595 return new promiseCtor(function (resolve, reject) {
1596 var subscriber = new SafeSubscriber({
1597 next: function (value) {
1598 try {
1599 next(value);
1600 }
1601 catch (err) {
1602 reject(err);
1603 subscriber.unsubscribe();
1604 }
1605 },
1606 error: reject,
1607 complete: resolve,
1608 });
1609 _this.subscribe(subscriber);
1610 });
1611 };
1612 Observable.prototype._subscribe = function (subscriber) {
1613 var _a;
1614 return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1615 };
1616 Observable.prototype[observable] = function () {
1617 return this;
1618 };
1619 Observable.prototype.pipe = function () {
1620 var operations = [];
1621 for (var _i = 0; _i < arguments.length; _i++) {
1622 operations[_i] = arguments[_i];
1623 }
1624 return pipeFromArray(operations)(this);
1625 };
1626 Observable.prototype.toPromise = function (promiseCtor) {
1627 var _this = this;
1628 promiseCtor = getPromiseCtor(promiseCtor);
1629 return new promiseCtor(function (resolve, reject) {
1630 var value;
1631 _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
1632 });
1633 };
1634 Observable.create = function (subscribe) {
1635 return new Observable(subscribe);
1636 };
1637 return Observable;
1638 }());
1639 function getPromiseCtor(promiseCtor) {
1640 var _a;
1641 return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1642 }
1643 function isObserver(value) {
1644 return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1645 }
1646 function isSubscriber(value) {
1647 return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
1648 }
1649
1650 function hasLift(source) {
1651 return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1652 }
1653 function operate(init) {
1654 return function (source) {
1655 if (hasLift(source)) {
1656 return source.lift(function (liftedSource) {
1657 try {
1658 return init(liftedSource, this);
1659 }
1660 catch (err) {
1661 this.error(err);
1662 }
1663 });
1664 }
1665 throw new TypeError('Unable to lift unknown Observable type');
1666 };
1667 }
1668
1669 function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1670 return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1671 }
1672 var OperatorSubscriber = (function (_super) {
1673 __extends(OperatorSubscriber, _super);
1674 function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1675 var _this = _super.call(this, destination) || this;
1676 _this.onFinalize = onFinalize;
1677 _this.shouldUnsubscribe = shouldUnsubscribe;
1678 _this._next = onNext
1679 ? function (value) {
1680 try {
1681 onNext(value);
1682 }
1683 catch (err) {
1684 destination.error(err);
1685 }
1686 }
1687 : _super.prototype._next;
1688 _this._error = onError
1689 ? function (err) {
1690 try {
1691 onError(err);
1692 }
1693 catch (err) {
1694 destination.error(err);
1695 }
1696 finally {
1697 this.unsubscribe();
1698 }
1699 }
1700 : _super.prototype._error;
1701 _this._complete = onComplete
1702 ? function () {
1703 try {
1704 onComplete();
1705 }
1706 catch (err) {
1707 destination.error(err);
1708 }
1709 finally {
1710 this.unsubscribe();
1711 }
1712 }
1713 : _super.prototype._complete;
1714 return _this;
1715 }
1716 OperatorSubscriber.prototype.unsubscribe = function () {
1717 var _a;
1718 if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1719 var closed_1 = this.closed;
1720 _super.prototype.unsubscribe.call(this);
1721 !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1722 }
1723 };
1724 return OperatorSubscriber;
1725 }(Subscriber));
1726
1727 function refCount() {
1728 return operate(function (source, subscriber) {
1729 var connection = null;
1730 source._refCount++;
1731 var refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, function () {
1732 if (!source || source._refCount <= 0 || 0 < --source._refCount) {
1733 connection = null;
1734 return;
1735 }
1736 var sharedConnection = source._connection;
1737 var conn = connection;
1738 connection = null;
1739 if (sharedConnection && (!conn || sharedConnection === conn)) {
1740 sharedConnection.unsubscribe();
1741 }
1742 subscriber.unsubscribe();
1743 });
1744 source.subscribe(refCounter);
1745 if (!refCounter.closed) {
1746 connection = source.connect();
1747 }
1748 });
1749 }
1750
1751 var ConnectableObservable = (function (_super) {
1752 __extends(ConnectableObservable, _super);
1753 function ConnectableObservable(source, subjectFactory) {
1754 var _this = _super.call(this) || this;
1755 _this.source = source;
1756 _this.subjectFactory = subjectFactory;
1757 _this._subject = null;
1758 _this._refCount = 0;
1759 _this._connection = null;
1760 if (hasLift(source)) {
1761 _this.lift = source.lift;
1762 }
1763 return _this;
1764 }
1765 ConnectableObservable.prototype._subscribe = function (subscriber) {
1766 return this.getSubject().subscribe(subscriber);
1767 };
1768 ConnectableObservable.prototype.getSubject = function () {
1769 var subject = this._subject;
1770 if (!subject || subject.isStopped) {
1771 this._subject = this.subjectFactory();
1772 }
1773 return this._subject;
1774 };
1775 ConnectableObservable.prototype._teardown = function () {
1776 this._refCount = 0;
1777 var _connection = this._connection;
1778 this._subject = this._connection = null;
1779 _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();
1780 };
1781 ConnectableObservable.prototype.connect = function () {
1782 var _this = this;
1783 var connection = this._connection;
1784 if (!connection) {
1785 connection = this._connection = new Subscription();
1786 var subject_1 = this.getSubject();
1787 connection.add(this.source.subscribe(createOperatorSubscriber(subject_1, undefined, function () {
1788 _this._teardown();
1789 subject_1.complete();
1790 }, function (err) {
1791 _this._teardown();
1792 subject_1.error(err);
1793 }, function () { return _this._teardown(); })));
1794 if (connection.closed) {
1795 this._connection = null;
1796 connection = Subscription.EMPTY;
1797 }
1798 }
1799 return connection;
1800 };
1801 ConnectableObservable.prototype.refCount = function () {
1802 return refCount()(this);
1803 };
1804 return ConnectableObservable;
1805 }(Observable));
1806
1807 var performanceTimestampProvider = {
1808 now: function () {
1809 return (performanceTimestampProvider.delegate || performance).now();
1810 },
1811 delegate: undefined,
1812 };
1813
1814 var animationFrameProvider = {
1815 schedule: function (callback) {
1816 var request = requestAnimationFrame;
1817 var cancel = cancelAnimationFrame;
1818 var handle = request(function (timestamp) {
1819 cancel = undefined;
1820 callback(timestamp);
1821 });
1822 return new Subscription(function () { return cancel === null || cancel === void 0 ? void 0 : cancel(handle); });
1823 },
1824 requestAnimationFrame: function () {
1825 var args = [];
1826 for (var _i = 0; _i < arguments.length; _i++) {
1827 args[_i] = arguments[_i];
1828 }
1829 var delegate = animationFrameProvider.delegate;
1830 return ((delegate === null || delegate === void 0 ? void 0 : delegate.requestAnimationFrame) || requestAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
1831 },
1832 cancelAnimationFrame: function () {
1833 var args = [];
1834 for (var _i = 0; _i < arguments.length; _i++) {
1835 args[_i] = arguments[_i];
1836 }
1837 return (cancelAnimationFrame).apply(void 0, __spreadArray([], __read(args)));
1838 },
1839 delegate: undefined,
1840 };
1841
1842 function animationFramesFactory(timestampProvider) {
1843 var schedule = animationFrameProvider.schedule;
1844 return new Observable(function (subscriber) {
1845 var subscription = new Subscription();
1846 var provider = timestampProvider || performanceTimestampProvider;
1847 var start = provider.now();
1848 var run = function (timestamp) {
1849 var now = provider.now();
1850 subscriber.next({
1851 timestamp: timestampProvider ? now : timestamp,
1852 elapsed: now - start,
1853 });
1854 if (!subscriber.closed) {
1855 subscription.add(schedule(run));
1856 }
1857 };
1858 subscription.add(schedule(run));
1859 return subscription;
1860 });
1861 }
1862 animationFramesFactory();
1863
1864 var ObjectUnsubscribedError = createErrorClass(function (_super) {
1865 return function ObjectUnsubscribedErrorImpl() {
1866 _super(this);
1867 this.name = 'ObjectUnsubscribedError';
1868 this.message = 'object unsubscribed';
1869 };
1870 });
1871
1872 var Subject = (function (_super) {
1873 __extends(Subject, _super);
1874 function Subject() {
1875 var _this = _super.call(this) || this;
1876 _this.closed = false;
1877 _this.currentObservers = null;
1878 _this.observers = [];
1879 _this.isStopped = false;
1880 _this.hasError = false;
1881 _this.thrownError = null;
1882 return _this;
1883 }
1884 Subject.prototype.lift = function (operator) {
1885 var subject = new AnonymousSubject(this, this);
1886 subject.operator = operator;
1887 return subject;
1888 };
1889 Subject.prototype._throwIfClosed = function () {
1890 if (this.closed) {
1891 throw new ObjectUnsubscribedError();
1892 }
1893 };
1894 Subject.prototype.next = function (value) {
1895 var _this = this;
1896 errorContext(function () {
1897 var e_1, _a;
1898 _this._throwIfClosed();
1899 if (!_this.isStopped) {
1900 if (!_this.currentObservers) {
1901 _this.currentObservers = Array.from(_this.observers);
1902 }
1903 try {
1904 for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1905 var observer = _c.value;
1906 observer.next(value);
1907 }
1908 }
1909 catch (e_1_1) { e_1 = { error: e_1_1 }; }
1910 finally {
1911 try {
1912 if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1913 }
1914 finally { if (e_1) throw e_1.error; }
1915 }
1916 }
1917 });
1918 };
1919 Subject.prototype.error = function (err) {
1920 var _this = this;
1921 errorContext(function () {
1922 _this._throwIfClosed();
1923 if (!_this.isStopped) {
1924 _this.hasError = _this.isStopped = true;
1925 _this.thrownError = err;
1926 var observers = _this.observers;
1927 while (observers.length) {
1928 observers.shift().error(err);
1929 }
1930 }
1931 });
1932 };
1933 Subject.prototype.complete = function () {
1934 var _this = this;
1935 errorContext(function () {
1936 _this._throwIfClosed();
1937 if (!_this.isStopped) {
1938 _this.isStopped = true;
1939 var observers = _this.observers;
1940 while (observers.length) {
1941 observers.shift().complete();
1942 }
1943 }
1944 });
1945 };
1946 Subject.prototype.unsubscribe = function () {
1947 this.isStopped = this.closed = true;
1948 this.observers = this.currentObservers = null;
1949 };
1950 Object.defineProperty(Subject.prototype, "observed", {
1951 get: function () {
1952 var _a;
1953 return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1954 },
1955 enumerable: false,
1956 configurable: true
1957 });
1958 Subject.prototype._trySubscribe = function (subscriber) {
1959 this._throwIfClosed();
1960 return _super.prototype._trySubscribe.call(this, subscriber);
1961 };
1962 Subject.prototype._subscribe = function (subscriber) {
1963 this._throwIfClosed();
1964 this._checkFinalizedStatuses(subscriber);
1965 return this._innerSubscribe(subscriber);
1966 };
1967 Subject.prototype._innerSubscribe = function (subscriber) {
1968 var _this = this;
1969 var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1970 if (hasError || isStopped) {
1971 return EMPTY_SUBSCRIPTION;
1972 }
1973 this.currentObservers = null;
1974 observers.push(subscriber);
1975 return new Subscription(function () {
1976 _this.currentObservers = null;
1977 arrRemove(observers, subscriber);
1978 });
1979 };
1980 Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1981 var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1982 if (hasError) {
1983 subscriber.error(thrownError);
1984 }
1985 else if (isStopped) {
1986 subscriber.complete();
1987 }
1988 };
1989 Subject.prototype.asObservable = function () {
1990 var observable = new Observable();
1991 observable.source = this;
1992 return observable;
1993 };
1994 Subject.create = function (destination, source) {
1995 return new AnonymousSubject(destination, source);
1996 };
1997 return Subject;
1998 }(Observable));
1999 var AnonymousSubject = (function (_super) {
2000 __extends(AnonymousSubject, _super);
2001 function AnonymousSubject(destination, source) {
2002 var _this = _super.call(this) || this;
2003 _this.destination = destination;
2004 _this.source = source;
2005 return _this;
2006 }
2007 AnonymousSubject.prototype.next = function (value) {
2008 var _a, _b;
2009 (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
2010 };
2011 AnonymousSubject.prototype.error = function (err) {
2012 var _a, _b;
2013 (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
2014 };
2015 AnonymousSubject.prototype.complete = function () {
2016 var _a, _b;
2017 (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
2018 };
2019 AnonymousSubject.prototype._subscribe = function (subscriber) {
2020 var _a, _b;
2021 return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
2022 };
2023 return AnonymousSubject;
2024 }(Subject));
2025
2026 var BehaviorSubject = (function (_super) {
2027 __extends(BehaviorSubject, _super);
2028 function BehaviorSubject(_value) {
2029 var _this = _super.call(this) || this;
2030 _this._value = _value;
2031 return _this;
2032 }
2033 Object.defineProperty(BehaviorSubject.prototype, "value", {
2034 get: function () {
2035 return this.getValue();
2036 },
2037 enumerable: false,
2038 configurable: true
2039 });
2040 BehaviorSubject.prototype._subscribe = function (subscriber) {
2041 var subscription = _super.prototype._subscribe.call(this, subscriber);
2042 !subscription.closed && subscriber.next(this._value);
2043 return subscription;
2044 };
2045 BehaviorSubject.prototype.getValue = function () {
2046 var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
2047 if (hasError) {
2048 throw thrownError;
2049 }
2050 this._throwIfClosed();
2051 return _value;
2052 };
2053 BehaviorSubject.prototype.next = function (value) {
2054 _super.prototype.next.call(this, (this._value = value));
2055 };
2056 return BehaviorSubject;
2057 }(Subject));
2058
2059 var dateTimestampProvider = {
2060 now: function () {
2061 return (dateTimestampProvider.delegate || Date).now();
2062 },
2063 delegate: undefined,
2064 };
2065
2066 var ReplaySubject = (function (_super) {
2067 __extends(ReplaySubject, _super);
2068 function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
2069 if (_bufferSize === void 0) { _bufferSize = Infinity; }
2070 if (_windowTime === void 0) { _windowTime = Infinity; }
2071 if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider; }
2072 var _this = _super.call(this) || this;
2073 _this._bufferSize = _bufferSize;
2074 _this._windowTime = _windowTime;
2075 _this._timestampProvider = _timestampProvider;
2076 _this._buffer = [];
2077 _this._infiniteTimeWindow = true;
2078 _this._infiniteTimeWindow = _windowTime === Infinity;
2079 _this._bufferSize = Math.max(1, _bufferSize);
2080 _this._windowTime = Math.max(1, _windowTime);
2081 return _this;
2082 }
2083 ReplaySubject.prototype.next = function (value) {
2084 var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
2085 if (!isStopped) {
2086 _buffer.push(value);
2087 !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
2088 }
2089 this._trimBuffer();
2090 _super.prototype.next.call(this, value);
2091 };
2092 ReplaySubject.prototype._subscribe = function (subscriber) {
2093 this._throwIfClosed();
2094 this._trimBuffer();
2095 var subscription = this._innerSubscribe(subscriber);
2096 var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
2097 var copy = _buffer.slice();
2098 for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
2099 subscriber.next(copy[i]);
2100 }
2101 this._checkFinalizedStatuses(subscriber);
2102 return subscription;
2103 };
2104 ReplaySubject.prototype._trimBuffer = function () {
2105 var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
2106 var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
2107 _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
2108 if (!_infiniteTimeWindow) {
2109 var now = _timestampProvider.now();
2110 var last = 0;
2111 for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
2112 last = i;
2113 }
2114 last && _buffer.splice(0, last + 1);
2115 }
2116 };
2117 return ReplaySubject;
2118 }(Subject));
2119
2120 ((function (_super) {
2121 __extends(AsyncSubject, _super);
2122 function AsyncSubject() {
2123 var _this = _super !== null && _super.apply(this, arguments) || this;
2124 _this._value = null;
2125 _this._hasValue = false;
2126 _this._isComplete = false;
2127 return _this;
2128 }
2129 AsyncSubject.prototype._checkFinalizedStatuses = function (subscriber) {
2130 var _a = this, hasError = _a.hasError, _hasValue = _a._hasValue, _value = _a._value, thrownError = _a.thrownError, isStopped = _a.isStopped, _isComplete = _a._isComplete;
2131 if (hasError) {
2132 subscriber.error(thrownError);
2133 }
2134 else if (isStopped || _isComplete) {
2135 _hasValue && subscriber.next(_value);
2136 subscriber.complete();
2137 }
2138 };
2139 AsyncSubject.prototype.next = function (value) {
2140 if (!this.isStopped) {
2141 this._value = value;
2142 this._hasValue = true;
2143 }
2144 };
2145 AsyncSubject.prototype.complete = function () {
2146 var _a = this, _hasValue = _a._hasValue, _value = _a._value, _isComplete = _a._isComplete;
2147 if (!_isComplete) {
2148 this._isComplete = true;
2149 _hasValue && _super.prototype.next.call(this, _value);
2150 _super.prototype.complete.call(this);
2151 }
2152 };
2153 return AsyncSubject;
2154 })(Subject));
2155
2156 var Action = (function (_super) {
2157 __extends(Action, _super);
2158 function Action(scheduler, work) {
2159 return _super.call(this) || this;
2160 }
2161 Action.prototype.schedule = function (state, delay) {
2162 return this;
2163 };
2164 return Action;
2165 }(Subscription));
2166
2167 var intervalProvider = {
2168 setInterval: function (handler, timeout) {
2169 var args = [];
2170 for (var _i = 2; _i < arguments.length; _i++) {
2171 args[_i - 2] = arguments[_i];
2172 }
2173 return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
2174 },
2175 clearInterval: function (handle) {
2176 return (clearInterval)(handle);
2177 },
2178 delegate: undefined,
2179 };
2180
2181 var AsyncAction = (function (_super) {
2182 __extends(AsyncAction, _super);
2183 function AsyncAction(scheduler, work) {
2184 var _this = _super.call(this, scheduler, work) || this;
2185 _this.scheduler = scheduler;
2186 _this.work = work;
2187 _this.pending = false;
2188 return _this;
2189 }
2190 AsyncAction.prototype.schedule = function (state, delay) {
2191 if (delay === void 0) { delay = 0; }
2192 if (this.closed) {
2193 return this;
2194 }
2195 this.state = state;
2196 var id = this.id;
2197 var scheduler = this.scheduler;
2198 if (id != null) {
2199 this.id = this.recycleAsyncId(scheduler, id, delay);
2200 }
2201 this.pending = true;
2202 this.delay = delay;
2203 this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
2204 return this;
2205 };
2206 AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
2207 if (delay === void 0) { delay = 0; }
2208 return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
2209 };
2210 AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
2211 if (delay === void 0) { delay = 0; }
2212 if (delay != null && this.delay === delay && this.pending === false) {
2213 return id;
2214 }
2215 intervalProvider.clearInterval(id);
2216 return undefined;
2217 };
2218 AsyncAction.prototype.execute = function (state, delay) {
2219 if (this.closed) {
2220 return new Error('executing a cancelled action');
2221 }
2222 this.pending = false;
2223 var error = this._execute(state, delay);
2224 if (error) {
2225 return error;
2226 }
2227 else if (this.pending === false && this.id != null) {
2228 this.id = this.recycleAsyncId(this.scheduler, this.id, null);
2229 }
2230 };
2231 AsyncAction.prototype._execute = function (state, _delay) {
2232 var errored = false;
2233 var errorValue;
2234 try {
2235 this.work(state);
2236 }
2237 catch (e) {
2238 errored = true;
2239 errorValue = e ? e : new Error('Scheduled action threw falsy error');
2240 }
2241 if (errored) {
2242 this.unsubscribe();
2243 return errorValue;
2244 }
2245 };
2246 AsyncAction.prototype.unsubscribe = function () {
2247 if (!this.closed) {
2248 var _a = this, id = _a.id, scheduler = _a.scheduler;
2249 var actions = scheduler.actions;
2250 this.work = this.state = this.scheduler = null;
2251 this.pending = false;
2252 arrRemove(actions, this);
2253 if (id != null) {
2254 this.id = this.recycleAsyncId(scheduler, id, null);
2255 }
2256 this.delay = null;
2257 _super.prototype.unsubscribe.call(this);
2258 }
2259 };
2260 return AsyncAction;
2261 }(Action));
2262
2263 var nextHandle = 1;
2264 var resolved;
2265 var activeHandles = {};
2266 function findAndClearHandle(handle) {
2267 if (handle in activeHandles) {
2268 delete activeHandles[handle];
2269 return true;
2270 }
2271 return false;
2272 }
2273 var Immediate = {
2274 setImmediate: function (cb) {
2275 var handle = nextHandle++;
2276 activeHandles[handle] = true;
2277 if (!resolved) {
2278 resolved = Promise.resolve();
2279 }
2280 resolved.then(function () { return findAndClearHandle(handle) && cb(); });
2281 return handle;
2282 },
2283 clearImmediate: function (handle) {
2284 findAndClearHandle(handle);
2285 },
2286 };
2287
2288 var setImmediate = Immediate.setImmediate, clearImmediate = Immediate.clearImmediate;
2289 var immediateProvider = {
2290 setImmediate: function () {
2291 var args = [];
2292 for (var _i = 0; _i < arguments.length; _i++) {
2293 args[_i] = arguments[_i];
2294 }
2295 var delegate = immediateProvider.delegate;
2296 return ((delegate === null || delegate === void 0 ? void 0 : delegate.setImmediate) || setImmediate).apply(void 0, __spreadArray([], __read(args)));
2297 },
2298 clearImmediate: function (handle) {
2299 return (clearImmediate)(handle);
2300 },
2301 delegate: undefined,
2302 };
2303
2304 var AsapAction = (function (_super) {
2305 __extends(AsapAction, _super);
2306 function AsapAction(scheduler, work) {
2307 var _this = _super.call(this, scheduler, work) || this;
2308 _this.scheduler = scheduler;
2309 _this.work = work;
2310 return _this;
2311 }
2312 AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
2313 if (delay === void 0) { delay = 0; }
2314 if (delay !== null && delay > 0) {
2315 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
2316 }
2317 scheduler.actions.push(this);
2318 return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));
2319 };
2320 AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
2321 if (delay === void 0) { delay = 0; }
2322 if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {
2323 return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
2324 }
2325 if (!scheduler.actions.some(function (action) { return action.id === id; })) {
2326 immediateProvider.clearImmediate(id);
2327 scheduler._scheduled = undefined;
2328 }
2329 return undefined;
2330 };
2331 return AsapAction;
2332 }(AsyncAction));
2333
2334 var Scheduler = (function () {
2335 function Scheduler(schedulerActionCtor, now) {
2336 if (now === void 0) { now = Scheduler.now; }
2337 this.schedulerActionCtor = schedulerActionCtor;
2338 this.now = now;
2339 }
2340 Scheduler.prototype.schedule = function (work, delay, state) {
2341 if (delay === void 0) { delay = 0; }
2342 return new this.schedulerActionCtor(this, work).schedule(state, delay);
2343 };
2344 Scheduler.now = dateTimestampProvider.now;
2345 return Scheduler;
2346 }());
2347
2348 var AsyncScheduler = (function (_super) {
2349 __extends(AsyncScheduler, _super);
2350 function AsyncScheduler(SchedulerAction, now) {
2351 if (now === void 0) { now = Scheduler.now; }
2352 var _this = _super.call(this, SchedulerAction, now) || this;
2353 _this.actions = [];
2354 _this._active = false;
2355 _this._scheduled = undefined;
2356 return _this;
2357 }
2358 AsyncScheduler.prototype.flush = function (action) {
2359 var actions = this.actions;
2360 if (this._active) {
2361 actions.push(action);
2362 return;
2363 }
2364 var error;
2365 this._active = true;
2366 do {
2367 if ((error = action.execute(action.state, action.delay))) {
2368 break;
2369 }
2370 } while ((action = actions.shift()));
2371 this._active = false;
2372 if (error) {
2373 while ((action = actions.shift())) {
2374 action.unsubscribe();
2375 }
2376 throw error;
2377 }
2378 };
2379 return AsyncScheduler;
2380 }(Scheduler));
2381
2382 var AsapScheduler = (function (_super) {
2383 __extends(AsapScheduler, _super);
2384 function AsapScheduler() {
2385 return _super !== null && _super.apply(this, arguments) || this;
2386 }
2387 AsapScheduler.prototype.flush = function (action) {
2388 this._active = true;
2389 var flushId = this._scheduled;
2390 this._scheduled = undefined;
2391 var actions = this.actions;
2392 var error;
2393 action = action || actions.shift();
2394 do {
2395 if ((error = action.execute(action.state, action.delay))) {
2396 break;
2397 }
2398 } while ((action = actions[0]) && action.id === flushId && actions.shift());
2399 this._active = false;
2400 if (error) {
2401 while ((action = actions[0]) && action.id === flushId && actions.shift()) {
2402 action.unsubscribe();
2403 }
2404 throw error;
2405 }
2406 };
2407 return AsapScheduler;
2408 }(AsyncScheduler));
2409
2410 var asapScheduler = new AsapScheduler(AsapAction);
2411
2412 new AsyncScheduler(AsyncAction);
2413
2414 var QueueAction = (function (_super) {
2415 __extends(QueueAction, _super);
2416 function QueueAction(scheduler, work) {
2417 var _this = _super.call(this, scheduler, work) || this;
2418 _this.scheduler = scheduler;
2419 _this.work = work;
2420 return _this;
2421 }
2422 QueueAction.prototype.schedule = function (state, delay) {
2423 if (delay === void 0) { delay = 0; }
2424 if (delay > 0) {
2425 return _super.prototype.schedule.call(this, state, delay);
2426 }
2427 this.delay = delay;
2428 this.state = state;
2429 this.scheduler.flush(this);
2430 return this;
2431 };
2432 QueueAction.prototype.execute = function (state, delay) {
2433 return (delay > 0 || this.closed) ?
2434 _super.prototype.execute.call(this, state, delay) :
2435 this._execute(state, delay);
2436 };
2437 QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
2438 if (delay === void 0) { delay = 0; }
2439 if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {
2440 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
2441 }
2442 return scheduler.flush(this);
2443 };
2444 return QueueAction;
2445 }(AsyncAction));
2446
2447 var QueueScheduler = (function (_super) {
2448 __extends(QueueScheduler, _super);
2449 function QueueScheduler() {
2450 return _super !== null && _super.apply(this, arguments) || this;
2451 }
2452 return QueueScheduler;
2453 }(AsyncScheduler));
2454
2455 new QueueScheduler(QueueAction);
2456
2457 var AnimationFrameAction = (function (_super) {
2458 __extends(AnimationFrameAction, _super);
2459 function AnimationFrameAction(scheduler, work) {
2460 var _this = _super.call(this, scheduler, work) || this;
2461 _this.scheduler = scheduler;
2462 _this.work = work;
2463 return _this;
2464 }
2465 AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
2466 if (delay === void 0) { delay = 0; }
2467 if (delay !== null && delay > 0) {
2468 return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
2469 }
2470 scheduler.actions.push(this);
2471 return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(function () { return scheduler.flush(undefined); }));
2472 };
2473 AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
2474 if (delay === void 0) { delay = 0; }
2475 if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {
2476 return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
2477 }
2478 if (!scheduler.actions.some(function (action) { return action.id === id; })) {
2479 animationFrameProvider.cancelAnimationFrame(id);
2480 scheduler._scheduled = undefined;
2481 }
2482 return undefined;
2483 };
2484 return AnimationFrameAction;
2485 }(AsyncAction));
2486
2487 var AnimationFrameScheduler = (function (_super) {
2488 __extends(AnimationFrameScheduler, _super);
2489 function AnimationFrameScheduler() {
2490 return _super !== null && _super.apply(this, arguments) || this;
2491 }
2492 AnimationFrameScheduler.prototype.flush = function (action) {
2493 this._active = true;
2494 var flushId = this._scheduled;
2495 this._scheduled = undefined;
2496 var actions = this.actions;
2497 var error;
2498 action = action || actions.shift();
2499 do {
2500 if ((error = action.execute(action.state, action.delay))) {
2501 break;
2502 }
2503 } while ((action = actions[0]) && action.id === flushId && actions.shift());
2504 this._active = false;
2505 if (error) {
2506 while ((action = actions[0]) && action.id === flushId && actions.shift()) {
2507 action.unsubscribe();
2508 }
2509 throw error;
2510 }
2511 };
2512 return AnimationFrameScheduler;
2513 }(AsyncScheduler));
2514
2515 new AnimationFrameScheduler(AnimationFrameAction);
2516
2517 ((function (_super) {
2518 __extends(VirtualTimeScheduler, _super);
2519 function VirtualTimeScheduler(schedulerActionCtor, maxFrames) {
2520 if (schedulerActionCtor === void 0) { schedulerActionCtor = VirtualAction; }
2521 if (maxFrames === void 0) { maxFrames = Infinity; }
2522 var _this = _super.call(this, schedulerActionCtor, function () { return _this.frame; }) || this;
2523 _this.maxFrames = maxFrames;
2524 _this.frame = 0;
2525 _this.index = -1;
2526 return _this;
2527 }
2528 VirtualTimeScheduler.prototype.flush = function () {
2529 var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
2530 var error;
2531 var action;
2532 while ((action = actions[0]) && action.delay <= maxFrames) {
2533 actions.shift();
2534 this.frame = action.delay;
2535 if ((error = action.execute(action.state, action.delay))) {
2536 break;
2537 }
2538 }
2539 if (error) {
2540 while ((action = actions.shift())) {
2541 action.unsubscribe();
2542 }
2543 throw error;
2544 }
2545 };
2546 VirtualTimeScheduler.frameTimeFactor = 10;
2547 return VirtualTimeScheduler;
2548 })(AsyncScheduler));
2549 var VirtualAction = (function (_super) {
2550 __extends(VirtualAction, _super);
2551 function VirtualAction(scheduler, work, index) {
2552 if (index === void 0) { index = (scheduler.index += 1); }
2553 var _this = _super.call(this, scheduler, work) || this;
2554 _this.scheduler = scheduler;
2555 _this.work = work;
2556 _this.index = index;
2557 _this.active = true;
2558 _this.index = scheduler.index = index;
2559 return _this;
2560 }
2561 VirtualAction.prototype.schedule = function (state, delay) {
2562 if (delay === void 0) { delay = 0; }
2563 if (Number.isFinite(delay)) {
2564 if (!this.id) {
2565 return _super.prototype.schedule.call(this, state, delay);
2566 }
2567 this.active = false;
2568 var action = new VirtualAction(this.scheduler, this.work);
2569 this.add(action);
2570 return action.schedule(state, delay);
2571 }
2572 else {
2573 return Subscription.EMPTY;
2574 }
2575 };
2576 VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
2577 if (delay === void 0) { delay = 0; }
2578 this.delay = scheduler.frame + delay;
2579 var actions = scheduler.actions;
2580 actions.push(this);
2581 actions.sort(VirtualAction.sortActions);
2582 return true;
2583 };
2584 VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
2585 return undefined;
2586 };
2587 VirtualAction.prototype._execute = function (state, delay) {
2588 if (this.active === true) {
2589 return _super.prototype._execute.call(this, state, delay);
2590 }
2591 };
2592 VirtualAction.sortActions = function (a, b) {
2593 if (a.delay === b.delay) {
2594 if (a.index === b.index) {
2595 return 0;
2596 }
2597 else if (a.index > b.index) {
2598 return 1;
2599 }
2600 else {
2601 return -1;
2602 }
2603 }
2604 else if (a.delay > b.delay) {
2605 return 1;
2606 }
2607 else {
2608 return -1;
2609 }
2610 };
2611 return VirtualAction;
2612 }(AsyncAction));
2613
2614 var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); });
2615
2616 function isScheduler(value) {
2617 return value && isFunction(value.schedule);
2618 }
2619
2620 function last(arr) {
2621 return arr[arr.length - 1];
2622 }
2623 function popResultSelector(args) {
2624 return isFunction(last(args)) ? args.pop() : undefined;
2625 }
2626 function popScheduler(args) {
2627 return isScheduler(last(args)) ? args.pop() : undefined;
2628 }
2629
2630 var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
2631
2632 function isPromise(value) {
2633 return isFunction(value === null || value === void 0 ? void 0 : value.then);
2634 }
2635
2636 function isInteropObservable(input) {
2637 return isFunction(input[observable]);
2638 }
2639
2640 function isAsyncIterable(obj) {
2641 return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
2642 }
2643
2644 function createInvalidObservableTypeError(input) {
2645 return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
2646 }
2647
2648 function getSymbolIterator() {
2649 if (typeof Symbol !== 'function' || !Symbol.iterator) {
2650 return '@@iterator';
2651 }
2652 return Symbol.iterator;
2653 }
2654 var iterator = getSymbolIterator();
2655
2656 function isIterable(input) {
2657 return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
2658 }
2659
2660 function readableStreamLikeToAsyncGenerator(readableStream) {
2661 return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
2662 var reader, _a, value, done;
2663 return __generator(this, function (_b) {
2664 switch (_b.label) {
2665 case 0:
2666 reader = readableStream.getReader();
2667 _b.label = 1;
2668 case 1:
2669 _b.trys.push([1, , 9, 10]);
2670 _b.label = 2;
2671 case 2:
2672 return [4, __await(reader.read())];
2673 case 3:
2674 _a = _b.sent(), value = _a.value, done = _a.done;
2675 if (!done) return [3, 5];
2676 return [4, __await(void 0)];
2677 case 4: return [2, _b.sent()];
2678 case 5: return [4, __await(value)];
2679 case 6: return [4, _b.sent()];
2680 case 7:
2681 _b.sent();
2682 return [3, 2];
2683 case 8: return [3, 10];
2684 case 9:
2685 reader.releaseLock();
2686 return [7];
2687 case 10: return [2];
2688 }
2689 });
2690 });
2691 }
2692 function isReadableStreamLike(obj) {
2693 return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
2694 }
2695
2696 function innerFrom(input) {
2697 if (input instanceof Observable) {
2698 return input;
2699 }
2700 if (input != null) {
2701 if (isInteropObservable(input)) {
2702 return fromInteropObservable(input);
2703 }
2704 if (isArrayLike(input)) {
2705 return fromArrayLike(input);
2706 }
2707 if (isPromise(input)) {
2708 return fromPromise(input);
2709 }
2710 if (isAsyncIterable(input)) {
2711 return fromAsyncIterable(input);
2712 }
2713 if (isIterable(input)) {
2714 return fromIterable(input);
2715 }
2716 if (isReadableStreamLike(input)) {
2717 return fromReadableStreamLike(input);
2718 }
2719 }
2720 throw createInvalidObservableTypeError(input);
2721 }
2722 function fromInteropObservable(obj) {
2723 return new Observable(function (subscriber) {
2724 var obs = obj[observable]();
2725 if (isFunction(obs.subscribe)) {
2726 return obs.subscribe(subscriber);
2727 }
2728 throw new TypeError('Provided object does not correctly implement Symbol.observable');
2729 });
2730 }
2731 function fromArrayLike(array) {
2732 return new Observable(function (subscriber) {
2733 for (var i = 0; i < array.length && !subscriber.closed; i++) {
2734 subscriber.next(array[i]);
2735 }
2736 subscriber.complete();
2737 });
2738 }
2739 function fromPromise(promise) {
2740 return new Observable(function (subscriber) {
2741 promise
2742 .then(function (value) {
2743 if (!subscriber.closed) {
2744 subscriber.next(value);
2745 subscriber.complete();
2746 }
2747 }, function (err) { return subscriber.error(err); })
2748 .then(null, reportUnhandledError);
2749 });
2750 }
2751 function fromIterable(iterable) {
2752 return new Observable(function (subscriber) {
2753 var e_1, _a;
2754 try {
2755 for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
2756 var value = iterable_1_1.value;
2757 subscriber.next(value);
2758 if (subscriber.closed) {
2759 return;
2760 }
2761 }
2762 }
2763 catch (e_1_1) { e_1 = { error: e_1_1 }; }
2764 finally {
2765 try {
2766 if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
2767 }
2768 finally { if (e_1) throw e_1.error; }
2769 }
2770 subscriber.complete();
2771 });
2772 }
2773 function fromAsyncIterable(asyncIterable) {
2774 return new Observable(function (subscriber) {
2775 process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
2776 });
2777 }
2778 function fromReadableStreamLike(readableStream) {
2779 return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
2780 }
2781 function process(asyncIterable, subscriber) {
2782 var asyncIterable_1, asyncIterable_1_1;
2783 var e_2, _a;
2784 return __awaiter(this, void 0, void 0, function () {
2785 var value, e_2_1;
2786 return __generator(this, function (_b) {
2787 switch (_b.label) {
2788 case 0:
2789 _b.trys.push([0, 5, 6, 11]);
2790 asyncIterable_1 = __asyncValues(asyncIterable);
2791 _b.label = 1;
2792 case 1: return [4, asyncIterable_1.next()];
2793 case 2:
2794 if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
2795 value = asyncIterable_1_1.value;
2796 subscriber.next(value);
2797 if (subscriber.closed) {
2798 return [2];
2799 }
2800 _b.label = 3;
2801 case 3: return [3, 1];
2802 case 4: return [3, 11];
2803 case 5:
2804 e_2_1 = _b.sent();
2805 e_2 = { error: e_2_1 };
2806 return [3, 11];
2807 case 6:
2808 _b.trys.push([6, , 9, 10]);
2809 if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
2810 return [4, _a.call(asyncIterable_1)];
2811 case 7:
2812 _b.sent();
2813 _b.label = 8;
2814 case 8: return [3, 10];
2815 case 9:
2816 if (e_2) throw e_2.error;
2817 return [7];
2818 case 10: return [7];
2819 case 11:
2820 subscriber.complete();
2821 return [2];
2822 }
2823 });
2824 });
2825 }
2826
2827 function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
2828 if (delay === void 0) { delay = 0; }
2829 if (repeat === void 0) { repeat = false; }
2830 var scheduleSubscription = scheduler.schedule(function () {
2831 work();
2832 if (repeat) {
2833 parentSubscription.add(this.schedule(null, delay));
2834 }
2835 else {
2836 this.unsubscribe();
2837 }
2838 }, delay);
2839 parentSubscription.add(scheduleSubscription);
2840 if (!repeat) {
2841 return scheduleSubscription;
2842 }
2843 }
2844
2845 function observeOn(scheduler, delay) {
2846 if (delay === void 0) { delay = 0; }
2847 return operate(function (source, subscriber) {
2848 source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
2849 });
2850 }
2851
2852 function subscribeOn(scheduler, delay) {
2853 if (delay === void 0) { delay = 0; }
2854 return operate(function (source, subscriber) {
2855 subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
2856 });
2857 }
2858
2859 function scheduleObservable(input, scheduler) {
2860 return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
2861 }
2862
2863 function schedulePromise(input, scheduler) {
2864 return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
2865 }
2866
2867 function scheduleArray(input, scheduler) {
2868 return new Observable(function (subscriber) {
2869 var i = 0;
2870 return scheduler.schedule(function () {
2871 if (i === input.length) {
2872 subscriber.complete();
2873 }
2874 else {
2875 subscriber.next(input[i++]);
2876 if (!subscriber.closed) {
2877 this.schedule();
2878 }
2879 }
2880 });
2881 });
2882 }
2883
2884 function scheduleIterable(input, scheduler) {
2885 return new Observable(function (subscriber) {
2886 var iterator$1;
2887 executeSchedule(subscriber, scheduler, function () {
2888 iterator$1 = input[iterator]();
2889 executeSchedule(subscriber, scheduler, function () {
2890 var _a;
2891 var value;
2892 var done;
2893 try {
2894 (_a = iterator$1.next(), value = _a.value, done = _a.done);
2895 }
2896 catch (err) {
2897 subscriber.error(err);
2898 return;
2899 }
2900 if (done) {
2901 subscriber.complete();
2902 }
2903 else {
2904 subscriber.next(value);
2905 }
2906 }, 0, true);
2907 });
2908 return function () { return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
2909 });
2910 }
2911
2912 function scheduleAsyncIterable(input, scheduler) {
2913 if (!input) {
2914 throw new Error('Iterable cannot be null');
2915 }
2916 return new Observable(function (subscriber) {
2917 executeSchedule(subscriber, scheduler, function () {
2918 var iterator = input[Symbol.asyncIterator]();
2919 executeSchedule(subscriber, scheduler, function () {
2920 iterator.next().then(function (result) {
2921 if (result.done) {
2922 subscriber.complete();
2923 }
2924 else {
2925 subscriber.next(result.value);
2926 }
2927 });
2928 }, 0, true);
2929 });
2930 });
2931 }
2932
2933 function scheduleReadableStreamLike(input, scheduler) {
2934 return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
2935 }
2936
2937 function scheduled(input, scheduler) {
2938 if (input != null) {
2939 if (isInteropObservable(input)) {
2940 return scheduleObservable(input, scheduler);
2941 }
2942 if (isArrayLike(input)) {
2943 return scheduleArray(input, scheduler);
2944 }
2945 if (isPromise(input)) {
2946 return schedulePromise(input, scheduler);
2947 }
2948 if (isAsyncIterable(input)) {
2949 return scheduleAsyncIterable(input, scheduler);
2950 }
2951 if (isIterable(input)) {
2952 return scheduleIterable(input, scheduler);
2953 }
2954 if (isReadableStreamLike(input)) {
2955 return scheduleReadableStreamLike(input, scheduler);
2956 }
2957 }
2958 throw createInvalidObservableTypeError(input);
2959 }
2960
2961 function from(input, scheduler) {
2962 return scheduler ? scheduled(input, scheduler) : innerFrom(input);
2963 }
2964
2965 function of() {
2966 var args = [];
2967 for (var _i = 0; _i < arguments.length; _i++) {
2968 args[_i] = arguments[_i];
2969 }
2970 var scheduler = popScheduler(args);
2971 return from(args, scheduler);
2972 }
2973
2974 var NotificationKind;
2975 (function (NotificationKind) {
2976 NotificationKind["NEXT"] = "N";
2977 NotificationKind["ERROR"] = "E";
2978 NotificationKind["COMPLETE"] = "C";
2979 })(NotificationKind || (NotificationKind = {}));
2980
2981 var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
2982 _super(this);
2983 this.name = 'EmptyError';
2984 this.message = 'no elements in sequence';
2985 }; });
2986
2987 function firstValueFrom(source, config) {
2988 var hasConfig = typeof config === 'object';
2989 return new Promise(function (resolve, reject) {
2990 var subscriber = new SafeSubscriber({
2991 next: function (value) {
2992 resolve(value);
2993 subscriber.unsubscribe();
2994 },
2995 error: reject,
2996 complete: function () {
2997 if (hasConfig) {
2998 resolve(config.defaultValue);
2999 }
3000 else {
3001 reject(new EmptyError());
3002 }
3003 },
3004 });
3005 source.subscribe(subscriber);
3006 });
3007 }
3008
3009 createErrorClass(function (_super) {
3010 return function ArgumentOutOfRangeErrorImpl() {
3011 _super(this);
3012 this.name = 'ArgumentOutOfRangeError';
3013 this.message = 'argument out of range';
3014 };
3015 });
3016
3017 createErrorClass(function (_super) {
3018 return function NotFoundErrorImpl(message) {
3019 _super(this);
3020 this.name = 'NotFoundError';
3021 this.message = message;
3022 };
3023 });
3024
3025 createErrorClass(function (_super) {
3026 return function SequenceErrorImpl(message) {
3027 _super(this);
3028 this.name = 'SequenceError';
3029 this.message = message;
3030 };
3031 });
3032
3033 createErrorClass(function (_super) {
3034 return function TimeoutErrorImpl(info) {
3035 if (info === void 0) { info = null; }
3036 _super(this);
3037 this.message = 'Timeout has occurred';
3038 this.name = 'TimeoutError';
3039 this.info = info;
3040 };
3041 });
3042
3043 function map(project, thisArg) {
3044 return operate(function (source, subscriber) {
3045 var index = 0;
3046 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3047 subscriber.next(project.call(thisArg, value, index++));
3048 }));
3049 });
3050 }
3051
3052 var isArray$1 = Array.isArray;
3053 function callOrApply(fn, args) {
3054 return isArray$1(args) ? fn.apply(void 0, __spreadArray([], __read(args))) : fn(args);
3055 }
3056 function mapOneOrManyArgs(fn) {
3057 return map(function (args) { return callOrApply(fn, args); });
3058 }
3059
3060 var isArray = Array.isArray;
3061 var getPrototypeOf = Object.getPrototypeOf, objectProto = Object.prototype, getKeys = Object.keys;
3062 function argsArgArrayOrObject(args) {
3063 if (args.length === 1) {
3064 var first_1 = args[0];
3065 if (isArray(first_1)) {
3066 return { args: first_1, keys: null };
3067 }
3068 if (isPOJO(first_1)) {
3069 var keys = getKeys(first_1);
3070 return {
3071 args: keys.map(function (key) { return first_1[key]; }),
3072 keys: keys,
3073 };
3074 }
3075 }
3076 return { args: args, keys: null };
3077 }
3078 function isPOJO(obj) {
3079 return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;
3080 }
3081
3082 function createObject(keys, values) {
3083 return keys.reduce(function (result, key, i) { return ((result[key] = values[i]), result); }, {});
3084 }
3085
3086 function combineLatest() {
3087 var args = [];
3088 for (var _i = 0; _i < arguments.length; _i++) {
3089 args[_i] = arguments[_i];
3090 }
3091 var scheduler = popScheduler(args);
3092 var resultSelector = popResultSelector(args);
3093 var _a = argsArgArrayOrObject(args), observables = _a.args, keys = _a.keys;
3094 if (observables.length === 0) {
3095 return from([], scheduler);
3096 }
3097 var result = new Observable(combineLatestInit(observables, scheduler, keys
3098 ?
3099 function (values) { return createObject(keys, values); }
3100 :
3101 identity$2));
3102 return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;
3103 }
3104 function combineLatestInit(observables, scheduler, valueTransform) {
3105 if (valueTransform === void 0) { valueTransform = identity$2; }
3106 return function (subscriber) {
3107 maybeSchedule(scheduler, function () {
3108 var length = observables.length;
3109 var values = new Array(length);
3110 var active = length;
3111 var remainingFirstValues = length;
3112 var _loop_1 = function (i) {
3113 maybeSchedule(scheduler, function () {
3114 var source = from(observables[i], scheduler);
3115 var hasFirstValue = false;
3116 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3117 values[i] = value;
3118 if (!hasFirstValue) {
3119 hasFirstValue = true;
3120 remainingFirstValues--;
3121 }
3122 if (!remainingFirstValues) {
3123 subscriber.next(valueTransform(values.slice()));
3124 }
3125 }, function () {
3126 if (!--active) {
3127 subscriber.complete();
3128 }
3129 }));
3130 }, subscriber);
3131 };
3132 for (var i = 0; i < length; i++) {
3133 _loop_1(i);
3134 }
3135 }, subscriber);
3136 };
3137 }
3138 function maybeSchedule(scheduler, execute, subscription) {
3139 if (scheduler) {
3140 executeSchedule(subscription, scheduler, execute);
3141 }
3142 else {
3143 execute();
3144 }
3145 }
3146
3147 function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
3148 var buffer = [];
3149 var active = 0;
3150 var index = 0;
3151 var isComplete = false;
3152 var checkComplete = function () {
3153 if (isComplete && !buffer.length && !active) {
3154 subscriber.complete();
3155 }
3156 };
3157 var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
3158 var doInnerSub = function (value) {
3159 expand && subscriber.next(value);
3160 active++;
3161 var innerComplete = false;
3162 innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
3163 onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
3164 if (expand) {
3165 outerNext(innerValue);
3166 }
3167 else {
3168 subscriber.next(innerValue);
3169 }
3170 }, function () {
3171 innerComplete = true;
3172 }, undefined, function () {
3173 if (innerComplete) {
3174 try {
3175 active--;
3176 var _loop_1 = function () {
3177 var bufferedValue = buffer.shift();
3178 if (innerSubScheduler) {
3179 executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
3180 }
3181 else {
3182 doInnerSub(bufferedValue);
3183 }
3184 };
3185 while (buffer.length && active < concurrent) {
3186 _loop_1();
3187 }
3188 checkComplete();
3189 }
3190 catch (err) {
3191 subscriber.error(err);
3192 }
3193 }
3194 }));
3195 };
3196 source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
3197 isComplete = true;
3198 checkComplete();
3199 }));
3200 return function () {
3201 additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
3202 };
3203 }
3204
3205 function mergeMap(project, resultSelector, concurrent) {
3206 if (concurrent === void 0) { concurrent = Infinity; }
3207 if (isFunction(resultSelector)) {
3208 return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
3209 }
3210 else if (typeof resultSelector === 'number') {
3211 concurrent = resultSelector;
3212 }
3213 return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
3214 }
3215
3216 function mergeAll(concurrent) {
3217 if (concurrent === void 0) { concurrent = Infinity; }
3218 return mergeMap(identity$2, concurrent);
3219 }
3220
3221 function concatAll() {
3222 return mergeAll(1);
3223 }
3224
3225 function concat() {
3226 var args = [];
3227 for (var _i = 0; _i < arguments.length; _i++) {
3228 args[_i] = arguments[_i];
3229 }
3230 return concatAll()(from(args, popScheduler(args)));
3231 }
3232
3233 new Observable(noop);
3234
3235 function filter(predicate, thisArg) {
3236 return operate(function (source, subscriber) {
3237 var index = 0;
3238 source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
3239 });
3240 }
3241
3242 function catchError(selector) {
3243 return operate(function (source, subscriber) {
3244 var innerSub = null;
3245 var syncUnsub = false;
3246 var handledResult;
3247 innerSub = source.subscribe(createOperatorSubscriber(subscriber, undefined, undefined, function (err) {
3248 handledResult = innerFrom(selector(err, catchError(selector)(source)));
3249 if (innerSub) {
3250 innerSub.unsubscribe();
3251 innerSub = null;
3252 handledResult.subscribe(subscriber);
3253 }
3254 else {
3255 syncUnsub = true;
3256 }
3257 }));
3258 if (syncUnsub) {
3259 innerSub.unsubscribe();
3260 innerSub = null;
3261 handledResult.subscribe(subscriber);
3262 }
3263 });
3264 }
3265
3266 function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
3267 return function (source, subscriber) {
3268 var hasState = hasSeed;
3269 var state = seed;
3270 var index = 0;
3271 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3272 var i = index++;
3273 state = hasState
3274 ?
3275 accumulator(state, value, i)
3276 :
3277 ((hasState = true), value);
3278 emitOnNext && subscriber.next(state);
3279 }, emitBeforeComplete &&
3280 (function () {
3281 hasState && subscriber.next(state);
3282 subscriber.complete();
3283 })));
3284 };
3285 }
3286
3287 function reduce(accumulator, seed) {
3288 return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
3289 }
3290
3291 var arrReducer = function (arr, value) { return (arr.push(value), arr); };
3292 function toArray() {
3293 return operate(function (source, subscriber) {
3294 reduce(arrReducer, [])(source).subscribe(subscriber);
3295 });
3296 }
3297
3298 function fromSubscribable(subscribable) {
3299 return new Observable(function (subscriber) { return subscribable.subscribe(subscriber); });
3300 }
3301
3302 var DEFAULT_CONFIG = {
3303 connector: function () { return new Subject(); },
3304 };
3305 function connect(selector, config) {
3306 if (config === void 0) { config = DEFAULT_CONFIG; }
3307 var connector = config.connector;
3308 return operate(function (source, subscriber) {
3309 var subject = connector();
3310 from(selector(fromSubscribable(subject))).subscribe(subscriber);
3311 subscriber.add(source.subscribe(subject));
3312 });
3313 }
3314
3315 function defaultIfEmpty(defaultValue) {
3316 return operate(function (source, subscriber) {
3317 var hasValue = false;
3318 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3319 hasValue = true;
3320 subscriber.next(value);
3321 }, function () {
3322 if (!hasValue) {
3323 subscriber.next(defaultValue);
3324 }
3325 subscriber.complete();
3326 }));
3327 });
3328 }
3329
3330 function take(count) {
3331 return count <= 0
3332 ?
3333 function () { return EMPTY; }
3334 : operate(function (source, subscriber) {
3335 var seen = 0;
3336 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3337 if (++seen <= count) {
3338 subscriber.next(value);
3339 if (count <= seen) {
3340 subscriber.complete();
3341 }
3342 }
3343 }));
3344 });
3345 }
3346
3347 function mapTo(value) {
3348 return map(function () { return value; });
3349 }
3350
3351 function distinctUntilChanged(comparator, keySelector) {
3352 if (keySelector === void 0) { keySelector = identity$2; }
3353 comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;
3354 return operate(function (source, subscriber) {
3355 var previousKey;
3356 var first = true;
3357 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3358 var currentKey = keySelector(value);
3359 if (first || !comparator(previousKey, currentKey)) {
3360 first = false;
3361 previousKey = currentKey;
3362 subscriber.next(value);
3363 }
3364 }));
3365 });
3366 }
3367 function defaultCompare(a, b) {
3368 return a === b;
3369 }
3370
3371 function throwIfEmpty(errorFactory) {
3372 if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
3373 return operate(function (source, subscriber) {
3374 var hasValue = false;
3375 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3376 hasValue = true;
3377 subscriber.next(value);
3378 }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
3379 });
3380 }
3381 function defaultErrorFactory() {
3382 return new EmptyError();
3383 }
3384
3385 function first(predicate, defaultValue) {
3386 var hasDefaultValue = arguments.length >= 2;
3387 return function (source) {
3388 return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$2, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
3389 };
3390 }
3391
3392 function multicast(subjectOrSubjectFactory, selector) {
3393 var subjectFactory = isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : function () { return subjectOrSubjectFactory; };
3394 if (isFunction(selector)) {
3395 return connect(selector, {
3396 connector: subjectFactory,
3397 });
3398 }
3399 return function (source) { return new ConnectableObservable(source, subjectFactory); };
3400 }
3401
3402 function publishReplay(bufferSize, windowTime, selectorOrScheduler, timestampProvider) {
3403 if (selectorOrScheduler && !isFunction(selectorOrScheduler)) {
3404 timestampProvider = selectorOrScheduler;
3405 }
3406 var selector = isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined;
3407 return function (source) { return multicast(new ReplaySubject(bufferSize, windowTime, timestampProvider), selector)(source); };
3408 }
3409
3410 function startWith() {
3411 var values = [];
3412 for (var _i = 0; _i < arguments.length; _i++) {
3413 values[_i] = arguments[_i];
3414 }
3415 var scheduler = popScheduler(values);
3416 return operate(function (source, subscriber) {
3417 (scheduler ? concat(values, source, scheduler) : concat(values, source)).subscribe(subscriber);
3418 });
3419 }
3420
3421 function switchMap(project, resultSelector) {
3422 return operate(function (source, subscriber) {
3423 var innerSubscriber = null;
3424 var index = 0;
3425 var isComplete = false;
3426 var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
3427 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3428 innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
3429 var innerIndex = 0;
3430 var outerIndex = index++;
3431 innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
3432 innerSubscriber = null;
3433 checkComplete();
3434 })));
3435 }, function () {
3436 isComplete = true;
3437 checkComplete();
3438 }));
3439 });
3440 }
3441
3442 function tap(observerOrNext, error, complete) {
3443 var tapObserver = isFunction(observerOrNext) || error || complete
3444 ?
3445 { next: observerOrNext, error: error, complete: complete }
3446 : observerOrNext;
3447 return tapObserver
3448 ? operate(function (source, subscriber) {
3449 var _a;
3450 (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
3451 var isUnsub = true;
3452 source.subscribe(createOperatorSubscriber(subscriber, function (value) {
3453 var _a;
3454 (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);
3455 subscriber.next(value);
3456 }, function () {
3457 var _a;
3458 isUnsub = false;
3459 (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
3460 subscriber.complete();
3461 }, function (err) {
3462 var _a;
3463 isUnsub = false;
3464 (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);
3465 subscriber.error(err);
3466 }, function () {
3467 var _a, _b;
3468 if (isUnsub) {
3469 (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
3470 }
3471 (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
3472 }));
3473 })
3474 :
3475 identity$2;
3476 }
3477
3478 function refCountDelay(delay = 1750) {
3479 return source => {
3480 let [state, refCount, connection, scheduler] = [0, 0, Subscription.EMPTY, Subscription.EMPTY];
3481 return new Observable(ob => {
3482 source.subscribe(ob);
3483 if (refCount++ === 0) {
3484 if (state === 1) {
3485 scheduler.unsubscribe();
3486 } else {
3487 connection = source.connect();
3488 }
3489 state = 3;
3490 }
3491 return () => {
3492 if (--refCount === 0) {
3493 if (state === 2) {
3494 state = 0;
3495 scheduler.unsubscribe();
3496 } else {
3497 state = 1;
3498 scheduler = asapScheduler.schedule(() => {
3499 state = 0;
3500 connection.unsubscribe();
3501 }, delay);
3502 }
3503 }
3504 };
3505 });
3506 };
3507 }
3508
3509 const l$5 = util.logger('drr');
3510 const CMP = (a, b) => util.stringify({
3511 t: a
3512 }) === util.stringify({
3513 t: b
3514 });
3515 const ERR = error => {
3516 l$5.error(error.message);
3517 throw error;
3518 };
3519 const NOOP = () => undefined;
3520 const drr = ({
3521 delay,
3522 skipChange = false,
3523 skipTimeout = false
3524 } = {}) => source$ => source$.pipe(catchError(ERR), skipChange ? tap(NOOP) : distinctUntilChanged(CMP), publishReplay(1), skipTimeout ? refCount() : refCountDelay(delay));
3525
3526 function memo(instanceId, inner) {
3527 const options = {
3528 getInstanceId: () => instanceId
3529 };
3530 const cached = util.memoize((...params) => new Observable(observer => {
3531 const subscription = inner(...params).subscribe(observer);
3532 return () => {
3533 cached.unmemoize(...params);
3534 subscription.unsubscribe();
3535 };
3536 }).pipe(drr()), options);
3537 return cached;
3538 }
3539
3540 ({
3541 name: '@polkadot/rpc-core',
3542 path: (({ url: (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href)) }) && (typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))) ? new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.substring(0, new URL((typeof document === 'undefined' && typeof location === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : typeof document === 'undefined' ? location.href : (document.currentScript && document.currentScript.src || new URL('bundle-polkadot-api.js', document.baseURI).href))).pathname.lastIndexOf('/') + 1) : 'auto',
3543 type: 'esm',
3544 version: '8.10.1'
3545 });
3546
3547 const l$4 = util.logger('rpc-core');
3548 const EMPTY_META = {
3549 fallback: undefined,
3550 modifier: {
3551 isOptional: true
3552 },
3553 type: {
3554 asMap: {
3555 linked: {
3556 isTrue: false
3557 }
3558 },
3559 isMap: false
3560 }
3561 };
3562 function logErrorMessage(method, {
3563 noErrorLog,
3564 params,
3565 type
3566 }, error) {
3567 if (noErrorLog) {
3568 return;
3569 }
3570 const inputs = params.map(({
3571 isOptional,
3572 name,
3573 type
3574 }) => `${name}${isOptional ? '?' : ''}: ${type}`).join(', ');
3575 l$4.error(`${method}(${inputs}): ${type}:: ${error.message}`);
3576 }
3577 function isTreatAsHex(key) {
3578 return ['0x3a636f6465'].includes(key.toHex());
3579 }
3580 class RpcCore {
3581 #instanceId;
3582 #registryDefault;
3583 #getBlockRegistry;
3584 #getBlockHash;
3585 #storageCache = new Map();
3586 mapping = new Map();
3587 sections = [];
3588 constructor(instanceId, registry, provider, userRpc = {}) {
3589 if (!provider || !util.isFunction(provider.send)) {
3590 throw new Error('Expected Provider to API create');
3591 }
3592 this.#instanceId = instanceId;
3593 this.#registryDefault = registry;
3594 this.provider = provider;
3595 const sectionNames = Object.keys(types.rpcDefinitions);
3596 this.sections.push(...sectionNames);
3597 this.addUserInterfaces(userRpc);
3598 }
3599 get isConnected() {
3600 return this.provider.isConnected;
3601 }
3602 connect() {
3603 return this.provider.connect();
3604 }
3605 disconnect() {
3606 return this.provider.disconnect();
3607 }
3608 setRegistrySwap(registrySwap) {
3609 this.#getBlockRegistry = util.memoize(registrySwap, {
3610 getInstanceId: () => this.#instanceId
3611 });
3612 }
3613 setResolveBlockHash(resolveBlockHash) {
3614 this.#getBlockHash = util.memoize(resolveBlockHash, {
3615 getInstanceId: () => this.#instanceId
3616 });
3617 }
3618 addUserInterfaces(userRpc) {
3619 this.sections.push(...Object.keys(userRpc).filter(k => !this.sections.includes(k)));
3620 for (let s = 0; s < this.sections.length; s++) {
3621 const section = this.sections[s];
3622 const defs = util.objectSpread({}, types.rpcDefinitions[section], userRpc[section]);
3623 const methods = Object.keys(defs);
3624 for (let m = 0; m < methods.length; m++) {
3625 const method = methods[m];
3626 const def = defs[method];
3627 const jsonrpc = def.endpoint || `${section}_${method}`;
3628 if (!this.mapping.has(jsonrpc)) {
3629 const isSubscription = !!def.pubsub;
3630 if (!this[section]) {
3631 this[section] = {};
3632 }
3633 this.mapping.set(jsonrpc, util.objectSpread({}, def, {
3634 isSubscription,
3635 jsonrpc,
3636 method,
3637 section
3638 }));
3639 util.lazyMethod(this[section], method, () => isSubscription ? this._createMethodSubscribe(section, method, def) : this._createMethodSend(section, method, def));
3640 }
3641 }
3642 }
3643 }
3644 _memomize(creator, def) {
3645 const memoOpts = {
3646 getInstanceId: () => this.#instanceId
3647 };
3648 const memoized = util.memoize(creator(true), memoOpts);
3649 memoized.raw = util.memoize(creator(false), memoOpts);
3650 memoized.meta = def;
3651 return memoized;
3652 }
3653 _formatResult(isScale, registry, blockHash, method, def, params, result) {
3654 return isScale ? this._formatOutput(registry, blockHash, method, def, params, result) : result;
3655 }
3656 _createMethodSend(section, method, def) {
3657 const rpcName = def.endpoint || `${section}_${method}`;
3658 const hashIndex = def.params.findIndex(({
3659 isHistoric
3660 }) => isHistoric);
3661 let memoized = null;
3662 const callWithRegistry = async (isScale, values) => {
3663 var _this$getBlockHash;
3664 const blockId = hashIndex === -1 ? null : values[hashIndex];
3665 const blockHash = blockId && def.params[hashIndex].type === 'BlockNumber' ? await ((_this$getBlockHash = this.#getBlockHash) === null || _this$getBlockHash === void 0 ? void 0 : _this$getBlockHash.call(this, blockId)) : blockId;
3666 const {
3667 registry
3668 } = isScale && blockHash && this.#getBlockRegistry ? await this.#getBlockRegistry(util.u8aToU8a(blockHash)) : {
3669 registry: this.#registryDefault
3670 };
3671 const params = this._formatInputs(registry, null, def, values);
3672 const result = await this.provider.send(rpcName, params.map(p => p.toJSON()), !!blockHash);
3673 return this._formatResult(isScale, registry, blockHash, method, def, params, result);
3674 };
3675 const creator = isScale => (...values) => {
3676 const isDelayed = isScale && hashIndex !== -1 && !!values[hashIndex];
3677 return new Observable(observer => {
3678 callWithRegistry(isScale, values).then(value => {
3679 observer.next(value);
3680 observer.complete();
3681 }).catch(error => {
3682 logErrorMessage(method, def, error);
3683 observer.error(error);
3684 observer.complete();
3685 });
3686 return () => {
3687 if (isScale) {
3688 var _memoized;
3689 (_memoized = memoized) === null || _memoized === void 0 ? void 0 : _memoized.unmemoize(...values);
3690 } else {
3691 var _memoized2;
3692 (_memoized2 = memoized) === null || _memoized2 === void 0 ? void 0 : _memoized2.raw.unmemoize(...values);
3693 }
3694 };
3695 }).pipe(publishReplay(1),
3696 isDelayed ? refCountDelay()
3697 : refCount());
3698 };
3699 memoized = this._memomize(creator, def);
3700 return memoized;
3701 }
3702 _createSubscriber({
3703 paramsJson,
3704 subName,
3705 subType,
3706 update
3707 }, errorHandler) {
3708 return new Promise((resolve, reject) => {
3709 this.provider.subscribe(subType, subName, paramsJson, update).then(resolve).catch(error => {
3710 errorHandler(error);
3711 reject(error);
3712 });
3713 });
3714 }
3715 _createMethodSubscribe(section, method, def) {
3716 const [updateType, subMethod, unsubMethod] = def.pubsub;
3717 const subName = `${section}_${subMethod}`;
3718 const unsubName = `${section}_${unsubMethod}`;
3719 const subType = `${section}_${updateType}`;
3720 let memoized = null;
3721 const creator = isScale => (...values) => {
3722 return new Observable(observer => {
3723 let subscriptionPromise = Promise.resolve(null);
3724 const registry = this.#registryDefault;
3725 const errorHandler = error => {
3726 logErrorMessage(method, def, error);
3727 observer.error(error);
3728 };
3729 try {
3730 const params = this._formatInputs(registry, null, def, values);
3731 const paramsJson = params.map(p => p.toJSON());
3732 const update = (error, result) => {
3733 if (error) {
3734 logErrorMessage(method, def, error);
3735 return;
3736 }
3737 try {
3738 observer.next(this._formatResult(isScale, registry, null, method, def, params, result));
3739 } catch (error) {
3740 observer.error(error);
3741 }
3742 };
3743 subscriptionPromise = this._createSubscriber({
3744 paramsJson,
3745 subName,
3746 subType,
3747 update
3748 }, errorHandler);
3749 } catch (error) {
3750 errorHandler(error);
3751 }
3752 return () => {
3753 if (isScale) {
3754 var _memoized3;
3755 (_memoized3 = memoized) === null || _memoized3 === void 0 ? void 0 : _memoized3.unmemoize(...values);
3756 } else {
3757 var _memoized4;
3758 (_memoized4 = memoized) === null || _memoized4 === void 0 ? void 0 : _memoized4.raw.unmemoize(...values);
3759 }
3760 subscriptionPromise.then(subscriptionId => util.isNull(subscriptionId) ? Promise.resolve(false) : this.provider.unsubscribe(subType, unsubName, subscriptionId)).catch(error => logErrorMessage(method, def, error));
3761 };
3762 }).pipe(drr());
3763 };
3764 memoized = this._memomize(creator, def);
3765 return memoized;
3766 }
3767 _formatInputs(registry, blockHash, def, inputs) {
3768 const reqArgCount = def.params.filter(({
3769 isOptional
3770 }) => !isOptional).length;
3771 const optText = reqArgCount === def.params.length ? '' : ` (${def.params.length - reqArgCount} optional)`;
3772 if (inputs.length < reqArgCount || inputs.length > def.params.length) {
3773 throw new Error(`Expected ${def.params.length} parameters${optText}, ${inputs.length} found instead`);
3774 }
3775 return inputs.map((input, index) => registry.createTypeUnsafe(def.params[index].type, [input], {
3776 blockHash
3777 }));
3778 }
3779 _formatOutput(registry, blockHash, method, rpc, params, result) {
3780 if (rpc.type === 'StorageData') {
3781 const key = params[0];
3782 return this._formatStorageData(registry, blockHash, key, result);
3783 } else if (rpc.type === 'StorageChangeSet') {
3784 const keys = params[0];
3785 return keys ? this._formatStorageSet(registry, result.block, keys, result.changes) : registry.createType('StorageChangeSet', result);
3786 } else if (rpc.type === 'Vec<StorageChangeSet>') {
3787 const mapped = result.map(({
3788 block,
3789 changes
3790 }) => [registry.createType('Hash', block), this._formatStorageSet(registry, block, params[0], changes)]);
3791 return method === 'queryStorageAt' ? mapped[0][1] : mapped;
3792 }
3793 return registry.createTypeUnsafe(rpc.type, [result], {
3794 blockHash
3795 });
3796 }
3797 _formatStorageData(registry, blockHash, key, value) {
3798 const isEmpty = util.isNull(value);
3799 const input = isEmpty ? null : isTreatAsHex(key) ? value : util.u8aToU8a(value);
3800 return this._newType(registry, blockHash, key, input, isEmpty);
3801 }
3802 _formatStorageSet(registry, blockHash, keys, changes) {
3803 const withCache = keys.length !== 1;
3804 return keys.reduce((results, key, index) => {
3805 results.push(this._formatStorageSetEntry(registry, blockHash, key, changes, withCache, index));
3806 return results;
3807 }, []);
3808 }
3809 _formatStorageSetEntry(registry, blockHash, key, changes, withCache, entryIndex) {
3810 const hexKey = key.toHex();
3811 const found = changes.find(([key]) => key === hexKey);
3812 const isNotFound = util.isUndefined(found);
3813 if (isNotFound && withCache) {
3814 const cached = this.#storageCache.get(hexKey);
3815 if (cached) {
3816 return cached;
3817 }
3818 }
3819 const value = isNotFound ? null : found[1];
3820 const isEmpty = util.isNull(value);
3821 const input = isEmpty || isTreatAsHex(key) ? value : util.u8aToU8a(value);
3822 const codec = this._newType(registry, blockHash, key, input, isEmpty, entryIndex);
3823 this.#storageCache.set(hexKey, codec);
3824 return codec;
3825 }
3826 _newType(registry, blockHash, key, input, isEmpty, entryIndex = -1) {
3827 const type = key.outputType || 'Raw';
3828 const meta = key.meta || EMPTY_META;
3829 const entryNum = entryIndex === -1 ? '' : ` entry ${entryIndex}:`;
3830 try {
3831 return registry.createTypeUnsafe(type, [isEmpty ? meta.fallback
3832 ? type.includes('Linkage<') ? util.u8aConcat(util.hexToU8a(meta.fallback.toHex()), new Uint8Array(2)) : util.hexToU8a(meta.fallback.toHex()) : undefined : meta.modifier.isOptional ? registry.createTypeUnsafe(type, [input], {
3833 blockHash,
3834 isPedantic: true
3835 }) : input], {
3836 blockHash,
3837 isOptional: meta.modifier.isOptional,
3838 isPedantic: !meta.modifier.isOptional
3839 });
3840 } catch (error) {
3841 throw new Error(`Unable to decode storage ${key.section || 'unknown'}.${key.method || 'unknown'}:${entryNum}: ${error.message}`);
3842 }
3843 }
3844 }
3845
3846 const deriveNoopCache = {
3847 del: () => undefined,
3848 forEach: () => undefined,
3849 get: () => undefined,
3850 set: (_, value) => value
3851 };
3852
3853 const CHACHE_EXPIRY = 7 * (24 * 60) * (60 * 1000);
3854 let deriveCache;
3855 function wrapCache(keyStart, cache) {
3856 return {
3857 del: partial => cache.del(`${keyStart}${partial}`),
3858 forEach: cache.forEach,
3859 get: partial => {
3860 const key = `${keyStart}${partial}`;
3861 const cached = cache.get(key);
3862 if (cached) {
3863 cached.x = Date.now();
3864 cache.set(key, cached);
3865 return cached.v;
3866 }
3867 return undefined;
3868 },
3869 set: (partial, v) => {
3870 cache.set(`${keyStart}${partial}`, {
3871 v,
3872 x: Date.now()
3873 });
3874 }
3875 };
3876 }
3877 function clearCache(cache) {
3878 const now = Date.now();
3879 const all = [];
3880 cache.forEach((key, {
3881 x
3882 }) => {
3883 now - x > CHACHE_EXPIRY && all.push(key);
3884 });
3885 all.forEach(key => cache.del(key));
3886 }
3887 function setDeriveCache(prefix = '', cache) {
3888 deriveCache = cache ? wrapCache(`derive:${prefix}:`, cache) : deriveNoopCache;
3889 if (cache) {
3890 clearCache(cache);
3891 }
3892 }
3893 setDeriveCache();
3894
3895 function firstObservable(obs) {
3896 return obs.pipe(map(([a]) => a));
3897 }
3898 function firstMemo(fn) {
3899 return (instanceId, api) => memo(instanceId, (...args) => firstObservable(fn(api, ...args)));
3900 }
3901
3902 function lazyDeriveSection(result, section, getKeys, creator) {
3903 util.lazyMethod(result, section, () => util.lazyMethods({}, getKeys(section), method => creator(section, method)));
3904 }
3905
3906 function accountId(instanceId, api) {
3907 return memo(instanceId, address => {
3908 const decoded = util.isU8a(address) ? address : utilCrypto.decodeAddress((address || '').toString());
3909 if (decoded.length > 8) {
3910 return of(api.registry.createType('AccountId', decoded));
3911 }
3912 const accountIndex = api.registry.createType('AccountIndex', decoded);
3913 return api.derive.accounts.indexToId(accountIndex.toString()).pipe(map(a => util.assertReturn(a, 'Unable to retrieve accountId')));
3914 });
3915 }
3916
3917 function parseFlags(address, [electionsMembers, councilMembers, technicalCommitteeMembers, societyMembers, sudoKey]) {
3918 const addrStr = address && address.toString();
3919 const isIncluded = id => id.toString() === addrStr;
3920 return {
3921 isCouncil: ((electionsMembers === null || electionsMembers === void 0 ? void 0 : electionsMembers.map(r => Array.isArray(r) ? r[0] : r.who)) || councilMembers || []).some(isIncluded),
3922 isSociety: (societyMembers || []).some(isIncluded),
3923 isSudo: (sudoKey === null || sudoKey === void 0 ? void 0 : sudoKey.toString()) === addrStr,
3924 isTechCommittee: (technicalCommitteeMembers || []).some(isIncluded)
3925 };
3926 }
3927 function _flags(instanceId, api) {
3928 return memo(instanceId, () => {
3929 var _ref, _api$query$council, _api$query$technicalC, _api$query$society, _api$query$sudo;
3930 const results = [undefined, [], [], [], undefined];
3931 const calls = [(_ref = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections) === null || _ref === void 0 ? void 0 : _ref.members, (_api$query$council = api.query.council) === null || _api$query$council === void 0 ? void 0 : _api$query$council.members, (_api$query$technicalC = api.query.technicalCommittee) === null || _api$query$technicalC === void 0 ? void 0 : _api$query$technicalC.members, (_api$query$society = api.query.society) === null || _api$query$society === void 0 ? void 0 : _api$query$society.members, (_api$query$sudo = api.query.sudo) === null || _api$query$sudo === void 0 ? void 0 : _api$query$sudo.key];
3932 const filtered = calls.filter(c => c);
3933 if (!filtered.length) {
3934 return of(results);
3935 }
3936 return api.queryMulti(filtered).pipe(map(values => {
3937 let resultIndex = -1;
3938 for (let i = 0; i < calls.length; i++) {
3939 if (util.isFunction(calls[i])) {
3940 results[i] = values[++resultIndex];
3941 }
3942 }
3943 return results;
3944 }));
3945 });
3946 }
3947 function flags(instanceId, api) {
3948 return memo(instanceId, address => api.derive.accounts._flags().pipe(map(r => parseFlags(address, r))));
3949 }
3950
3951 function idAndIndex(instanceId, api) {
3952 return memo(instanceId, address => {
3953 try {
3954 const decoded = util.isU8a(address) ? address : utilCrypto.decodeAddress((address || '').toString());
3955 if (decoded.length > 8) {
3956 const accountId = api.registry.createType('AccountId', decoded);
3957 return api.derive.accounts.idToIndex(accountId).pipe(map(accountIndex => [accountId, accountIndex]));
3958 }
3959 const accountIndex = api.registry.createType('AccountIndex', decoded);
3960 return api.derive.accounts.indexToId(accountIndex.toString()).pipe(map(accountId => [accountId, accountIndex]));
3961 } catch (error) {
3962 return of([undefined, undefined]);
3963 }
3964 });
3965 }
3966
3967 function idToIndex(instanceId, api) {
3968 return memo(instanceId, accountId => api.derive.accounts.indexes().pipe(map(indexes => (indexes || {})[accountId.toString()])));
3969 }
3970
3971 const UNDEF_HEX = {
3972 toHex: () => undefined
3973 };
3974 function dataAsString(data) {
3975 return data.isRaw ? util.u8aToString(data.asRaw.toU8a(true)) : data.isNone ? undefined : data.toHex();
3976 }
3977 function extractOther(additional) {
3978 return additional.reduce((other, [_key, _value]) => {
3979 const key = dataAsString(_key);
3980 const value = dataAsString(_value);
3981 if (key && value) {
3982 other[key] = value;
3983 }
3984 return other;
3985 }, {});
3986 }
3987 function extractIdentity(identityOfOpt, superOf) {
3988 if (!(identityOfOpt !== null && identityOfOpt !== void 0 && identityOfOpt.isSome)) {
3989 return {
3990 judgements: []
3991 };
3992 }
3993 const {
3994 info,
3995 judgements
3996 } = identityOfOpt.unwrap();
3997 const topDisplay = dataAsString(info.display);
3998 return {
3999 display: superOf && dataAsString(superOf[1]) || topDisplay,
4000 displayParent: superOf && topDisplay,
4001 email: dataAsString(info.email),
4002 image: dataAsString(info.image),
4003 judgements,
4004 legal: dataAsString(info.legal),
4005 other: extractOther(info.additional),
4006 parent: superOf && superOf[0],
4007 pgp: info.pgpFingerprint.unwrapOr(UNDEF_HEX).toHex(),
4008 riot: dataAsString(info.riot),
4009 twitter: dataAsString(info.twitter),
4010 web: dataAsString(info.web)
4011 };
4012 }
4013 function getParent(api, identityOfOpt, superOfOpt) {
4014 if (identityOfOpt !== null && identityOfOpt !== void 0 && identityOfOpt.isSome) {
4015 return of([identityOfOpt, undefined]);
4016 } else if (superOfOpt !== null && superOfOpt !== void 0 && superOfOpt.isSome) {
4017 const superOf = superOfOpt.unwrap();
4018 return combineLatest([api.derive.accounts._identity(superOf[0]).pipe(map(([info]) => info)), of(superOf)]);
4019 }
4020 return of([undefined, undefined]);
4021 }
4022 function _identity(instanceId, api) {
4023 return memo(instanceId, accountId => {
4024 var _api$query$identity;
4025 return accountId && (_api$query$identity = api.query.identity) !== null && _api$query$identity !== void 0 && _api$query$identity.identityOf ? combineLatest([api.query.identity.identityOf(accountId), api.query.identity.superOf(accountId)]) : of([undefined, undefined]);
4026 });
4027 }
4028 function identity$1(instanceId, api) {
4029 return memo(instanceId, accountId => api.derive.accounts._identity(accountId).pipe(switchMap(([identityOfOpt, superOfOpt]) => getParent(api, identityOfOpt, superOfOpt)), map(([identityOfOpt, superOf]) => extractIdentity(identityOfOpt, superOf))));
4030 }
4031 const hasIdentity = firstMemo((api, accountId) => api.derive.accounts.hasIdentityMulti([accountId]));
4032 function hasIdentityMulti(instanceId, api) {
4033 return memo(instanceId, accountIds => {
4034 var _api$query$identity2;
4035 return (_api$query$identity2 = api.query.identity) !== null && _api$query$identity2 !== void 0 && _api$query$identity2.identityOf ? combineLatest([api.query.identity.identityOf.multi(accountIds), api.query.identity.superOf.multi(accountIds)]).pipe(map(([identities, supers]) => identities.map((identityOfOpt, index) => {
4036 const superOfOpt = supers[index];
4037 const parentId = superOfOpt && superOfOpt.isSome ? superOfOpt.unwrap()[0].toString() : undefined;
4038 let display;
4039 if (identityOfOpt && identityOfOpt.isSome) {
4040 const value = dataAsString(identityOfOpt.unwrap().info.display);
4041 if (value && !util.isHex(value)) {
4042 display = value;
4043 }
4044 }
4045 return {
4046 display,
4047 hasIdentity: !!(display || parentId),
4048 parentId
4049 };
4050 }))) : of(accountIds.map(() => ({
4051 hasIdentity: false
4052 })));
4053 });
4054 }
4055
4056 function indexToId(instanceId, api) {
4057 return memo(instanceId, accountIndex => api.query.indices ? api.query.indices.accounts(accountIndex).pipe(map(optResult => optResult.unwrapOr([])[0])) : of(undefined));
4058 }
4059
4060 let indicesCache = null;
4061 function queryAccounts(api) {
4062 return api.query.indices.accounts.entries().pipe(map(entries => entries.reduce((indexes, [key, idOpt]) => {
4063 if (idOpt.isSome) {
4064 indexes[idOpt.unwrap()[0].toString()] = api.registry.createType('AccountIndex', key.args[0]);
4065 }
4066 return indexes;
4067 }, {})));
4068 }
4069 function indexes$1(instanceId, api) {
4070 return memo(instanceId, () => indicesCache ? of(indicesCache) : (api.query.indices ? queryAccounts(api).pipe(startWith({})) : of({})).pipe(map(indices => {
4071 indicesCache = indices;
4072 return indices;
4073 })));
4074 }
4075
4076 function retrieveNick(api, accountId) {
4077 var _api$query$nicks;
4078 return (accountId && (_api$query$nicks = api.query.nicks) !== null && _api$query$nicks !== void 0 && _api$query$nicks.nameOf ? api.query.nicks.nameOf(accountId) : of(undefined)).pipe(map(nameOf => nameOf !== null && nameOf !== void 0 && nameOf.isSome ? util.u8aToString(nameOf.unwrap()[0]).substring(0, api.consts.nicks.maxLength.toNumber()) : undefined));
4079 }
4080 function info$4(instanceId, api) {
4081 return memo(instanceId, address => api.derive.accounts.idAndIndex(address).pipe(switchMap(([accountId, accountIndex]) => combineLatest([of({
4082 accountId,
4083 accountIndex
4084 }), api.derive.accounts.identity(accountId), retrieveNick(api, accountId)])), map(([{
4085 accountId,
4086 accountIndex
4087 }, identity, nickname]) => ({
4088 accountId,
4089 accountIndex,
4090 identity,
4091 nickname
4092 }))));
4093 }
4094
4095 const accounts$1 = /*#__PURE__*/Object.freeze({
4096 __proto__: null,
4097 accountId: accountId,
4098 _flags: _flags,
4099 flags: flags,
4100 idAndIndex: idAndIndex,
4101 idToIndex: idToIndex,
4102 _identity: _identity,
4103 identity: identity$1,
4104 hasIdentity: hasIdentity,
4105 hasIdentityMulti: hasIdentityMulti,
4106 indexToId: indexToId,
4107 indexes: indexes$1,
4108 info: info$4
4109 });
4110
4111 function orderBags(ids, bags) {
4112 const sorted = ids.map((id, index) => ({
4113 bag: bags[index].unwrapOr(null),
4114 id,
4115 key: id.toString()
4116 })).sort((a, b) => b.id.cmp(a.id)).map((base, index) => ({ ...base,
4117 bagLower: util.BN_ZERO,
4118 bagUpper: base.id,
4119 index
4120 }));
4121 const max = sorted.length - 1;
4122 return sorted.map((entry, index) => index === max ? entry
4123 : { ...entry,
4124 bagLower: sorted[index + 1].bagUpper
4125 });
4126 }
4127 function _getIds(instanceId, api) {
4128 return memo(instanceId, _ids => {
4129 const ids = _ids.map(id => util.bnToBn(id));
4130 return ids.length ? (api.query.voterList || api.query.bagsList).listBags.multi(ids).pipe(map(bags => orderBags(ids, bags))) : of([]);
4131 });
4132 }
4133 function all$1(instanceId, api) {
4134 return memo(instanceId, () => (api.query.voterList || api.query.bagsList).listBags.keys().pipe(switchMap(keys => api.derive.bagsList._getIds(keys.map(({
4135 args: [id]
4136 }) => id))), map(list => list.filter(({
4137 bag
4138 }) => bag))));
4139 }
4140 function get(instanceId, api) {
4141 return memo(instanceId, id => api.derive.bagsList._getIds([util.bnToBn(id)]).pipe(map(bags => bags[0])));
4142 }
4143
4144 function expand(instanceId, api) {
4145 return memo(instanceId, bag => api.derive.bagsList.listNodes(bag.bag).pipe(map(nodes => ({ ...bag,
4146 nodes
4147 }))));
4148 }
4149 function getExpanded(instanceId, api) {
4150 return memo(instanceId, id => api.derive.bagsList.get(id).pipe(switchMap(bag => api.derive.bagsList.expand(bag))));
4151 }
4152
4153 function traverseLinks(api, head) {
4154 const subject = new BehaviorSubject(head);
4155 return subject.pipe(switchMap(account => (api.query.voterList || api.query.bagsList).listNodes(account)), tap(node => {
4156 util.nextTick(() => {
4157 node.isSome && node.value.next.isSome ? subject.next(node.unwrap().next.unwrap()) : subject.complete();
4158 });
4159 }), toArray(),
4160 map(all => all.map(o => o.unwrap())));
4161 }
4162 function listNodes(instanceId, api) {
4163 return memo(instanceId, bag => bag && bag.head.isSome ? traverseLinks(api, bag.head.unwrap()) : of([]));
4164 }
4165
4166 const bagsList = /*#__PURE__*/Object.freeze({
4167 __proto__: null,
4168 _getIds: _getIds,
4169 all: all$1,
4170 get: get,
4171 expand: expand,
4172 getExpanded: getExpanded,
4173 listNodes: listNodes
4174 });
4175
4176 const VESTING_ID = '0x76657374696e6720';
4177 function calcLocked(api, bestNumber, locks) {
4178 let lockedBalance = api.registry.createType('Balance');
4179 let lockedBreakdown = [];
4180 let vestingLocked = api.registry.createType('Balance');
4181 let allLocked = false;
4182 if (Array.isArray(locks)) {
4183 lockedBreakdown = locks.filter(({
4184 until
4185 }) => !until || bestNumber && until.gt(bestNumber));
4186 allLocked = lockedBreakdown.some(({
4187 amount
4188 }) => amount && amount.isMax());
4189 vestingLocked = api.registry.createType('Balance', lockedBreakdown.filter(({
4190 id
4191 }) => id.eq(VESTING_ID)).reduce((result, {
4192 amount
4193 }) => result.iadd(amount), new util.BN(0)));
4194 const notAll = lockedBreakdown.filter(({
4195 amount
4196 }) => amount && !amount.isMax());
4197 if (notAll.length) {
4198 lockedBalance = api.registry.createType('Balance', util.bnMax(...notAll.map(({
4199 amount
4200 }) => amount)));
4201 }
4202 }
4203 return {
4204 allLocked,
4205 lockedBalance,
4206 lockedBreakdown,
4207 vestingLocked
4208 };
4209 }
4210 function calcShared(api, bestNumber, data, locks) {
4211 const {
4212 allLocked,
4213 lockedBalance,
4214 lockedBreakdown,
4215 vestingLocked
4216 } = calcLocked(api, bestNumber, locks);
4217 return { ...data,
4218 availableBalance: api.registry.createType('Balance', allLocked ? 0 : util.bnMax(new util.BN(0), data.freeBalance.sub(lockedBalance))),
4219 lockedBalance,
4220 lockedBreakdown,
4221 vestingLocked
4222 };
4223 }
4224 function calcVesting(bestNumber, shared, _vesting) {
4225 const vesting = _vesting || [];
4226 const isVesting = !shared.vestingLocked.isZero();
4227 const vestedBalances = vesting.map(({
4228 locked,
4229 perBlock,
4230 startingBlock
4231 }) => bestNumber.gt(startingBlock) ? util.bnMin(locked, perBlock.mul(bestNumber.sub(startingBlock))) : util.BN_ZERO);
4232 const vestedBalance = vestedBalances.reduce((all, value) => all.iadd(value), new util.BN(0));
4233 const vestingTotal = vesting.reduce((all, {
4234 locked
4235 }) => all.iadd(locked), new util.BN(0));
4236 return {
4237 isVesting,
4238 vestedBalance,
4239 vestedClaimable: isVesting ? shared.vestingLocked.sub(vestingTotal.sub(vestedBalance)) : util.BN_ZERO,
4240 vesting: vesting.map(({
4241 locked,
4242 perBlock,
4243 startingBlock
4244 }, index) => ({
4245 endBlock: locked.div(perBlock).iadd(startingBlock),
4246 locked,
4247 perBlock,
4248 startingBlock,
4249 vested: vestedBalances[index]
4250 })).filter(({
4251 locked
4252 }) => !locked.isZero()),
4253 vestingTotal
4254 };
4255 }
4256 function calcBalances$1(api, [data, [vesting, allLocks, namedReserves], bestNumber]) {
4257 const shared = calcShared(api, bestNumber, data, allLocks[0]);
4258 return { ...shared,
4259 ...calcVesting(bestNumber, shared, vesting),
4260 accountId: data.accountId,
4261 accountNonce: data.accountNonce,
4262 additional: allLocks.filter((_, index) => index !== 0).map((l, index) => calcShared(api, bestNumber, data.additional[index], l)),
4263 namedReserves
4264 };
4265 }
4266 function queryOld(api, accountId) {
4267 return combineLatest([api.query.balances.locks(accountId), api.query.balances.vesting(accountId)]).pipe(map(([locks, optVesting]) => {
4268 let vestingNew = null;
4269 if (optVesting.isSome) {
4270 const {
4271 offset: locked,
4272 perBlock,
4273 startingBlock
4274 } = optVesting.unwrap();
4275 vestingNew = api.registry.createType('VestingInfo', {
4276 locked,
4277 perBlock,
4278 startingBlock
4279 });
4280 }
4281 return [vestingNew ? [vestingNew] : null, [locks], []];
4282 }));
4283 }
4284 const isNonNullable = nullable => !!nullable;
4285 function createCalls(calls) {
4286 return [calls.map(c => !c), calls.filter(isNonNullable)];
4287 }
4288 function queryCurrent(api, accountId, balanceInstances = ['balances']) {
4289 var _api$query$vesting;
4290 const [lockEmpty, lockQueries] = createCalls(balanceInstances.map(m => {
4291 var _m, _api$query;
4292 return ((_m = api.derive[m]) === null || _m === void 0 ? void 0 : _m.customLocks) || ((_api$query = api.query[m]) === null || _api$query === void 0 ? void 0 : _api$query.locks);
4293 }));
4294 const [reserveEmpty, reserveQueries] = createCalls(balanceInstances.map(m => {
4295 var _api$query2;
4296 return (_api$query2 = api.query[m]) === null || _api$query2 === void 0 ? void 0 : _api$query2.reserves;
4297 }));
4298 return combineLatest([(_api$query$vesting = api.query.vesting) !== null && _api$query$vesting !== void 0 && _api$query$vesting.vesting ? api.query.vesting.vesting(accountId) : of(api.registry.createType('Option<VestingInfo>')), lockQueries.length ? combineLatest(lockQueries.map(c => c(accountId))) : of([]), reserveQueries.length ? combineLatest(reserveQueries.map(c => c(accountId))) : of([])]).pipe(map(([opt, locks, reserves]) => {
4299 let offsetLock = -1;
4300 let offsetReserve = -1;
4301 const vesting = opt.unwrapOr(null);
4302 return [vesting ? Array.isArray(vesting) ? vesting : [vesting] : null, lockEmpty.map(e => e ? api.registry.createType('Vec<BalanceLock>') : locks[++offsetLock]), reserveEmpty.map(e => e ? api.registry.createType('Vec<PalletBalancesReserveData>') : reserves[++offsetReserve])];
4303 }));
4304 }
4305 function all(instanceId, api) {
4306 const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
4307 return memo(instanceId, address => {
4308 var _api$query$system, _api$query$balances;
4309 return combineLatest([api.derive.balances.account(address), util.isFunction((_api$query$system = api.query.system) === null || _api$query$system === void 0 ? void 0 : _api$query$system.account) || util.isFunction((_api$query$balances = api.query.balances) === null || _api$query$balances === void 0 ? void 0 : _api$query$balances.account) ? queryCurrent(api, address, balanceInstances) : queryOld(api, address)]).pipe(switchMap(([account, locks]) => combineLatest([of(account), of(locks), api.derive.chain.bestNumber()])), map(result => calcBalances$1(api, result)));
4310 });
4311 }
4312
4313 function zeroBalance(api) {
4314 return api.registry.createType('Balance');
4315 }
4316 function getBalance(api, [freeBalance, reservedBalance, frozenFee, frozenMisc]) {
4317 const votingBalance = api.registry.createType('Balance', freeBalance.toBn());
4318 return {
4319 freeBalance,
4320 frozenFee,
4321 frozenMisc,
4322 reservedBalance,
4323 votingBalance
4324 };
4325 }
4326 function calcBalances(api, [accountId, [accountNonce, [primary, ...additional]]]) {
4327 return {
4328 accountId,
4329 accountNonce,
4330 additional: additional.map(b => getBalance(api, b)),
4331 ...getBalance(api, primary)
4332 };
4333 }
4334 function queryBalancesFree(api, accountId) {
4335 return combineLatest([api.query.balances.freeBalance(accountId), api.query.balances.reservedBalance(accountId), api.query.system.accountNonce(accountId)]).pipe(map(([freeBalance, reservedBalance, accountNonce]) => [accountNonce, [[freeBalance, reservedBalance, zeroBalance(api), zeroBalance(api)]]]));
4336 }
4337 function queryNonceOnly(api, accountId) {
4338 const fill = nonce => [nonce, [[zeroBalance(api), zeroBalance(api), zeroBalance(api), zeroBalance(api)]]];
4339 return util.isFunction(api.query.system.account) ? api.query.system.account(accountId).pipe(map(({
4340 nonce
4341 }) => fill(nonce))) : util.isFunction(api.query.system.accountNonce) ? api.query.system.accountNonce(accountId).pipe(map(nonce => fill(nonce))) : of(fill(api.registry.createType('Index')));
4342 }
4343 function queryBalancesAccount(api, accountId, modules = ['balances']) {
4344 const balances = modules.map(m => {
4345 var _m, _api$query$m;
4346 return ((_m = api.derive[m]) === null || _m === void 0 ? void 0 : _m.customAccount) || ((_api$query$m = api.query[m]) === null || _api$query$m === void 0 ? void 0 : _api$query$m.account);
4347 }).filter(q => util.isFunction(q));
4348 const extract = (nonce, data) => [nonce, data.map(({
4349 feeFrozen,
4350 free,
4351 miscFrozen,
4352 reserved
4353 }) => [free, reserved, feeFrozen, miscFrozen])];
4354 return balances.length ? util.isFunction(api.query.system.account) ? combineLatest([api.query.system.account(accountId), ...balances.map(c => c(accountId))]).pipe(map(([{
4355 nonce
4356 }, ...balances]) => extract(nonce, balances))) : combineLatest([api.query.system.accountNonce(accountId), ...balances.map(c => c(accountId))]).pipe(map(([nonce, ...balances]) => extract(nonce, balances))) : queryNonceOnly(api, accountId);
4357 }
4358 function querySystemAccount(api, accountId) {
4359 return api.query.system.account(accountId).pipe(map(infoOrTuple => {
4360 const data = infoOrTuple.nonce ? infoOrTuple.data : infoOrTuple[1];
4361 const nonce = infoOrTuple.nonce || infoOrTuple[0];
4362 if (!data || data.isEmpty) {
4363 return [nonce, [[zeroBalance(api), zeroBalance(api), zeroBalance(api), zeroBalance(api)]]];
4364 }
4365 const {
4366 feeFrozen,
4367 free,
4368 miscFrozen,
4369 reserved
4370 } = data;
4371 return [nonce, [[free, reserved, feeFrozen, miscFrozen]]];
4372 }));
4373 }
4374 function account$1(instanceId, api) {
4375 const balanceInstances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'balances');
4376 return memo(instanceId, address => api.derive.accounts.accountId(address).pipe(switchMap(accountId => {
4377 var _api$query$system, _api$query$balances, _api$query$balances2;
4378 return accountId ? combineLatest([of(accountId), balanceInstances ? queryBalancesAccount(api, accountId, balanceInstances) : util.isFunction((_api$query$system = api.query.system) === null || _api$query$system === void 0 ? void 0 : _api$query$system.account) ? querySystemAccount(api, accountId) : util.isFunction((_api$query$balances = api.query.balances) === null || _api$query$balances === void 0 ? void 0 : _api$query$balances.account) ? queryBalancesAccount(api, accountId) : util.isFunction((_api$query$balances2 = api.query.balances) === null || _api$query$balances2 === void 0 ? void 0 : _api$query$balances2.freeBalance) ? queryBalancesFree(api, accountId) : queryNonceOnly(api, accountId)]) : of([api.registry.createType('AccountId'), [api.registry.createType('Index'), [[zeroBalance(api), zeroBalance(api), zeroBalance(api), zeroBalance(api)]]]]);
4379 }), map(result => calcBalances(api, result))));
4380 }
4381
4382 function votingBalances(instanceId, api) {
4383 return memo(instanceId, addresses => !addresses || !addresses.length ? of([]) : combineLatest(addresses.map(accountId => api.derive.balances.account(accountId))));
4384 }
4385
4386 const votingBalance = all;
4387
4388 const balances = /*#__PURE__*/Object.freeze({
4389 __proto__: null,
4390 all: all,
4391 votingBalance: votingBalance,
4392 account: account$1,
4393 votingBalances: votingBalances
4394 });
4395
4396 function filterBountiesProposals(api, allProposals) {
4397 const bountyTxBase = api.tx.bounties ? api.tx.bounties : api.tx.treasury;
4398 const bountyProposalCalls = [bountyTxBase.approveBounty, bountyTxBase.closeBounty, bountyTxBase.proposeCurator, bountyTxBase.unassignCurator];
4399 return allProposals.filter(proposal => bountyProposalCalls.find(bountyCall => proposal.proposal && bountyCall.is(proposal.proposal)));
4400 }
4401
4402 function parseResult$2([maybeBounties, maybeDescriptions, ids, bountyProposals]) {
4403 const bounties = [];
4404 maybeBounties.forEach((bounty, index) => {
4405 if (bounty.isSome) {
4406 bounties.push({
4407 bounty: bounty.unwrap(),
4408 description: maybeDescriptions[index].unwrapOrDefault().toUtf8(),
4409 index: ids[index],
4410 proposals: bountyProposals.filter(bountyProposal => bountyProposal.proposal && ids[index].eq(bountyProposal.proposal.args[0]))
4411 });
4412 }
4413 });
4414 return bounties;
4415 }
4416 function bounties$1(instanceId, api) {
4417 const bountyBase = api.query.bounties || api.query.treasury;
4418 return memo(instanceId, () => bountyBase.bounties ? combineLatest([bountyBase.bountyCount(), api.query.council ? api.query.council.proposalCount() : of(0)]).pipe(switchMap(() => combineLatest([bountyBase.bounties.keys(), api.derive.council ? api.derive.council.proposals() : of([])])), switchMap(([keys, proposals]) => {
4419 const ids = keys.map(({
4420 args: [id]
4421 }) => id);
4422 return combineLatest([bountyBase.bounties.multi(ids), bountyBase.bountyDescriptions.multi(ids), of(ids), of(filterBountiesProposals(api, proposals))]);
4423 }), map(parseResult$2)) : of(parseResult$2([[], [], [], []])));
4424 }
4425
4426 const bounties = /*#__PURE__*/Object.freeze({
4427 __proto__: null,
4428 bounties: bounties$1
4429 });
4430
4431 function unwrapBlockNumber(fn) {
4432 return (instanceId, api) => memo(instanceId, () => fn(api).pipe(map(r => r.number.unwrap())));
4433 }
4434
4435 const bestNumber = unwrapBlockNumber(api => api.derive.chain.subscribeNewHeads());
4436
4437 const bestNumberFinalized = unwrapBlockNumber(api => api.rpc.chain.subscribeFinalizedHeads());
4438
4439 function bestNumberLag(instanceId, api) {
4440 return memo(instanceId, () => combineLatest([api.derive.chain.bestNumber(), api.derive.chain.bestNumberFinalized()]).pipe(map(([bestNumber, bestNumberFinalized]) => api.registry.createType('BlockNumber', bestNumber.sub(bestNumberFinalized)))));
4441 }
4442
4443 function extractAuthor(digest, sessionValidators = []) {
4444 const [citem] = digest.logs.filter(e => e.isConsensus);
4445 const [pitem] = digest.logs.filter(e => e.isPreRuntime);
4446 const [sitem] = digest.logs.filter(e => e.isSeal);
4447 let accountId;
4448 try {
4449 if (pitem) {
4450 const [engine, data] = pitem.asPreRuntime;
4451 accountId = engine.extractAuthor(data, sessionValidators);
4452 }
4453 if (!accountId && citem) {
4454 const [engine, data] = citem.asConsensus;
4455 accountId = engine.extractAuthor(data, sessionValidators);
4456 }
4457 if (!accountId && sitem) {
4458 const [engine, data] = sitem.asSeal;
4459 accountId = engine.extractAuthor(data, sessionValidators);
4460 }
4461 } catch {
4462 }
4463 return accountId;
4464 }
4465
4466 function createHeaderExtended(registry, header, validators) {
4467 const HeaderBase = registry.createClass('Header');
4468 class Implementation extends HeaderBase {
4469 #author;
4470 #validators;
4471 constructor(registry, header, validators) {
4472 super(registry, header);
4473 this.#author = extractAuthor(this.digest, validators);
4474 this.#validators = validators;
4475 this.createdAtHash = header === null || header === void 0 ? void 0 : header.createdAtHash;
4476 }
4477 get author() {
4478 return this.#author;
4479 }
4480 get validators() {
4481 return this.#validators;
4482 }
4483 }
4484 return new Implementation(registry, header, validators);
4485 }
4486
4487 function mapExtrinsics(extrinsics, records) {
4488 return extrinsics.map((extrinsic, index) => {
4489 let dispatchError;
4490 let dispatchInfo;
4491 const events = records.filter(({
4492 phase
4493 }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eq(index)).map(({
4494 event
4495 }) => {
4496 if (event.section === 'system') {
4497 if (event.method === 'ExtrinsicSuccess') {
4498 dispatchInfo = event.data[0];
4499 } else if (event.method === 'ExtrinsicFailed') {
4500 dispatchError = event.data[0];
4501 dispatchInfo = event.data[1];
4502 }
4503 }
4504 return event;
4505 });
4506 return {
4507 dispatchError,
4508 dispatchInfo,
4509 events,
4510 extrinsic
4511 };
4512 });
4513 }
4514 function createSignedBlockExtended(registry, block, events, validators) {
4515 const SignedBlockBase = registry.createClass('SignedBlock');
4516 class Implementation extends SignedBlockBase {
4517 #author;
4518 #events;
4519 #extrinsics;
4520 constructor(registry, block, events, validators) {
4521 super(registry, block);
4522 this.#author = extractAuthor(this.block.header.digest, validators);
4523 this.#events = events || [];
4524 this.#extrinsics = mapExtrinsics(this.block.extrinsics, this.#events);
4525 this.createdAtHash = block === null || block === void 0 ? void 0 : block.createdAtHash;
4526 }
4527 get author() {
4528 return this.#author;
4529 }
4530 get events() {
4531 return this.#events;
4532 }
4533 get extrinsics() {
4534 return this.#extrinsics;
4535 }
4536 }
4537 return new Implementation(registry, block, events, validators);
4538 }
4539
4540 function getHeader(instanceId, api) {
4541 return memo(instanceId, blockHash => combineLatest([api.rpc.chain.getHeader(blockHash), api.queryAt(blockHash).pipe(switchMap(queryAt => queryAt.session ? queryAt.session.validators() : of([])))]).pipe(map(([header, validators]) => createHeaderExtended(header.registry, header, validators)), catchError(() =>
4542 of())));
4543 }
4544
4545 function getBlock(instanceId, api) {
4546 return memo(instanceId, blockHash => combineLatest([api.rpc.chain.getBlock(blockHash), api.queryAt(blockHash).pipe(switchMap(queryAt => combineLatest([queryAt.system.events(), queryAt.session ? queryAt.session.validators() : of([])])))]).pipe(map(([signedBlock, [events, validators]]) => createSignedBlockExtended(api.registry, signedBlock, events, validators)), catchError(() =>
4547 of())));
4548 }
4549
4550 function getBlockByNumber(instanceId, api) {
4551 return memo(instanceId, blockNumber => api.rpc.chain.getBlockHash(blockNumber).pipe(switchMap(h => api.derive.chain.getBlock(h))));
4552 }
4553
4554 function subscribeNewBlocks(instanceId, api) {
4555 return memo(instanceId, () => api.derive.chain.subscribeNewHeads().pipe(switchMap(header => {
4556 const blockHash = header.createdAtHash || header.hash;
4557 return combineLatest([of(header), api.rpc.chain.getBlock(blockHash), api.queryAt(blockHash).pipe(switchMap(queryAt => queryAt.system.events()))]);
4558 }), map(([header, block, events]) => createSignedBlockExtended(block.registry, block, events, header.validators))));
4559 }
4560
4561 function subscribeNewHeads(instanceId, api) {
4562 return memo(instanceId, () => combineLatest([api.rpc.chain.subscribeNewHeads(), api.query.session ? api.query.session.validators() : of(undefined)]).pipe(map(([header, validators]) => {
4563 header.createdAtHash = header.hash;
4564 return createHeaderExtended(header.registry, header, validators);
4565 })));
4566 }
4567
4568 const chain = /*#__PURE__*/Object.freeze({
4569 __proto__: null,
4570 bestNumber: bestNumber,
4571 bestNumberFinalized: bestNumberFinalized,
4572 bestNumberLag: bestNumberLag,
4573 getHeader: getHeader,
4574 getBlock: getBlock,
4575 getBlockByNumber: getBlockByNumber,
4576 subscribeNewBlocks: subscribeNewBlocks,
4577 subscribeNewHeads: subscribeNewHeads
4578 });
4579
4580 function queryConstants(api) {
4581 return of([
4582 api.consts.contracts.callBaseFee || api.registry.createType('Balance'), api.consts.contracts.contractFee || api.registry.createType('Balance'), api.consts.contracts.creationFee || api.registry.createType('Balance'), api.consts.contracts.transactionBaseFee || api.registry.createType('Balance'), api.consts.contracts.transactionByteFee || api.registry.createType('Balance'), api.consts.contracts.transferFee || api.registry.createType('Balance'),
4583 api.consts.contracts.rentByteFee, api.consts.contracts.rentDepositOffset, api.consts.contracts.surchargeReward, api.consts.contracts.tombstoneDeposit]);
4584 }
4585 function fees(instanceId, api) {
4586 return memo(instanceId, () => {
4587 return queryConstants(api).pipe(map(([callBaseFee, contractFee, creationFee, transactionBaseFee, transactionByteFee, transferFee, rentByteFee, rentDepositOffset, surchargeReward, tombstoneDeposit]) => ({
4588 callBaseFee,
4589 contractFee,
4590 creationFee,
4591 rentByteFee,
4592 rentDepositOffset,
4593 surchargeReward,
4594 tombstoneDeposit,
4595 transactionBaseFee,
4596 transactionByteFee,
4597 transferFee
4598 })));
4599 });
4600 }
4601
4602 const contracts = /*#__PURE__*/Object.freeze({
4603 __proto__: null,
4604 fees: fees
4605 });
4606
4607 function getInstance(api, section) {
4608 const instances = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), section);
4609 const name = instances && instances.length ? instances[0] : section;
4610 return api.query[name];
4611 }
4612 function withSection(section, fn) {
4613 return (instanceId, api) => memo(instanceId, fn(getInstance(api, section), api, instanceId));
4614 }
4615 function callMethod(method, empty) {
4616 return section => withSection(section, query => () => util.isFunction(query === null || query === void 0 ? void 0 : query[method]) ? query[method]() : of(empty));
4617 }
4618
4619 const members$4 = callMethod('members', []);
4620
4621 function prime$3(section) {
4622 return withSection(section, query => () => util.isFunction(query === null || query === void 0 ? void 0 : query.prime) ? query.prime().pipe(map(o => o.unwrapOr(null))) : of(null));
4623 }
4624
4625 function parse$4(api, [hashes, proposals, votes]) {
4626 return proposals.map((o, index) => ({
4627 hash: api.registry.createType('Hash', hashes[index]),
4628 proposal: o && o.isSome ? o.unwrap() : null,
4629 votes: votes[index].unwrapOr(null)
4630 }));
4631 }
4632 function _proposalsFrom(api, query, hashes) {
4633 return (util.isFunction(query === null || query === void 0 ? void 0 : query.proposals) && hashes.length ? combineLatest([of(hashes),
4634 query.proposalOf.multi(hashes).pipe(catchError(() => of(hashes.map(() => null)))), query.voting.multi(hashes)]) : of([[], [], []])).pipe(map(r => parse$4(api, r)));
4635 }
4636 function hasProposals$3(section) {
4637 return withSection(section, query => () => of(util.isFunction(query === null || query === void 0 ? void 0 : query.proposals)));
4638 }
4639 function proposals$5(section) {
4640 return withSection(section, (query, api) => () => api.derive[section].proposalHashes().pipe(switchMap(all => _proposalsFrom(api, query, all))));
4641 }
4642 function proposal$3(section) {
4643 return withSection(section, (query, api) => hash => util.isFunction(query === null || query === void 0 ? void 0 : query.proposals) ? firstObservable(_proposalsFrom(api, query, [hash])) : of(null));
4644 }
4645 const proposalCount$3 = callMethod('proposalCount', null);
4646 const proposalHashes$3 = callMethod('proposals', []);
4647
4648 function isVoter(value) {
4649 return !Array.isArray(value);
4650 }
4651 function retrieveStakeOf(elections) {
4652 return elections.stakeOf.entries().pipe(map(entries => entries.map(([{
4653 args: [accountId]
4654 }, stake]) => [accountId, stake])));
4655 }
4656 function retrieveVoteOf(elections) {
4657 return elections.votesOf.entries().pipe(map(entries => entries.map(([{
4658 args: [accountId]
4659 }, votes]) => [accountId, votes])));
4660 }
4661 function retrievePrev(api, elections) {
4662 return combineLatest([retrieveStakeOf(elections), retrieveVoteOf(elections)]).pipe(map(([stakes, votes]) => {
4663 const result = [];
4664 votes.forEach(([voter, votes]) => {
4665 result.push([voter, {
4666 stake: api.registry.createType('Balance'),
4667 votes
4668 }]);
4669 });
4670 stakes.forEach(([staker, stake]) => {
4671 const entry = result.find(([voter]) => voter.eq(staker));
4672 if (entry) {
4673 entry[1].stake = stake;
4674 } else {
4675 result.push([staker, {
4676 stake,
4677 votes: []
4678 }]);
4679 }
4680 });
4681 return result;
4682 }));
4683 }
4684 function retrieveCurrent(elections) {
4685 return elections.voting.entries().pipe(map(entries => entries.map(([{
4686 args: [accountId]
4687 }, value]) => [accountId, isVoter(value) ? {
4688 stake: value.stake,
4689 votes: value.votes
4690 } : {
4691 stake: value[0],
4692 votes: value[1]
4693 }])));
4694 }
4695 function votes(instanceId, api) {
4696 const elections = api.query.phragmenElection || api.query.electionsPhragmen || api.query.elections;
4697 return memo(instanceId, () => elections ? elections.stakeOf ? retrievePrev(api, elections) : retrieveCurrent(elections) : of([]));
4698 }
4699
4700 function votesOf(instanceId, api) {
4701 return memo(instanceId, accountId => api.derive.council.votes().pipe(map(votes => (votes.find(([from]) => from.eq(accountId)) || [null, {
4702 stake: api.registry.createType('Balance'),
4703 votes: []
4704 }])[1])));
4705 }
4706
4707 const members$3 = members$4('council');
4708 const hasProposals$2 = hasProposals$3('council');
4709 const proposal$2 = proposal$3('council');
4710 const proposalCount$2 = proposalCount$3('council');
4711 const proposalHashes$2 = proposalHashes$3('council');
4712 const proposals$4 = proposals$5('council');
4713 const prime$2 = prime$3('council');
4714
4715 const council = /*#__PURE__*/Object.freeze({
4716 __proto__: null,
4717 members: members$3,
4718 hasProposals: hasProposals$2,
4719 proposal: proposal$2,
4720 proposalCount: proposalCount$2,
4721 proposalHashes: proposalHashes$2,
4722 proposals: proposals$4,
4723 prime: prime$2,
4724 votes: votes,
4725 votesOf: votesOf
4726 });
4727
4728 function createChildKey(info) {
4729 return util.u8aToHex(util.u8aConcat(':child_storage:default:', utilCrypto.blake2AsU8a(util.u8aConcat('crowdloan', (info.fundIndex || info.trieIndex).toU8a()))));
4730 }
4731 function childKey(instanceId, api) {
4732 return memo(instanceId, paraId => api.query.crowdloan.funds(paraId).pipe(map(optInfo => optInfo.isSome ? createChildKey(optInfo.unwrap()) : null)));
4733 }
4734
4735 function extractContributed(paraId, events) {
4736 var _events$createdAtHash;
4737 const added = [];
4738 const removed = [];
4739 return events.filter(({
4740 event: {
4741 data: [, eventParaId],
4742 method,
4743 section
4744 }
4745 }) => section === 'crowdloan' && ['Contributed', 'Withdrew'].includes(method) && eventParaId.eq(paraId)).reduce((result, {
4746 event: {
4747 data: [accountId],
4748 method
4749 }
4750 }) => {
4751 if (method === 'Contributed') {
4752 result.added.push(accountId.toHex());
4753 } else {
4754 result.removed.push(accountId.toHex());
4755 }
4756 return result;
4757 }, {
4758 added,
4759 blockHash: ((_events$createdAtHash = events.createdAtHash) === null || _events$createdAtHash === void 0 ? void 0 : _events$createdAtHash.toHex()) || '-',
4760 removed
4761 });
4762 }
4763
4764 const PAGE_SIZE_K$1 = 1000;
4765 function _getUpdates(api, paraId) {
4766 let added = [];
4767 let removed = [];
4768 return api.query.system.events().pipe(switchMap(events => {
4769 const changes = extractContributed(paraId, events);
4770 if (changes.added.length || changes.removed.length) {
4771 var _events$createdAtHash;
4772 added = added.concat(...changes.added);
4773 removed = removed.concat(...changes.removed);
4774 return of({
4775 added,
4776 addedDelta: changes.added,
4777 blockHash: ((_events$createdAtHash = events.createdAtHash) === null || _events$createdAtHash === void 0 ? void 0 : _events$createdAtHash.toHex()) || '-',
4778 removed,
4779 removedDelta: changes.removed
4780 });
4781 }
4782 return EMPTY;
4783 }), startWith({
4784 added,
4785 addedDelta: [],
4786 blockHash: '-',
4787 removed,
4788 removedDelta: []
4789 }));
4790 }
4791 function _eventTriggerAll(api, paraId) {
4792 return api.query.system.events().pipe(switchMap(events => {
4793 var _events$createdAtHash2;
4794 const items = events.filter(({
4795 event: {
4796 data: [eventParaId],
4797 method,
4798 section
4799 }
4800 }) => section === 'crowdloan' && ['AllRefunded', 'Dissolved', 'PartiallyRefunded'].includes(method) && eventParaId.eq(paraId));
4801 return items.length ? of(((_events$createdAtHash2 = events.createdAtHash) === null || _events$createdAtHash2 === void 0 ? void 0 : _events$createdAtHash2.toHex()) || '-') : EMPTY;
4802 }), startWith('-'));
4803 }
4804 function _getKeysPaged(api, childKey) {
4805 const subject = new BehaviorSubject(undefined);
4806 return subject.pipe(switchMap(startKey => api.rpc.childstate.getKeysPaged(childKey, '0x', PAGE_SIZE_K$1, startKey)), tap(keys => {
4807 util.nextTick(() => {
4808 keys.length === PAGE_SIZE_K$1 ? subject.next(keys[PAGE_SIZE_K$1 - 1].toHex()) : subject.complete();
4809 });
4810 }), toArray(),
4811 map(keyArr => util.arrayFlatten(keyArr)));
4812 }
4813 function _getAll(api, paraId, childKey) {
4814 return _eventTriggerAll(api, paraId).pipe(switchMap(() => util.isFunction(api.rpc.childstate.getKeysPaged) ? _getKeysPaged(api, childKey) : api.rpc.childstate.getKeys(childKey, '0x')), map(keys => keys.map(k => k.toHex())));
4815 }
4816 function _contributions$1(api, paraId, childKey) {
4817 return combineLatest([_getAll(api, paraId, childKey), _getUpdates(api, paraId)]).pipe(map(([keys, {
4818 added,
4819 blockHash,
4820 removed
4821 }]) => {
4822 const contributorsMap = {};
4823 keys.forEach(k => {
4824 contributorsMap[k] = true;
4825 });
4826 added.forEach(k => {
4827 contributorsMap[k] = true;
4828 });
4829 removed.forEach(k => {
4830 delete contributorsMap[k];
4831 });
4832 return {
4833 blockHash,
4834 contributorsHex: Object.keys(contributorsMap)
4835 };
4836 }));
4837 }
4838 function contributions(instanceId, api) {
4839 return memo(instanceId, paraId => api.derive.crowdloan.childKey(paraId).pipe(switchMap(childKey => childKey ? _contributions$1(api, paraId, childKey) : of({
4840 blockHash: '-',
4841 contributorsHex: []
4842 }))));
4843 }
4844
4845 function _getValues(api, childKey, keys) {
4846 return combineLatest(keys.map(k => api.rpc.childstate.getStorage(childKey, k))).pipe(map(values => values.map(v => api.registry.createType('Option<StorageData>', v)).map(o => o.isSome ? api.registry.createType('Balance', o.unwrap()) : api.registry.createType('Balance')).reduce((all, b, index) => ({ ...all,
4847 [keys[index]]: b
4848 }), {})));
4849 }
4850 function _watchOwnChanges(api, paraId, childkey, keys) {
4851 return api.query.system.events().pipe(switchMap(events => {
4852 const changes = extractContributed(paraId, events);
4853 const filtered = keys.filter(k => changes.added.includes(k) || changes.removed.includes(k));
4854 return filtered.length ? _getValues(api, childkey, filtered) : EMPTY;
4855 }), startWith({}));
4856 }
4857 function _contributions(api, paraId, childKey, keys) {
4858 return combineLatest([_getValues(api, childKey, keys), _watchOwnChanges(api, paraId, childKey, keys)]).pipe(map(([all, latest]) => ({ ...all,
4859 ...latest
4860 })));
4861 }
4862 function ownContributions(instanceId, api) {
4863 return memo(instanceId, (paraId, keys) => api.derive.crowdloan.childKey(paraId).pipe(switchMap(childKey => childKey && keys.length ? _contributions(api, paraId, childKey, keys) : of({}))));
4864 }
4865
4866 const crowdloan = /*#__PURE__*/Object.freeze({
4867 __proto__: null,
4868 childKey: childKey,
4869 contributions: contributions,
4870 ownContributions: ownContributions
4871 });
4872
4873 const DEMOCRACY_ID = util.stringToHex('democrac');
4874 function isMaybeHashed(call) {
4875 return call instanceof types.Enum;
4876 }
4877 function queryQueue(api) {
4878 return api.query.democracy.dispatchQueue().pipe(switchMap(dispatches => combineLatest([of(dispatches), api.derive.democracy.preimages(dispatches.map(([, hash]) => hash))])), map(([dispatches, images]) => dispatches.map(([at, imageHash, index], dispatchIndex) => ({
4879 at,
4880 image: images[dispatchIndex],
4881 imageHash,
4882 index
4883 }))));
4884 }
4885 function schedulerEntries(api) {
4886 return api.derive.democracy.referendumsFinished().pipe(switchMap(() => api.query.scheduler.agenda.keys()), switchMap(keys => {
4887 const blockNumbers = keys.map(({
4888 args: [blockNumber]
4889 }) => blockNumber);
4890 return blockNumbers.length ? combineLatest([of(blockNumbers),
4891 api.query.scheduler.agenda.multi(blockNumbers).pipe(catchError(() => of(blockNumbers.map(() => []))))]) : of([[], []]);
4892 }));
4893 }
4894 function queryScheduler(api) {
4895 return schedulerEntries(api).pipe(switchMap(([blockNumbers, agendas]) => {
4896 const result = [];
4897 blockNumbers.forEach((at, index) => {
4898 (agendas[index] || []).filter(o => o.isSome).forEach(o => {
4899 const scheduled = o.unwrap();
4900 if (scheduled.maybeId.isSome) {
4901 const id = scheduled.maybeId.unwrap().toHex();
4902 if (id.startsWith(DEMOCRACY_ID)) {
4903 const imageHash = isMaybeHashed(scheduled.call) ? scheduled.call.isHash ? scheduled.call.asHash : scheduled.call.asValue.args[0] : scheduled.call.args[0];
4904 result.push({
4905 at,
4906 imageHash,
4907 index: api.registry.createType('(u64, ReferendumIndex)', id)[1]
4908 });
4909 }
4910 }
4911 });
4912 });
4913 return combineLatest([of(result), result.length ? api.derive.democracy.preimages(result.map(({
4914 imageHash
4915 }) => imageHash)) : of([])]);
4916 }), map(([infos, images]) => infos.map((info, index) => ({ ...info,
4917 image: images[index]
4918 }))));
4919 }
4920 function dispatchQueue(instanceId, api) {
4921 return memo(instanceId, () => {
4922 var _api$query$scheduler;
4923 return util.isFunction((_api$query$scheduler = api.query.scheduler) === null || _api$query$scheduler === void 0 ? void 0 : _api$query$scheduler.agenda) ? queryScheduler(api) : api.query.democracy.dispatchQueue ? queryQueue(api) : of([]);
4924 });
4925 }
4926
4927 const LOCKUPS = [0, 1, 2, 4, 8, 16, 32];
4928 function parseEnd(api, vote, {
4929 approved,
4930 end
4931 }) {
4932 return [end, approved.isTrue && vote.isAye || approved.isFalse && vote.isNay ? end.add((api.consts.democracy.voteLockingPeriod || api.consts.democracy.enactmentPeriod).muln(LOCKUPS[vote.conviction.index])) : util.BN_ZERO];
4933 }
4934 function parseLock(api, [referendumId, accountVote], referendum) {
4935 const {
4936 balance,
4937 vote
4938 } = accountVote.asStandard;
4939 const [referendumEnd, unlockAt] = referendum.isFinished ? parseEnd(api, vote, referendum.asFinished) : [util.BN_ZERO, util.BN_ZERO];
4940 return {
4941 balance,
4942 isDelegated: false,
4943 isFinished: referendum.isFinished,
4944 referendumEnd,
4945 referendumId,
4946 unlockAt,
4947 vote
4948 };
4949 }
4950 function delegateLocks(api, {
4951 balance,
4952 conviction,
4953 target
4954 }) {
4955 return api.derive.democracy.locks(target).pipe(map(available => available.map(({
4956 isFinished,
4957 referendumEnd,
4958 referendumId,
4959 unlockAt,
4960 vote
4961 }) => ({
4962 balance,
4963 isDelegated: true,
4964 isFinished,
4965 referendumEnd,
4966 referendumId,
4967 unlockAt: unlockAt.isZero() ? unlockAt : referendumEnd.add((api.consts.democracy.voteLockingPeriod || api.consts.democracy.enactmentPeriod).muln(LOCKUPS[conviction.index])),
4968 vote: api.registry.createType('Vote', {
4969 aye: vote.isAye,
4970 conviction
4971 })
4972 }))));
4973 }
4974 function directLocks(api, {
4975 votes
4976 }) {
4977 if (!votes.length) {
4978 return of([]);
4979 }
4980 return api.query.democracy.referendumInfoOf.multi(votes.map(([referendumId]) => referendumId)).pipe(map(referendums => votes.map((vote, index) => [vote, referendums[index].unwrapOr(null)]).filter(item => !!item[1] && util.isUndefined(item[1].end) && item[0][1].isStandard).map(([directVote, referendum]) => parseLock(api, directVote, referendum))));
4981 }
4982 function locks(instanceId, api) {
4983 return memo(instanceId, accountId => api.query.democracy.votingOf ? api.query.democracy.votingOf(accountId).pipe(switchMap(voting => voting.isDirect ? directLocks(api, voting.asDirect) : voting.isDelegating ? delegateLocks(api, voting.asDelegating) : of([]))) : of([]));
4984 }
4985
4986 function withImage(api, nextOpt) {
4987 if (nextOpt.isNone) {
4988 return of(null);
4989 }
4990 const [imageHash, threshold] = nextOpt.unwrap();
4991 return api.derive.democracy.preimage(imageHash).pipe(map(image => ({
4992 image,
4993 imageHash,
4994 threshold
4995 })));
4996 }
4997 function nextExternal(instanceId, api) {
4998 return memo(instanceId, () => {
4999 var _api$query$democracy;
5000 return (_api$query$democracy = api.query.democracy) !== null && _api$query$democracy !== void 0 && _api$query$democracy.nextExternal ? api.query.democracy.nextExternal().pipe(switchMap(nextOpt => withImage(api, nextOpt))) : of(null);
5001 });
5002 }
5003
5004 function isDemocracyPreimage(api, imageOpt) {
5005 return !!imageOpt && !api.query.democracy.dispatchQueue;
5006 }
5007 function constructProposal(api, [bytes, proposer, balance, at]) {
5008 let proposal;
5009 try {
5010 proposal = api.registry.createType('Proposal', bytes.toU8a(true));
5011 } catch (error) {
5012 console.error(error);
5013 }
5014 return {
5015 at,
5016 balance,
5017 proposal,
5018 proposer
5019 };
5020 }
5021 function parseDemocracy(api, imageOpt) {
5022 if (imageOpt.isNone) {
5023 return;
5024 }
5025 if (isDemocracyPreimage(api, imageOpt)) {
5026 const status = imageOpt.unwrap();
5027 if (status.isMissing) {
5028 return;
5029 }
5030 const {
5031 data,
5032 deposit,
5033 provider,
5034 since
5035 } = status.asAvailable;
5036 return constructProposal(api, [data, provider, deposit, since]);
5037 }
5038 return constructProposal(api, imageOpt.unwrap());
5039 }
5040 function getDemocracyImages(api, hashes) {
5041 return api.query.democracy.preimages.multi(hashes).pipe(map(images => images.map(imageOpt => parseDemocracy(api, imageOpt))));
5042 }
5043 function preimages(instanceId, api) {
5044 return memo(instanceId, hashes => hashes.length ? util.isFunction(api.query.democracy.preimages) ? getDemocracyImages(api, hashes) : of([]) : of([]));
5045 }
5046 const preimage = firstMemo((api, hash) => api.derive.democracy.preimages([hash]));
5047
5048 function isNewDepositors(depositors) {
5049 return util.isFunction(depositors[1].mul);
5050 }
5051 function parse$3([proposals, images, optDepositors]) {
5052 return proposals.filter(([,, proposer], index) => {
5053 var _optDepositors$index;
5054 return !!((_optDepositors$index = optDepositors[index]) !== null && _optDepositors$index !== void 0 && _optDepositors$index.isSome) && !proposer.isEmpty;
5055 }).map(([index, imageHash, proposer], proposalIndex) => {
5056 const depositors = optDepositors[proposalIndex].unwrap();
5057 return { ...(isNewDepositors(depositors) ? {
5058 balance: depositors[1],
5059 seconds: depositors[0]
5060 } : {
5061 balance: depositors[0],
5062 seconds: depositors[1]
5063 }),
5064 image: images[proposalIndex],
5065 imageHash,
5066 index,
5067 proposer
5068 };
5069 });
5070 }
5071 function proposals$3(instanceId, api) {
5072 return memo(instanceId, () => {
5073 var _api$query$democracy, _api$query$democracy2;
5074 return util.isFunction((_api$query$democracy = api.query.democracy) === null || _api$query$democracy === void 0 ? void 0 : _api$query$democracy.publicProps) && util.isFunction((_api$query$democracy2 = api.query.democracy) === null || _api$query$democracy2 === void 0 ? void 0 : _api$query$democracy2.preimages) ? api.query.democracy.publicProps().pipe(switchMap(proposals => proposals.length ? combineLatest([of(proposals), api.derive.democracy.preimages(proposals.map(([, hash]) => hash)), api.query.democracy.depositOf.multi(proposals.map(([index]) => index))]) : of([[], [], []])), map(parse$3)) : of([]);
5075 });
5076 }
5077
5078 function referendumIds(instanceId, api) {
5079 return memo(instanceId, () => {
5080 var _api$query$democracy;
5081 return (_api$query$democracy = api.query.democracy) !== null && _api$query$democracy !== void 0 && _api$query$democracy.lowestUnbaked ? api.queryMulti([api.query.democracy.lowestUnbaked, api.query.democracy.referendumCount]).pipe(map(([first, total]) => total.gt(first)
5082 ? [...Array(total.sub(first).toNumber())].map((_, i) => first.addn(i)) : [])) : of([]);
5083 });
5084 }
5085
5086 function referendums(instanceId, api) {
5087 return memo(instanceId, () => api.derive.democracy.referendumsActive().pipe(switchMap(referendums => referendums.length ? combineLatest([of(referendums), api.derive.democracy._referendumsVotes(referendums)]) : of([[], []])), map(([referendums, votes]) => referendums.map((referendum, index) => ({ ...referendum,
5088 ...votes[index]
5089 })))));
5090 }
5091
5092 function referendumsActive(instanceId, api) {
5093 return memo(instanceId, () => api.derive.democracy.referendumIds().pipe(switchMap(ids => ids.length ? api.derive.democracy.referendumsInfo(ids) : of([]))));
5094 }
5095
5096 function referendumsFinished(instanceId, api) {
5097 return memo(instanceId, () => api.derive.democracy.referendumIds().pipe(switchMap(ids => api.query.democracy.referendumInfoOf.multi(ids)), map(infos => infos.map(o => o.unwrapOr(null)).filter(info => !!info && info.isFinished).map(info => info.asFinished))));
5098 }
5099
5100 function isOldInfo(info) {
5101 return !!info.proposalHash;
5102 }
5103 function isCurrentStatus(status) {
5104 return !!status.tally;
5105 }
5106 function compareRationals(n1, d1, n2, d2) {
5107 while (true) {
5108 const q1 = n1.div(d1);
5109 const q2 = n2.div(d2);
5110 if (q1.lt(q2)) {
5111 return true;
5112 } else if (q2.lt(q1)) {
5113 return false;
5114 }
5115 const r1 = n1.mod(d1);
5116 const r2 = n2.mod(d2);
5117 if (r2.isZero()) {
5118 return false;
5119 } else if (r1.isZero()) {
5120 return true;
5121 }
5122 n1 = d2;
5123 n2 = d1;
5124 d1 = r2;
5125 d2 = r1;
5126 }
5127 }
5128 function calcPassingOther(threshold, sqrtElectorate, {
5129 votedAye,
5130 votedNay,
5131 votedTotal
5132 }) {
5133 const sqrtVoters = util.bnSqrt(votedTotal);
5134 return sqrtVoters.isZero() ? false : threshold.isSuperMajorityApprove ? compareRationals(votedNay, sqrtVoters, votedAye, sqrtElectorate) : compareRationals(votedNay, sqrtElectorate, votedAye, sqrtVoters);
5135 }
5136 function calcPassing(threshold, sqrtElectorate, state) {
5137 return threshold.isSimpleMajority ? state.votedAye.gt(state.votedNay) : calcPassingOther(threshold, sqrtElectorate, state);
5138 }
5139 function calcVotesPrev(votesFor) {
5140 return votesFor.reduce((state, derived) => {
5141 const {
5142 balance,
5143 vote
5144 } = derived;
5145 const isDefault = vote.conviction.index === 0;
5146 const counted = balance.muln(isDefault ? 1 : vote.conviction.index).divn(isDefault ? 10 : 1);
5147 if (vote.isAye) {
5148 state.allAye.push(derived);
5149 state.voteCountAye++;
5150 state.votedAye.iadd(counted);
5151 } else {
5152 state.allNay.push(derived);
5153 state.voteCountNay++;
5154 state.votedNay.iadd(counted);
5155 }
5156 state.voteCount++;
5157 state.votedTotal.iadd(counted);
5158 return state;
5159 }, {
5160 allAye: [],
5161 allNay: [],
5162 voteCount: 0,
5163 voteCountAye: 0,
5164 voteCountNay: 0,
5165 votedAye: new util.BN(0),
5166 votedNay: new util.BN(0),
5167 votedTotal: new util.BN(0)
5168 });
5169 }
5170 function calcVotesCurrent(tally, votes) {
5171 const allAye = [];
5172 const allNay = [];
5173 votes.forEach(derived => {
5174 if (derived.vote.isAye) {
5175 allAye.push(derived);
5176 } else {
5177 allNay.push(derived);
5178 }
5179 });
5180 return {
5181 allAye,
5182 allNay,
5183 voteCount: allAye.length + allNay.length,
5184 voteCountAye: allAye.length,
5185 voteCountNay: allNay.length,
5186 votedAye: tally.ayes,
5187 votedNay: tally.nays,
5188 votedTotal: tally.turnout
5189 };
5190 }
5191 function calcVotes(sqrtElectorate, referendum, votes) {
5192 const state = isCurrentStatus(referendum.status) ? calcVotesCurrent(referendum.status.tally, votes) : calcVotesPrev(votes);
5193 return { ...state,
5194 isPassing: calcPassing(referendum.status.threshold, sqrtElectorate, state),
5195 votes
5196 };
5197 }
5198 function getStatus(info) {
5199 if (info.isNone) {
5200 return null;
5201 }
5202 const unwrapped = info.unwrap();
5203 return isOldInfo(unwrapped) ? unwrapped : unwrapped.isOngoing ? unwrapped.asOngoing
5204 : null;
5205 }
5206
5207 function votesPrev(api, referendumId) {
5208 return api.query.democracy.votersFor(referendumId).pipe(switchMap(votersFor => combineLatest([of(votersFor), votersFor.length ? api.query.democracy.voteOf.multi(votersFor.map(accountId => [referendumId, accountId])) : of([]), api.derive.balances.votingBalances(votersFor)])), map(([votersFor, votes, balances]) => votersFor.map((accountId, index) => ({
5209 accountId,
5210 balance: balances[index].votingBalance || api.registry.createType('Balance'),
5211 isDelegating: false,
5212 vote: votes[index] || api.registry.createType('Vote')
5213 }))));
5214 }
5215 function extractVotes(mapped, referendumId) {
5216 return mapped.filter(([, voting]) => voting.isDirect).map(([accountId, voting]) => [accountId, voting.asDirect.votes.filter(([idx]) => idx.eq(referendumId))]).filter(([, directVotes]) => !!directVotes.length).reduce((result, [accountId, votes]) =>
5217 votes.reduce((result, [, vote]) => {
5218 if (vote.isStandard) {
5219 result.push({
5220 accountId,
5221 isDelegating: false,
5222 ...vote.asStandard
5223 });
5224 }
5225 return result;
5226 }, result), []);
5227 }
5228 function votesCurr(api, referendumId) {
5229 return api.query.democracy.votingOf.entries().pipe(map(allVoting => {
5230 const mapped = allVoting.map(([{
5231 args: [accountId]
5232 }, voting]) => [accountId, voting]);
5233 const votes = extractVotes(mapped, referendumId);
5234 const delegations = mapped.filter(([, voting]) => voting.isDelegating).map(([accountId, voting]) => [accountId, voting.asDelegating]);
5235 delegations.forEach(([accountId, {
5236 balance,
5237 conviction,
5238 target
5239 }]) => {
5240 const toDelegator = delegations.find(([accountId]) => accountId.eq(target));
5241 const to = votes.find(({
5242 accountId
5243 }) => accountId.eq(toDelegator ? toDelegator[0] : target));
5244 if (to) {
5245 votes.push({
5246 accountId,
5247 balance,
5248 isDelegating: true,
5249 vote: api.registry.createType('Vote', {
5250 aye: to.vote.isAye,
5251 conviction
5252 })
5253 });
5254 }
5255 });
5256 return votes;
5257 }));
5258 }
5259 function _referendumVotes(instanceId, api) {
5260 return memo(instanceId, referendum => combineLatest([api.derive.democracy.sqrtElectorate(), util.isFunction(api.query.democracy.votingOf) ? votesCurr(api, referendum.index) : votesPrev(api, referendum.index)]).pipe(map(([sqrtElectorate, votes]) => calcVotes(sqrtElectorate, referendum, votes))));
5261 }
5262 function _referendumsVotes(instanceId, api) {
5263 return memo(instanceId, referendums => referendums.length ? combineLatest(referendums.map(referendum => api.derive.democracy._referendumVotes(referendum))) : of([]));
5264 }
5265 function _referendumInfo(instanceId, api) {
5266 return memo(instanceId, (index, info) => {
5267 const status = getStatus(info);
5268 return status ? api.derive.democracy.preimage(status.proposalHash).pipe(map(image => ({
5269 image,
5270 imageHash: status.proposalHash,
5271 index: api.registry.createType('ReferendumIndex', index),
5272 status
5273 }))) : of(null);
5274 });
5275 }
5276 function referendumsInfo(instanceId, api) {
5277 return memo(instanceId, ids => ids.length ? api.query.democracy.referendumInfoOf.multi(ids).pipe(switchMap(infos => combineLatest(ids.map((id, index) => api.derive.democracy._referendumInfo(id, infos[index])))), map(infos => infos.filter(referendum => !!referendum))) : of([]));
5278 }
5279
5280 function sqrtElectorate(instanceId, api) {
5281 return memo(instanceId, () => api.query.balances.totalIssuance().pipe(map(util.bnSqrt)));
5282 }
5283
5284 const democracy = /*#__PURE__*/Object.freeze({
5285 __proto__: null,
5286 dispatchQueue: dispatchQueue,
5287 locks: locks,
5288 nextExternal: nextExternal,
5289 preimages: preimages,
5290 preimage: preimage,
5291 proposals: proposals$3,
5292 referendumIds: referendumIds,
5293 referendums: referendums,
5294 referendumsActive: referendumsActive,
5295 referendumsFinished: referendumsFinished,
5296 _referendumVotes: _referendumVotes,
5297 _referendumsVotes: _referendumsVotes,
5298 _referendumInfo: _referendumInfo,
5299 referendumsInfo: referendumsInfo,
5300 sqrtElectorate: sqrtElectorate
5301 });
5302
5303 function isSeatHolder(value) {
5304 return !Array.isArray(value);
5305 }
5306 function isCandidateTuple(value) {
5307 return Array.isArray(value);
5308 }
5309 function getAccountTuple(value) {
5310 return isSeatHolder(value) ? [value.who, value.stake] : value;
5311 }
5312 function getCandidate(value) {
5313 return isCandidateTuple(value) ? value[0] : value;
5314 }
5315 function sortAccounts([, balanceA], [, balanceB]) {
5316 return balanceB.cmp(balanceA);
5317 }
5318 function getConstants(api, elections) {
5319 return elections ? {
5320 candidacyBond: api.consts[elections].candidacyBond,
5321 desiredRunnersUp: api.consts[elections].desiredRunnersUp,
5322 desiredSeats: api.consts[elections].desiredMembers,
5323 termDuration: api.consts[elections].termDuration,
5324 votingBond: api.consts[elections].votingBond
5325 } : {};
5326 }
5327 function getModules(api) {
5328 const [council] = api.registry.getModuleInstances(api.runtimeVersion.specName.toString(), 'council') || ['council'];
5329 const elections = api.query.phragmenElection ? 'phragmenElection' : api.query.electionsPhragmen ? 'electionsPhragmen' : api.query.elections ? 'elections' : null;
5330 return [council, elections];
5331 }
5332 function queryAll(api, council, elections) {
5333 return api.queryMulti([api.query[council].members, api.query[elections].candidates, api.query[elections].members, api.query[elections].runnersUp]);
5334 }
5335 function queryCouncil(api, council) {
5336 return combineLatest([api.query[council].members(), of([]), of([]), of([])]);
5337 }
5338 function info$3(instanceId, api) {
5339 return memo(instanceId, () => {
5340 const [council, elections] = getModules(api);
5341 return (elections ? queryAll(api, council, elections) : queryCouncil(api, council)).pipe(map(([councilMembers, candidates, members, runnersUp]) => ({ ...getConstants(api, elections),
5342 candidateCount: api.registry.createType('u32', candidates.length),
5343 candidates: candidates.map(getCandidate),
5344 members: members.length ? members.map(getAccountTuple).sort(sortAccounts) : councilMembers.map(a => [a, api.registry.createType('Balance')]),
5345 runnersUp: runnersUp.map(getAccountTuple).sort(sortAccounts)
5346 })));
5347 });
5348 }
5349
5350 const elections = /*#__PURE__*/Object.freeze({
5351 __proto__: null,
5352 info: info$3
5353 });
5354
5355 function mapResult([result, validators, heartbeats, numBlocks]) {
5356 validators.forEach((validator, index) => {
5357 const validatorId = validator.toString();
5358 const blockCount = numBlocks[index];
5359 const hasMessage = !heartbeats[index].isEmpty;
5360 const prev = result[validatorId];
5361 if (!prev || prev.hasMessage !== hasMessage || !prev.blockCount.eq(blockCount)) {
5362 result[validatorId] = {
5363 blockCount,
5364 hasMessage,
5365 isOnline: hasMessage || blockCount.gt(util.BN_ZERO)
5366 };
5367 }
5368 });
5369 return result;
5370 }
5371 function receivedHeartbeats(instanceId, api) {
5372 return memo(instanceId, () => {
5373 var _api$query$imOnline;
5374 return (_api$query$imOnline = api.query.imOnline) !== null && _api$query$imOnline !== void 0 && _api$query$imOnline.receivedHeartbeats ? api.derive.staking.overview().pipe(switchMap(({
5375 currentIndex,
5376 validators
5377 }) => combineLatest([of({}), of(validators), api.query.imOnline.receivedHeartbeats.multi(validators.map((_address, index) => [currentIndex, index])), api.query.imOnline.authoredBlocks.multi(validators.map(address => [currentIndex, address]))])), map(mapResult)) : of({});
5378 });
5379 }
5380
5381 const imOnline = /*#__PURE__*/Object.freeze({
5382 __proto__: null,
5383 receivedHeartbeats: receivedHeartbeats
5384 });
5385
5386 const members$2 = members$4('membership');
5387 const hasProposals$1 = hasProposals$3('membership');
5388 const proposal$1 = proposal$3('membership');
5389 const proposalCount$1 = proposalCount$3('membership');
5390 const proposalHashes$1 = proposalHashes$3('membership');
5391 const proposals$2 = proposals$5('membership');
5392 const prime$1 = prime$3('membership');
5393
5394 const membership = /*#__PURE__*/Object.freeze({
5395 __proto__: null,
5396 members: members$2,
5397 hasProposals: hasProposals$1,
5398 proposal: proposal$1,
5399 proposalCount: proposalCount$1,
5400 proposalHashes: proposalHashes$1,
5401 proposals: proposals$2,
5402 prime: prime$1
5403 });
5404
5405 function didUpdateToBool(didUpdate, id) {
5406 return didUpdate.isSome ? didUpdate.unwrap().some(paraId => paraId.eq(id)) : false;
5407 }
5408
5409 function parseActive(id, active) {
5410 const found = active.find(([paraId]) => paraId === id);
5411 if (found && found[1].isSome) {
5412 const [collatorId, retriable] = found[1].unwrap();
5413 return {
5414 collatorId,
5415 ...(retriable.isWithRetries ? {
5416 isRetriable: true,
5417 retries: retriable.asWithRetries.toNumber()
5418 } : {
5419 isRetriable: false,
5420 retries: 0
5421 })
5422 };
5423 }
5424 return null;
5425 }
5426 function parseCollators(id, collatorQueue) {
5427 return collatorQueue.map(queue => {
5428 const found = queue.find(([paraId]) => paraId === id);
5429 return found ? found[1] : null;
5430 });
5431 }
5432 function parse$2(id, [active, retryQueue, selectedThreads, didUpdate, info, pendingSwap, heads, relayDispatchQueue]) {
5433 if (info.isNone) {
5434 return null;
5435 }
5436 return {
5437 active: parseActive(id, active),
5438 didUpdate: didUpdateToBool(didUpdate, id),
5439 heads,
5440 id,
5441 info: {
5442 id,
5443 ...info.unwrap()
5444 },
5445 pendingSwapId: pendingSwap.unwrapOr(null),
5446 relayDispatchQueue,
5447 retryCollators: parseCollators(id, retryQueue),
5448 selectedCollators: parseCollators(id, selectedThreads)
5449 };
5450 }
5451 function info$2(instanceId, api) {
5452 return memo(instanceId, id => api.query.registrar && api.query.parachains ? api.queryMulti([api.query.registrar.active, api.query.registrar.retryQueue, api.query.registrar.selectedThreads, api.query.parachains.didUpdate, [api.query.registrar.paras, id], [api.query.registrar.pendingSwap, id], [api.query.parachains.heads, id], [api.query.parachains.relayDispatchQueue, id]]).pipe(map(result => parse$2(api.registry.createType('ParaId', id), result))) : of(null));
5453 }
5454
5455 function parse$1([ids, didUpdate, infos, pendingSwaps, relayDispatchQueueSizes]) {
5456 return ids.map((id, index) => ({
5457 didUpdate: didUpdateToBool(didUpdate, id),
5458 id,
5459 info: {
5460 id,
5461 ...infos[index].unwrapOr(null)
5462 },
5463 pendingSwapId: pendingSwaps[index].unwrapOr(null),
5464 relayDispatchQueueSize: relayDispatchQueueSizes[index][0].toNumber()
5465 }));
5466 }
5467 function overview$1(instanceId, api) {
5468 return memo(instanceId, () => {
5469 var _api$query$registrar;
5470 return (_api$query$registrar = api.query.registrar) !== null && _api$query$registrar !== void 0 && _api$query$registrar.parachains && api.query.parachains ? api.query.registrar.parachains().pipe(switchMap(paraIds => combineLatest([of(paraIds), api.query.parachains.didUpdate(), api.query.registrar.paras.multi(paraIds), api.query.registrar.pendingSwap.multi(paraIds), api.query.parachains.relayDispatchQueueSize.multi(paraIds)])), map(parse$1)) : of([]);
5471 });
5472 }
5473
5474 const parachains = /*#__PURE__*/Object.freeze({
5475 __proto__: null,
5476 info: info$2,
5477 overview: overview$1
5478 });
5479
5480 function parse([currentIndex, activeEra, activeEraStart, currentEra, validatorCount]) {
5481 return {
5482 activeEra,
5483 activeEraStart,
5484 currentEra,
5485 currentIndex,
5486 validatorCount
5487 };
5488 }
5489 function queryStaking(api) {
5490 return api.queryMulti([api.query.session.currentIndex, api.query.staking.activeEra, api.query.staking.currentEra, api.query.staking.validatorCount]).pipe(map(([currentIndex, activeOpt, currentEra, validatorCount]) => {
5491 const {
5492 index,
5493 start
5494 } = activeOpt.unwrapOrDefault();
5495 return parse([currentIndex, index, start, currentEra.unwrapOrDefault(), validatorCount]);
5496 }));
5497 }
5498 function querySession(api) {
5499 return api.query.session.currentIndex().pipe(map(currentIndex => parse([currentIndex, api.registry.createType('EraIndex'), api.registry.createType('Option<Moment>'), api.registry.createType('EraIndex'), api.registry.createType('u32')])));
5500 }
5501 function empty(api) {
5502 return of(parse([api.registry.createType('SessionIndex', 1), api.registry.createType('EraIndex'), api.registry.createType('Option<Moment>'), api.registry.createType('EraIndex'), api.registry.createType('u32')]));
5503 }
5504 function indexes(instanceId, api) {
5505 return memo(instanceId, () => api.query.session ? api.query.staking ? queryStaking(api) : querySession(api) : empty(api));
5506 }
5507
5508 function info$1(instanceId, api) {
5509 return memo(instanceId, () => api.derive.session.indexes().pipe(map(indexes => {
5510 var _api$consts, _api$consts$babe, _api$consts2, _api$consts2$staking;
5511 const sessionLength = ((_api$consts = api.consts) === null || _api$consts === void 0 ? void 0 : (_api$consts$babe = _api$consts.babe) === null || _api$consts$babe === void 0 ? void 0 : _api$consts$babe.epochDuration) || api.registry.createType('u64', 1);
5512 const sessionsPerEra = ((_api$consts2 = api.consts) === null || _api$consts2 === void 0 ? void 0 : (_api$consts2$staking = _api$consts2.staking) === null || _api$consts2$staking === void 0 ? void 0 : _api$consts2$staking.sessionsPerEra) || api.registry.createType('SessionIndex', 1);
5513 return { ...indexes,
5514 eraLength: api.registry.createType('BlockNumber', sessionsPerEra.mul(sessionLength)),
5515 isEpoch: !!api.query.babe,
5516 sessionLength,
5517 sessionsPerEra
5518 };
5519 })));
5520 }
5521
5522 function withProgressField(field) {
5523 return (instanceId, api) => memo(instanceId, () => api.derive.session.progress().pipe(map(info => info[field])));
5524 }
5525 function createDerive(api, info, [currentSlot, epochIndex, epochOrGenesisStartSlot, activeEraStartSessionIndex]) {
5526 const epochStartSlot = epochIndex.mul(info.sessionLength).iadd(epochOrGenesisStartSlot);
5527 const sessionProgress = currentSlot.sub(epochStartSlot);
5528 const eraProgress = info.currentIndex.sub(activeEraStartSessionIndex).imul(info.sessionLength).iadd(sessionProgress);
5529 return { ...info,
5530 eraProgress: api.registry.createType('BlockNumber', eraProgress),
5531 sessionProgress: api.registry.createType('BlockNumber', sessionProgress)
5532 };
5533 }
5534 function queryAura(api) {
5535 return api.derive.session.info().pipe(map(info => ({ ...info,
5536 eraProgress: api.registry.createType('BlockNumber'),
5537 sessionProgress: api.registry.createType('BlockNumber')
5538 })));
5539 }
5540 function queryBabe(api) {
5541 return api.derive.session.info().pipe(switchMap(info => {
5542 var _api$query$staking;
5543 return combineLatest([of(info),
5544 (_api$query$staking = api.query.staking) !== null && _api$query$staking !== void 0 && _api$query$staking.erasStartSessionIndex ? api.queryMulti([api.query.babe.currentSlot, api.query.babe.epochIndex, api.query.babe.genesisSlot, [api.query.staking.erasStartSessionIndex, info.activeEra]]) : api.queryMulti([api.query.babe.currentSlot, api.query.babe.epochIndex, api.query.babe.genesisSlot])]);
5545 }), map(([info, [currentSlot, epochIndex, genesisSlot, optStartIndex]]) => [info, [currentSlot, epochIndex, genesisSlot, optStartIndex && optStartIndex.isSome ? optStartIndex.unwrap() : api.registry.createType('SessionIndex', 1)]]));
5546 }
5547 function progress(instanceId, api) {
5548 return memo(instanceId, () => api.query.babe ? queryBabe(api).pipe(map(([info, slots]) => createDerive(api, info, slots))) : queryAura(api));
5549 }
5550 const eraLength = withProgressField('eraLength');
5551 const eraProgress = withProgressField('eraProgress');
5552 const sessionProgress = withProgressField('sessionProgress');
5553
5554 const session = /*#__PURE__*/Object.freeze({
5555 __proto__: null,
5556 indexes: indexes,
5557 info: info$1,
5558 progress: progress,
5559 eraLength: eraLength,
5560 eraProgress: eraProgress,
5561 sessionProgress: sessionProgress
5562 });
5563
5564 function candidates(instanceId, api) {
5565 return memo(instanceId, () => api.query.society.candidates().pipe(switchMap(candidates => combineLatest([of(candidates), api.query.society.suspendedCandidates.multi(candidates.map(({
5566 who
5567 }) => who))])), map(([candidates, suspended]) => candidates.map(({
5568 kind,
5569 value,
5570 who
5571 }, index) => ({
5572 accountId: who,
5573 isSuspended: suspended[index].isSome,
5574 kind,
5575 value
5576 })))));
5577 }
5578
5579 function info(instanceId, api) {
5580 return memo(instanceId, () => api.queryMulti([api.query.society.bids, api.query.society.defender, api.query.society.founder, api.query.society.head, api.query.society.maxMembers, api.query.society.pot]).pipe(map(([bids, defender, founder, head, maxMembers, pot]) => ({
5581 bids,
5582 defender: defender.unwrapOr(undefined),
5583 founder: founder.unwrapOr(undefined),
5584 hasDefender: defender.isSome && head.isSome && !head.eq(defender) || false,
5585 head: head.unwrapOr(undefined),
5586 maxMembers,
5587 pot
5588 }))));
5589 }
5590
5591 function member(instanceId, api) {
5592 return memo(instanceId, accountId => api.derive.society._members([accountId]).pipe(map(([result]) => result)));
5593 }
5594
5595 function _members(instanceId, api) {
5596 return memo(instanceId, accountIds => combineLatest([of(accountIds), api.query.society.payouts.multi(accountIds), api.query.society.strikes.multi(accountIds), api.query.society.defenderVotes.multi(accountIds), api.query.society.suspendedMembers.multi(accountIds), api.query.society.vouching.multi(accountIds)]).pipe(map(([accountIds, payouts, strikes, defenderVotes, suspended, vouching]) => accountIds.map((accountId, index) => ({
5597 accountId,
5598 isDefenderVoter: defenderVotes[index].isSome,
5599 isSuspended: suspended[index].isTrue,
5600 payouts: payouts[index],
5601 strikes: strikes[index],
5602 vote: defenderVotes[index].unwrapOr(undefined),
5603 vouching: vouching[index].unwrapOr(undefined)
5604 })))));
5605 }
5606 function members$1(instanceId, api) {
5607 return memo(instanceId, () => api.query.society.members().pipe(switchMap(members => api.derive.society._members(members))));
5608 }
5609
5610 const society = /*#__PURE__*/Object.freeze({
5611 __proto__: null,
5612 candidates: candidates,
5613 info: info,
5614 member: member,
5615 _members: _members,
5616 members: members$1
5617 });
5618
5619 const QUERY_OPTS = {
5620 withDestination: true,
5621 withLedger: true,
5622 withNominations: true,
5623 withPrefs: true
5624 };
5625 function groupByEra(list) {
5626 return list.reduce((map, {
5627 era,
5628 value
5629 }) => {
5630 const key = era.toString();
5631 map[key] = (map[key] || util.BN_ZERO).add(value.unwrap());
5632 return map;
5633 }, {});
5634 }
5635 function calculateUnlocking(api, stakingLedger, sessionInfo) {
5636 const results = Object.entries(groupByEra(((stakingLedger === null || stakingLedger === void 0 ? void 0 : stakingLedger.unlocking) || []).filter(({
5637 era
5638 }) => era.unwrap().gt(sessionInfo.activeEra)))).map(([eraString, value]) => ({
5639 remainingEras: new util.BN(eraString).isub(sessionInfo.activeEra),
5640 value: api.registry.createType('Balance', value)
5641 }));
5642 return results.length ? results : undefined;
5643 }
5644 function redeemableSum(api, stakingLedger, sessionInfo) {
5645 return api.registry.createType('Balance', ((stakingLedger === null || stakingLedger === void 0 ? void 0 : stakingLedger.unlocking) || []).reduce((total, {
5646 era,
5647 value
5648 }) => {
5649 return sessionInfo.activeEra.gte(era.unwrap()) ? total.iadd(value.unwrap()) : total;
5650 }, new util.BN(0)));
5651 }
5652 function parseResult$1(api, sessionInfo, keys, query) {
5653 return { ...keys,
5654 ...query,
5655 redeemable: redeemableSum(api, query.stakingLedger, sessionInfo),
5656 unlocking: calculateUnlocking(api, query.stakingLedger, sessionInfo)
5657 };
5658 }
5659 function accounts(instanceId, api) {
5660 return memo(instanceId, accountIds => api.derive.session.info().pipe(switchMap(sessionInfo => combineLatest([api.derive.staking.keysMulti(accountIds), api.derive.staking.queryMulti(accountIds, QUERY_OPTS)]).pipe(map(([keys, queries]) => queries.map((q, index) => parseResult$1(api, sessionInfo, keys[index], q)))))));
5661 }
5662 const account = firstMemo((api, accountId) => api.derive.staking.accounts([accountId]));
5663
5664 function currentPoints(instanceId, api) {
5665 return memo(instanceId, () => api.derive.session.indexes().pipe(switchMap(({
5666 activeEra
5667 }) => api.query.staking.erasRewardPoints(activeEra))));
5668 }
5669
5670 function getEraCache(CACHE_KEY, era, withActive) {
5671 const cacheKey = `${CACHE_KEY}-${era.toString()}`;
5672 return [cacheKey, withActive ? undefined : deriveCache.get(cacheKey)];
5673 }
5674 function getEraMultiCache(CACHE_KEY, eras, withActive) {
5675 const cached = withActive ? [] : eras.map(e => deriveCache.get(`${CACHE_KEY}-${e.toString()}`)).filter(v => !!v);
5676 return cached;
5677 }
5678 function setEraCache(cacheKey, withActive, value) {
5679 !withActive && deriveCache.set(cacheKey, value);
5680 return value;
5681 }
5682 function setEraMultiCache(CACHE_KEY, withActive, values) {
5683 !withActive && values.forEach(v => deriveCache.set(`${CACHE_KEY}-${v.era.toString()}`, v));
5684 return values;
5685 }
5686 function filterCachedEras(eras, cached, query) {
5687 return eras.map(e => cached.find(({
5688 era
5689 }) => e.eq(era)) || query.find(({
5690 era
5691 }) => e.eq(era)));
5692 }
5693
5694 const ERA_CHUNK_SIZE = 14;
5695 function chunkEras(eras, fn) {
5696 const chunked = util.arrayChunk(eras, ERA_CHUNK_SIZE);
5697 let index = 0;
5698 const subject = new BehaviorSubject(chunked[index]);
5699 return subject.pipe(switchMap(fn), tap(() => {
5700 util.nextTick(() => {
5701 index++;
5702 index === chunked.length ? subject.complete() : subject.next(chunked[index]);
5703 });
5704 }), toArray(), map(util.arrayFlatten));
5705 }
5706 function filterEras(eras, list) {
5707 return eras.filter(e => !list.some(({
5708 era
5709 }) => e.eq(era)));
5710 }
5711 function erasHistoricApply(fn) {
5712 return (instanceId, api) =>
5713 memo(instanceId, (withActive = false) => api.derive.staking.erasHistoric(withActive).pipe(switchMap(e => api.derive.staking[fn](e, withActive))));
5714 }
5715 function erasHistoricApplyAccount(fn) {
5716 return (instanceId, api) =>
5717 memo(instanceId, (accountId, withActive = false) => api.derive.staking.erasHistoric(withActive).pipe(switchMap(e => api.derive.staking[fn](accountId, e, withActive))));
5718 }
5719 function singleEra(fn) {
5720 return (instanceId, api) =>
5721 memo(instanceId, era => api.derive.staking[fn](era, true));
5722 }
5723 function combineEras(fn) {
5724 return (instanceId, api) =>
5725 memo(instanceId, (eras, withActive) => !eras.length ? of([]) : chunkEras(eras, eras => combineLatest(eras.map(e => api.derive.staking[fn](e, withActive)))));
5726 }
5727
5728 const CACHE_KEY$4 = 'eraExposure';
5729 function mapStakers(era, stakers) {
5730 const nominators = {};
5731 const validators = {};
5732 stakers.forEach(([key, exposure]) => {
5733 const validatorId = key.args[1].toString();
5734 validators[validatorId] = exposure;
5735 exposure.others.forEach(({
5736 who
5737 }, validatorIndex) => {
5738 const nominatorId = who.toString();
5739 nominators[nominatorId] = nominators[nominatorId] || [];
5740 nominators[nominatorId].push({
5741 validatorId,
5742 validatorIndex
5743 });
5744 });
5745 });
5746 return {
5747 era,
5748 nominators,
5749 validators
5750 };
5751 }
5752 function _eraExposure(instanceId, api) {
5753 return memo(instanceId, (era, withActive = false) => {
5754 const [cacheKey, cached] = getEraCache(CACHE_KEY$4, era, withActive);
5755 return cached ? of(cached) : api.query.staking.erasStakersClipped.entries(era).pipe(map(r => setEraCache(cacheKey, withActive, mapStakers(era, r))));
5756 });
5757 }
5758 const eraExposure = singleEra('_eraExposure');
5759 const _erasExposure = combineEras('_eraExposure');
5760 const erasExposure = erasHistoricApply('_erasExposure');
5761
5762 function erasHistoric(instanceId, api) {
5763 return memo(instanceId, withActive => api.queryMulti([api.query.staking.activeEra, api.query.staking.historyDepth]).pipe(map(([activeEraOpt, historyDepth]) => {
5764 const result = [];
5765 const max = historyDepth.toNumber();
5766 const activeEra = activeEraOpt.unwrapOrDefault().index;
5767 let lastEra = activeEra;
5768 while (lastEra.gte(util.BN_ZERO) && result.length < max) {
5769 if (lastEra !== activeEra || withActive === true) {
5770 result.push(api.registry.createType('EraIndex', lastEra));
5771 }
5772 lastEra = lastEra.sub(util.BN_ONE);
5773 }
5774 return result.reverse();
5775 })));
5776 }
5777
5778 const CACHE_KEY$3 = 'eraPoints';
5779 function mapValidators({
5780 individual
5781 }) {
5782 return [...individual.entries()].filter(([, points]) => points.gt(util.BN_ZERO)).reduce((result, [validatorId, points]) => {
5783 result[validatorId.toString()] = points;
5784 return result;
5785 }, {});
5786 }
5787 function mapPoints(eras, points) {
5788 return eras.map((era, index) => ({
5789 era,
5790 eraPoints: points[index].total,
5791 validators: mapValidators(points[index])
5792 }));
5793 }
5794 function _erasPoints(instanceId, api) {
5795 return memo(instanceId, (eras, withActive) => {
5796 if (!eras.length) {
5797 return of([]);
5798 }
5799 const cached = getEraMultiCache(CACHE_KEY$3, eras, withActive);
5800 const remaining = filterEras(eras, cached);
5801 return !remaining.length ? of(cached) : api.query.staking.erasRewardPoints.multi(remaining).pipe(map(p => filterCachedEras(eras, cached, setEraMultiCache(CACHE_KEY$3, withActive, mapPoints(remaining, p)))));
5802 });
5803 }
5804 const erasPoints = erasHistoricApply('_erasPoints');
5805
5806 const CACHE_KEY$2 = 'eraPrefs';
5807 function mapPrefs(era, all) {
5808 const validators = {};
5809 all.forEach(([key, prefs]) => {
5810 validators[key.args[1].toString()] = prefs;
5811 });
5812 return {
5813 era,
5814 validators
5815 };
5816 }
5817 function _eraPrefs(instanceId, api) {
5818 return memo(instanceId, (era, withActive) => {
5819 const [cacheKey, cached] = getEraCache(CACHE_KEY$2, era, withActive);
5820 return cached ? of(cached) : api.query.staking.erasValidatorPrefs.entries(era).pipe(map(r => setEraCache(cacheKey, withActive, mapPrefs(era, r))));
5821 });
5822 }
5823 const eraPrefs = singleEra('_eraPrefs');
5824 const _erasPrefs = combineEras('_eraPrefs');
5825 const erasPrefs = erasHistoricApply('_erasPrefs');
5826
5827 const CACHE_KEY$1 = 'eraRewards';
5828 function mapRewards(eras, optRewards) {
5829 return eras.map((era, index) => ({
5830 era,
5831 eraReward: optRewards[index].unwrapOrDefault()
5832 }));
5833 }
5834 function _erasRewards(instanceId, api) {
5835 return memo(instanceId, (eras, withActive) => {
5836 if (!eras.length) {
5837 return of([]);
5838 }
5839 const cached = getEraMultiCache(CACHE_KEY$1, eras, withActive);
5840 const remaining = filterEras(eras, cached);
5841 if (!remaining.length) {
5842 return of(cached);
5843 }
5844 return api.query.staking.erasValidatorReward.multi(remaining).pipe(map(r => filterCachedEras(eras, cached, setEraMultiCache(CACHE_KEY$1, withActive, mapRewards(remaining, r)))));
5845 });
5846 }
5847 const erasRewards = erasHistoricApply('_erasRewards');
5848
5849 const CACHE_KEY = 'eraSlashes';
5850 function mapSlashes(era, noms, vals) {
5851 const nominators = {};
5852 const validators = {};
5853 noms.forEach(([key, optBalance]) => {
5854 nominators[key.args[1].toString()] = optBalance.unwrap();
5855 });
5856 vals.forEach(([key, optRes]) => {
5857 validators[key.args[1].toString()] = optRes.unwrapOrDefault()[1];
5858 });
5859 return {
5860 era,
5861 nominators,
5862 validators
5863 };
5864 }
5865 function _eraSlashes(instanceId, api) {
5866 return memo(instanceId, (era, withActive) => {
5867 const [cacheKey, cached] = getEraCache(CACHE_KEY, era, withActive);
5868 return cached ? of(cached) : combineLatest([api.query.staking.nominatorSlashInEra.entries(era), api.query.staking.validatorSlashInEra.entries(era)]).pipe(map(([n, v]) => setEraCache(cacheKey, withActive, mapSlashes(era, n, v))));
5869 });
5870 }
5871 const eraSlashes = singleEra('_eraSlashes');
5872 const _erasSlashes = combineEras('_eraSlashes');
5873 const erasSlashes = erasHistoricApply('_erasSlashes');
5874
5875 const DEFAULT_FLAGS$1 = {
5876 withController: true,
5877 withExposure: true,
5878 withPrefs: true
5879 };
5880 function combineAccounts(nextElected, validators) {
5881 return util.arrayFlatten([nextElected, validators.filter(v => !nextElected.find(n => n.eq(v)))]);
5882 }
5883 function electedInfo(instanceId, api) {
5884 return memo(instanceId, (flags = DEFAULT_FLAGS$1) => api.derive.staking.validators().pipe(switchMap(({
5885 nextElected,
5886 validators
5887 }) => api.derive.staking.queryMulti(combineAccounts(nextElected, validators), flags).pipe(map(info => ({
5888 info,
5889 nextElected,
5890 validators
5891 }))))));
5892 }
5893
5894 function extractsIds(stashId, queuedKeys, nextKeys) {
5895 const sessionIds = (queuedKeys.find(([currentId]) => currentId.eq(stashId)) || [undefined, []])[1];
5896 const nextSessionIds = nextKeys.unwrapOr([]);
5897 return {
5898 nextSessionIds: Array.isArray(nextSessionIds) ? nextSessionIds : [...nextSessionIds.values()],
5899 sessionIds: Array.isArray(sessionIds) ? sessionIds : [...sessionIds.values()]
5900 };
5901 }
5902 const keys = firstMemo((api, stashId) => api.derive.staking.keysMulti([stashId]));
5903 function keysMulti(instanceId, api) {
5904 return memo(instanceId, stashIds => stashIds.length ? api.query.session.queuedKeys().pipe(switchMap(queuedKeys => {
5905 var _api$consts$session;
5906 return combineLatest([of(queuedKeys), (_api$consts$session = api.consts.session) !== null && _api$consts$session !== void 0 && _api$consts$session.dedupKeyPrefix ? api.query.session.nextKeys.multi(stashIds.map(s => [api.consts.session.dedupKeyPrefix, s])) : combineLatest(stashIds.map(s => api.query.session.nextKeys(s)))]);
5907 }), map(([queuedKeys, nextKeys]) => stashIds.map((stashId, index) => extractsIds(stashId, queuedKeys, nextKeys[index])))) : of([]));
5908 }
5909
5910 function overview(instanceId, api) {
5911 return memo(instanceId, () => combineLatest([api.derive.session.indexes(), api.derive.staking.validators()]).pipe(map(([indexes, {
5912 nextElected,
5913 validators
5914 }]) => ({ ...indexes,
5915 nextElected,
5916 validators
5917 }))));
5918 }
5919
5920 function _ownExposures(instanceId, api) {
5921 return memo(instanceId, (accountId, eras, _withActive) => eras.length ? combineLatest([combineLatest(eras.map(e => api.query.staking.erasStakersClipped(e, accountId))), combineLatest(eras.map(e => api.query.staking.erasStakers(e, accountId)))]).pipe(map(([clp, exp]) => eras.map((era, index) => ({
5922 clipped: clp[index],
5923 era,
5924 exposure: exp[index]
5925 })))) : of([]));
5926 }
5927 const ownExposure = firstMemo((api, accountId, era) => api.derive.staking._ownExposures(accountId, [era], true));
5928 const ownExposures = erasHistoricApplyAccount('_ownExposures');
5929
5930 function _ownSlashes(instanceId, api) {
5931 return memo(instanceId, (accountId, eras, _withActive) => eras.length ? combineLatest([combineLatest(eras.map(e => api.query.staking.validatorSlashInEra(e, accountId))), combineLatest(eras.map(e => api.query.staking.nominatorSlashInEra(e, accountId)))]).pipe(map(([vals, noms]) => eras.map((era, index) => ({
5932 era,
5933 total: vals[index].isSome ? vals[index].unwrap()[1] : noms[index].unwrapOrDefault()
5934 })))) : of([]));
5935 }
5936 const ownSlash = firstMemo((api, accountId, era) => api.derive.staking._ownSlashes(accountId, [era], true));
5937 const ownSlashes = erasHistoricApplyAccount('_ownSlashes');
5938
5939 function parseDetails(stashId, controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure, stakingLedgerOpt) {
5940 return {
5941 accountId: stashId,
5942 controllerId: controllerIdOpt && controllerIdOpt.unwrapOr(null),
5943 exposure,
5944 nominators: nominatorsOpt.isSome ? nominatorsOpt.unwrap().targets : [],
5945 rewardDestination,
5946 stakingLedger: stakingLedgerOpt.unwrapOrDefault(),
5947 stashId,
5948 validatorPrefs
5949 };
5950 }
5951 function getLedgers(api, optIds, {
5952 withLedger = false
5953 }) {
5954 const ids = optIds.filter(o => withLedger && !!o && o.isSome).map(o => o.unwrap());
5955 const emptyLed = api.registry.createType('Option<StakingLedger>');
5956 return (ids.length ? combineLatest(ids.map(s => api.query.staking.ledger(s))) : of([])).pipe(map(optLedgers => {
5957 let offset = -1;
5958 return optIds.map(o => o && o.isSome ? optLedgers[++offset] || emptyLed : emptyLed);
5959 }));
5960 }
5961 function getStashInfo(api, stashIds, activeEra, {
5962 withController,
5963 withDestination,
5964 withExposure,
5965 withLedger,
5966 withNominations,
5967 withPrefs
5968 }) {
5969 const emptyNoms = api.registry.createType('Option<Nominations>');
5970 const emptyRewa = api.registry.createType('RewardDestination');
5971 const emptyExpo = api.registry.createType('Exposure');
5972 const emptyPrefs = api.registry.createType('ValidatorPrefs');
5973 return combineLatest([withController || withLedger ? combineLatest(stashIds.map(s => api.query.staking.bonded(s))) : of(stashIds.map(() => null)), withNominations ? combineLatest(stashIds.map(s => api.query.staking.nominators(s))) : of(stashIds.map(() => emptyNoms)), withDestination ? combineLatest(stashIds.map(s => api.query.staking.payee(s))) : of(stashIds.map(() => emptyRewa)), withPrefs ? combineLatest(stashIds.map(s => api.query.staking.validators(s))) : of(stashIds.map(() => emptyPrefs)), withExposure ? combineLatest(stashIds.map(s => api.query.staking.erasStakers(activeEra, s))) : of(stashIds.map(() => emptyExpo))]);
5974 }
5975 function getBatch(api, activeEra, stashIds, flags) {
5976 return getStashInfo(api, stashIds, activeEra, flags).pipe(switchMap(([controllerIdOpt, nominatorsOpt, rewardDestination, validatorPrefs, exposure]) => getLedgers(api, controllerIdOpt, flags).pipe(map(stakingLedgerOpts => stashIds.map((stashId, index) => parseDetails(stashId, controllerIdOpt[index], nominatorsOpt[index], rewardDestination[index], validatorPrefs[index], exposure[index], stakingLedgerOpts[index]))))));
5977 }
5978 const query = firstMemo((api, accountId, flags) => api.derive.staking.queryMulti([accountId], flags));
5979 function queryMulti(instanceId, api) {
5980 return memo(instanceId, (accountIds, flags) => accountIds.length ? api.derive.session.indexes().pipe(switchMap(({
5981 activeEra
5982 }) => {
5983 const stashIds = accountIds.map(accountId => api.registry.createType('AccountId', accountId));
5984 return getBatch(api, activeEra, stashIds, flags);
5985 })) : of([]));
5986 }
5987
5988 function _stakerExposures(instanceId, api) {
5989 return memo(instanceId, (accountIds, eras, withActive = false) => {
5990 const stakerIds = accountIds.map(a => api.registry.createType('AccountId', a).toString());
5991 return api.derive.staking._erasExposure(eras, withActive).pipe(map(exposures => stakerIds.map(stakerId => exposures.map(({
5992 era,
5993 nominators: allNominators,
5994 validators: allValidators
5995 }) => {
5996 const isValidator = !!allValidators[stakerId];
5997 const validators = {};
5998 const nominating = allNominators[stakerId] || [];
5999 if (isValidator) {
6000 validators[stakerId] = allValidators[stakerId];
6001 } else if (nominating) {
6002 nominating.forEach(({
6003 validatorId
6004 }) => {
6005 validators[validatorId] = allValidators[validatorId];
6006 });
6007 }
6008 return {
6009 era,
6010 isEmpty: !Object.keys(validators).length,
6011 isValidator,
6012 nominating,
6013 validators
6014 };
6015 }))));
6016 });
6017 }
6018 function stakerExposures(instanceId, api) {
6019 return memo(instanceId, (accountIds, withActive = false) => api.derive.staking.erasHistoric(withActive).pipe(switchMap(eras => api.derive.staking._stakerExposures(accountIds, eras, withActive))));
6020 }
6021 const stakerExposure = firstMemo((api, accountId, withActive) => api.derive.staking.stakerExposures([accountId], withActive));
6022
6023 function _stakerPoints(instanceId, api) {
6024 return memo(instanceId, (accountId, eras, withActive) => {
6025 const stakerId = api.registry.createType('AccountId', accountId).toString();
6026 return api.derive.staking._erasPoints(eras, withActive).pipe(map(points => points.map(({
6027 era,
6028 eraPoints,
6029 validators
6030 }) => ({
6031 era,
6032 eraPoints,
6033 points: validators[stakerId] || api.registry.createType('RewardPoint')
6034 }))));
6035 });
6036 }
6037 const stakerPoints = erasHistoricApplyAccount('_stakerPoints');
6038
6039 function _stakerPrefs(instanceId, api) {
6040 return memo(instanceId, (accountId, eras, _withActive) => api.query.staking.erasValidatorPrefs.multi(eras.map(e => [e, accountId])).pipe(map(all => all.map((validatorPrefs, index) => ({
6041 era: eras[index],
6042 validatorPrefs
6043 })))));
6044 }
6045 const stakerPrefs = erasHistoricApplyAccount('_stakerPrefs');
6046
6047 function parseRewards(api, stashId, [erasPoints, erasPrefs, erasRewards], exposures) {
6048 return exposures.map(({
6049 era,
6050 isEmpty,
6051 isValidator,
6052 nominating,
6053 validators: eraValidators
6054 }) => {
6055 const {
6056 eraPoints,
6057 validators: allValPoints
6058 } = erasPoints.find(p => p.era.eq(era)) || {
6059 eraPoints: util.BN_ZERO,
6060 validators: {}
6061 };
6062 const {
6063 eraReward
6064 } = erasRewards.find(r => r.era.eq(era)) || {
6065 eraReward: api.registry.createType('Balance')
6066 };
6067 const {
6068 validators: allValPrefs
6069 } = erasPrefs.find(p => p.era.eq(era)) || {
6070 validators: {}
6071 };
6072 const validators = {};
6073 const stakerId = stashId.toString();
6074 Object.entries(eraValidators).forEach(([validatorId, exposure]) => {
6075 var _allValPrefs$validato, _exposure$total;
6076 const valPoints = allValPoints[validatorId] || util.BN_ZERO;
6077 const valComm = ((_allValPrefs$validato = allValPrefs[validatorId]) === null || _allValPrefs$validato === void 0 ? void 0 : _allValPrefs$validato.commission.unwrap()) || util.BN_ZERO;
6078 const expTotal = ((_exposure$total = exposure.total) === null || _exposure$total === void 0 ? void 0 : _exposure$total.unwrap()) || util.BN_ZERO;
6079 let avail = util.BN_ZERO;
6080 let value;
6081 if (!(expTotal.isZero() || valPoints.isZero() || eraPoints.isZero())) {
6082 avail = eraReward.mul(valPoints).div(eraPoints);
6083 const valCut = valComm.mul(avail).div(util.BN_BILLION);
6084 let staked;
6085 if (validatorId === stakerId) {
6086 staked = exposure.own.unwrap();
6087 } else {
6088 const stakerExp = exposure.others.find(({
6089 who
6090 }) => who.eq(stakerId));
6091 staked = stakerExp ? stakerExp.value.unwrap() : util.BN_ZERO;
6092 }
6093 value = avail.sub(valCut).imul(staked).div(expTotal).iadd(validatorId === stakerId ? valCut : util.BN_ZERO);
6094 }
6095 validators[validatorId] = {
6096 total: api.registry.createType('Balance', avail),
6097 value: api.registry.createType('Balance', value)
6098 };
6099 });
6100 return {
6101 era,
6102 eraReward,
6103 isEmpty,
6104 isValidator,
6105 nominating,
6106 validators
6107 };
6108 });
6109 }
6110 function allUniqValidators(rewards) {
6111 return rewards.reduce(([all, perStash], rewards) => {
6112 const uniq = [];
6113 perStash.push(uniq);
6114 rewards.forEach(({
6115 validators
6116 }) => Object.keys(validators).forEach(validatorId => {
6117 if (!uniq.includes(validatorId)) {
6118 uniq.push(validatorId);
6119 if (!all.includes(validatorId)) {
6120 all.push(validatorId);
6121 }
6122 }
6123 }));
6124 return [all, perStash];
6125 }, [[], []]);
6126 }
6127 function removeClaimed(validators, queryValidators, reward) {
6128 const rm = [];
6129 Object.keys(reward.validators).forEach(validatorId => {
6130 const index = validators.indexOf(validatorId);
6131 if (index !== -1) {
6132 const valLedger = queryValidators[index].stakingLedger;
6133 if (valLedger !== null && valLedger !== void 0 && valLedger.claimedRewards.some(e => reward.era.eq(e))) {
6134 rm.push(validatorId);
6135 }
6136 }
6137 });
6138 rm.forEach(validatorId => {
6139 delete reward.validators[validatorId];
6140 });
6141 }
6142 function filterRewards(eras, valInfo, {
6143 rewards,
6144 stakingLedger
6145 }) {
6146 const filter = eras.filter(e => !stakingLedger.claimedRewards.some(s => s.eq(e)));
6147 const validators = valInfo.map(([v]) => v);
6148 const queryValidators = valInfo.map(([, q]) => q);
6149 return rewards.filter(({
6150 isEmpty
6151 }) => !isEmpty).filter(reward => {
6152 if (!filter.some(e => reward.era.eq(e))) {
6153 return false;
6154 }
6155 removeClaimed(validators, queryValidators, reward);
6156 return true;
6157 }).filter(({
6158 validators
6159 }) => Object.keys(validators).length !== 0).map(reward => ({ ...reward,
6160 nominators: reward.nominating.filter(n => reward.validators[n.validatorId])
6161 }));
6162 }
6163 function _stakerRewardsEras(instanceId, api) {
6164 return memo(instanceId, (eras, withActive = false) => combineLatest([api.derive.staking._erasPoints(eras, withActive), api.derive.staking._erasPrefs(eras, withActive), api.derive.staking._erasRewards(eras, withActive)]));
6165 }
6166 function _stakerRewards(instanceId, api) {
6167 return memo(instanceId, (accountIds, eras, withActive = false) => combineLatest([api.derive.staking.queryMulti(accountIds, {
6168 withLedger: true
6169 }), api.derive.staking._stakerExposures(accountIds, eras, withActive), api.derive.staking._stakerRewardsEras(eras, withActive)]).pipe(switchMap(([queries, exposures, erasResult]) => {
6170 const allRewards = queries.map(({
6171 stakingLedger,
6172 stashId
6173 }, index) => !stashId || !stakingLedger ? [] : parseRewards(api, stashId, erasResult, exposures[index]));
6174 if (withActive) {
6175 return of(allRewards);
6176 }
6177 const [allValidators, stashValidators] = allUniqValidators(allRewards);
6178 return api.derive.staking.queryMulti(allValidators, {
6179 withLedger: true
6180 }).pipe(map(queriedVals => queries.map(({
6181 stakingLedger
6182 }, index) => filterRewards(eras, stashValidators[index].map(validatorId => [validatorId, queriedVals.find(q => q.accountId.eq(validatorId))]), {
6183 rewards: allRewards[index],
6184 stakingLedger
6185 }))));
6186 })));
6187 }
6188 const stakerRewards = firstMemo((api, accountId, withActive) => api.derive.staking.erasHistoric(withActive).pipe(switchMap(eras => api.derive.staking._stakerRewards([accountId], eras, withActive))));
6189 function stakerRewardsMultiEras(instanceId, api) {
6190 return memo(instanceId, (accountIds, eras) => accountIds.length && eras.length ? api.derive.staking._stakerRewards(accountIds, eras, false) : of([]));
6191 }
6192 function stakerRewardsMulti(instanceId, api) {
6193 return memo(instanceId, (accountIds, withActive = false) => api.derive.staking.erasHistoric(withActive).pipe(switchMap(eras => api.derive.staking.stakerRewardsMultiEras(accountIds, eras))));
6194 }
6195
6196 function _stakerSlashes(instanceId, api) {
6197 return memo(instanceId, (accountId, eras, withActive) => {
6198 const stakerId = api.registry.createType('AccountId', accountId).toString();
6199 return api.derive.staking._erasSlashes(eras, withActive).pipe(map(slashes => slashes.map(({
6200 era,
6201 nominators,
6202 validators
6203 }) => ({
6204 era,
6205 total: nominators[stakerId] || validators[stakerId] || api.registry.createType('Balance')
6206 }))));
6207 });
6208 }
6209 const stakerSlashes = erasHistoricApplyAccount('_stakerSlashes');
6210
6211 function onBondedEvent(api) {
6212 let current = Date.now();
6213 return api.query.system.events().pipe(map(events => {
6214 current = events.filter(({
6215 event,
6216 phase
6217 }) => {
6218 try {
6219 return phase.isApplyExtrinsic && event.section === 'staking' && event.method === 'Bonded';
6220 } catch {
6221 return false;
6222 }
6223 }) ? Date.now() : current;
6224 return current;
6225 }), startWith(current), drr({
6226 skipTimeout: true
6227 }));
6228 }
6229 function stashes(instanceId, api) {
6230 return memo(instanceId, () => onBondedEvent(api).pipe(switchMap(() => api.query.staking.validators.keys()), map(keys => keys.map(({
6231 args: [v]
6232 }) => v).filter(a => a))));
6233 }
6234
6235 function nextElected(instanceId, api) {
6236 return memo(instanceId, () => api.query.staking.erasStakers ? api.derive.session.indexes().pipe(
6237 switchMap(({
6238 currentEra
6239 }) => api.query.staking.erasStakers.keys(currentEra)), map(keys => keys.map(({
6240 args: [, accountId]
6241 }) => accountId))) : api.query.staking.currentElected());
6242 }
6243 function validators(instanceId, api) {
6244 return memo(instanceId, () =>
6245 combineLatest([api.query.session ? api.query.session.validators() : of([]), api.query.staking ? api.derive.staking.nextElected() : of([])]).pipe(map(([validators, nextElected]) => ({
6246 nextElected: nextElected.length ? nextElected : validators,
6247 validators
6248 }))));
6249 }
6250
6251 const DEFAULT_FLAGS = {
6252 withController: true,
6253 withPrefs: true
6254 };
6255 function waitingInfo(instanceId, api) {
6256 return memo(instanceId, (flags = DEFAULT_FLAGS) => combineLatest([api.derive.staking.validators(), api.derive.staking.stashes()]).pipe(switchMap(([{
6257 nextElected
6258 }, stashes]) => {
6259 const elected = nextElected.map(a => a.toString());
6260 const waiting = stashes.filter(v => !elected.includes(v.toString()));
6261 return api.derive.staking.queryMulti(waiting, flags).pipe(map(info => ({
6262 info,
6263 waiting
6264 })));
6265 })));
6266 }
6267
6268 const staking = /*#__PURE__*/Object.freeze({
6269 __proto__: null,
6270 accounts: accounts,
6271 account: account,
6272 currentPoints: currentPoints,
6273 _eraExposure: _eraExposure,
6274 eraExposure: eraExposure,
6275 _erasExposure: _erasExposure,
6276 erasExposure: erasExposure,
6277 erasHistoric: erasHistoric,
6278 _erasPoints: _erasPoints,
6279 erasPoints: erasPoints,
6280 _eraPrefs: _eraPrefs,
6281 eraPrefs: eraPrefs,
6282 _erasPrefs: _erasPrefs,
6283 erasPrefs: erasPrefs,
6284 _erasRewards: _erasRewards,
6285 erasRewards: erasRewards,
6286 _eraSlashes: _eraSlashes,
6287 eraSlashes: eraSlashes,
6288 _erasSlashes: _erasSlashes,
6289 erasSlashes: erasSlashes,
6290 electedInfo: electedInfo,
6291 keys: keys,
6292 keysMulti: keysMulti,
6293 overview: overview,
6294 _ownExposures: _ownExposures,
6295 ownExposure: ownExposure,
6296 ownExposures: ownExposures,
6297 _ownSlashes: _ownSlashes,
6298 ownSlash: ownSlash,
6299 ownSlashes: ownSlashes,
6300 query: query,
6301 queryMulti: queryMulti,
6302 _stakerExposures: _stakerExposures,
6303 stakerExposures: stakerExposures,
6304 stakerExposure: stakerExposure,
6305 _stakerPoints: _stakerPoints,
6306 stakerPoints: stakerPoints,
6307 _stakerPrefs: _stakerPrefs,
6308 stakerPrefs: stakerPrefs,
6309 _stakerRewardsEras: _stakerRewardsEras,
6310 _stakerRewards: _stakerRewards,
6311 stakerRewards: stakerRewards,
6312 stakerRewardsMultiEras: stakerRewardsMultiEras,
6313 stakerRewardsMulti: stakerRewardsMulti,
6314 _stakerSlashes: _stakerSlashes,
6315 stakerSlashes: stakerSlashes,
6316 stashes: stashes,
6317 nextElected: nextElected,
6318 validators: validators,
6319 waitingInfo: waitingInfo
6320 });
6321
6322 const members = members$4('technicalCommittee');
6323 const hasProposals = hasProposals$3('technicalCommittee');
6324 const proposal = proposal$3('technicalCommittee');
6325 const proposalCount = proposalCount$3('technicalCommittee');
6326 const proposalHashes = proposalHashes$3('technicalCommittee');
6327 const proposals$1 = proposals$5('technicalCommittee');
6328 const prime = prime$3('technicalCommittee');
6329
6330 const technicalCommittee = /*#__PURE__*/Object.freeze({
6331 __proto__: null,
6332 members: members,
6333 hasProposals: hasProposals,
6334 proposal: proposal,
6335 proposalCount: proposalCount,
6336 proposalHashes: proposalHashes,
6337 proposals: proposals$1,
6338 prime: prime
6339 });
6340
6341 function parseResult(api, {
6342 allIds,
6343 allProposals,
6344 approvalIds,
6345 councilProposals,
6346 proposalCount
6347 }) {
6348 const approvals = [];
6349 const proposals = [];
6350 const councilTreasury = councilProposals.filter(({
6351 proposal
6352 }) => proposal && (api.tx.treasury.approveProposal.is(proposal) || api.tx.treasury.rejectProposal.is(proposal)));
6353 allIds.forEach((id, index) => {
6354 if (allProposals[index].isSome) {
6355 const council = councilTreasury.filter(({
6356 proposal
6357 }) => proposal && id.eq(proposal.args[0])).sort((a, b) => a.proposal && b.proposal ? a.proposal.method.localeCompare(b.proposal.method) : a.proposal ? -1 : 1);
6358 const isApproval = approvalIds.some(approvalId => approvalId.eq(id));
6359 const derived = {
6360 council,
6361 id,
6362 proposal: allProposals[index].unwrap()
6363 };
6364 if (isApproval) {
6365 approvals.push(derived);
6366 } else {
6367 proposals.push(derived);
6368 }
6369 }
6370 });
6371 return {
6372 approvals,
6373 proposalCount,
6374 proposals
6375 };
6376 }
6377 function retrieveProposals(api, proposalCount, approvalIds) {
6378 const proposalIds = [];
6379 const count = proposalCount.toNumber();
6380 for (let index = 0; index < count; index++) {
6381 if (!approvalIds.some(id => id.eqn(index))) {
6382 proposalIds.push(api.registry.createType('ProposalIndex', index));
6383 }
6384 }
6385 const allIds = [...proposalIds, ...approvalIds];
6386 return combineLatest([api.query.treasury.proposals.multi(allIds), api.derive.council ? api.derive.council.proposals() : of([])]).pipe(map(([allProposals, councilProposals]) => parseResult(api, {
6387 allIds,
6388 allProposals,
6389 approvalIds,
6390 councilProposals,
6391 proposalCount
6392 })));
6393 }
6394 function proposals(instanceId, api) {
6395 return memo(instanceId, () => api.query.treasury ? combineLatest([api.query.treasury.proposalCount(), api.query.treasury.approvals()]).pipe(switchMap(([proposalCount, approvalIds]) => retrieveProposals(api, proposalCount, approvalIds))) : of({
6396 approvals: [],
6397 proposalCount: api.registry.createType('ProposalIndex'),
6398 proposals: []
6399 }));
6400 }
6401
6402 const treasury = /*#__PURE__*/Object.freeze({
6403 __proto__: null,
6404 proposals: proposals
6405 });
6406
6407 function events(instanceId, api) {
6408 return memo(instanceId, blockHash => combineLatest([api.rpc.chain.getBlock(blockHash), api.queryAt(blockHash).pipe(switchMap(queryAt => queryAt.system.events()))]).pipe(map(([block, events]) => ({
6409 block,
6410 events
6411 }))));
6412 }
6413
6414 const FALLBACK_MAX_HASH_COUNT = 250;
6415 const FALLBACK_PERIOD = new util.BN(6 * 1000);
6416 const MAX_FINALITY_LAG = new util.BN(5);
6417 const MORTAL_PERIOD = new util.BN(5 * 60 * 1000);
6418
6419 function latestNonce(api, address) {
6420 return api.derive.balances.account(address).pipe(map(({
6421 accountNonce
6422 }) => accountNonce));
6423 }
6424 function nextNonce(api, address) {
6425 var _api$rpc$system;
6426 return (_api$rpc$system = api.rpc.system) !== null && _api$rpc$system !== void 0 && _api$rpc$system.accountNextIndex ? api.rpc.system.accountNextIndex(address) : latestNonce(api, address);
6427 }
6428 function signingHeader(api) {
6429 return combineLatest([api.rpc.chain.getHeader().pipe(switchMap(header =>
6430 header.parentHash.isEmpty ? of(header)
6431 : api.rpc.chain.getHeader(header.parentHash))), api.rpc.chain.getFinalizedHead().pipe(switchMap(hash => api.rpc.chain.getHeader(hash)))]).pipe(map(([current, finalized]) =>
6432 current.number.unwrap().sub(finalized.number.unwrap()).gt(MAX_FINALITY_LAG) ? current : finalized));
6433 }
6434 function signingInfo(_instanceId, api) {
6435 return (address, nonce, era) => combineLatest([
6436 util.isUndefined(nonce) ? latestNonce(api, address) : nonce === -1 ? nextNonce(api, address) : of(api.registry.createType('Index', nonce)),
6437 util.isUndefined(era) || util.isNumber(era) && era > 0 ? signingHeader(api) : of(null)]).pipe(map(([nonce, header]) => {
6438 var _api$consts$system, _api$consts$system$bl, _api$consts$babe, _api$consts$timestamp;
6439 return {
6440 header,
6441 mortalLength: Math.min(((_api$consts$system = api.consts.system) === null || _api$consts$system === void 0 ? void 0 : (_api$consts$system$bl = _api$consts$system.blockHashCount) === null || _api$consts$system$bl === void 0 ? void 0 : _api$consts$system$bl.toNumber()) || FALLBACK_MAX_HASH_COUNT, MORTAL_PERIOD.div(((_api$consts$babe = api.consts.babe) === null || _api$consts$babe === void 0 ? void 0 : _api$consts$babe.expectedBlockTime) || ((_api$consts$timestamp = api.consts.timestamp) === null || _api$consts$timestamp === void 0 ? void 0 : _api$consts$timestamp.minimumPeriod.muln(2)) || FALLBACK_PERIOD).iadd(MAX_FINALITY_LAG).toNumber()),
6442 nonce
6443 };
6444 }));
6445 }
6446
6447 const tx = /*#__PURE__*/Object.freeze({
6448 __proto__: null,
6449 events: events,
6450 signingInfo: signingInfo
6451 });
6452
6453 const derive = {
6454 accounts: accounts$1,
6455 bagsList,
6456 balances,
6457 bounties,
6458 chain,
6459 contracts,
6460 council,
6461 crowdloan,
6462 democracy,
6463 elections,
6464 imOnline,
6465 membership,
6466 parachains,
6467 session,
6468 society,
6469 staking,
6470 technicalCommittee,
6471 treasury,
6472 tx
6473 };
6474
6475 const checks = {
6476 bagsList: {
6477 instances: ['voterList', 'bagsList'],
6478 methods: [],
6479 withDetect: true
6480 },
6481 contracts: {
6482 instances: ['contracts'],
6483 methods: []
6484 },
6485 council: {
6486 instances: ['council'],
6487 methods: [],
6488 withDetect: true
6489 },
6490 crowdloan: {
6491 instances: ['crowdloan'],
6492 methods: []
6493 },
6494 democracy: {
6495 instances: ['democracy'],
6496 methods: []
6497 },
6498 elections: {
6499 instances: ['phragmenElection', 'electionsPhragmen', 'elections', 'council'],
6500 methods: [],
6501 withDetect: true
6502 },
6503 imOnline: {
6504 instances: ['imOnline'],
6505 methods: []
6506 },
6507 membership: {
6508 instances: ['membership'],
6509 methods: []
6510 },
6511 parachains: {
6512 instances: ['parachains', 'registrar'],
6513 methods: []
6514 },
6515 session: {
6516 instances: ['session'],
6517 methods: []
6518 },
6519 society: {
6520 instances: ['society'],
6521 methods: []
6522 },
6523 staking: {
6524 instances: ['staking'],
6525 methods: ['erasRewardPoints']
6526 },
6527 technicalCommittee: {
6528 instances: ['technicalCommittee'],
6529 methods: [],
6530 withDetect: true
6531 },
6532 treasury: {
6533 instances: ['treasury'],
6534 methods: []
6535 }
6536 };
6537 function getModuleInstances(api, specName, moduleName) {
6538 return api.registry.getModuleInstances(specName, moduleName) || [];
6539 }
6540 function injectFunctions(instanceId, api, derives) {
6541 const result = {};
6542 const names = Object.keys(derives);
6543 const keys = Object.keys(api.query);
6544 const specName = api.runtimeVersion.specName.toString();
6545 const filterKeys = q => keys.includes(q);
6546 const filterInstances = q => getModuleInstances(api, specName, q).some(filterKeys);
6547 const filterMethods = all => m => all.some(q => keys.includes(q) && api.query[q][m]);
6548 const getKeys = s => Object.keys(derives[s]);
6549 const creator = (s, m) => derives[s][m](instanceId, api);
6550 const isIncluded = c => !checks[c] || checks[c].instances.some(filterKeys) && (!checks[c].methods.length || checks[c].methods.every(filterMethods(checks[c].instances))) || checks[c].withDetect && checks[c].instances.some(filterInstances);
6551 for (let i = 0; i < names.length; i++) {
6552 const name = names[i];
6553 isIncluded(name) && lazyDeriveSection(result, name, getKeys, creator);
6554 }
6555 return result;
6556 }
6557 function getAvailableDerives(instanceId, api, custom = {}) {
6558 return { ...injectFunctions(instanceId, api, derive),
6559 ...injectFunctions(instanceId, api, custom)
6560 };
6561 }
6562
6563 function decorateDeriveSections(decorateMethod, derives) {
6564 const getKeys = s => Object.keys(derives[s]);
6565 const creator = (s, m) => decorateMethod(derives[s][m]);
6566 const result = {};
6567 const names = Object.keys(derives);
6568 for (let i = 0; i < names.length; i++) {
6569 lazyDeriveSection(result, names[i], getKeys, creator);
6570 }
6571 return result;
6572 }
6573
6574 const l$3 = util.logger('api/util');
6575
6576 function filterEvents(txHash, {
6577 block: {
6578 extrinsics,
6579 header
6580 }
6581 }, allEvents, status) {
6582 for (const [txIndex, x] of extrinsics.entries()) {
6583 if (x.hash.eq(txHash)) {
6584 return {
6585 events: allEvents.filter(({
6586 phase
6587 }) => phase.isApplyExtrinsic && phase.asApplyExtrinsic.eqn(txIndex)),
6588 txIndex
6589 };
6590 }
6591 }
6592 if (status.isInBlock) {
6593 const allHashes = extrinsics.map(x => x.hash.toHex());
6594 l$3.warn(`block ${header.hash.toHex()}: Unable to find extrinsic ${txHash.toHex()} inside ${allHashes.join(', ')}`);
6595 }
6596 return {};
6597 }
6598
6599 function isKeyringPair(account) {
6600 return util.isFunction(account.sign);
6601 }
6602
6603 const recordIdentity = record => record;
6604 function filterAndApply(events, section, methods, onFound) {
6605 return events.filter(({
6606 event
6607 }) => section === event.section && methods.includes(event.method)).map(record => onFound(record));
6608 }
6609 function getDispatchError({
6610 event: {
6611 data: [dispatchError]
6612 }
6613 }) {
6614 return dispatchError;
6615 }
6616 function getDispatchInfo({
6617 event: {
6618 data,
6619 method
6620 }
6621 }) {
6622 return method === 'ExtrinsicSuccess' ? data[0] : data[1];
6623 }
6624 function extractError(events = []) {
6625 return filterAndApply(events, 'system', ['ExtrinsicFailed'], getDispatchError)[0];
6626 }
6627 function extractInfo(events = []) {
6628 return filterAndApply(events, 'system', ['ExtrinsicFailed', 'ExtrinsicSuccess'], getDispatchInfo)[0];
6629 }
6630 class SubmittableResult {
6631 constructor({
6632 dispatchError,
6633 dispatchInfo,
6634 events,
6635 internalError,
6636 status,
6637 txHash,
6638 txIndex
6639 }) {
6640 this.dispatchError = dispatchError || extractError(events);
6641 this.dispatchInfo = dispatchInfo || extractInfo(events);
6642 this.events = events || [];
6643 this.internalError = internalError;
6644 this.status = status;
6645 this.txHash = txHash;
6646 this.txIndex = txIndex;
6647 }
6648 get isCompleted() {
6649 return this.isError || this.status.isInBlock || this.status.isFinalized;
6650 }
6651 get isError() {
6652 return this.status.isDropped || this.status.isFinalityTimeout || this.status.isInvalid || this.status.isUsurped;
6653 }
6654 get isFinalized() {
6655 return this.status.isFinalized;
6656 }
6657 get isInBlock() {
6658 return this.status.isInBlock;
6659 }
6660 get isWarning() {
6661 return this.status.isRetracted;
6662 }
6663 filterRecords(section, method) {
6664 return filterAndApply(this.events, section, Array.isArray(method) ? method : [method], recordIdentity);
6665 }
6666 findRecord(section, method) {
6667 return this.filterRecords(section, method)[0];
6668 }
6669 toHuman(isExtended) {
6670 var _this$dispatchError, _this$dispatchInfo, _this$internalError;
6671 return {
6672 dispatchError: (_this$dispatchError = this.dispatchError) === null || _this$dispatchError === void 0 ? void 0 : _this$dispatchError.toHuman(),
6673 dispatchInfo: (_this$dispatchInfo = this.dispatchInfo) === null || _this$dispatchInfo === void 0 ? void 0 : _this$dispatchInfo.toHuman(),
6674 events: this.events.map(e => e.toHuman(isExtended)),
6675 internalError: (_this$internalError = this.internalError) === null || _this$internalError === void 0 ? void 0 : _this$internalError.message.toString(),
6676 status: this.status.toHuman(isExtended)
6677 };
6678 }
6679 }
6680
6681 const identity = input => input;
6682 function makeEraOptions(api, registry, partialOptions, {
6683 header,
6684 mortalLength,
6685 nonce
6686 }) {
6687 if (!header) {
6688 util.assert(partialOptions.era === 0 || !util.isUndefined(partialOptions.blockHash), 'Expected blockHash to be passed alongside non-immortal era options');
6689 if (util.isNumber(partialOptions.era)) {
6690 delete partialOptions.era;
6691 delete partialOptions.blockHash;
6692 }
6693 return makeSignOptions(api, partialOptions, {
6694 nonce
6695 });
6696 }
6697 return makeSignOptions(api, partialOptions, {
6698 blockHash: header.hash,
6699 era: registry.createTypeUnsafe('ExtrinsicEra', [{
6700 current: header.number,
6701 period: partialOptions.era || mortalLength
6702 }]),
6703 nonce
6704 });
6705 }
6706 function makeSignAndSendOptions(partialOptions, statusCb) {
6707 let options = {};
6708 if (util.isFunction(partialOptions)) {
6709 statusCb = partialOptions;
6710 } else {
6711 options = util.objectSpread({}, partialOptions);
6712 }
6713 return [options, statusCb];
6714 }
6715 function makeSignOptions(api, partialOptions, extras) {
6716 return util.objectSpread({
6717 blockHash: api.genesisHash,
6718 genesisHash: api.genesisHash
6719 }, partialOptions, extras, {
6720 runtimeVersion: api.runtimeVersion,
6721 signedExtensions: api.registry.signedExtensions,
6722 version: api.extrinsicType
6723 });
6724 }
6725 function optionsOrNonce(partialOptions = {}) {
6726 return util.isBn(partialOptions) || util.isNumber(partialOptions) ? {
6727 nonce: partialOptions
6728 } : partialOptions;
6729 }
6730 function createClass({
6731 api,
6732 apiType,
6733 blockHash,
6734 decorateMethod
6735 }) {
6736 const ExtrinsicBase = api.registry.createClass('Extrinsic');
6737 class Submittable extends ExtrinsicBase {
6738 #ignoreStatusCb;
6739 #transformResult = identity;
6740 constructor(registry, extrinsic) {
6741 super(registry, extrinsic, {
6742 version: api.extrinsicType
6743 });
6744 this.#ignoreStatusCb = apiType === 'rxjs';
6745 }
6746 dryRun(account, optionsOrHash) {
6747 if (blockHash || util.isString(optionsOrHash) || util.isU8a(optionsOrHash)) {
6748 return decorateMethod(() => api.rpc.system.dryRun(this.toHex(), blockHash || optionsOrHash));
6749 }
6750 return decorateMethod(() => this.#observeSign(account, optionsOrHash).pipe(switchMap(() => api.rpc.system.dryRun(this.toHex()))))();
6751 }
6752 paymentInfo(account, optionsOrHash) {
6753 if (blockHash || util.isString(optionsOrHash) || util.isU8a(optionsOrHash)) {
6754 return decorateMethod(() => api.rpc.payment.queryInfo(this.toHex(), blockHash || optionsOrHash));
6755 }
6756 const [allOptions] = makeSignAndSendOptions(optionsOrHash);
6757 const address = isKeyringPair(account) ? account.address : account.toString();
6758 return decorateMethod(() => api.derive.tx.signingInfo(address, allOptions.nonce, allOptions.era).pipe(first(), switchMap(signingInfo => {
6759 const eraOptions = makeEraOptions(api, this.registry, allOptions, signingInfo);
6760 const signOptions = makeSignOptions(api, eraOptions, {});
6761 return api.rpc.payment.queryInfo(this.isSigned ? api.tx(this).signFake(address, signOptions).toHex() : this.signFake(address, signOptions).toHex());
6762 })))();
6763 }
6764 send(statusCb) {
6765 const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
6766 return decorateMethod(isSubscription ? this.#observeSubscribe : this.#observeSend)(statusCb);
6767 }
6768 sign(account, partialOptions) {
6769 super.sign(account, makeSignOptions(api, optionsOrNonce(partialOptions), {}));
6770 return this;
6771 }
6772 signAsync(account, partialOptions) {
6773 return decorateMethod(() => this.#observeSign(account, partialOptions).pipe(mapTo(this)))();
6774 }
6775 signAndSend(account, partialOptions, optionalStatusCb) {
6776 const [options, statusCb] = makeSignAndSendOptions(partialOptions, optionalStatusCb);
6777 const isSubscription = api.hasSubscriptions && (this.#ignoreStatusCb || !!statusCb);
6778 return decorateMethod(() => this.#observeSign(account, options).pipe(switchMap(info => isSubscription ? this.#observeSubscribe(info) : this.#observeSend(info)))
6779 )(statusCb);
6780 }
6781 withResultTransform(transform) {
6782 this.#transformResult = transform;
6783 return this;
6784 }
6785 #observeSign = (account, partialOptions) => {
6786 const address = isKeyringPair(account) ? account.address : account.toString();
6787 const options = optionsOrNonce(partialOptions);
6788 return api.derive.tx.signingInfo(address, options.nonce, options.era).pipe(first(), mergeMap(async signingInfo => {
6789 const eraOptions = makeEraOptions(api, this.registry, options, signingInfo);
6790 let updateId = -1;
6791 if (isKeyringPair(account)) {
6792 this.sign(account, eraOptions);
6793 } else {
6794 updateId = await this.#signViaSigner(address, eraOptions, signingInfo.header);
6795 }
6796 return {
6797 options: eraOptions,
6798 updateId
6799 };
6800 }));
6801 };
6802 #observeStatus = (txHash, status) => {
6803 if (!status.isFinalized && !status.isInBlock) {
6804 return of(this.#transformResult(new SubmittableResult({
6805 status,
6806 txHash
6807 })));
6808 }
6809 const blockHash = status.isInBlock ? status.asInBlock : status.asFinalized;
6810 return api.derive.tx.events(blockHash).pipe(map(({
6811 block,
6812 events
6813 }) => this.#transformResult(new SubmittableResult({ ...filterEvents(txHash, block, events, status),
6814 status,
6815 txHash
6816 }))), catchError(internalError => of(this.#transformResult(new SubmittableResult({
6817 internalError,
6818 status,
6819 txHash
6820 })))));
6821 };
6822 #observeSend = info => {
6823 return api.rpc.author.submitExtrinsic(this).pipe(tap(hash => {
6824 this.#updateSigner(hash, info);
6825 }));
6826 };
6827 #observeSubscribe = info => {
6828 const txHash = this.hash;
6829 return api.rpc.author.submitAndWatchExtrinsic(this).pipe(switchMap(status => this.#observeStatus(txHash, status)), tap(status => {
6830 this.#updateSigner(status, info);
6831 }));
6832 };
6833 #signViaSigner = async (address, options, header) => {
6834 const signer = options.signer || api.signer;
6835 util.assert(signer, 'No signer specified, either via api.setSigner or via sign options. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.');
6836 const payload = this.registry.createTypeUnsafe('SignerPayload', [util.objectSpread({}, options, {
6837 address,
6838 blockNumber: header ? header.number : 0,
6839 method: this.method
6840 })]);
6841 let result;
6842 if (util.isFunction(signer.signPayload)) {
6843 result = await signer.signPayload(payload.toPayload());
6844 } else if (util.isFunction(signer.signRaw)) {
6845 result = await signer.signRaw(payload.toRaw());
6846 } else {
6847 throw new Error('Invalid signer interface, it should implement either signPayload or signRaw (or both)');
6848 }
6849 super.addSignature(address, result.signature, payload.toPayload());
6850 return result.id;
6851 };
6852 #updateSigner = (status, info) => {
6853 if (info && info.updateId !== -1) {
6854 const {
6855 options,
6856 updateId
6857 } = info;
6858 const signer = options.signer || api.signer;
6859 if (signer && util.isFunction(signer.update)) {
6860 signer.update(updateId, status);
6861 }
6862 }
6863 };
6864 }
6865 return Submittable;
6866 }
6867
6868 function createSubmittable(apiType, api, decorateMethod, registry, blockHash) {
6869 const Submittable = createClass({
6870 api,
6871 apiType,
6872 blockHash,
6873 decorateMethod
6874 });
6875 return extrinsic => new Submittable(registry || api.registry, extrinsic);
6876 }
6877
6878 function findCall(registry, callIndex) {
6879 return registry.findMetaCall(util.u8aToU8a(callIndex));
6880 }
6881 function findError(registry, errorIndex) {
6882 return registry.findMetaError(util.u8aToU8a(errorIndex));
6883 }
6884
6885 const XCM_MAPPINGS = ['AssetInstance', 'Fungibility', 'Junction', 'Junctions', 'MultiAsset', 'MultiAssetFilter', 'MultiLocation', 'Response', 'WildFungibility', 'WildMultiAsset', 'Xcm', 'XcmError', 'XcmOrder'];
6886 function mapXcmTypes(version) {
6887 return XCM_MAPPINGS.reduce((all, key) => util.objectSpread(all, {
6888 [key]: `${key}${version}`
6889 }), {});
6890 }
6891
6892 const typesChain = {};
6893
6894 const sharedTypes$5 = {
6895 AnchorData: {
6896 anchoredBlock: 'u64',
6897 docRoot: 'H256',
6898 id: 'H256'
6899 },
6900 DispatchErrorModule: 'DispatchErrorModuleU8',
6901 PreCommitData: {
6902 expirationBlock: 'u64',
6903 identity: 'H256',
6904 signingRoot: 'H256'
6905 },
6906 Fee: {
6907 key: 'Hash',
6908 price: 'Balance'
6909 },
6910 MultiAccountData: {
6911 deposit: 'Balance',
6912 depositor: 'AccountId',
6913 signatories: 'Vec<AccountId>',
6914 threshold: 'u16'
6915 },
6916 ChainId: 'u8',
6917 DepositNonce: 'u64',
6918 ResourceId: '[u8; 32]',
6919 'chainbridge::ChainId': 'u8',
6920 RegistryId: 'H160',
6921 TokenId: 'U256',
6922 AssetId: {
6923 registryId: 'RegistryId',
6924 tokenId: 'TokenId'
6925 },
6926 AssetInfo: {
6927 metadata: 'Bytes'
6928 },
6929 MintInfo: {
6930 anchorId: 'Hash',
6931 proofs: 'Vec<ProofMint>',
6932 staticHashes: '[Hash; 3]'
6933 },
6934 Proof: {
6935 leafHash: 'H256',
6936 sortedHashes: 'H256'
6937 },
6938 ProofMint: {
6939 hashes: 'Vec<Hash>',
6940 property: 'Bytes',
6941 salt: '[u8; 32]',
6942 value: 'Bytes'
6943 },
6944 RegistryInfo: {
6945 fields: 'Vec<Bytes>',
6946 ownerCanBurn: 'bool'
6947 },
6948 ProxyType: {
6949 _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'NonProxy']
6950 }
6951 };
6952 const standaloneTypes = util.objectSpread({}, sharedTypes$5, {
6953 AccountInfo: 'AccountInfoWithRefCount',
6954 Address: 'LookupSource',
6955 LookupSource: 'IndicesLookupSource',
6956 Multiplier: 'Fixed64',
6957 RefCount: 'RefCountTo259'
6958 });
6959 const versioned$8 = [{
6960 minmax: [240, 243],
6961 types: util.objectSpread({}, standaloneTypes, {
6962 ProxyType: {
6963 _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'Vesting']
6964 }
6965 })
6966 }, {
6967 minmax: [244, 999],
6968 types: util.objectSpread({}, standaloneTypes)
6969 }, {
6970 minmax: [1000, undefined],
6971 types: util.objectSpread({}, sharedTypes$5)
6972 }];
6973
6974 const sharedTypes$4 = {
6975 CompactAssignments: 'CompactAssignmentsWith24',
6976 DispatchErrorModule: 'DispatchErrorModuleU8',
6977 RawSolution: 'RawSolutionWith24',
6978 Keys: 'SessionKeys6',
6979 ProxyType: {
6980 _enum: ['Any', 'NonTransfer', 'Governance', 'Staking', 'IdentityJudgement', 'CancelProxy', 'Auction']
6981 }
6982 };
6983 const addrIndicesTypes = {
6984 AccountInfo: 'AccountInfoWithRefCount',
6985 Address: 'LookupSource',
6986 CompactAssignments: 'CompactAssignmentsWith16',
6987 RawSolution: 'RawSolutionWith16',
6988 Keys: 'SessionKeys5',
6989 LookupSource: 'IndicesLookupSource',
6990 ValidatorPrefs: 'ValidatorPrefsWithCommission'
6991 };
6992 const addrAccountIdTypes$2 = {
6993 AccountInfo: 'AccountInfoWithRefCount',
6994 Address: 'AccountId',
6995 CompactAssignments: 'CompactAssignmentsWith16',
6996 RawSolution: 'RawSolutionWith16',
6997 Keys: 'SessionKeys5',
6998 LookupSource: 'AccountId',
6999 ValidatorPrefs: 'ValidatorPrefsWithCommission'
7000 };
7001 const versioned$7 = [{
7002 minmax: [1019, 1031],
7003 types: util.objectSpread({}, addrIndicesTypes, {
7004 BalanceLock: 'BalanceLockTo212',
7005 CompactAssignments: 'CompactAssignmentsTo257',
7006 DispatchError: 'DispatchErrorTo198',
7007 DispatchInfo: 'DispatchInfoTo244',
7008 Heartbeat: 'HeartbeatTo244',
7009 IdentityInfo: 'IdentityInfoTo198',
7010 Keys: 'SessionKeys5',
7011 Multiplier: 'Fixed64',
7012 OpenTip: 'OpenTipTo225',
7013 RefCount: 'RefCountTo259',
7014 ReferendumInfo: 'ReferendumInfoTo239',
7015 SlashingSpans: 'SlashingSpansTo204',
7016 StakingLedger: 'StakingLedgerTo223',
7017 Votes: 'VotesTo230',
7018 Weight: 'u32'
7019 })
7020 }, {
7021 minmax: [1032, 1042],
7022 types: util.objectSpread({}, addrIndicesTypes, {
7023 BalanceLock: 'BalanceLockTo212',
7024 CompactAssignments: 'CompactAssignmentsTo257',
7025 DispatchInfo: 'DispatchInfoTo244',
7026 Heartbeat: 'HeartbeatTo244',
7027 Keys: 'SessionKeys5',
7028 Multiplier: 'Fixed64',
7029 OpenTip: 'OpenTipTo225',
7030 RefCount: 'RefCountTo259',
7031 ReferendumInfo: 'ReferendumInfoTo239',
7032 SlashingSpans: 'SlashingSpansTo204',
7033 StakingLedger: 'StakingLedgerTo223',
7034 Votes: 'VotesTo230',
7035 Weight: 'u32'
7036 })
7037 }, {
7038 minmax: [1043, 1045],
7039 types: util.objectSpread({}, addrIndicesTypes, {
7040 BalanceLock: 'BalanceLockTo212',
7041 CompactAssignments: 'CompactAssignmentsTo257',
7042 DispatchInfo: 'DispatchInfoTo244',
7043 Heartbeat: 'HeartbeatTo244',
7044 Keys: 'SessionKeys5',
7045 Multiplier: 'Fixed64',
7046 OpenTip: 'OpenTipTo225',
7047 RefCount: 'RefCountTo259',
7048 ReferendumInfo: 'ReferendumInfoTo239',
7049 StakingLedger: 'StakingLedgerTo223',
7050 Votes: 'VotesTo230',
7051 Weight: 'u32'
7052 })
7053 }, {
7054 minmax: [1046, 1050],
7055 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7056 CompactAssignments: 'CompactAssignmentsTo257',
7057 DispatchInfo: 'DispatchInfoTo244',
7058 Heartbeat: 'HeartbeatTo244',
7059 Multiplier: 'Fixed64',
7060 OpenTip: 'OpenTipTo225',
7061 RefCount: 'RefCountTo259',
7062 ReferendumInfo: 'ReferendumInfoTo239',
7063 StakingLedger: 'StakingLedgerTo223',
7064 Weight: 'u32'
7065 })
7066 }, {
7067 minmax: [1051, 1054],
7068 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7069 CompactAssignments: 'CompactAssignmentsTo257',
7070 DispatchInfo: 'DispatchInfoTo244',
7071 Heartbeat: 'HeartbeatTo244',
7072 Multiplier: 'Fixed64',
7073 OpenTip: 'OpenTipTo225',
7074 RefCount: 'RefCountTo259',
7075 ReferendumInfo: 'ReferendumInfoTo239',
7076 StakingLedger: 'StakingLedgerTo240',
7077 Weight: 'u32'
7078 })
7079 }, {
7080 minmax: [1055, 1056],
7081 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7082 CompactAssignments: 'CompactAssignmentsTo257',
7083 DispatchInfo: 'DispatchInfoTo244',
7084 Heartbeat: 'HeartbeatTo244',
7085 Multiplier: 'Fixed64',
7086 OpenTip: 'OpenTipTo225',
7087 RefCount: 'RefCountTo259',
7088 StakingLedger: 'StakingLedgerTo240',
7089 Weight: 'u32'
7090 })
7091 }, {
7092 minmax: [1057, 1061],
7093 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7094 CompactAssignments: 'CompactAssignmentsTo257',
7095 DispatchInfo: 'DispatchInfoTo244',
7096 Heartbeat: 'HeartbeatTo244',
7097 OpenTip: 'OpenTipTo225',
7098 RefCount: 'RefCountTo259'
7099 })
7100 }, {
7101 minmax: [1062, 2012],
7102 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7103 CompactAssignments: 'CompactAssignmentsTo257',
7104 OpenTip: 'OpenTipTo225',
7105 RefCount: 'RefCountTo259'
7106 })
7107 }, {
7108 minmax: [2013, 2022],
7109 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7110 CompactAssignments: 'CompactAssignmentsTo257',
7111 RefCount: 'RefCountTo259'
7112 })
7113 }, {
7114 minmax: [2023, 2024],
7115 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2, {
7116 RefCount: 'RefCountTo259'
7117 })
7118 }, {
7119 minmax: [2025, 2027],
7120 types: util.objectSpread({}, sharedTypes$4, addrAccountIdTypes$2)
7121 }, {
7122 minmax: [2028, 2029],
7123 types: util.objectSpread({}, sharedTypes$4, {
7124 AccountInfo: 'AccountInfoWithDualRefCount',
7125 CompactAssignments: 'CompactAssignmentsWith16',
7126 RawSolution: 'RawSolutionWith16'
7127 })
7128 }, {
7129 minmax: [2030, 9000],
7130 types: util.objectSpread({}, sharedTypes$4, {
7131 CompactAssignments: 'CompactAssignmentsWith16',
7132 RawSolution: 'RawSolutionWith16'
7133 })
7134 }, {
7135 minmax: [9010, 9099],
7136 types: util.objectSpread({}, sharedTypes$4, mapXcmTypes('V0'))
7137 }, {
7138 minmax: [9100, 9105],
7139 types: util.objectSpread({}, sharedTypes$4, mapXcmTypes('V1'))
7140 }, {
7141 minmax: [9106, undefined],
7142 types: {}
7143 }];
7144
7145 const versioned$6 = [{
7146 minmax: [0, undefined],
7147 types: {
7148 }
7149 }];
7150
7151 const versioned$5 = [{
7152 minmax: [0, undefined],
7153 types: {
7154 }
7155 }];
7156
7157 const sharedTypes$3 = {
7158 CompactAssignments: 'CompactAssignmentsWith16',
7159 DispatchErrorModule: 'DispatchErrorModuleU8',
7160 RawSolution: 'RawSolutionWith16',
7161 Keys: 'SessionKeys6',
7162 ProxyType: {
7163 _enum: {
7164 Any: 0,
7165 NonTransfer: 1,
7166 Governance: 2,
7167 Staking: 3,
7168 UnusedSudoBalances: 4,
7169 IdentityJudgement: 5,
7170 CancelProxy: 6,
7171 Auction: 7
7172 }
7173 }
7174 };
7175 const addrAccountIdTypes$1 = {
7176 AccountInfo: 'AccountInfoWithRefCount',
7177 Address: 'AccountId',
7178 Keys: 'SessionKeys5',
7179 LookupSource: 'AccountId',
7180 ValidatorPrefs: 'ValidatorPrefsWithCommission'
7181 };
7182 const versioned$4 = [{
7183 minmax: [0, 12],
7184 types: util.objectSpread({}, sharedTypes$3, addrAccountIdTypes$1, {
7185 CompactAssignments: 'CompactAssignmentsTo257',
7186 OpenTip: 'OpenTipTo225',
7187 RefCount: 'RefCountTo259'
7188 })
7189 }, {
7190 minmax: [13, 22],
7191 types: util.objectSpread({}, sharedTypes$3, addrAccountIdTypes$1, {
7192 CompactAssignments: 'CompactAssignmentsTo257',
7193 RefCount: 'RefCountTo259'
7194 })
7195 }, {
7196 minmax: [23, 24],
7197 types: util.objectSpread({}, sharedTypes$3, addrAccountIdTypes$1, {
7198 RefCount: 'RefCountTo259'
7199 })
7200 }, {
7201 minmax: [25, 27],
7202 types: util.objectSpread({}, sharedTypes$3, addrAccountIdTypes$1)
7203 }, {
7204 minmax: [28, 29],
7205 types: util.objectSpread({}, sharedTypes$3, {
7206 AccountInfo: 'AccountInfoWithDualRefCount'
7207 })
7208 }, {
7209 minmax: [30, 9109],
7210 types: util.objectSpread({}, sharedTypes$3)
7211 }, {
7212 minmax: [9110, undefined],
7213 types: {}
7214 }];
7215
7216 const sharedTypes$2 = {
7217 DispatchErrorModule: 'DispatchErrorModuleU8',
7218 FullIdentification: '()',
7219 Keys: 'SessionKeys7B'
7220 };
7221 const versioned$3 = [{
7222 minmax: [0, 200],
7223 types: util.objectSpread({}, sharedTypes$2, {
7224 AccountInfo: 'AccountInfoWithDualRefCount',
7225 Address: 'AccountId',
7226 LookupSource: 'AccountId'
7227 })
7228 }, {
7229 minmax: [201, 214],
7230 types: util.objectSpread({}, sharedTypes$2, {
7231 AccountInfo: 'AccountInfoWithDualRefCount'
7232 })
7233 }, {
7234 minmax: [215, 228],
7235 types: util.objectSpread({}, sharedTypes$2, {
7236 Keys: 'SessionKeys6'
7237 })
7238 }, {
7239 minmax: [229, 9099],
7240 types: util.objectSpread({}, sharedTypes$2, mapXcmTypes('V0'))
7241 }, {
7242 minmax: [9100, 9105],
7243 types: util.objectSpread({}, sharedTypes$2, mapXcmTypes('V1'))
7244 }, {
7245 minmax: [9106, undefined],
7246 types: {}
7247 }];
7248
7249 const versioned$2 = [{
7250 minmax: [0, undefined],
7251 types: {
7252 }
7253 }];
7254
7255 const sharedTypes$1 = {
7256 DispatchErrorModule: 'DispatchErrorModuleU8',
7257 TAssetBalance: 'u128',
7258 ProxyType: {
7259 _enum: ['Any', 'NonTransfer', 'CancelProxy', 'Assets', 'AssetOwner', 'AssetManager', 'Staking']
7260 }
7261 };
7262 const versioned$1 = [{
7263 minmax: [0, 3],
7264 types: util.objectSpread({}, sharedTypes$1, mapXcmTypes('V0'))
7265 }, {
7266 minmax: [4, 5],
7267 types: util.objectSpread({}, sharedTypes$1, mapXcmTypes('V1'))
7268 }, {
7269 minmax: [500, undefined],
7270 types: {}
7271 }];
7272
7273 const sharedTypes = {
7274 CompactAssignments: 'CompactAssignmentsWith16',
7275 DispatchErrorModule: 'DispatchErrorModuleU8',
7276 RawSolution: 'RawSolutionWith16',
7277 Keys: 'SessionKeys6',
7278 ProxyType: {
7279 _enum: ['Any', 'NonTransfer', 'Staking', 'SudoBalances', 'IdentityJudgement', 'CancelProxy']
7280 }
7281 };
7282 const addrAccountIdTypes = {
7283 AccountInfo: 'AccountInfoWithRefCount',
7284 Address: 'AccountId',
7285 CompactAssignments: 'CompactAssignmentsWith16',
7286 LookupSource: 'AccountId',
7287 Keys: 'SessionKeys5',
7288 RawSolution: 'RawSolutionWith16',
7289 ValidatorPrefs: 'ValidatorPrefsWithCommission'
7290 };
7291 const versioned = [{
7292 minmax: [1, 2],
7293 types: util.objectSpread({}, sharedTypes, addrAccountIdTypes, {
7294 CompactAssignments: 'CompactAssignmentsTo257',
7295 DispatchInfo: 'DispatchInfoTo244',
7296 Heartbeat: 'HeartbeatTo244',
7297 Multiplier: 'Fixed64',
7298 OpenTip: 'OpenTipTo225',
7299 RefCount: 'RefCountTo259',
7300 Weight: 'u32'
7301 })
7302 }, {
7303 minmax: [3, 22],
7304 types: util.objectSpread({}, sharedTypes, addrAccountIdTypes, {
7305 CompactAssignments: 'CompactAssignmentsTo257',
7306 DispatchInfo: 'DispatchInfoTo244',
7307 Heartbeat: 'HeartbeatTo244',
7308 OpenTip: 'OpenTipTo225',
7309 RefCount: 'RefCountTo259'
7310 })
7311 }, {
7312 minmax: [23, 42],
7313 types: util.objectSpread({}, sharedTypes, addrAccountIdTypes, {
7314 CompactAssignments: 'CompactAssignmentsTo257',
7315 DispatchInfo: 'DispatchInfoTo244',
7316 Heartbeat: 'HeartbeatTo244',
7317 RefCount: 'RefCountTo259'
7318 })
7319 }, {
7320 minmax: [43, 44],
7321 types: util.objectSpread({}, sharedTypes, addrAccountIdTypes, {
7322 DispatchInfo: 'DispatchInfoTo244',
7323 Heartbeat: 'HeartbeatTo244',
7324 RefCount: 'RefCountTo259'
7325 })
7326 }, {
7327 minmax: [45, 47],
7328 types: util.objectSpread({}, sharedTypes, addrAccountIdTypes)
7329 }, {
7330 minmax: [48, 49],
7331 types: util.objectSpread({}, sharedTypes, {
7332 AccountInfo: 'AccountInfoWithDualRefCount'
7333 })
7334 }, {
7335 minmax: [50, 9099],
7336 types: util.objectSpread({}, sharedTypes, mapXcmTypes('V0'))
7337 }, {
7338 minmax: [9100, 9105],
7339 types: util.objectSpread({}, sharedTypes, mapXcmTypes('V1'))
7340 }, {
7341 minmax: [9106, undefined],
7342 types: {}
7343 }];
7344
7345 const typesSpec = {
7346 'centrifuge-chain': versioned$8,
7347 kusama: versioned$7,
7348 node: versioned$6,
7349 'node-template': versioned$5,
7350 polkadot: versioned$4,
7351 rococo: versioned$3,
7352 shell: versioned$2,
7353 statemine: versioned$1,
7354 statemint: versioned$1,
7355 westend: versioned,
7356 westmint: versioned$1
7357 };
7358
7359 const upgrades$4 = [[0, 1020], [26669, 1021], [38245, 1022], [54248, 1023], [59659, 1024], [67651, 1025], [82191, 1027], [83238, 1028], [101503, 1029], [203466, 1030], [295787, 1031], [461692, 1032], [504329, 1033], [569327, 1038], [587687, 1039], [653183, 1040], [693488, 1042], [901442, 1045], [1375086, 1050], [1445458, 1051], [1472960, 1052], [1475648, 1053], [1491596, 1054], [1574408, 1055], [2064961, 1058], [2201991, 1062], [2671528, 2005], [2704202, 2007], [2728002, 2008], [2832534, 2011], [2962294, 2012], [3240000, 2013], [3274408, 2015], [3323565, 2019], [3534175, 2022], [3860281, 2023], [4143129, 2024], [4401242, 2025], [4841367, 2026], [5961600, 2027], [6137912, 2028], [6561855, 2029], [7100891, 2030], [7468792, 9010], [7668600, 9030], [7812476, 9040], [8010981, 9050], [8073833, 9070], [8555825, 9080], [8945245, 9090], [9611377, 9100], [9625129, 9111], [9866422, 9122], [10403784, 9130], [10960765, 9150], [11006614, 9151], [11404482, 9160], [11601803, 9170], [12008022, 9180], [12405451, 9190], [12665416, 9200], [12909508, 9220], [13109752, 9230]];
7360
7361 const upgrades$3 = [[0, 0], [29231, 1], [188836, 5], [199405, 6], [214264, 7], [244358, 8], [303079, 9], [314201, 10], [342400, 11], [443963, 12], [528470, 13], [687751, 14], [746085, 15], [787923, 16], [799302, 17], [1205128, 18], [1603423, 23], [1733218, 24], [2005673, 25], [2436698, 26], [3613564, 27], [3899547, 28], [4345767, 29], [4876134, 30], [5661442, 9050], [6321619, 9080], [6713249, 9090], [7217907, 9100], [7229126, 9110], [7560558, 9122], [8115869, 9140], [8638103, 9151], [9280179, 9170], [9738717, 9180], [10156856, 9190], [10458576, 9200], [10655116, 9220]];
7362
7363 const upgrades$2 = [[214356, 4], [392764, 7], [409740, 8], [809976, 20], [877581, 24], [879238, 25], [889472, 26], [902937, 27], [932751, 28], [991142, 29], [1030162, 31], [1119657, 32], [1199282, 33], [1342534, 34], [1392263, 35], [1431703, 36], [1433369, 37], [1490972, 41], [2087397, 43], [2316688, 44], [2549864, 45], [3925782, 46], [3925843, 47], [4207800, 48], [4627944, 49], [5124076, 50], [5478664, 900], [5482450, 9000], [5584305, 9010], [5784566, 9030], [5879822, 9031], [5896856, 9032], [5897316, 9033], [6117927, 9050], [6210274, 9070], [6379314, 9080], [6979141, 9090], [7568453, 9100], [7766394, 9111], [7911691, 9120], [7968866, 9121], [7982889, 9122], [8514322, 9130], [9091726, 9140], [9091774, 9150], [9406726, 9160], [9921066, 9170], [10007115, 9180], [10480973, 9190], [10578091, 9200], [10678509, 9210], [10811001, 9220], [11096116, 9230], [11409279, 9250]];
7364
7365 const allKnown = {
7366 kusama: upgrades$4,
7367 polkadot: upgrades$3,
7368 westend: upgrades$2
7369 };
7370 const NET_EXTRA = {
7371 westend: {
7372 genesisHash: ['0xe143f23803ac50e8f6f8e62695d1ce9e4e1d68aa36c1cd2cfd15340213f3423e']
7373 }
7374 };
7375 function checkOrder(network, versions) {
7376 const ooo = versions.filter((curr, index) => {
7377 const prev = versions[index - 1];
7378 return index === 0 ? false : curr[0] <= prev[0] || curr[1] <= prev[1];
7379 });
7380 if (ooo.length) {
7381 throw new Error(`${network}: Mismatched upgrade ordering: ${util.stringify(ooo)}`);
7382 }
7383 return versions;
7384 }
7385 function mapRaw([network, versions]) {
7386 const chain = utilCrypto.selectableNetworks.find(n => n.network === network) || NET_EXTRA[network];
7387 if (!chain) {
7388 throw new Error(`Unable to find info for chain ${network}`);
7389 }
7390 return {
7391 genesisHash: util.hexToU8a(chain.genesisHash[0]),
7392 network,
7393 versions: checkOrder(network, versions).map(([blockNumber, specVersion]) => ({
7394 blockNumber: new util.BN(blockNumber),
7395 specVersion: new util.BN(specVersion)
7396 }))
7397 };
7398 }
7399 const upgrades = Object.entries(allKnown).map(mapRaw);
7400 const upgrades$1 = upgrades;
7401
7402 function withNames(chainName, specName, fn) {
7403 return fn(chainName.toString(), specName.toString());
7404 }
7405 function filterVersions(versions = [], specVersion) {
7406 return versions.filter(({
7407 minmax: [min, max]
7408 }) => (util.isUndefined(min) || util.isNull(min) || specVersion >= min) && (util.isUndefined(max) || util.isNull(max) || specVersion <= max)).reduce((result, {
7409 types
7410 }) => util.objectSpread(result, types), {});
7411 }
7412 function getSpecExtensions({
7413 knownTypes
7414 }, chainName, specName) {
7415 return withNames(chainName, specName, (c, s) => {
7416 var _knownTypes$typesBund, _knownTypes$typesBund2, _knownTypes$typesBund3, _knownTypes$typesBund4, _knownTypes$typesBund5, _knownTypes$typesBund6;
7417 return util.objectSpread({}, (_knownTypes$typesBund = knownTypes.typesBundle) === null || _knownTypes$typesBund === void 0 ? void 0 : (_knownTypes$typesBund2 = _knownTypes$typesBund.spec) === null || _knownTypes$typesBund2 === void 0 ? void 0 : (_knownTypes$typesBund3 = _knownTypes$typesBund2[s]) === null || _knownTypes$typesBund3 === void 0 ? void 0 : _knownTypes$typesBund3.signedExtensions, (_knownTypes$typesBund4 = knownTypes.typesBundle) === null || _knownTypes$typesBund4 === void 0 ? void 0 : (_knownTypes$typesBund5 = _knownTypes$typesBund4.chain) === null || _knownTypes$typesBund5 === void 0 ? void 0 : (_knownTypes$typesBund6 = _knownTypes$typesBund5[c]) === null || _knownTypes$typesBund6 === void 0 ? void 0 : _knownTypes$typesBund6.signedExtensions);
7418 });
7419 }
7420 function getSpecTypes({
7421 knownTypes
7422 }, chainName, specName, specVersion) {
7423 const _specVersion = util.bnToBn(specVersion).toNumber();
7424 return withNames(chainName, specName, (c, s) => {
7425 var _knownTypes$typesBund7, _knownTypes$typesBund8, _knownTypes$typesBund9, _knownTypes$typesBund10, _knownTypes$typesBund11, _knownTypes$typesBund12, _knownTypes$typesSpec, _knownTypes$typesChai;
7426 return (
7427 util.objectSpread({}, filterVersions(typesSpec[s], _specVersion), filterVersions(typesChain[c], _specVersion), filterVersions((_knownTypes$typesBund7 = knownTypes.typesBundle) === null || _knownTypes$typesBund7 === void 0 ? void 0 : (_knownTypes$typesBund8 = _knownTypes$typesBund7.spec) === null || _knownTypes$typesBund8 === void 0 ? void 0 : (_knownTypes$typesBund9 = _knownTypes$typesBund8[s]) === null || _knownTypes$typesBund9 === void 0 ? void 0 : _knownTypes$typesBund9.types, _specVersion), filterVersions((_knownTypes$typesBund10 = knownTypes.typesBundle) === null || _knownTypes$typesBund10 === void 0 ? void 0 : (_knownTypes$typesBund11 = _knownTypes$typesBund10.chain) === null || _knownTypes$typesBund11 === void 0 ? void 0 : (_knownTypes$typesBund12 = _knownTypes$typesBund11[c]) === null || _knownTypes$typesBund12 === void 0 ? void 0 : _knownTypes$typesBund12.types, _specVersion), (_knownTypes$typesSpec = knownTypes.typesSpec) === null || _knownTypes$typesSpec === void 0 ? void 0 : _knownTypes$typesSpec[s], (_knownTypes$typesChai = knownTypes.typesChain) === null || _knownTypes$typesChai === void 0 ? void 0 : _knownTypes$typesChai[c], knownTypes.types)
7428 );
7429 });
7430 }
7431 function getSpecHasher({
7432 knownTypes
7433 }, chainName, specName) {
7434 return withNames(chainName, specName, (c, s) => {
7435 var _knownTypes$typesBund13, _knownTypes$typesBund14, _knownTypes$typesBund15, _knownTypes$typesBund16, _knownTypes$typesBund17, _knownTypes$typesBund18;
7436 return knownTypes.hasher || ((_knownTypes$typesBund13 = knownTypes.typesBundle) === null || _knownTypes$typesBund13 === void 0 ? void 0 : (_knownTypes$typesBund14 = _knownTypes$typesBund13.chain) === null || _knownTypes$typesBund14 === void 0 ? void 0 : (_knownTypes$typesBund15 = _knownTypes$typesBund14[c]) === null || _knownTypes$typesBund15 === void 0 ? void 0 : _knownTypes$typesBund15.hasher) || ((_knownTypes$typesBund16 = knownTypes.typesBundle) === null || _knownTypes$typesBund16 === void 0 ? void 0 : (_knownTypes$typesBund17 = _knownTypes$typesBund16.spec) === null || _knownTypes$typesBund17 === void 0 ? void 0 : (_knownTypes$typesBund18 = _knownTypes$typesBund17[s]) === null || _knownTypes$typesBund18 === void 0 ? void 0 : _knownTypes$typesBund18.hasher) || null;
7437 });
7438 }
7439 function getSpecRpc({
7440 knownTypes
7441 }, chainName, specName) {
7442 return withNames(chainName, specName, (c, s) => {
7443 var _knownTypes$typesBund19, _knownTypes$typesBund20, _knownTypes$typesBund21, _knownTypes$typesBund22, _knownTypes$typesBund23, _knownTypes$typesBund24;
7444 return util.objectSpread({}, (_knownTypes$typesBund19 = knownTypes.typesBundle) === null || _knownTypes$typesBund19 === void 0 ? void 0 : (_knownTypes$typesBund20 = _knownTypes$typesBund19.spec) === null || _knownTypes$typesBund20 === void 0 ? void 0 : (_knownTypes$typesBund21 = _knownTypes$typesBund20[s]) === null || _knownTypes$typesBund21 === void 0 ? void 0 : _knownTypes$typesBund21.rpc, (_knownTypes$typesBund22 = knownTypes.typesBundle) === null || _knownTypes$typesBund22 === void 0 ? void 0 : (_knownTypes$typesBund23 = _knownTypes$typesBund22.chain) === null || _knownTypes$typesBund23 === void 0 ? void 0 : (_knownTypes$typesBund24 = _knownTypes$typesBund23[c]) === null || _knownTypes$typesBund24 === void 0 ? void 0 : _knownTypes$typesBund24.rpc);
7445 });
7446 }
7447 function getSpecAlias({
7448 knownTypes
7449 }, chainName, specName) {
7450 return withNames(chainName, specName, (c, s) => {
7451 var _knownTypes$typesBund25, _knownTypes$typesBund26, _knownTypes$typesBund27, _knownTypes$typesBund28, _knownTypes$typesBund29, _knownTypes$typesBund30;
7452 return (
7453 util.objectSpread({}, (_knownTypes$typesBund25 = knownTypes.typesBundle) === null || _knownTypes$typesBund25 === void 0 ? void 0 : (_knownTypes$typesBund26 = _knownTypes$typesBund25.spec) === null || _knownTypes$typesBund26 === void 0 ? void 0 : (_knownTypes$typesBund27 = _knownTypes$typesBund26[s]) === null || _knownTypes$typesBund27 === void 0 ? void 0 : _knownTypes$typesBund27.alias, (_knownTypes$typesBund28 = knownTypes.typesBundle) === null || _knownTypes$typesBund28 === void 0 ? void 0 : (_knownTypes$typesBund29 = _knownTypes$typesBund28.chain) === null || _knownTypes$typesBund29 === void 0 ? void 0 : (_knownTypes$typesBund30 = _knownTypes$typesBund29[c]) === null || _knownTypes$typesBund30 === void 0 ? void 0 : _knownTypes$typesBund30.alias, knownTypes.typesAlias)
7454 );
7455 });
7456 }
7457 function getUpgradeVersion(genesisHash, blockNumber) {
7458 const known = upgrades$1.find(u => genesisHash.eq(u.genesisHash));
7459 return known ? [known.versions.reduce((last, version) => {
7460 return blockNumber.gt(version.blockNumber) ? version : last;
7461 }, undefined), known.versions.find(version => blockNumber.lte(version.blockNumber))] : [undefined, undefined];
7462 }
7463
7464 const l$2 = util.logger('api/augment');
7465 function logLength(type, values, and = []) {
7466 return values.length ? ` ${values.length} ${type}${and.length ? ' and' : ''}` : '';
7467 }
7468 function logValues(type, values) {
7469 return values.length ? `\n\t${type.padStart(7)}: ${values.sort().join(', ')}` : '';
7470 }
7471 function warn(prefix, type, [added, removed]) {
7472 if (added.length || removed.length) {
7473 l$2.warn(`api.${prefix}: Found${logLength('added', added, removed)}${logLength('removed', removed)} ${type}:${logValues('added', added)}${logValues('removed', removed)}`);
7474 }
7475 }
7476 function findSectionExcludes(a, b) {
7477 return a.filter(s => !b.includes(s));
7478 }
7479 function findSectionIncludes(a, b) {
7480 return a.filter(s => b.includes(s));
7481 }
7482 function extractSections(src, dst) {
7483 const srcSections = Object.keys(src);
7484 const dstSections = Object.keys(dst);
7485 return [findSectionExcludes(srcSections, dstSections), findSectionExcludes(dstSections, srcSections)];
7486 }
7487 function findMethodExcludes(src, dst) {
7488 const srcSections = Object.keys(src);
7489 const dstSections = findSectionIncludes(Object.keys(dst), srcSections);
7490 const excludes = [];
7491 for (let s = 0; s < dstSections.length; s++) {
7492 const section = dstSections[s];
7493 const srcMethods = Object.keys(src[section]);
7494 const dstMethods = Object.keys(dst[section]);
7495 excludes.push(...dstMethods.filter(m => !srcMethods.includes(m)).map(m => `${section}.${m}`));
7496 }
7497 return excludes;
7498 }
7499 function extractMethods(src, dst) {
7500 return [findMethodExcludes(dst, src), findMethodExcludes(src, dst)];
7501 }
7502 function lazySection(src, dst) {
7503 const creator = m => src[m];
7504 const methods = Object.keys(src);
7505 for (let i = 0; i < methods.length; i++) {
7506 const method = methods[i];
7507 if (!Object.prototype.hasOwnProperty.call(dst, method)) {
7508 util.lazyMethod(dst, method, creator);
7509 }
7510 }
7511 }
7512 function augmentObject(prefix, src, dst, fromEmpty = false) {
7513 fromEmpty && util.objectClear(dst);
7514 if (prefix && Object.keys(dst).length) {
7515 warn(prefix, 'modules', extractSections(src, dst));
7516 warn(prefix, 'calls', extractMethods(src, dst));
7517 }
7518 const sections = Object.keys(src);
7519 for (let i = 0; i < sections.length; i++) {
7520 const section = sections[i];
7521 if (!dst[section]) {
7522 dst[section] = {};
7523 }
7524 lazySection(src[section], dst[section]);
7525 }
7526 return dst;
7527 }
7528
7529 function sig({
7530 lookup
7531 }, {
7532 method,
7533 section
7534 }, args) {
7535 return `${section}.${method}(${args.map(a => lookup.getTypeDef(a).type).join(', ')})`;
7536 }
7537 function extractStorageArgs(registry, creator, _args) {
7538 const args = _args.filter(a => !util.isUndefined(a));
7539 if (creator.meta.type.isPlain) {
7540 util.assert(args.length === 0, () => `${sig(registry, creator, [])} does not take any arguments, ${args.length} found`);
7541 } else {
7542 const {
7543 hashers,
7544 key
7545 } = creator.meta.type.asMap;
7546 const keys = hashers.length === 1 ? [key] : registry.lookup.getSiType(key).def.asTuple.map(t => t);
7547 util.assert(args.length === keys.length, () => `${sig(registry, creator, keys)} is a map, requiring ${keys.length} arguments, ${args.length} found`);
7548 }
7549 return [creator, args];
7550 }
7551
7552 class Events {
7553 #eventemitter = new EventEmitter();
7554 emit(type, ...args) {
7555 return this.#eventemitter.emit(type, ...args);
7556 }
7557 on(type, handler) {
7558 this.#eventemitter.on(type, handler);
7559 return this;
7560 }
7561 off(type, handler) {
7562 this.#eventemitter.removeListener(type, handler);
7563 return this;
7564 }
7565 once(type, handler) {
7566 this.#eventemitter.once(type, handler);
7567 return this;
7568 }
7569 }
7570
7571 const PAGE_SIZE_K = 1000;
7572 const PAGE_SIZE_V = 250;
7573 const PAGE_SIZE_Q = 50;
7574 const l$1 = util.logger('api/init');
7575 let instanceCounter = 0;
7576 function getAtQueryFn(api, {
7577 method,
7578 section
7579 }) {
7580 return util.assertReturn(api.rx.query[section] && api.rx.query[section][method], () => `query.${section}.${method} is not available in this version of the metadata`);
7581 }
7582 class Decorate extends Events {
7583 #instanceId;
7584 #registry;
7585 #storageGetQ = [];
7586 #storageSubQ = [];
7587 __phantom = new util.BN(0);
7588 _consts = {};
7589 _errors = {};
7590 _events = {};
7591 _extrinsicType = 4;
7592 _isReady = false;
7593 _query = {};
7594 _rx = {
7595 consts: {},
7596 query: {},
7597 tx: {}
7598 };
7599 constructor(options, type, decorateMethod) {
7600 var _options$source;
7601 super();
7602 this.#instanceId = `${++instanceCounter}`;
7603 this.#registry = ((_options$source = options.source) === null || _options$source === void 0 ? void 0 : _options$source.registry) || options.registry || new types.TypeRegistry();
7604 this._rx.queryAt = (blockHash, knownVersion) => from(this.at(blockHash, knownVersion)).pipe(map(a => a.rx.query));
7605 this._rx.registry = this.#registry;
7606 const thisProvider = options.source ? options.source._rpcCore.provider.clone() : options.provider || new WsProvider();
7607 this._decorateMethod = decorateMethod;
7608 this._options = options;
7609 this._type = type;
7610 this._rpcCore = new RpcCore(this.#instanceId, this.#registry, thisProvider, this._options.rpc);
7611 this._isConnected = new BehaviorSubject(this._rpcCore.provider.isConnected);
7612 this._rx.hasSubscriptions = this._rpcCore.provider.hasSubscriptions;
7613 }
7614 get registry() {
7615 return this.#registry;
7616 }
7617 createType(type, ...params) {
7618 return this.#registry.createType(type, ...params);
7619 }
7620 registerTypes(types) {
7621 types && this.#registry.register(types);
7622 }
7623 get hasSubscriptions() {
7624 return this._rpcCore.provider.hasSubscriptions;
7625 }
7626 get supportMulti() {
7627 return this._rpcCore.provider.hasSubscriptions || !!this._rpcCore.state.queryStorageAt;
7628 }
7629 _emptyDecorated(registry, blockHash) {
7630 return {
7631 consts: {},
7632 errors: {},
7633 events: {},
7634 query: {},
7635 registry,
7636 rx: {
7637 query: {}
7638 },
7639 tx: createSubmittable(this._type, this._rx, this._decorateMethod, registry, blockHash)
7640 };
7641 }
7642 _createDecorated(registry, fromEmpty, decoratedApi, blockHash) {
7643 if (!decoratedApi) {
7644 decoratedApi = this._emptyDecorated(registry.registry, blockHash);
7645 }
7646 if (fromEmpty || !registry.decoratedMeta) {
7647 registry.decoratedMeta = types.expandMetadata(registry.registry, registry.metadata);
7648 }
7649 const storage = this._decorateStorage(registry.decoratedMeta, this._decorateMethod, blockHash);
7650 const storageRx = this._decorateStorage(registry.decoratedMeta, this._rxDecorateMethod, blockHash);
7651 augmentObject('consts', registry.decoratedMeta.consts, decoratedApi.consts, fromEmpty);
7652 augmentObject('errors', registry.decoratedMeta.errors, decoratedApi.errors, fromEmpty);
7653 augmentObject('events', registry.decoratedMeta.events, decoratedApi.events, fromEmpty);
7654 augmentObject('query', storage, decoratedApi.query, fromEmpty);
7655 augmentObject('query', storageRx, decoratedApi.rx.query, fromEmpty);
7656 decoratedApi.findCall = callIndex => findCall(registry.registry, callIndex);
7657 decoratedApi.findError = errorIndex => findError(registry.registry, errorIndex);
7658 decoratedApi.queryMulti = blockHash ? this._decorateMultiAt(decoratedApi, this._decorateMethod, blockHash) : this._decorateMulti(this._decorateMethod);
7659 decoratedApi.runtimeVersion = registry.runtimeVersion;
7660 return {
7661 decoratedApi,
7662 decoratedMeta: registry.decoratedMeta
7663 };
7664 }
7665 _injectMetadata(registry, fromEmpty = false) {
7666 if (fromEmpty || !registry.decoratedApi) {
7667 registry.decoratedApi = this._emptyDecorated(registry.registry);
7668 }
7669 const {
7670 decoratedApi,
7671 decoratedMeta
7672 } = this._createDecorated(registry, fromEmpty, registry.decoratedApi);
7673 this._consts = decoratedApi.consts;
7674 this._errors = decoratedApi.errors;
7675 this._events = decoratedApi.events;
7676 this._query = decoratedApi.query;
7677 this._rx.query = decoratedApi.rx.query;
7678 const tx = this._decorateExtrinsics(decoratedMeta, this._decorateMethod);
7679 const rxtx = this._decorateExtrinsics(decoratedMeta, this._rxDecorateMethod);
7680 if (fromEmpty || !this._extrinsics) {
7681 this._extrinsics = tx;
7682 this._rx.tx = rxtx;
7683 } else {
7684 augmentObject('tx', tx, this._extrinsics, false);
7685 augmentObject(null, rxtx, this._rx.tx, false);
7686 }
7687 augmentObject(null, decoratedMeta.consts, this._rx.consts, fromEmpty);
7688 this.emit('decorated');
7689 }
7690 injectMetadata(metadata, fromEmpty, registry) {
7691 this._injectMetadata({
7692 metadata,
7693 registry: registry || this.#registry,
7694 runtimeVersion: this.#registry.createType('RuntimeVersionPartial')
7695 }, fromEmpty);
7696 }
7697 _decorateFunctionMeta(input, output) {
7698 output.meta = input.meta;
7699 output.method = input.method;
7700 output.section = input.section;
7701 output.toJSON = input.toJSON;
7702 if (input.callIndex) {
7703 output.callIndex = input.callIndex;
7704 }
7705 return output;
7706 }
7707 _filterRpc(methods, additional) {
7708 if (Object.keys(additional).length !== 0) {
7709 this._rpcCore.addUserInterfaces(additional);
7710 this._decorateRpc(this._rpcCore, this._decorateMethod, this._rpc);
7711 this._decorateRpc(this._rpcCore, this._rxDecorateMethod, this._rx.rpc);
7712 }
7713 this._filterRpcMethods(methods);
7714 }
7715 _filterRpcMethods(exposed) {
7716 const hasResults = exposed.length !== 0;
7717 const allKnown = [...this._rpcCore.mapping.entries()];
7718 const allKeys = [];
7719 for (let i = 0; i < allKnown.length; i++) {
7720 const [, {
7721 alias,
7722 endpoint,
7723 method,
7724 pubsub,
7725 section
7726 }] = allKnown[i];
7727 allKeys.push(`${section}_${method}`);
7728 if (pubsub) {
7729 allKeys.push(`${section}_${pubsub[1]}`);
7730 allKeys.push(`${section}_${pubsub[2]}`);
7731 }
7732 if (alias) {
7733 allKeys.push(...alias);
7734 }
7735 if (endpoint) {
7736 allKeys.push(endpoint);
7737 }
7738 }
7739 const filterKey = k => !allKeys.includes(k);
7740 const unknown = exposed.filter(filterKey);
7741 if (unknown.length) {
7742 l$1.warn(`RPC methods not decorated: ${unknown.join(', ')}`);
7743 }
7744 for (let i = 0; i < allKnown.length; i++) {
7745 const [k, {
7746 method,
7747 section
7748 }] = allKnown[i];
7749 if (hasResults && !exposed.includes(k) && k !== 'rpc_methods') {
7750 if (this._rpc[section]) {
7751 delete this._rpc[section][method];
7752 delete this._rx.rpc[section][method];
7753 }
7754 }
7755 }
7756 }
7757 _decorateRpc(rpc, decorateMethod, input = {}) {
7758 const out = input;
7759 const decorateFn = (section, method) => {
7760 const source = rpc[section][method];
7761 const fn = decorateMethod(source, {
7762 methodName: method
7763 });
7764 fn.meta = source.meta;
7765 fn.raw = decorateMethod(source.raw, {
7766 methodName: method
7767 });
7768 return fn;
7769 };
7770 for (let s = 0; s < rpc.sections.length; s++) {
7771 const section = rpc.sections[s];
7772 if (!Object.prototype.hasOwnProperty.call(out, section)) {
7773 const methods = Object.keys(rpc[section]);
7774 const decorateInternal = method => decorateFn(section, method);
7775 for (let m = 0; m < methods.length; m++) {
7776 const method = methods[m];
7777 if (this.hasSubscriptions || !(method.startsWith('subscribe') || method.startsWith('unsubscribe'))) {
7778 if (!Object.prototype.hasOwnProperty.call(out, section)) {
7779 out[section] = {};
7780 }
7781 util.lazyMethod(out[section], method, decorateInternal);
7782 }
7783 }
7784 }
7785 }
7786 return out;
7787 }
7788 _decorateMulti(decorateMethod) {
7789 return decorateMethod(keys => (this.hasSubscriptions ? this._rpcCore.state.subscribeStorage : this._rpcCore.state.queryStorageAt)(keys.map(args => Array.isArray(args) ? args[0].creator.meta.type.isPlain ? [args[0].creator] : args[0].creator.meta.type.asMap.hashers.length === 1 ? [args[0].creator, args.slice(1)] : [args[0].creator, ...args.slice(1)] : [args.creator])));
7790 }
7791 _decorateMultiAt(atApi, decorateMethod, blockHash) {
7792 return decorateMethod(calls => this._rpcCore.state.queryStorageAt(calls.map(args => {
7793 if (Array.isArray(args)) {
7794 const {
7795 creator
7796 } = getAtQueryFn(atApi, args[0].creator);
7797 return creator.meta.type.isPlain ? [creator] : creator.meta.type.asMap.hashers.length === 1 ? [creator, args.slice(1)] : [creator, ...args.slice(1)];
7798 }
7799 return [getAtQueryFn(atApi, args.creator).creator];
7800 }), blockHash));
7801 }
7802 _decorateExtrinsics({
7803 tx
7804 }, decorateMethod) {
7805 const result = createSubmittable(this._type, this._rx, decorateMethod);
7806 const lazySection = section => util.lazyMethods({}, Object.keys(tx[section]), method => this._decorateExtrinsicEntry(tx[section][method], result));
7807 const sections = Object.keys(tx);
7808 for (let i = 0; i < sections.length; i++) {
7809 util.lazyMethod(result, sections[i], lazySection);
7810 }
7811 return result;
7812 }
7813 _decorateExtrinsicEntry(method, creator) {
7814 const decorated = (...params) => creator(method(...params));
7815 decorated.is = other => method.is(other);
7816 return this._decorateFunctionMeta(method, decorated);
7817 }
7818 _decorateStorage({
7819 query,
7820 registry
7821 }, decorateMethod, blockHash) {
7822 const result = {};
7823 const lazySection = section => util.lazyMethods({}, Object.keys(query[section]), method => blockHash ? this._decorateStorageEntryAt(registry, query[section][method], decorateMethod, blockHash) : this._decorateStorageEntry(query[section][method], decorateMethod));
7824 const sections = Object.keys(query);
7825 for (let i = 0; i < sections.length; i++) {
7826 util.lazyMethod(result, sections[i], lazySection);
7827 }
7828 return result;
7829 }
7830 _decorateStorageEntry(creator, decorateMethod) {
7831 const getArgs = (args, registry) => extractStorageArgs(registry || this.#registry, creator, args);
7832 const getQueryAt = blockHash => from(this.at(blockHash)).pipe(map(api => getAtQueryFn(api, creator)));
7833 const decorated = this._decorateStorageCall(creator, decorateMethod);
7834 decorated.creator = creator;
7835 decorated.at = decorateMethod((blockHash, ...args) => getQueryAt(blockHash).pipe(switchMap(q => q(...args))));
7836 decorated.hash = decorateMethod((...args) => this._rpcCore.state.getStorageHash(getArgs(args)));
7837 decorated.is = key => key.section === creator.section && key.method === creator.method;
7838 decorated.key = (...args) => util.u8aToHex(util.compactStripLength(creator(...args))[1]);
7839 decorated.keyPrefix = (...args) => util.u8aToHex(creator.keyPrefix(...args));
7840 decorated.range = decorateMethod((range, ...args) => this._decorateStorageRange(decorated, args, range));
7841 decorated.size = decorateMethod((...args) => this._rpcCore.state.getStorageSize(getArgs(args)));
7842 decorated.sizeAt = decorateMethod((blockHash, ...args) => getQueryAt(blockHash).pipe(switchMap(q => this._rpcCore.state.getStorageSize(getArgs(args, q.creator.meta.registry), blockHash))));
7843 if (creator.iterKey && creator.meta.type.isMap) {
7844 decorated.entries = decorateMethod(memo(this.#instanceId, (...args) => this._retrieveMapEntries(creator, null, args)));
7845 decorated.entriesAt = decorateMethod(memo(this.#instanceId, (blockHash, ...args) => getQueryAt(blockHash).pipe(switchMap(q => this._retrieveMapEntries(q.creator, blockHash, args)))));
7846 decorated.entriesPaged = decorateMethod(memo(this.#instanceId, opts => this._retrieveMapEntriesPaged(creator, undefined, opts)));
7847 decorated.keys = decorateMethod(memo(this.#instanceId, (...args) => this._retrieveMapKeys(creator, null, args)));
7848 decorated.keysAt = decorateMethod(memo(this.#instanceId, (blockHash, ...args) => getQueryAt(blockHash).pipe(switchMap(q => this._retrieveMapKeys(q.creator, blockHash, args)))));
7849 decorated.keysPaged = decorateMethod(memo(this.#instanceId, opts => this._retrieveMapKeysPaged(creator, undefined, opts)));
7850 }
7851 if (this.supportMulti && creator.meta.type.isMap) {
7852 decorated.multi = decorateMethod(args => creator.meta.type.asMap.hashers.length === 1 ? this._retrieveMulti(args.map(a => [creator, [a]])) : this._retrieveMulti(args.map(a => [creator, a])));
7853 }
7854 return this._decorateFunctionMeta(creator, decorated);
7855 }
7856 _decorateStorageEntryAt(registry, creator, decorateMethod, blockHash) {
7857 const getArgs = args => extractStorageArgs(registry, creator, args);
7858 const decorated = decorateMethod((...args) => this._rpcCore.state.getStorage(getArgs(args), blockHash));
7859 decorated.creator = creator;
7860 decorated.hash = decorateMethod((...args) => this._rpcCore.state.getStorageHash(getArgs(args), blockHash));
7861 decorated.is = key => key.section === creator.section && key.method === creator.method;
7862 decorated.key = (...args) => util.u8aToHex(util.compactStripLength(creator(creator.meta.type.isPlain ? undefined : args))[1]);
7863 decorated.keyPrefix = (...keys) => util.u8aToHex(creator.keyPrefix(...keys));
7864 decorated.size = decorateMethod((...args) => this._rpcCore.state.getStorageSize(getArgs(args), blockHash));
7865 if (creator.iterKey && creator.meta.type.isMap) {
7866 decorated.entries = decorateMethod(memo(this.#instanceId, (...args) => this._retrieveMapEntries(creator, blockHash, args)));
7867 decorated.entriesPaged = decorateMethod(memo(this.#instanceId, opts => this._retrieveMapEntriesPaged(creator, blockHash, opts)));
7868 decorated.keys = decorateMethod(memo(this.#instanceId, (...args) => this._retrieveMapKeys(creator, blockHash, args)));
7869 decorated.keysPaged = decorateMethod(memo(this.#instanceId, opts => this._retrieveMapKeysPaged(creator, blockHash, opts)));
7870 }
7871 if (this.supportMulti && creator.meta.type.isMap) {
7872 decorated.multi = decorateMethod(args => creator.meta.type.asMap.hashers.length === 1 ? this._retrieveMulti(args.map(a => [creator, [a]]), blockHash) : this._retrieveMulti(args.map(a => [creator, a]), blockHash));
7873 }
7874 return this._decorateFunctionMeta(creator, decorated);
7875 }
7876 _queueStorage(call, queue) {
7877 const query = queue === this.#storageSubQ ? this._rpcCore.state.subscribeStorage : this._rpcCore.state.queryStorageAt;
7878 let queueIdx = queue.length - 1;
7879 let valueIdx = 0;
7880 let valueObs;
7881 if (queueIdx === -1 || !queue[queueIdx] || queue[queueIdx][1].length === PAGE_SIZE_Q) {
7882 queueIdx++;
7883 valueObs = from(
7884 Promise.resolve().then(() => {
7885 const calls = queue[queueIdx][1];
7886 delete queue[queueIdx];
7887 return calls;
7888 })).pipe(switchMap(calls => query(calls)));
7889 queue.push([valueObs, [call]]);
7890 } else {
7891 valueObs = queue[queueIdx][0];
7892 valueIdx = queue[queueIdx][1].length;
7893 queue[queueIdx][1].push(call);
7894 }
7895 return valueObs.pipe(map(values => values[valueIdx]));
7896 }
7897 _decorateStorageCall(creator, decorateMethod) {
7898 return decorateMethod((...args) => {
7899 const call = extractStorageArgs(this.#registry, creator, args);
7900 if (!this.hasSubscriptions) {
7901 return this._rpcCore.state.getStorage(call);
7902 }
7903 return this._queueStorage(call, this.#storageSubQ);
7904 }, {
7905 methodName: creator.method,
7906 overrideNoSub: (...args) => this._queueStorage(extractStorageArgs(this.#registry, creator, args), this.#storageGetQ)
7907 });
7908 }
7909 _decorateStorageRange(decorated, args, range) {
7910 const outputType = types.unwrapStorageType(this.#registry, decorated.creator.meta.type, decorated.creator.meta.modifier.isOptional);
7911 return this._rpcCore.state.queryStorage([decorated.key(...args)], ...range).pipe(map(result => result.map(([blockHash, [value]]) => [blockHash, this.createType(outputType, value.isSome ? value.unwrap().toHex() : undefined)])));
7912 }
7913 _retrieveMulti(keys, blockHash) {
7914 if (!keys.length) {
7915 return of([]);
7916 }
7917 const query = this.hasSubscriptions && !blockHash ? this._rpcCore.state.subscribeStorage : this._rpcCore.state.queryStorageAt;
7918 if (keys.length <= PAGE_SIZE_V) {
7919 return blockHash ? query(keys, blockHash) : query(keys);
7920 }
7921 return combineLatest(util.arrayChunk(keys, PAGE_SIZE_V).map(k => blockHash ? query(k, blockHash) : query(k))).pipe(map(util.arrayFlatten));
7922 }
7923 _retrieveMapKeys({
7924 iterKey,
7925 meta,
7926 method,
7927 section
7928 }, at, args) {
7929 util.assert(iterKey && meta.type.isMap, 'keys can only be retrieved on maps');
7930 const headKey = iterKey(...args).toHex();
7931 const startSubject = new BehaviorSubject(headKey);
7932 const query = at ? startKey => this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey, at) : startKey => this._rpcCore.state.getKeysPaged(headKey, PAGE_SIZE_K, startKey);
7933 const setMeta = key => key.setMeta(meta, section, method);
7934 return startSubject.pipe(switchMap(query), map(keys => keys.map(setMeta)), tap(keys => util.nextTick(() => {
7935 keys.length === PAGE_SIZE_K ? startSubject.next(keys[PAGE_SIZE_K - 1].toHex()) : startSubject.complete();
7936 })), toArray(),
7937 map(util.arrayFlatten));
7938 }
7939 _retrieveMapKeysPaged({
7940 iterKey,
7941 meta,
7942 method,
7943 section
7944 }, at, opts) {
7945 util.assert(iterKey && meta.type.isMap, 'keys can only be retrieved on maps');
7946 const setMeta = key => key.setMeta(meta, section, method);
7947 const query = at ? headKey => this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey, at) : headKey => this._rpcCore.state.getKeysPaged(headKey, opts.pageSize, opts.startKey || headKey);
7948 return query(iterKey(...opts.args).toHex()).pipe(map(keys => keys.map(setMeta)));
7949 }
7950 _retrieveMapEntries(entry, at, args) {
7951 const query = at ? keys => this._rpcCore.state.queryStorageAt(keys, at) : keys => this._rpcCore.state.queryStorageAt(keys);
7952 return this._retrieveMapKeys(entry, at, args).pipe(switchMap(keys => keys.length ? combineLatest(util.arrayChunk(keys, PAGE_SIZE_V).map(query)).pipe(map(valsArr => util.arrayFlatten(valsArr).map((value, index) => [keys[index], value]))) : of([])));
7953 }
7954 _retrieveMapEntriesPaged(entry, at, opts) {
7955 const query = at ? keys => this._rpcCore.state.queryStorageAt(keys, at) : keys => this._rpcCore.state.queryStorageAt(keys);
7956 return this._retrieveMapKeysPaged(entry, at, opts).pipe(switchMap(keys => keys.length ? query(keys).pipe(map(valsArr => valsArr.map((value, index) => [keys[index], value]))) : of([])));
7957 }
7958 _decorateDeriveRx(decorateMethod) {
7959 var _this$_runtimeVersion, _this$_options$typesB, _this$_options$typesB2, _this$_options$typesB3;
7960 const specName = (_this$_runtimeVersion = this._runtimeVersion) === null || _this$_runtimeVersion === void 0 ? void 0 : _this$_runtimeVersion.specName.toString();
7961 const available = getAvailableDerives(this.#instanceId, this._rx, util.objectSpread({}, this._options.derives, (_this$_options$typesB = this._options.typesBundle) === null || _this$_options$typesB === void 0 ? void 0 : (_this$_options$typesB2 = _this$_options$typesB.spec) === null || _this$_options$typesB2 === void 0 ? void 0 : (_this$_options$typesB3 = _this$_options$typesB2[specName || '']) === null || _this$_options$typesB3 === void 0 ? void 0 : _this$_options$typesB3.derives));
7962 return decorateDeriveSections(decorateMethod, available);
7963 }
7964 _decorateDerive(decorateMethod) {
7965 return decorateDeriveSections(decorateMethod, this._rx.derive);
7966 }
7967 _rxDecorateMethod = method => {
7968 return method;
7969 };
7970 }
7971
7972 const KEEPALIVE_INTERVAL = 10000;
7973 const l = util.logger('api/init');
7974 function textToString(t) {
7975 return t.toString();
7976 }
7977 var _healthTimer = _classPrivateFieldKey("healthTimer");
7978 var _registries = _classPrivateFieldKey("registries");
7979 var _updateSub = _classPrivateFieldKey("updateSub");
7980 var _waitingRegistries = _classPrivateFieldKey("waitingRegistries");
7981 var _onProviderConnect = _classPrivateFieldKey("onProviderConnect");
7982 var _onProviderDisconnect = _classPrivateFieldKey("onProviderDisconnect");
7983 var _onProviderError = _classPrivateFieldKey("onProviderError");
7984 class Init extends Decorate {
7985 constructor(options, type, decorateMethod) {
7986 super(options, type, decorateMethod);
7987 Object.defineProperty(this, _onProviderError, {
7988 value: _onProviderError2
7989 });
7990 Object.defineProperty(this, _onProviderDisconnect, {
7991 value: _onProviderDisconnect2
7992 });
7993 Object.defineProperty(this, _onProviderConnect, {
7994 value: _onProviderConnect2
7995 });
7996 Object.defineProperty(this, _healthTimer, {
7997 writable: true,
7998 value: null
7999 });
8000 Object.defineProperty(this, _registries, {
8001 writable: true,
8002 value: []
8003 });
8004 Object.defineProperty(this, _updateSub, {
8005 writable: true,
8006 value: null
8007 });
8008 Object.defineProperty(this, _waitingRegistries, {
8009 writable: true,
8010 value: {}
8011 });
8012 this.registry.setKnownTypes(options);
8013 if (!options.source) {
8014 this.registerTypes(options.types);
8015 } else {
8016 _classPrivateFieldBase(this, _registries)[_registries] = _classPrivateFieldBase(options.source, _registries)[_registries];
8017 }
8018 this._rpc = this._decorateRpc(this._rpcCore, this._decorateMethod);
8019 this._rx.rpc = this._decorateRpc(this._rpcCore, this._rxDecorateMethod);
8020 if (this.supportMulti) {
8021 this._queryMulti = this._decorateMulti(this._decorateMethod);
8022 this._rx.queryMulti = this._decorateMulti(this._rxDecorateMethod);
8023 }
8024 this._rx.signer = options.signer;
8025 this._rpcCore.setRegistrySwap(blockHash => this.getBlockRegistry(blockHash));
8026 this._rpcCore.setResolveBlockHash(blockNumber => firstValueFrom(this._rpcCore.chain.getBlockHash(blockNumber)));
8027 if (this.hasSubscriptions) {
8028 this._rpcCore.provider.on('disconnected', () => _classPrivateFieldBase(this, _onProviderDisconnect)[_onProviderDisconnect]());
8029 this._rpcCore.provider.on('error', e => _classPrivateFieldBase(this, _onProviderError)[_onProviderError](e));
8030 this._rpcCore.provider.on('connected', () => _classPrivateFieldBase(this, _onProviderConnect)[_onProviderConnect]());
8031 } else {
8032 l.warn('Api will be available in a limited mode since the provider does not support subscriptions');
8033 }
8034 if (this._rpcCore.provider.isConnected) {
8035 _classPrivateFieldBase(this, _onProviderConnect)[_onProviderConnect]();
8036 }
8037 }
8038 _initRegistry(registry, chain, version, metadata, chainProps) {
8039 registry.clearCache();
8040 registry.setChainProperties(chainProps || this.registry.getChainProperties());
8041 registry.setKnownTypes(this._options);
8042 registry.register(getSpecTypes(registry, chain, version.specName, version.specVersion));
8043 registry.setHasher(getSpecHasher(registry, chain, version.specName));
8044 if (registry.knownTypes.typesBundle) {
8045 registry.knownTypes.typesAlias = getSpecAlias(registry, chain, version.specName);
8046 }
8047 registry.setMetadata(metadata, undefined, util.objectSpread({}, getSpecExtensions(registry, chain, version.specName), this._options.signedExtensions));
8048 }
8049 _getDefaultRegistry() {
8050 return util.assertReturn(_classPrivateFieldBase(this, _registries)[_registries].find(({
8051 isDefault
8052 }) => isDefault), 'Initialization error, cannot find the default registry');
8053 }
8054 async at(blockHash, knownVersion) {
8055 const u8aHash = util.u8aToU8a(blockHash);
8056 const registry = await this.getBlockRegistry(u8aHash, knownVersion);
8057 return this._createDecorated(registry, true, null, u8aHash).decoratedApi;
8058 }
8059 async _createBlockRegistry(blockHash, header, version) {
8060 const registry = new types.TypeRegistry(blockHash);
8061 const metadata = new types.Metadata(registry, await firstValueFrom(this._rpcCore.state.getMetadata.raw(header.parentHash)));
8062 this._initRegistry(registry, this._runtimeChain, version, metadata);
8063 const result = {
8064 lastBlockHash: blockHash,
8065 metadata,
8066 registry,
8067 runtimeVersion: version
8068 };
8069 _classPrivateFieldBase(this, _registries)[_registries].push(result);
8070 return result;
8071 }
8072 _cacheBlockRegistryProgress(key, creator) {
8073 let waiting = _classPrivateFieldBase(this, _waitingRegistries)[_waitingRegistries][key];
8074 if (util.isUndefined(waiting)) {
8075 waiting = _classPrivateFieldBase(this, _waitingRegistries)[_waitingRegistries][key] = new Promise((resolve, reject) => {
8076 creator().then(registry => {
8077 delete _classPrivateFieldBase(this, _waitingRegistries)[_waitingRegistries][key];
8078 resolve(registry);
8079 }).catch(error => {
8080 delete _classPrivateFieldBase(this, _waitingRegistries)[_waitingRegistries][key];
8081 reject(error);
8082 });
8083 });
8084 }
8085 return waiting;
8086 }
8087 _getBlockRegistryViaVersion(blockHash, version) {
8088 if (version) {
8089 const existingViaVersion = _classPrivateFieldBase(this, _registries)[_registries].find(({
8090 runtimeVersion: {
8091 specName,
8092 specVersion
8093 }
8094 }) => specName.eq(version.specName) && specVersion.eq(version.specVersion));
8095 if (existingViaVersion) {
8096 existingViaVersion.lastBlockHash = blockHash;
8097 return existingViaVersion;
8098 }
8099 }
8100 return null;
8101 }
8102 async _getBlockRegistryViaHash(blockHash) {
8103 util.assert(this._genesisHash && this._runtimeVersion, 'Cannot retrieve data on an uninitialized chain');
8104 const header = this.registry.createType('HeaderPartial', this._genesisHash.eq(blockHash) ? {
8105 number: util.BN_ZERO,
8106 parentHash: this._genesisHash
8107 } : await firstValueFrom(this._rpcCore.chain.getHeader.raw(blockHash)));
8108 util.assert(!header.parentHash.isEmpty, 'Unable to retrieve header and parent from supplied hash');
8109 const [firstVersion, lastVersion] = getUpgradeVersion(this._genesisHash, header.number);
8110 const version = this.registry.createType('RuntimeVersionPartial', firstVersion && (lastVersion || firstVersion.specVersion.eq(this._runtimeVersion.specVersion)) ? {
8111 specName: this._runtimeVersion.specName,
8112 specVersion: firstVersion.specVersion
8113 } : await firstValueFrom(this._rpcCore.state.getRuntimeVersion.raw(header.parentHash)));
8114 return (
8115 this._getBlockRegistryViaVersion(blockHash, version) || (
8116 await this._cacheBlockRegistryProgress(version.toHex(), () => this._createBlockRegistry(blockHash, header, version)))
8117 );
8118 }
8119 async getBlockRegistry(blockHash, knownVersion) {
8120 return (
8121 _classPrivateFieldBase(this, _registries)[_registries].find(({
8122 lastBlockHash
8123 }) => lastBlockHash && util.u8aEq(lastBlockHash, blockHash)) ||
8124 this._getBlockRegistryViaVersion(blockHash, knownVersion) || (
8125 await this._cacheBlockRegistryProgress(util.u8aToHex(blockHash), () => this._getBlockRegistryViaHash(blockHash)))
8126 );
8127 }
8128 async _loadMeta() {
8129 var _this$_options$source;
8130 if (this._isReady) {
8131 return true;
8132 }
8133 this._unsubscribeUpdates();
8134 [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);
8135 return this._initFromMeta(this._runtimeMetadata);
8136 }
8137 async _metaFromSource(source) {
8138 this._extrinsicType = source.extrinsicVersion;
8139 this._runtimeChain = source.runtimeChain;
8140 this._runtimeVersion = source.runtimeVersion;
8141 const sections = Object.keys(source.rpc);
8142 const rpcs = [];
8143 for (let s = 0; s < sections.length; s++) {
8144 const section = sections[s];
8145 const methods = Object.keys(source.rpc[section]);
8146 for (let m = 0; m < methods.length; m++) {
8147 rpcs.push(`${section}_${methods[m]}`);
8148 }
8149 }
8150 this._filterRpc(rpcs, getSpecRpc(this.registry, source.runtimeChain, source.runtimeVersion.specName));
8151 return [source.genesisHash, source.runtimeMetadata];
8152 }
8153 _subscribeUpdates() {
8154 if (_classPrivateFieldBase(this, _updateSub)[_updateSub] || !this.hasSubscriptions) {
8155 return;
8156 }
8157 _classPrivateFieldBase(this, _updateSub)[_updateSub] = this._rpcCore.state.subscribeRuntimeVersion().pipe(switchMap(version => {
8158 var _this$_runtimeVersion;
8159 return (
8160 (_this$_runtimeVersion = this._runtimeVersion) !== null && _this$_runtimeVersion !== void 0 && _this$_runtimeVersion.specVersion.eq(version.specVersion) ? of(false) : this._rpcCore.state.getMetadata().pipe(map(metadata => {
8161 l.log(`Runtime version updated to spec=${version.specVersion.toString()}, tx=${version.transactionVersion.toString()}`);
8162 this._runtimeMetadata = metadata;
8163 this._runtimeVersion = version;
8164 this._rx.runtimeVersion = version;
8165 const thisRegistry = this._getDefaultRegistry();
8166 thisRegistry.metadata = metadata;
8167 thisRegistry.runtimeVersion = version;
8168 this._initRegistry(this.registry, this._runtimeChain, version, metadata);
8169 this._injectMetadata(thisRegistry, true);
8170 return true;
8171 }))
8172 );
8173 })).subscribe();
8174 }
8175 async _metaFromChain(optMetadata) {
8176 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())]);
8177 this._runtimeChain = chain;
8178 this._runtimeVersion = runtimeVersion;
8179 this._rx.runtimeVersion = runtimeVersion;
8180 const metadataKey = `${genesisHash.toHex() || '0x'}-${runtimeVersion.specVersion.toString()}`;
8181 const metadata = chainMetadata || (optMetadata && optMetadata[metadataKey] ? new types.Metadata(this.registry, optMetadata[metadataKey]) : await firstValueFrom(this._rpcCore.state.getMetadata()));
8182 this._initRegistry(this.registry, chain, runtimeVersion, metadata, chainProps);
8183 this._filterRpc(rpcMethods.methods.map(textToString), getSpecRpc(this.registry, chain, runtimeVersion.specName));
8184 this._subscribeUpdates();
8185 if (!_classPrivateFieldBase(this, _registries)[_registries].length) {
8186 _classPrivateFieldBase(this, _registries)[_registries].push({
8187 isDefault: true,
8188 metadata,
8189 registry: this.registry,
8190 runtimeVersion
8191 });
8192 }
8193 metadata.getUniqTypes(this._options.throwOnUnknown || false);
8194 return [genesisHash, metadata];
8195 }
8196 _initFromMeta(metadata) {
8197 this._extrinsicType = metadata.asLatest.extrinsic.version.toNumber();
8198 this._rx.extrinsicType = this._extrinsicType;
8199 this._rx.genesisHash = this._genesisHash;
8200 this._rx.runtimeVersion = this._runtimeVersion;
8201 this._injectMetadata(this._getDefaultRegistry(), true);
8202 this._rx.derive = this._decorateDeriveRx(this._rxDecorateMethod);
8203 this._derive = this._decorateDerive(this._decorateMethod);
8204 return true;
8205 }
8206 _subscribeHealth() {
8207 _classPrivateFieldBase(this, _healthTimer)[_healthTimer] = this.hasSubscriptions ? setInterval(() => {
8208 firstValueFrom(this._rpcCore.system.health.raw()).catch(() => undefined);
8209 }, KEEPALIVE_INTERVAL) : null;
8210 }
8211 _unsubscribeHealth() {
8212 if (_classPrivateFieldBase(this, _healthTimer)[_healthTimer]) {
8213 clearInterval(_classPrivateFieldBase(this, _healthTimer)[_healthTimer]);
8214 _classPrivateFieldBase(this, _healthTimer)[_healthTimer] = null;
8215 }
8216 }
8217 _unsubscribeUpdates() {
8218 if (_classPrivateFieldBase(this, _updateSub)[_updateSub]) {
8219 _classPrivateFieldBase(this, _updateSub)[_updateSub].unsubscribe();
8220 _classPrivateFieldBase(this, _updateSub)[_updateSub] = null;
8221 }
8222 }
8223 _unsubscribe() {
8224 this._unsubscribeHealth();
8225 this._unsubscribeUpdates();
8226 }
8227 }
8228 async function _onProviderConnect2() {
8229 this._isConnected.next(true);
8230 this.emit('connected');
8231 try {
8232 const cryptoReady = this._options.initWasm === false ? true : await utilCrypto.cryptoWaitReady();
8233 const hasMeta = await this._loadMeta();
8234 this._subscribeHealth();
8235 if (hasMeta && !this._isReady && cryptoReady) {
8236 this._isReady = true;
8237 this.emit('ready', this);
8238 }
8239 } catch (_error) {
8240 const error = new Error(`FATAL: Unable to initialize the API: ${_error.message}`);
8241 l.error(error);
8242 this.emit('error', error);
8243 }
8244 }
8245 function _onProviderDisconnect2() {
8246 this._isConnected.next(false);
8247 this._unsubscribeHealth();
8248 this.emit('disconnected');
8249 }
8250 function _onProviderError2(error) {
8251 this.emit('error', error);
8252 }
8253
8254 function assertResult(value) {
8255 return util.assertReturn(value, 'Api needs to be initialized before using, listen on \'ready\'');
8256 }
8257 class Getters extends Init {
8258 get consts() {
8259 return assertResult(this._consts);
8260 }
8261 get derive() {
8262 return assertResult(this._derive);
8263 }
8264 get errors() {
8265 return assertResult(this._errors);
8266 }
8267 get events() {
8268 return assertResult(this._events);
8269 }
8270 get extrinsicVersion() {
8271 return this._extrinsicType;
8272 }
8273 get genesisHash() {
8274 return assertResult(this._genesisHash);
8275 }
8276 get isConnected() {
8277 return this._isConnected.getValue();
8278 }
8279 get libraryInfo() {
8280 return `${packageInfo.name} v${packageInfo.version}`;
8281 }
8282 get query() {
8283 return assertResult(this._query);
8284 }
8285 get queryMulti() {
8286 return assertResult(this._queryMulti);
8287 }
8288 get rpc() {
8289 return assertResult(this._rpc);
8290 }
8291 get runtimeChain() {
8292 return assertResult(this._runtimeChain);
8293 }
8294 get runtimeMetadata() {
8295 return assertResult(this._runtimeMetadata);
8296 }
8297 get runtimeVersion() {
8298 return assertResult(this._runtimeVersion);
8299 }
8300 get rx() {
8301 return assertResult(this._rx);
8302 }
8303 get stats() {
8304 return this._rpcCore.provider.stats;
8305 }
8306 get type() {
8307 return this._type;
8308 }
8309 get tx() {
8310 return assertResult(this._extrinsics);
8311 }
8312 findCall(callIndex) {
8313 return findCall(this.registry, callIndex);
8314 }
8315 findError(errorIndex) {
8316 return findError(this.registry, errorIndex);
8317 }
8318 }
8319
8320 class ApiBase extends Getters {
8321 constructor(options = {}, type, decorateMethod) {
8322 super(options, type, decorateMethod);
8323 }
8324 connect() {
8325 return this._rpcCore.connect();
8326 }
8327 disconnect() {
8328 this._unsubscribe();
8329 return this._rpcCore.disconnect();
8330 }
8331 setSigner(signer) {
8332 this._rx.signer = signer;
8333 }
8334 async sign(address, data, {
8335 signer
8336 } = {}) {
8337 if (util.isString(address)) {
8338 const _signer = signer || this._rx.signer;
8339 util.assert(_signer === null || _signer === void 0 ? void 0 : _signer.signRaw, 'No signer exists with a signRaw interface. You possibly need to pass through an explicit keypair for the origin so it can be used for signing.');
8340 return (await _signer.signRaw(util.objectSpread({
8341 type: 'bytes'
8342 }, data, {
8343 address
8344 }))).signature;
8345 }
8346 return util.u8aToHex(address.sign(util.u8aToU8a(data.data)));
8347 }
8348 }
8349
8350 class Combinator {
8351 #allHasFired = false;
8352 #callback;
8353 #fired = [];
8354 #fns = [];
8355 #isActive = true;
8356 #results = [];
8357 #subscriptions = [];
8358 constructor(fns, callback) {
8359 this.#callback = callback;
8360 this.#subscriptions = fns.map(async (input, index) => {
8361 const [fn, ...args] = Array.isArray(input) ? input : [input];
8362 this.#fired.push(false);
8363 this.#fns.push(fn);
8364 return fn(...args, this._createCallback(index));
8365 });
8366 }
8367 _allHasFired() {
8368 this.#allHasFired || (this.#allHasFired = this.#fired.filter(hasFired => !hasFired).length === 0);
8369 return this.#allHasFired;
8370 }
8371 _createCallback(index) {
8372 return value => {
8373 this.#fired[index] = true;
8374 this.#results[index] = value;
8375 this._triggerUpdate();
8376 };
8377 }
8378 _triggerUpdate() {
8379 if (!this.#isActive || !util.isFunction(this.#callback) || !this._allHasFired()) {
8380 return;
8381 }
8382 try {
8383 this.#callback(this.#results);
8384 } catch (error) {
8385 }
8386 }
8387 unsubscribe() {
8388 if (!this.#isActive) {
8389 return;
8390 }
8391 this.#isActive = false;
8392 this.#subscriptions.forEach(async subscription => {
8393 try {
8394 const unsubscribe = await subscription;
8395 if (util.isFunction(unsubscribe)) {
8396 unsubscribe();
8397 }
8398 } catch (error) {
8399 }
8400 });
8401 }
8402 }
8403
8404 function promiseTracker(resolve, reject) {
8405 let isCompleted = false;
8406 return {
8407 reject: error => {
8408 if (!isCompleted) {
8409 isCompleted = true;
8410 reject(error);
8411 }
8412 return EMPTY;
8413 },
8414 resolve: value => {
8415 if (!isCompleted) {
8416 isCompleted = true;
8417 resolve(value);
8418 }
8419 }
8420 };
8421 }
8422 function extractArgs(args, needsCallback) {
8423 const actualArgs = args.slice();
8424 const callback = args.length && util.isFunction(args[args.length - 1]) ? actualArgs.pop() : undefined;
8425 util.assert(!needsCallback || util.isFunction(callback), 'Expected a callback to be passed with subscriptions');
8426 return [actualArgs, callback];
8427 }
8428 function decorateCall(method, args) {
8429 return new Promise((resolve, reject) => {
8430 const tracker = promiseTracker(resolve, reject);
8431 const subscription = method(...args).pipe(catchError(error => tracker.reject(error))).subscribe(result => {
8432 tracker.resolve(result);
8433 util.nextTick(() => subscription.unsubscribe());
8434 });
8435 });
8436 }
8437 function decorateSubscribe(method, args, resultCb) {
8438 return new Promise((resolve, reject) => {
8439 const tracker = promiseTracker(resolve, reject);
8440 const subscription = method(...args).pipe(catchError(error => tracker.reject(error)), tap(() => tracker.resolve(() => subscription.unsubscribe()))).subscribe(result => {
8441 util.nextTick(() => resultCb(result));
8442 });
8443 });
8444 }
8445 function toPromiseMethod(method, options) {
8446 const needsCallback = !!(options && options.methodName && options.methodName.includes('subscribe'));
8447 return function (...args) {
8448 const [actualArgs, resultCb] = extractArgs(args, needsCallback);
8449 return resultCb ? decorateSubscribe(method, actualArgs, resultCb) : decorateCall((options === null || options === void 0 ? void 0 : options.overrideNoSub) || method, actualArgs);
8450 };
8451 }
8452
8453 class ApiPromise extends ApiBase {
8454 #isReadyPromise;
8455 #isReadyOrErrorPromise;
8456 constructor(options) {
8457 super(options, 'promise', toPromiseMethod);
8458 this.#isReadyPromise = new Promise(resolve => {
8459 super.once('ready', () => resolve(this));
8460 });
8461 this.#isReadyOrErrorPromise = new Promise((resolve, reject) => {
8462 const tracker = promiseTracker(resolve, reject);
8463 super.once('ready', () => tracker.resolve(this));
8464 super.once('error', error => tracker.reject(error));
8465 });
8466 }
8467 static create(options) {
8468 const instance = new ApiPromise(options);
8469 if (options && options.throwOnConnect) {
8470 return instance.isReadyOrError;
8471 }
8472 instance.isReadyOrError.catch(() => {
8473 });
8474 return instance.isReady;
8475 }
8476 get isReady() {
8477 return this.#isReadyPromise;
8478 }
8479 get isReadyOrError() {
8480 return this.#isReadyOrErrorPromise;
8481 }
8482 clone() {
8483 return new ApiPromise(util.objectSpread({}, this._options, {
8484 source: this
8485 }));
8486 }
8487 async combineLatest(fns, callback) {
8488 const combinator = new Combinator(fns, callback);
8489 return () => {
8490 combinator.unsubscribe();
8491 };
8492 }
8493 }
8494
8495 function toRxMethod(method) {
8496 return method;
8497 }
8498
8499 class ApiRx extends ApiBase {
8500 #isReadyRx;
8501 constructor(options) {
8502 super(options, 'rxjs', toRxMethod);
8503 this.#isReadyRx = from(
8504 new Promise(resolve => {
8505 super.on('ready', () => resolve(this));
8506 }));
8507 }
8508 static create(options) {
8509 return new ApiRx(options).isReady;
8510 }
8511 get isReady() {
8512 return this.#isReadyRx;
8513 }
8514 clone() {
8515 return new ApiRx(util.objectSpread({}, this._options, {
8516 source: this
8517 }));
8518 }
8519 }
8520
8521 Object.defineProperty(exports, 'Keyring', {
8522 enumerable: true,
8523 get: function () { return keyring.Keyring; }
8524 });
8525 exports.ApiPromise = ApiPromise;
8526 exports.ApiRx = ApiRx;
8527 exports.HttpProvider = HttpProvider;
8528 exports.SubmittableResult = SubmittableResult;
8529 exports.WsProvider = WsProvider;
8530 exports.packageInfo = packageInfo;
8531 exports.toPromiseMethod = toPromiseMethod;
8532 exports.toRxMethod = toRxMethod;
8533
8534 Object.defineProperty(exports, '__esModule', { value: true });
8535
8536}));