# All files / src/ExtensionProvider ExtensionProvider.ts

42% Statements 42/100
31.03% Branches 9/29
41.67% Functions 10/24
44.21% Lines 42/95

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
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384

    2x
    2x

    2x

    2x

    5x
    5x
    5x
    5x
    5x
    5x

    5x
    5x

    5x
    5x

    1x

    1x

    5x
    7x
    3x
    3x
    3x

    4x
    4x
    4x

    5x

    5x

    4x

    4x
    4x
    19x

    7x

    4x
    4x

    4x

    1x

    1x
    1x
    1x

    3x

    4x

    4x

    12x

     import {RpcCoder} from '@polkadot/rpc-provider/coder';
    import {
      JsonRpcResponse,
      ProviderInterface,
      ProviderInterfaceCallback,
      ProviderInterfaceEmitCb,
      ProviderInterfaceEmitted,
    } from '@polkadot/rpc-provider/types';
    import { logger } from '@polkadot/util';
    import EventEmitter from 'eventemitter3';
    import { isUndefined } from '../utils/index.js';
    import {
      MessageFromManager,
      ProviderMessageData,
      ExtensionMessage,
      ExtensionMessageData,
      provider
    } from '@substrate/connect-extension-protocol';

    const CONTENT_SCRIPT_ORIGIN = 'content-script';
    const EXTENSION_PROVIDER_ORIGIN = 'extension-provider';

    const l = logger(EXTENSION_PROVIDER_ORIGIN);

    interface RpcStateAwaiting {
      callback: ProviderInterfaceCallback;
      method: string;
      subscription?: SubscriptionHandler;
    }

    interface SubscriptionHandler {
      callback: ProviderInterfaceCallback;
      // type is the value of the method property in the JSON responses to this
      // subscription
      type: string;
    }

    interface StateSubscription extends SubscriptionHandler {
      method: string;
    }

    const ANGLICISMS: { [index: string]: string } = {
      chain_finalisedHead: 'chain_finalizedHead',
      chain_subscribeFinalisedHeads: 'chain_subscribeFinalizedHeads',
      chain_unsubscribeFinalisedHeads: 'chain_unsubscribeFinalizedHeads'
    };

    /**
     * The ExtensionProvider allows interacting with a smoldot-based WASM light
     * client running in a browser extension.  It is not designed to be used
     * directly.  You should use the `\@substrate/connect` package.
     */
    export class ExtensionProvider implements ProviderInterface {
      readonly #coder: RpcCoder = new RpcCoder();
      readonly #eventemitter: EventEmitter = new EventEmitter();
      readonly #handlers: Record<string, RpcStateAwaiting> = {};
      readonly #subscriptions: Record<string, StateSubscription> = {};
      readonly #waitingForId: Record<string, JsonRpcResponse> = {};
      #isConnected = false;

      #appName: string;
      #chainName: string;

      public constructor(appName: string, chainName: string) {
        this.#appName = appName;
        this.#chainName = chainName;
      }

      /**
       * name
       *
       * @returns the name of this app to be used by the extension for display
       * purposes.
       *
       * @remarks Apps are expected to make efforts to make this name reasonably
       * unique.
       */
      public get name(): string {
        return this.#appName;
      }

      /**
       * chainName
       *
       * @returns the name of the chain this `ExtensionProvider` is talking to.
       */
      public get chainName(): string {
        return this.#chainName;
      }

      /**
       * Lets polkadot-js know we support subscriptions
       *
       * @remarks Always returns `true` - this provider supports subscriptions.
       * PolkadotJS uses this internally.
       */
      public get hasSubscriptions(): boolean {
        return true;
      }

      /**
       * clone
       *
       * @remarks This method is not supported
       * @throws {@link Error}
       */
      public clone(): ExtensionProvider {
        throw new Error('clone() is not supported.');
      }

      #handleMessage = (data: ExtensionMessageData): void => {
        if (data.disconnect && data.disconnect === true) {
          this.#isConnected = false;
          this.emit('disconnected');
          return;
        }

        const message = data.message as MessageFromManager;
        Eif (message.type === 'error') {
          return this.emit('error', new Error(message.payload));
        }

        if (message.type === 'rpc') {
          const rpcString = message.payload;
          l.debug(() => ['received', rpcString]);
          const response = JSON.parse(rpcString) as JsonRpcResponse;

          return isUndefined(response.method)
            ? this.#onMessageResult(response)
            : this.#onMessageSubscribe(response);
        }

        const errorMessage =`Unrecognised message type from extension ${message.type}`;
        return this.emit('error', new Error(errorMessage));
      }

      #onMessageResult = (response: JsonRpcResponse): void => {
        const handler = this.#handlers[response.id];

        if (!handler) {
          l.debug(() => `Unable to find handler for id=${response.id}`);

          return;
        }

        try {
          const { method, subscription } = handler;
          const result = this.#coder.decodeResponse(response) as string;

          // 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}`;

            this.#subscriptions[subId] = {
              ...subscription,
              method,
            };

            // if we have a result waiting for this subscription already
            if (this.#waitingForId[subId]) {
              this.#onMessageSubscribe(this.#waitingForId[subId]);
            }
          }
        } catch (error) {
          handler.callback(error, undefined);
        }

        delete this.#handlers[response.id];
      }

      #onMessageSubscribe = (response: JsonRpcResponse): void => {
        const method = ANGLICISMS[response.method as string] || response.method || 'invalid';
        const subId = `${method}::${response.params.subscription}`;
        const handler = this.#subscriptions[subId];
        if (!handler) {
          // store the response, we could have out-of-order subid coming in
          this.#waitingForId[subId] = response;
          l.debug(() => `Unable to find handler for subscription=${subId} responseId=${response.id}`);
          return;
        }

        // housekeeping
        delete this.#waitingForId[subId];

        try {
          const result = this.#coder.decodeResponse(response);

          handler.callback(null, result);
        } catch (error) {
          handler.callback(error, undefined);
        }
      }

      /**
       * "Connect" to the extension - sends a message to the `ExtensionMessageRouter`
       * asking it to connect to the extension background.
       *
       * @returns a resolved Promise
       * @remarks this is async to fulfill the interface with PolkadotJS
       */
      public connect(): Promise<void> {
        const connectMsg: ProviderMessageData = {
          appName: this.#appName,
          chainName: this.#chainName,
          action: 'connect',
          origin: EXTENSION_PROVIDER_ORIGIN
        }
        provider.send(connectMsg);
        provider.listen(({data}: ExtensionMessage) => {
          if (data.origin && data.origin === CONTENT_SCRIPT_ORIGIN) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
            this.#handleMessage(data);
          }
        });
        this.#isConnected = true;
        this.emit('connected');

        return Promise.resolve();
      }

      /**
       * Manually "disconnect" - sends a message to the `ExtensionMessageRouter`
       * telling it to disconnect the port with the background manager.
       */
      // eslint-disable-next-line @typescript-eslint/require-await
      public async disconnect(): Promise<void> {
        const disconnectMsg: ProviderMessageData = {
          appName: this.#appName,
          chainName: this.#chainName,
          action: 'disconnect',
          origin: EXTENSION_PROVIDER_ORIGIN
        };

        provider.send(disconnectMsg);
        this.#isConnected = false;
        this.emit('disconnected');
      }

      /**
       * Whether the node is connected or not.
       *
       * @returns true - if connected otherwise false
       */
      public get isConnected (): boolean {
        return this.#isConnected;
      }

      /**
       * 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
       */
      public on(
        type: ProviderInterfaceEmitted,
        sub: ProviderInterfaceEmitCb
      ): () => void {
        this.#eventemitter.on(type, sub);

        return (): void => {
          this.#eventemitter.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`)
       */
      public async send(
        method: string,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        params: any[],
        subscription?: SubscriptionHandler
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
      ): Promise<any> {
        return new Promise((resolve, reject): void => {
          const json = this.#coder.encodeJson(method, params);
          const id = this.#coder.getId();

          const callback = (error?: Error | null, result?: unknown): void => {
            error
              ? reject(error)
              : resolve(result);
          };

          l.debug(() => ['calling', method, json]);

          this.#handlers[id] = {
            callback,
            method,
            subscription
          };

          const rpcMsg: ProviderMessageData = {
            appName: this.#appName,
            chainName: this.#chainName,
            action: 'forward',
            message: {
              type: 'rpc',
              payload: json,
              subscription: !!subscription
            },
            origin: EXTENSION_PROVIDER_ORIGIN
          }
          provider.send(rpcMsg);
        });
      }

      /**
       * Allows subscribing to a specific event.
       *
       * @param type     - Subscription type
       * @param method   - Subscription method
       * @param params   - Parameters
       * @param callback - Callback
       * @returns Promise  - resolves to the id of the subscription you can use with [[unsubscribe]].
       *
       * @example
       * <BR>
       *
       * ```javascript
       * const provider = new ExtensionProvider(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)
       * })
       * ```
       */
      public async subscribe(
        // the "method" property of the JSON response to this subscription
        type: string,
        // the "method" property of the JSON request to register the subscription
        method: string,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        params: any[],
        callback: ProviderInterfaceCallback
      ): Promise<number | string> {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-return
        return await this.send(method, params, { callback, type });
      }

      /**
       * Allows unsubscribing to subscriptions made with [[subscribe]].
       *
       * @param type   - Subscription type
       * @param method - Subscription method
       * @param id     - Id passed for send parameter
       * @returns Promise resolving to whether the unsunscribe request was successful.
       */
      public async unsubscribe(
        type: string,
        method: string,
        id: number | string
      ): Promise<boolean> {
        const subscription = `${type}::${id}`;

        if (isUndefined(this.#subscriptions[subscription])) {
          l.debug(() => `Unable to find active subscription=${subscription}`);

          return false;
        }

        delete this.#subscriptions[subscription];

        return await this.send(method, [id]) as Promise<boolean>;
      }

      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      private emit(type: ProviderInterfaceEmitted, ...args: any[]): void {
        this.#eventemitter.emit(type, ...args);
      }
    }