diff --git a/docs/pages/providers.md b/docs/pages/providers.md index acf48b87..4220a374 100644 --- a/docs/pages/providers.md +++ b/docs/pages/providers.md @@ -4,12 +4,12 @@ The entry point of Polkadot-API, `createClient(provider)` requires one `JsonRpcP ```ts interface JsonRpcProvider { - (onMessage: (message: string) => void) => JsonRpcConnection; + (onMessage: (message: string) => void) => JsonRpcConnection; } interface JsonRpcConnection { - send: (message: string) => void; - disconnect: () => void; + send: (message: string) => void; + disconnect: () => void; } ``` @@ -17,10 +17,10 @@ Calling it will initiate a connection. Messages coming from the service will com Polkadot-API offers a couple of providers for some of the most used ways of connecting to a chain: -- `getWsProvider(uri: string)` from `polkadot-api/ws-provider/web` or `polkadot-api/ws-provider/node` to connect through WebSocket. -- `getSmProvider(chain: smoldot.Chain)` from `polkadot-api/sm-provider` to connect through Smoldot. +- [`getWsProvider`](/providers/ws) from `polkadot-api/ws-provider/web` or `polkadot-api/ws-provider/node` (depending on where your code is running) to connect through WebSocket. +- [`getSmProvider`](/providers/sm) from `polkadot-api/sm-provider` to connect through Smoldot. -The `JsonRpcProvider` interface is designed so that it can be easily enhanced: You can wrap any JsonRpcProvider with another one that adds in more features, such as logging, statistics, or error recovery. +The `JsonRpcProvider` interface is designed so that it can be easily enhanced: You can wrap any JsonRpcProvider with another one that adds in more features, such as logging, statistics, or error recovery. Let's see the two PAPI builtin providers in the next pages. ## Logs provider diff --git a/docs/pages/providers/sm.md b/docs/pages/providers/sm.md new file mode 100644 index 00000000..30162f0f --- /dev/null +++ b/docs/pages/providers/sm.md @@ -0,0 +1,107 @@ +## Smoldot provider + +We love light-clients, and smoldot is our favorite way to connect to networks! + +Smoldot can be instantiated from PAPI using both the main thread or a worker. We strongly recommend using workers for it. + +## Instantiation + +### Main thread + +This is the easiest way of them all of instantiating smoldot. It blocks the main thread and it might have some performance issues: + +```ts +import { start } from "polkadot-api/smoldot" + +const smoldot = start() +``` + +### WebWorker + +[WebWorkers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API) are available in modern browser environments and [Bun](https://bun.sh). Having smoldot in a worker allows the main thread to be free to perform other tasks, since smoldot might block the main thread in some demanding tasks. + +Different bundlers have slightly different ways of creating workers, let's see them. + +- Vite: + +This option is only guaranteed to work on Vite, but might work on other bundlers. + +```ts +import { startFromWorker } from "polkadot-api/smoldot/from-worker" +import SmWorker from "polkadot-api/smoldot/worker?worker" + +const smoldot = startFromWorker(new SmWorker()) +``` + +- Bun + +This option is safer than the previous one and could work in other bundlers as well. + +```ts +import { startFromWorker } from "polkadot-api/smoldot/from-worker" + +const smWorker = new Worker(import.meta.resolve("polkadot-api/smoldot/worker")) +const smoldot = startFromWorker(smWorker) +``` + +- Webpack + +This option is the safest and should work in (almost) every bundler. + +```ts +import { startFromWorker } from "polkadot-api/smoldot/from-worker" + +const smWorker = new Worker( + new URL("polkadot-api/smoldot/worker", import.meta.url), +) +const smoldot = startFromWorker(smWorker) +``` + +## Adding a chain + +Once we have an instance of smoldot, we need to tell smoldot to connect to the chain we want. For that, we need the `chainSpec` of the chain. With `polkadot-api` we bundle chainspecs for certain well-known chains. We try to keep all 5 relay chains (Polkadot, Kusama, Westend, Paseo, and Rococo) and its system chains. + +In order to add a solo-chain (or a relay chain), it is very simple: + +```ts +import { chainSpec } from "polkadot-api/chains/polkadot" + +const polkadotChain: Promise = smoldot.addChain({ chainSpec }) +``` + +In case it is a parachain, we will need both the `chainSpec` of the relay chain, and the parachain one. It is simple as well: + +```ts +import { polkadot, polkadot_asset_hub } from "polkadot-api/chains" + +// without async-await +const assetHubChain: Promise = smoldot + .addChain({ chainSpec: polkadot }) + .then((relayChain) => + smoldot.addChain({ + chainSpec: polkadot_asset_hub, + potentialRelayChains: [relayChain], + }), + ) + +// or with an async-await structure: +const assetHubChain: Promise = smoldot.addChain({ + chainSpec: polkadot_asset_hub, + potentialRelayChains: [await smoldot.addChain({ chainSpec: polkadot })], +}) +``` + +## Getting the provider and initializing the client + +Once we have a `Chain` (or `Promise`), we can initialize the provider and the client. + +```ts +import { createClient } from "polkadot-api" +import { getSmProvider } from "polkadot-api/sm-provider" + +const chain = smoldot.addChain({ chainSpec }) +// no need to await! +const provider = getSmProvider(chain) + +const client = createClient(provider) +``` diff --git a/docs/pages/providers/ws.md b/docs/pages/providers/ws.md new file mode 100644 index 00000000..91924803 --- /dev/null +++ b/docs/pages/providers/ws.md @@ -0,0 +1,100 @@ +# WS Provider + +The WS provider enables PAPI to interact with JSON-RPC servers via WebSocket connection, generally Polkadot-SDK based nodes that include a JSON-RPC server. This provider is an special one, since its shape extends `JsonRpcProvider` and has some extra goodies. First of all, let's see its shape: + +```ts +interface WsJsonRpcProvider extends JsonRpcProvider { + switch: (uri?: string, protocol?: string[]) => void + getStatus: () => StatusChange +} + +interface GetWsProvider { + ( + uri: string, + protocols?: string | string[], + onStatusChanged?: (status: StatusChange) => void, + ): WsJsonRpcProvider + ( + uri: string, + onStatusChanged?: (status: StatusChange) => void, + ): WsJsonRpcProvider + ( + endpoints: Array, + onStatusChanged?: (status: StatusChange) => void, + ): WsJsonRpcProvider +} +``` + +In order to create the provider, there are three overloads for it. In a nutshell, one can pass one (or more) websocket `uri`s with its optional supported protocols. For example: + +```ts +import { getWsProvider } from "polkadot-api/ws-provider/web" + +// one option +getWsProvider("wss://myws.com") + +// two options +getWsProvider(["wss://myws.com", "wss://myfallbackws.com"]) +``` + +Passing more than one allows the provider to switch in case one particular websocket is down or has a wrong behavior. Besides that, the consumer can also force the switch with the exposed `switch` method, where they can specify optionally which socket to use instead. + +## Connection status + +The provider also has a `getStatus` method that it returns the current status of the connection. Let's see it: + +```ts +enum WsEvent { + CONNECTING, + CONNECTED, + ERROR, + CLOSE, +} +type WsConnecting = { + type: WsEvent.CONNECTING + uri: string + protocols?: string | string[] +} +type WsConnected = { + type: WsEvent.CONNECTED + uri: string + protocols?: string | string[] +} +type WsError = { + type: WsEvent.ERROR + event: any +} +type WsClose = { + type: WsEvent.CLOSE + event: any +} +type StatusChange = WsConnecting | WsConnected | WsError | WsClose +``` + +- `CONNECTING`: The connection is still being opened. It includes which socket and protocols is trying to connect to. +- `CONNECTED`: The connection has been established and is currently open. It includes which socket and protocols is trying to connect to. +- `ERROR`: The connection had an error. The provider will try to reconnect to other websockets (if available) or the same one. It includes the event sent by the server. +- `CLOSE`: The connection closed. If the server was the one closing the connection, the provider will try to reconnect to other websockets (if available) or the same one. It includes the event sent by the server. + +`provider.getStatus()` returns the current status. + +When creating the provider, the consumer can pass a callback that will be called every time the status changes: + +```ts +const provider = getWsProvider("wss://myws.com", (status) => { + switch (status.type) { + case WsEvent.CONNECTING: + console.log("Connecting... 🔌") + break + case WsEvent.CONNECTED: + console.log("Connected! ⚡") + break + case WsEvent.ERROR: + console.log("Errored... 😢") + break + case WsEvent.CLOSE: + console.log("Closed 🚪") + break + } +}) +``` diff --git a/vocs.config.tsx b/vocs.config.tsx index b3291bd5..71e4bfc3 100644 --- a/vocs.config.tsx +++ b/vocs.config.tsx @@ -20,7 +20,11 @@ export default defineConfig({ }, { text: "Providers", - link: "/providers", + items: [ + { text: "Providers", link: "/providers" }, + { text: "WebSocket", link: "/providers/ws" }, + { text: "Smoldot", link: "/providers/sm" }, + ], }, { text: "Codegen",