# All files / dist/SmoldotProvider SmoldotProvider.js

88.89% Statements 120/135
70.73% Branches 58/82
78.57% Functions 22/28
96% Lines 120/125

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    3453x
    157x
    157x
    157x
    157x

    3x
    2376x
    2376x
    2376x

    3x
    3x

    3x

    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x
    24x

    24x

    24x
    24x
    168x
    168x
    168x

    24x
    154x
    154x

    154x
    154x
    154x

    152x
    152x
    19x
    19x

    19x
    1x

    2x

    154x

    24x
    15x
    15x
    15x
    15x

    3x
    3x
    3x

    12x
    12x
    12x
    12x

    24x

    76x
    20x
    1x
    1x
    1x
    1x

    19x

    56x
    56x
    56x
    56x
    56x

    1x

    55x
    2x
    2x
    2x
    2x

    53x
    12x
    12x
    12x
    12x

    24x
    77x

    1x

    24x
    24x
    24x
    24x

    168x

    23x

    1x

    24x

    24x
    24x

    5094x

    24x
    24x

    24x

    24x
    24x

    24x
    24x

    16x

    36x
    36x
    3x

    173x
    173x
    173x
    173x
    173x
    154x

    173x
    173x

    173x

    22x

    2x
    2x
    1x
    1x

    1x
    1x

    41x

    3x
     var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
        Iif (kind === "m") throw new TypeError("Private method is not writable");
        Iif (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
        Iif (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    };
    var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
        Iif (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
        Iif (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    };
    var _SmoldotProvider_chainSpec, _SmoldotProvider_coder, _SmoldotProvider_eventemitter, _SmoldotProvider_handlers, _SmoldotProvider_subscriptions, _SmoldotProvider_waitingForId, _SmoldotProvider_connectionStatePingerId, _SmoldotProvider_isConnected, _SmoldotProvider_client, _SmoldotProvider_smoldot, _SmoldotProvider_handleRpcReponse, _SmoldotProvider_onMessageResult, _SmoldotProvider_onMessageSubscribe, _SmoldotProvider_simulateLifecycle, _SmoldotProvider_checkClientPeercount;
    import { RpcCoder } from '@polkadot/rpc-provider/coder';
    import { assert, logger } from '@polkadot/util';
    import EventEmitter from 'eventemitter3';
    import * as smoldot from 'smoldot';
    import { HealthCheckError } from './errors.js';
    import { isUndefined } from '../utils/index.js';
    const l = logger('smoldot-provider');
    const ANGLICISMS = {
        chain_finalisedHead: 'chain_finalizedHead',
        chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
        chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
    };
    /*
     * Number of milliseconds to wait between checks to see if we have any
     * connected peers in the smoldot client
     */
    const CONNECTION_STATE_PINGER_INTERVAL = 2000;
    /**
     * SmoldotProvider
     *
     * The SmoldotProvider allows interacting with a smoldot-based
     * WASM light client.  I.e. without doing RPC to a remote node over HTTP
     * or websockets
     *
     * @example
     * ```javascript
     * import readFileSync from 'fs';
     * import Api from '@polkadot/api/promise';
     * import { SmoldotProvider } from '../';
     *
     * const chainSpec = readFileSync('./path/to/chainSpec.json');
     * const provider = new SmoldotProvider(chainSpec);
     * const api = new Api(provider);
     * ```
     * @example
     * ```javascript
     * import readFileSync from 'fs';
     * import Api from '@polkadot/api/promise';
     * import { SmoldotProvider } from '../';
     *
     * const chainSpec = readFileSync('./path/to/polkadot.json');
     * const pp = new SmoldotProvider(chainSpec);
     * const polkadotApi = new Api(pp);
     *
     * const chainSpec = readFileSync('./path/to/kusama.json');
     * const kp = new SmoldotProvider(chainSpec);
     * const kusamaApi = new Api(pp);
     * ```
     */
    export class SmoldotProvider {
        /**
        * @param chainSpec - The chainSpec for the WASM client
        * @param sm - (only used for testing) defaults to the actual smoldot module
        */
        //eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types
        constructor(chainSpec, sm) {
            _SmoldotProvider_chainSpec.set(this, void 0);
            _SmoldotProvider_coder.set(this, new RpcCoder());
            _SmoldotProvider_eventemitter.set(this, new EventEmitter());
            _SmoldotProvider_handlers.set(this, {});
            _SmoldotProvider_subscriptions.set(this, {});
            _SmoldotProvider_waitingForId.set(this, {});
            _SmoldotProvider_connectionStatePingerId.set(this, void 0);
            _SmoldotProvider_isConnected.set(this, false);
            _SmoldotProvider_client.set(this, undefined);
            // reference to the smoldot module so we can defer loading the wasm client
            // until connect is called
            _SmoldotProvider_smoldot.set(this, void 0);
            /*
             * How frequently to see if we have any peers
             */
            this.healthPingerInterval = CONNECTION_STATE_PINGER_INTERVAL;
            _SmoldotProvider_handleRpcReponse.set(this, (res) => {
                l.debug(() => ['received', res]);
                const response = JSON.parse(res);
                return isUndefined(response.method)
                    ? __classPrivateFieldGet(this, _SmoldotProvider_onMessageResult, "f").call(this, response)
                    : __classPrivateFieldGet(this, _SmoldotProvider_onMessageSubscribe, "f").call(this, response);
            });
            _SmoldotProvider_onMessageResult.set(this, (response) => {
                const handler = __classPrivateFieldGet(this, _SmoldotProvider_handlers, "f")[response.id];
                Iif (!handler) {
                    l.debug(() => `Unable to find handler for id=${response.id}`);
                    return;
                }
                try {
                    const { method, subscription } = handler;
                    const result = __classPrivateFieldGet(this, _SmoldotProvider_coder, "f").decodeResponse(response);
                    // first send the result - in case of subs, we may have an update
                    // immediately if we have some queued results already
                    handler.callback(null, result);
                    if (subscription) {
                        const subId = `${subscription.type}::${result}`;
                        __classPrivateFieldGet(this, _SmoldotProvider_subscriptions, "f")[subId] = {
                            ...subscription,
                            method
                        };
                        // if we have a result waiting for this subscription already
                        if (__classPrivateFieldGet(this, _SmoldotProvider_waitingForId, "f")[subId]) {
                            __classPrivateFieldGet(this, _SmoldotProvider_onMessageSubscribe, "f").call(this, __classPrivateFieldGet(this, _SmoldotProvider_waitingForId, "f")[subId]);
                        }
                    }
                }
                catch (error) {
                    handler.callback(error, undefined);
                }
                delete __classPrivateFieldGet(this, _SmoldotProvider_handlers, "f")[response.id];
            });
            _SmoldotProvider_onMessageSubscribe.set(this, (response) => {
                const method = ANGLICISMS[response.method] || response.method || 'invalid';
                const subId = `${method}::${response.params.subscription}`;
                const handler = __classPrivateFieldGet(this, _SmoldotProvider_subscriptions, "f")[subId];
                if (!handler) {
                    // store the response, we could have out-of-order subid coming in
                    __classPrivateFieldGet(this, _SmoldotProvider_waitingForId, "f")[subId] = response;
                    l.debug(() => `Unable to find handler for subscription=${subId} responseId=${response.id}`);
                    return;
                }
                // housekeeping
                delete __classPrivateFieldGet(this, _SmoldotProvider_waitingForId, "f")[subId];
                try {
                    const result = __classPrivateFieldGet(this, _SmoldotProvider_coder, "f").decodeResponse(response);
                    handler.callback(null, result);
                }
                catch (error) {
                    handler.callback(error, undefined);
                }
            });
            _SmoldotProvider_simulateLifecycle.set(this, (health) => {
                // development chains should not have peers so we only emit connected
                // once and never disconnect
                if (health.shouldHavePeers == false) {
                    if (!__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f")) {
                        __classPrivateFieldSet(this, _SmoldotProvider_isConnected, true, "f");
                        this.emit('connected');
                        l.debug(`emitted CONNECTED`);
                        return;
                    }
                    return;
                }
                const peerCount = health.peers;
                const peerChecks = (peerCount > 0 || !health.shouldHavePeers) && !health.isSyncing;
                l.debug(`Simulating lifecylce events from system_health`);
                l.debug(`isConnected: ${__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f").toString()}, new peerCount: ${peerCount}`);
                if (__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f") && peerChecks) {
                    // still connected
                    return;
                }
                if (__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f") && peerCount === 0) {
                    __classPrivateFieldSet(this, _SmoldotProvider_isConnected, false, "f");
                    this.emit('disconnected');
                    l.debug(`emitted DISCONNECTED`);
                    return;
                }
                if (!__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f") && peerChecks) {
                    __classPrivateFieldSet(this, _SmoldotProvider_isConnected, true, "f");
                    this.emit('connected');
                    l.debug(`emitted CONNECTED`);
                    return;
                }
                // still not connected
            });
            _SmoldotProvider_checkClientPeercount.set(this, () => {
                this.send('system_health', [])
                    .then(__classPrivateFieldGet(this, _SmoldotProvider_simulateLifecycle, "f"))
                    .catch(error => this.emit('error', new HealthCheckError(error)));
            }
            /**
             * "Connect" the WASM client - starts the smoldot WASM client
             */
            );
            /**
             * "Connect" the WASM client - starts the smoldot WASM client
             */
            this.connect = async () => {
                assert(!__classPrivateFieldGet(this, _SmoldotProvider_client, "f") && !__classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f"), 'Client is already connected');
                try {
                    __classPrivateFieldSet(this, _SmoldotProvider_client, await __classPrivateFieldGet(this, _SmoldotProvider_smoldot, "f").start({
                        forbidWs: true,
                        chainSpecs: [__classPrivateFieldGet(this, _SmoldotProvider_chainSpec, "f")],
                        maxLogLevel: 3,
                        jsonRpcCallback: (response) => {
                            __classPrivateFieldGet(this, _SmoldotProvider_handleRpcReponse, "f").call(this, response);
                        }
                    }), "f");
                    __classPrivateFieldSet(this, _SmoldotProvider_connectionStatePingerId, setInterval(__classPrivateFieldGet(this, _SmoldotProvider_checkClientPeercount, "f"), this.healthPingerInterval), "f");
                }
                catch (error) {
                    this.emit('error', error);
                }
            };
            __classPrivateFieldSet(this, _SmoldotProvider_chainSpec, chainSpec, "f");
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
            __classPrivateFieldSet(this, _SmoldotProvider_smoldot, sm || smoldot, "f");
            __classPrivateFieldSet(this, _SmoldotProvider_connectionStatePingerId, null, "f");
        }
        /**
         * Lets polkadot-js know we support subscriptions
         * @returns `true`
         */
        get hasSubscriptions() {
            return true;
        }
        /**
         * Returns a clone of the object
         * @throws throws an error as this is not supported.
         */
        clone() {
            throw new Error('clone() is not supported.');
        }
        /**
         * Manually "disconnect" - drops the reference to the WASM client
         */
        // eslint-disable-next-line @typescript-eslint/require-await
        async disconnect() {
            try {
                Eif (__classPrivateFieldGet(this, _SmoldotProvider_client, "f")) {
                    // eslint-disable-next-line @typescript-eslint/no-unsafe-call
                    __classPrivateFieldGet(this, _SmoldotProvider_client, "f").terminate();
                }
            }
            catch (error) {
                this.emit('error', error);
            }
            finally {
                Eif (__classPrivateFieldGet(this, _SmoldotProvider_connectionStatePingerId, "f") !== null) {
                    clearInterval(__classPrivateFieldGet(this, _SmoldotProvider_connectionStatePingerId, "f"));
                }
                __classPrivateFieldSet(this, _SmoldotProvider_isConnected, false, "f");
                this.emit('disconnected');
            }
        }
        /**
         * Whether the node is connected or not.
         * @returns true if connected
         */
        get isConnected() {
            return __classPrivateFieldGet(this, _SmoldotProvider_isConnected, "f");
        }
        /**
         * Listen to provider events - in practice the smoldot provider only
         * emits a `connected` event after successfully starting the smoldot client
         * and `disconnected` after `disconnect` is called.
         * @param type - Event
         * @param sub  - Callback
         */
        on(type, sub) {
            __classPrivateFieldGet(this, _SmoldotProvider_eventemitter, "f").on(type, sub);
            return () => {
                __classPrivateFieldGet(this, _SmoldotProvider_eventemitter, "f").removeListener(type, sub);
            };
        }
        /**
         * Send an RPC request  the wasm client
         * @param method       - The RPC methods to execute
         * @param params       - Encoded paramaters as applicable for the method
         * @param subscription - Subscription details (internally used by `subscribe`)
         */
        async send(method,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        params, subscription
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        ) {
            return new Promise((resolve, reject) => {
                assert(__classPrivateFieldGet(this, _SmoldotProvider_client, "f"), 'Client is not initialised');
                const json = __classPrivateFieldGet(this, _SmoldotProvider_coder, "f").encodeJson(method, params);
                const id = __classPrivateFieldGet(this, _SmoldotProvider_coder, "f").getId();
                const callback = (error, result) => {
                    error
                        ? reject(error)
                        : resolve(result);
                };
                l.debug(() => ['calling', method, json]);
                __classPrivateFieldGet(this, _SmoldotProvider_handlers, "f")[id] = {
                    callback,
                    method,
                    subscription
                };
                __classPrivateFieldGet(this, _SmoldotProvider_client, "f").sendJsonRpc(json, 0);
            });
        }
        /**
         * subscribe
         * Allows subscribing to a specific event.
         * @param  type     - Subscription type
         * @param  method   - Subscription method
         * @param  params   - Parameters of type any[]
         * @param  callback - ProviderInterfaceCallback
         * @returns A promise (Promise\<number|string\>) resolving to the id of the subscription you can use with [[unsubscribe]].
         *
         * @example
         * <BR>
         *
         * ```javascript
         * const provider = new SmoldotProvider(client);
         * const rpc = new Rpc(provider);
         *
         * rpc.state.subscribeStorage([[storage.balances.freeBalance, <Address>]], (_, values) => {
         *   console.log(values)
         * }).then((subscriptionId) => {
         *   console.log('balance changes subscription id: ', subscriptionId)
         * })
         * ```
         */
        async subscribe(
        // the "method" property of the JSON response to this subscription
        type,
        // the "method" property of the JSON request to register the subscription
        method,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        params, callback) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            return await this.send(method, params, { callback, type });
        }
        /**
         * Allows unsubscribing to subscriptions made with [[subscribe]].
         */
        async unsubscribe(type, method, id) {
            const subscription = `${type}::${id}`;
            if (isUndefined(__classPrivateFieldGet(this, _SmoldotProvider_subscriptions, "f")[subscription])) {
                l.debug(() => `Unable to find active subscription=${subscription}`);
                return false;
            }
            delete __classPrivateFieldGet(this, _SmoldotProvider_subscriptions, "f")[subscription];
            return await this.send(method, [id]);
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        emit(type, ...args) {
            __classPrivateFieldGet(this, _SmoldotProvider_eventemitter, "f").emit(type, ...args);
        }
    }
    _SmoldotProvider_chainSpec = new WeakMap(), _SmoldotProvider_coder = new WeakMap(), _SmoldotProvider_eventemitter = new WeakMap(), _SmoldotProvider_handlers = new WeakMap(), _SmoldotProvider_subscriptions = new WeakMap(), _SmoldotProvider_waitingForId = new WeakMap(), _SmoldotProvider_connectionStatePingerId = new WeakMap(), _SmoldotProvider_isConnected = new WeakMap(), _SmoldotProvider_client = new WeakMap(), _SmoldotProvider_smoldot = new WeakMap(), _SmoldotProvider_handleRpcReponse = new WeakMap(), _SmoldotProvider_onMessageResult = new WeakMap(), _SmoldotProvider_onMessageSubscribe = new WeakMap(), _SmoldotProvider_simulateLifecycle = new WeakMap(), _SmoldotProvider_checkClientPeercount = new WeakMap();
    //# sourceMappingURL=SmoldotProvider.js.map