Providers

Providers are means to provide connection to the network, Dedot comes by default with providers for connection via WebSocket (wss://) and smoldot light client. But you can implement your own provider for your own needs.

WsProvider

Initialize from single Websocket endpoint

import { WsProvider } from 'dedot';

// Initialize the provider & connect to the network
const provider = new WsProvider('wss://rpc.polkadot.io');
await provider.connect();

// Fetch the genesis hash
const genesisHash = await provider.send('chain_getBlockHash', [0]);
console.log(genesisHash);

// Subscribe to runtimeVersion changes
await provider.subscribe({
  subname: 'chain_newHead', // subscription name for notification
  subscribe: 'chain_subscribeNewHeads', // subscribe method
  params: [], // params for subscribe method
  unsubscribe: 'chain_unsubscribeNewHeads', // unsubscribe method
}, (error, newHead, subscription) => {
  console.log('newHead', newHead);
});

// Disconnect from the network
await provider.disconnect();

Initialize from a list of endpoints

WsProvider can accept an array of WebSocket endpoints for automatic failover. Endpoints are randomly selected on initial connection, and reconnection attempts exclude previously failed endpoints when possible.

Initialize from a customized endpoint selector method

For advanced use-cases, WebSocket endpoint to use can also control by an external endpoint selector method, e.g: a wallet might want to selectively pick a RPC to switch to and display the selected RPC to the UI.

Disconnect and switch endpoint

The disconnect method accepts an optional switchEndpoint flag that allows you to disconnect from the current endpoint and automatically reconnect to a different one.

When switchEndpoint is true, the provider automatically reconnects to a different endpoint from the list. When false or not provided, the provider performs a normal disconnection with cleanup.

SmoldotProvider

SmoldotProvider take in a parameter of type Chain from smoldot, so before initialize a SmoldotProvider, one should install smoldot package and following the instruction to instanciate a Chain connection to the network.

If you're building a browser dapp, it's highly recommended to setup a worker for smoldot

  1. Install smoldot

  1. Initialize SmoldotProvider

Add your own custom provider?

Every provider must implement the JsonRpcProvider interface, defined as below:

One can easily add a custom provider by implementing this interface:

More detailed information about the JsonRpcProvider and related types can be found in the source code.

Last updated

Was this helpful?