### Staking SDK - Introduction and Setup Source: https://papi.how/sdks/staking-sdk Instructions on how to install and set up the Staking SDK with a Polkadot-API client. ```APIDOC ## Staking SDK Setup ### Description Install the Staking SDK using npm and create a client to initialize the SDK. ### Installation ```bash npm i @polkadot-api/sdk-staking ``` ### Initialization ```javascript import { createStakingSdk } from "@polkadot-api/sdk-staking" import { createClient } from "polkadot-api" import { getSmProvider } from "polkadot-api/sm-provider" import { polkadot, polkadot_asset_hub } from "polkadot-api/chains" import { start } from "polkadot-api/smoldot" import { dot } from "@polkadot-api/descriptors" const smoldot = start() const chain = smoldot.addChain({ chainSpec: polkadot }).then((relay) => smoldot.addChain({ chainSpec: polkadot_asset_hub, potentialRelayChains: [relay], }), ) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const stakingSdk = createStakingSdk(client) ``` ``` -------------------------------- ### Setup Project for Multi-Chain Connections Source: https://papi.how/recipes/connect-to-multiple-chains This snippet shows the necessary commands to initialize a new project using bun, install the polkadot-api, and add two well-known chains (polkadot and polkadot_people) for simultaneous connection. ```bash mkdir papi-multichain cd papi-multichain bun init -y bun i polkadot-api bun papi add -n polkadot dot --skip-codegen bun papi add -n polkadot_people people ``` -------------------------------- ### Create PolkadotClient with Smoldot Provider Source: https://papi.how/getting-started Demonstrates how to create a PolkadotClient instance using the Smoldot provider. This involves starting a Smoldot instance, adding a chain, and then creating the client with the provider. ```typescript // `dot` is the name we gave to `npx papi add` import { dot } from "@polkadot-api/descriptors" import { createClient } from "polkadot-api" import { getSmProvider } from "polkadot-api/sm-provider" import { chainSpec } from "polkadot-api/chains/polkadot" import { start } from "polkadot-api/smoldot" // if interested, check out how to create a smoldot instance in a WebWorker // http://papi.how/providers/sm#webworker const smoldot = start() const chain = await smoldot.addChain({ chainSpec }) // Connect to the polkadot relay chain. const client = createClient(getSmProvider(chain)) ``` -------------------------------- ### Install and Generate Polkadot-API Types Source: https://papi.how/getting-started Installs the polkadot-api package and generates chain-specific types using the npx papi command. This process involves downloading metadata from a specified chain. ```bash npm i polkadot-api # `papi add` is the command # `dot` is the name we're giving to this chain (can be any JS variable name) # `-n polkadot` specifies to download the metadata from the well-known chain polkadot npx papi add dot -n polkadot # Wait for the latest metadata to download, then generate the types: npx papi ``` -------------------------------- ### Install and Initialize Multisig SDK Source: https://papi.how/sdks/multisig-sdk Instructions for installing the Multisig SDK via npm and initializing it with a Polkadot-API client. ```APIDOC ## Installation ```bash npm i @polkadot-api/sdk-multisig ``` ## Initialization ```javascript import { createMultisigSdk } from "@polkadot-api/sdk-multisig" import { getWsProvider } from "polkadot-api/ws-provider" import { createClient } from "polkadot-api" const client = createClient(getWsProvider("wss://rpc.ibp.network/polkadot")) const multisigSdk = createMultisigSdk(client) // For chains using AccountId20, pass an optional parameter: // const multisigSdk = createMultisigSdk(client, "acc20") ``` ``` -------------------------------- ### Install Ink! SDK Source: https://papi.how/sdks/ink-sdk Installs the Ink! SDK using the pnpm package manager. This is the first step to start using the SDK for smart contract interactions. ```shell pnpm i @polkadot-api/sdk-ink ``` -------------------------------- ### Bounties SDK Installation and Initialization Source: https://papi.how/sdks/governance/bounties Instructions on how to install the Bounties SDK and initialize it with the typed API for a specific chain. ```APIDOC ## Installation Install the Governance SDK using your package manager: ```bash npm i @polkadot-api/sdk-governance ``` ## Initialization Initialize the SDK by passing in the `typedApi` for your chain: ```javascript import { createBountiesSdk } from "@polkadot-api/sdk-governance" import { dot } from "@polkadot-api/descriptors" import { getSmProvider } from "polkadot-api/sm-provider" import { chainSpec } from "polkadot-api/chains/polkadot" import { start } from "polkadot-api/smoldot" import { createClient } from "polkadot-api" const smoldot = start() const chain = await smoldot.addChain({ chainSpec }) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const bountiesSdk = createBountiesSdk(typedApi) ``` ``` -------------------------------- ### Initialize Project and Install Dependencies (Bun) Source: https://papi.how/recipes/simple-transfer This snippet shows how to set up a new project directory, initialize it with Bun, and install the necessary Polkadot-API and HDKD packages. It also includes adding the Westend network descriptor. ```bash mkdir papi-simple-transfer cd papi-simple-transfer bun init -y bun i polkadot-api @polkadot-labs/hdkd @polkadot-labs/hdkd-helpers bun papi add -n westend2 wnd ``` -------------------------------- ### Install Polkadot-API Staking SDK Source: https://papi.how/sdks/staking-sdk Installs the Staking SDK using npm. This is the initial step to integrate the SDK into your project. ```bash npm i @polkadot-api/sdk-staking ``` -------------------------------- ### Consume Polkadot-API Client Source: https://papi.how/getting-started Shows how to use the PolkadotClient to subscribe to finalized blocks and retrieve specific data, such as account information, using the Typed API. ```typescript // With the `client`, you can get information such as subscribing to the last // block to get the latest hash: client.finalizedBlock$.subscribe((finalizedBlock) => console.log(finalizedBlock.number, finalizedBlock.hash), ) // To interact with the chain, you need to get the `TypedApi`, which includes // all the types for every call in that chain: const dotApi = client.getTypedApi(dot) // get the value for an account const accountInfo = await dotApi.query.System.Account.getValue( "16JGzEsi8gcySKjpmxHVrkLTHdFHodRepEz8n244gNZpr9J", ) ``` -------------------------------- ### Install Polkadot-API Accounts SDK Source: https://papi.how/sdks/accounts/identity Installs the Accounts SDK package using npm. This is the first step to using the Identity SDK. ```bash npm i @polkadot-api/sdk-accounts ``` -------------------------------- ### Install Bounties SDK Source: https://papi.how/sdks/governance/bounties Installs the Polkadot-API Governance SDK using npm. This is the initial step to integrate the SDK into your project. ```bash npm i @polkadot-api/sdk-governance ``` -------------------------------- ### Initialize Referenda SDK with Polkadot typedApi Source: https://papi.how/sdks/governance/referenda Initializes the Referenda SDK by passing the typedApi obtained from a Polkadot-API client. This setup requires starting a smoldot instance and adding a chain. ```typescript import { createReferendaSdk } from "@polkadot-api/sdk-governance" import { dot } from "@polkadot-api/descriptors" import { getSmProvider } from "polkadot-api/sm-provider" import { chainSpec } from "polkadot-api/chains/polkadot" import { start } from "polkadot-api/smoldot" import { createClient } from "polkadot-api" const smoldot = start() const chain = await smoldot.addChain({ chainSpec }) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const referendaSdk = createReferendaSdk(typedApi) ``` -------------------------------- ### Install Multisig SDK using npm Source: https://papi.how/sdks/multisig-sdk Install the Multisig SDK package using npm. This is the initial step to integrate the SDK into your project. ```bash npm i @polkadot-api/sdk-multisig ``` -------------------------------- ### Statement SDK Installation Source: https://papi.how/sdks/statement Install the Statement SDK using your package manager. ```APIDOC ## Install Statement SDK ### Description Install the Statement SDK using your package manager. ### Method `pnpm` (or npm/yarn) ### Endpoint N/A ### Parameters None ### Request Example ```bash pnpm i @polkadot-api/sdk-statement ``` ### Response None ``` -------------------------------- ### Install Referenda SDK with npm Source: https://papi.how/sdks/governance/referenda Installs the Polkadot-API Referenda SDK using npm. This is the first step to integrating the SDK into your project. ```bash npm i @polkadot-api/sdk-governance ``` -------------------------------- ### Initialize Conviction Voting SDK Source: https://papi.how/sdks/governance/voting Initialize the Conviction Voting SDK by passing the `typedApi` for your chain. This setup involves starting smoldot, adding a chain, creating a client, and obtaining the typed API. ```typescript import { createConvictionVotingSdk } from "@polkadot-api/sdk-governance" import { dot } from "@polkadot-api/descriptors" import { getSmProvider } from "polkadot-api/sm-provider" import { chainSpec } from "polkadot-api/chains/polkadot" import { start } from "polkadot-api/smoldot" import { createClient } from "polkadot-api" const smoldot = start() const chain = await smoldot.addChain({ chainSpec }) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const votingSdk = createConvictionVotingSdk(typedApi) ``` -------------------------------- ### Instantiate Ink! SDK Source: https://papi.how/sdks/ink-sdk Initializes the Ink! SDK by creating a Polkadot-API client and then passing it to the `createInkSdk` function. This setup is required before interacting with any contracts. ```typescript import { createInkSdk } from "@polkadot-api/sdk-ink" import { createClient } from "polkadot-api" import { withPolkadotSdkCompat } from "polkadot-api/polkadot-sdk-compat" import { getWsProvider } from "polkadot-api/ws-provider" const client = createClient( withPolkadotSdkCompat(getWsProvider("wss://testnet-passet-hub.polkadot.io")), ) const inkSdk = createInkSdk(client) ``` -------------------------------- ### Initialize Multisig SDK with Polkadot Client Source: https://papi.how/sdks/multisig-sdk Initialize the Multisig SDK by passing in the client for your Polkadot chain. This setup is crucial for the SDK to interact with the blockchain. ```typescript import { createMultisigSdk } from "@polkadot-api/sdk-multisig" import { getWsProvider } from "polkadot-api/ws-provider" import { createClient } from "polkadot-api" const client = createClient(getWsProvider("wss://rpc.ibp.network/polkadot")) const multisigSdk = createMultisigSdk(client) ``` -------------------------------- ### Install Statement SDK using pnpm Source: https://papi.how/sdks/statement Installs the Statement SDK package using the pnpm package manager. This is the first step to integrating the SDK into your project. ```bash pnpm i @polkadot-api/sdk-statement ``` -------------------------------- ### Initialize Bounties SDK with Polkadot-API Source: https://papi.how/sdks/governance/bounties Initializes the Bounties SDK by creating a client and obtaining a typed API for the Polkadot chain. This setup is necessary before using any SDK functionalities. ```typescript import { createBountiesSdk } from "@polkadot-api/sdk-governance" import { dot } from "@polkadot-api/descriptors" import { getSmProvider } from "polkadot-api/sm-provider" import { chainSpec } from "polkadot-api/chains/polkadot" import { start } from "polkadot-api/smoldot" import { createClient } from "polkadot-api" const smoldot = start() const chain = await smoldot.addChain({ chainSpec }) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const bountiesSdk = createBountiesSdk(typedApi) ``` -------------------------------- ### Synchronous Compatibility Check Example Source: https://papi.how/typed Shows how to perform a synchronous compatibility check by first awaiting the `compatibilityToken` and then using it with the `isCompatible` method. This is useful for initializing compatibility checks early. ```typescript // Alternatively, we can await just once the compatibilityToken const compatibilityToken = await typedApi.compatibilityToken // And later on we can use it, so that `getCompatibilityLevel` is sync if ( query.isCompatible(CompatibilityLevel.BackwardsCompatible, compatibilityToken) ) { // do your stuff, the query is compatible } else { // the call is not compatible! // keep an eye on what you do } ``` -------------------------------- ### Asynchronous Compatibility Check Example Source: https://papi.how/typed Demonstrates how to use the `isCompatible` method asynchronously to check if a query is compatible with `CompatibilityLevel.BackwardsCompatible`. If not compatible, it suggests caution. ```typescript const query = typedApi.query.System.Number // in this case `getCompatibilityLevel` returns a Promise if (await query.isCompatible(CompatibilityLevel.BackwardsCompatible)) { // do your stuff, the query is compatible } else { // the call is not compatible! // keep an eye on what you do } ``` -------------------------------- ### Configure PAPI for No Descriptor Package Installation Source: https://papi.how/codegen For advanced use cases, you can configure the PAPI CLI to generate code without installing the `@polkadot-api/descriptors` package as a dependency. This is done by setting the `noDescriptorsPackage` option to `true` in the `.papi/polkadot-api.json` configuration file. The `descriptorPath` can also be customized. ```json { "descriptorPath": …, "entries": { … }, "options": { "noDescriptorsPackage": true } } ``` -------------------------------- ### Replaying Logs with Polkadot-API Source: https://papi.how/providers/enhancers This example demonstrates replaying previously recorded logs using the `logsProvider` from `polkadot-api/logs-provider`. It allows debugging specific scenarios by simulating node messages without an active connection. ```javascript // 2. replaying logs import { createClient } from "polkadot-api" import { logsProvider } from "polkadot-api/logs-provider" import logs from "./readLogs" const provider = logsProvider(logs) const client = createClient(provider) ``` -------------------------------- ### Initialize Polkadot-API Client with Smoldot Provider (JavaScript) Source: https://papi.how/providers/sm Initializes the Polkadot-API client using the Smoldot provider. This involves adding a chain to Smoldot, getting the Smoldot provider associated with that chain, and then creating the client. ```javascript import { chainSpec } from "polkadot-api/chains/polkadot" import { createClient } from "polkadot-api" import { getSmProvider } from "polkadot-api/sm-provider" import { start } from "polkadot-api/smoldot" const smoldot = start() const chain = smoldot.addChain({ chainSpec }) const provider = getSmProvider(chain) const client = createClient(provider) ``` -------------------------------- ### Add Polkadot Relay Chain Support Source: https://papi.how/recipes/upgrade This command adds support for the Polkadot relay chain to your Polkadot-API project. It involves installing the necessary packages and configuring the client for the 'dot' network. ```bash npx papi add dot -n polkadot ``` -------------------------------- ### Get Typed API for Polkadot-API Interactions Source: https://papi.how/client Provides the Typed API, the main entry point for runtime-specific interactions with Polkadot-API. It allows for storage queries, transaction creation, and running view functions. The Typed API has its own comprehensive documentation. ```typescript import { ChainDefinition, TypedApi } from '@polkadot-api/type-definitions'; // Assuming 'descriptors' is a ChainDefinition object const typedApi: TypedApi = getTypedApi(descriptors); // Now you can use typedApi for storage queries, transactions, etc. // Example: // const blockHash = await typedApi.chain.getBlockHash(100); // console.log(blockHash); ``` -------------------------------- ### Use PolkadotSigner for Signing (TypeScript) Source: https://papi.how/signers/extensions Demonstrates how to retrieve accounts from a connected extension and use the `polkadotSigner` to sign arbitrary byte arrays. It includes methods for getting current accounts and subscribing to account changes, along with unsubscribing. ```typescript let accountList = selectedExtension.getAccounts() const unsubscribe = selectedExtension.subscribe((newAccounts) => { accountList = newAccounts }) const firstSigner = accountList[0].polkadotSigner const mySignature = await firstSigner.signBytes(Uint8Array.from([0, 1, 2, 3])) // we call it if don't want to track account changes anymore unsubscribe() ``` -------------------------------- ### Get Referendum Confirmation Phase Timings Source: https://papi.how/sdks/governance/referenda Provides examples for retrieving the start and end blocks of a referendum's confirmation phase using the SDK. Returns a number representing the block or null if not applicable. ```typescript console.log(await referenda[0].getConfirmationStart()) // number | null console.log(await referenda[0].getConfirmationEnd()) // number | null ``` -------------------------------- ### Initialize Polkadot-API Client and Staking SDK Source: https://papi.how/sdks/staking-sdk Sets up the Polkadot-API client and initializes the Staking SDK. This involves configuring smoldot, adding chains, creating a client, obtaining a typed API, and finally creating the staking SDK instance. ```typescript import { createStakingSdk } from "@polkadot-api/sdk-staking" import { createClient } from "polkadot-api" import { getSmProvider } from "polkadot-api/sm-provider" import { polkadot, polkadot_asset_hub } from "polkadot-api/chains" import { start } from "polkadot-api/smoldot" import { dot } from "@polkadot-api/descriptors" const smoldot = start() const chain = smoldot.addChain({ chainSpec: polkadot }).then((relay) => smoldot.addChain({ chainSpec: polkadot_asset_hub, potentialRelayChains: [relay], }), ) const client = createClient(getSmProvider(chain)) const typedApi = client.getTypedApi(dot) const stakingSdk = createStakingSdk(client) ``` -------------------------------- ### Get Nomination Pools with Staking SDK Source: https://papi.how/sdks/staking-sdk The `getNominationPools` function retrieves a list of all current nomination pools, including their addresses, commission policies, active nominations, and state. The example filters for open pools and displays key information in a table. Requires the staking SDK. ```typescript const pools = await stakingSdk.getNominationPools() const openPools = pools.filter((pool) => pool.state === "Open") console.table( openPools.map(({ id, name, bond, memberCount, commission }) => ({ id, name, members: memberCount, totalBond: bond.toString(), commission: commission.current * 100, })), ) ``` -------------------------------- ### Get Single Nomination Pool Observable with Staking SDK Source: https://papi.how/sdks/staking-sdk The `getNominationPool$` function allows subscribing to updates for a specific nomination pool, tracking ledger changes and parameter adjustments in real-time. The example shows how to subscribe to pool ID 123 and unsubscribe later. Requires the staking SDK and a pool ID. ```typescript const pool$ = stakingSdk.getNominationPool$(123) const poolSub = pool$.subscribe((pool) => console.log("Pool 123 update", pool)) // Later, when done poolSub.unsubscribe() ``` -------------------------------- ### Create Client Source: https://papi.how/client Demonstrates how to create a PolkadotClient instance using the `createClient` function, requiring a provider and optionally accepting functions for metadata caching. ```APIDOC ## Create Client ### Description Creates a `PolkadotClient` instance. Requires a `provider` and optionally accepts `getMetadata` and `setMetadata` functions for caching. ### Method `createClient` ### Parameters #### Arguments - **provider** (*object*) - Required - The provider interface for the client. - **getMetadata** (*function*) - Optional - A function to retrieve cached metadata. - **setMetadata** (*function*) - Optional - A function to cache metadata. ### Request Example ```javascript import { createClient } from "polkadot-api" const client = createClient(provider) ``` ### Response Returns a `PolkadotClient` instance. ``` -------------------------------- ### Initialize Polkadot-API Identity SDK Source: https://papi.how/sdks/accounts/identity Initializes the Identity SDK by creating a client, obtaining the typed API for a specific chain (e.g., Polkadot), and then creating the identity SDK instance. Requires @polkadot-api/sdk-accounts, @polkadot-api/descriptors, polkadot-api/ws-provider, and polkadot-api. ```typescript import { createIdentitySdk } from "@polkadot-api/sdk-accounts" import { dot } from "@polkadot-api/descriptors" import { getWsProvider } from "polkadot-api/ws-provider" import { createClient } from "polkadot-api" const client = createClient( getWsProvider("wss://polkadot-people-rpc.polkadot.io"), ) const typedApi = client.getTypedApi(dot) const identitySdk = createIdentitySdk(typedApi) ``` -------------------------------- ### Initialize Referenda SDK with Kusama configuration Source: https://papi.how/sdks/governance/referenda Initializes the Referenda SDK with a specific configuration for Kusama, using the kusamaSpenderOrigin. This is necessary when dealing with Kusama's unique chain configurations. ```typescript import { createReferendaSdk, kusamaSpenderOrigin, } from "@polkadot-api/sdk-governance" const referendaSdk = createReferendaSdk(typedApi, { spenderOrigin: kusamaSpenderOrigin, }) ``` -------------------------------- ### Polkadot-API: StorageEntryWithoutKeys Type Definition Source: https://papi.how/typed/queries Defines the structure for a storage entry that does not require keys for indexing. It includes methods to check compatibility, get the compatibility level, retrieve the storage key, get the value at a specific block, and watch for value changes. ```typescript type CallOptions = Partial<{ at: string signal: AbortSignal }> type StorageEntryWithoutKeys = { isCompatible: IsCompatible getCompatibilityLevel: GetCompatibilityLevel getValue: (options?: CallOptions) => Promise watchValue: (bestOrFinalized?: "best" | "finalized") => Observable getKey: () => Promise getKey: (token: CompatibilityToken) => HexString } ``` -------------------------------- ### Get Filtered Statements (getStatements) Source: https://papi.how/sdks/statement Query for filtered statements by `topic` and/or `dest` key. ```APIDOC ## Get Filtered Statements (`getStatements`) ### Description Query for filtered statements by `topic` and/or `dest` key. Find meaning in Statement Store docs. ### Method `getStatements` ### Endpoint N/A ### Parameters - **dest** (`Binary` | `null` | `undefined`) - Required - A `Binary` for a specific destination key, `null` for no destination key, or `undefined` to disable filtering by `dest`. - **topics** (`Array`) - Required - An array of up to 4 topics to filter by. ### Request Example ```javascript import { stringToTopic } from "@polkadot-api/sdk-statement" import { Binary } from "polkadot-api" // statements with specific topics and specific decryptionkey. const statements = await statementSdk.getStatements({ topics: [stringToTopic("pop"), stringToTopic("chat"), stringToTopic("v1")], dest: Binary.fromHex( "0xf0673d30606ee26672707e4fd2bc8b58d3becb7aba2d5f60add64abb5fea4710", ), }) ``` ### Response - **statements** (`Array`) - An array of filtered statements. ### Response Example ```json [ { "topic": "pop", "dest": "0xf067...", "data": "0xdeadbeef", "signature": "0xabcd..." } ] ``` ``` -------------------------------- ### Initialize Linked Accounts SDK (TypeScript) Source: https://papi.how/sdks/accounts/linked-accounts Initializes the Linked Accounts SDK by creating a client, setting up a multisig provider (e.g., Subscan), and obtaining the typed API for a specific chain (e.g., Polkadot). This setup is crucial before using the SDK's functions. It requires the chain's WebSocket provider URL and potentially an API key for the multisig provider. ```typescript import { createLinkedAccountsSdk, subscanProvider, } from "@polkadot-api/sdk-accounts" import { dot } from "@polkadot-api/descriptors" import { getWsProvider } from "polkadot-api/ws-provider" import { createClient } from "polkadot-api" const client = createClient(getWsProvider("wss://rpc.ibp.network/polkadot")) const multisigProvider = subscanProvider("polkadot", process.env.SUBSCAN_KEY!) const typedApi = client.getTypedApi(dot) const linkedAccounts = createLinkedAccountsSdk(typedApi, multisigProvider) ``` -------------------------------- ### Get Complete Store (dump) Source: https://papi.how/sdks/statement Retrieve all statements from the provider's store. Note that this endpoint might be rate-limited. ```APIDOC ## Get Complete Store (`dump`) ### Description Retrieve all currently available statements from the provider's store. This endpoint might be rate-limited in some cases. ### Method `dump` ### Endpoint N/A ### Parameters None ### Request Example ```javascript // all currently available statements of that node. const statements = await statementSdk.dump() ``` ### Response - **statements** (`Array`) - An array of all statements in the store. ### Response Example ```json [ { "topic": "some_topic", "dest": "0x123...", "data": "0xdeadbeef", "signature": "0xabcd..." } ] ``` ``` -------------------------------- ### Inner Enum Variant Codec Example Source: https://papi.how/typed-codecs Illustrates accessing and encoding a specific inner enum variant using the typed codecs. ```APIDOC ## Inner Enum Variant Codec ### Description This example demonstrates how to access the codec for a specific enum variant, `XcmPalletQueryStatus.Ready`, and encode its structure. ### Method GET (Implicit via `getTypedCodecs`) ### Endpoint N/A (Code example) ### Parameters None ### Request Example ```javascript import { getTypedCodecs } from "polkadot-api" import { dot, XcmV4Response, XcmVersionedResponse, } from "@polkadot-api/descriptors" const codecs = await getTypedCodecs(dot) codecs.query.XcmPallet.Queries.value.inner.Ready.enc({ at: 100, response: XcmVersionedResponse.V4(XcmV4Response.Null()), }) ``` ### Response #### Success Response (200) N/A (Code example demonstrating output) #### Response Example The result of the `.enc()` call will be a Uint8Array representing the encoded structure of the `Ready` enum variant. ``` -------------------------------- ### Create Polkadot API Client Source: https://papi.how/client Demonstrates how to create a PolkadotClient instance using the `createClient` function. It requires a provider and optionally accepts functions for metadata caching. ```typescript import { createClient } from "polkadot-api" const client = createClient(provider) ``` -------------------------------- ### Initialize Polkadot-API Client for Ink! Contracts Source: https://papi.how/ink Demonstrates setting up a Polkadot-API client with support for ink! contracts. It involves creating a base client with a WebSocket provider and then initializing a specific ink! client using contract descriptors. It also shows how to obtain a typed API for a specific chain. ```typescript // Having added test AlephZero chain with `papi add` import { contracts, testAzero } from "@polkadot-api/descriptors" import { getInkClient } from "polkadot-api/ink" import { createClient } from "polkadot-api" import { withPolkadotSdkCompat } from "polkadot-api/polkadot-sdk-compat" import { getWsProvider } from "polkadot-api/ws-provider" const client = createClient( withPolkadotSdkCompat( getWsProvider("wss://aleph-zero-testnet-rpc.dwellir.com"), ), ) // Create a psp22 ink! client const psp22Client = getInkClient(contracts.psp22) // typedAPI for test AlephZero const typedApi = client.getTypedApi(testAzero) ``` -------------------------------- ### Manual Storage Entry Encoding Example Source: https://papi.how/typed-codecs Demonstrates how to use getTypedCodecs to manually encode a storage entry's key and value. ```APIDOC ## Manual Storage Entry Encoding ### Description This example shows how to manually encode the key and value for a storage entry, specifically `XcmPallet.Queries`. ### Method GET (Implicit via `getTypedCodecs`) ### Endpoint N/A (Code example) ### Parameters None ### Request Example ```javascript import { getTypedCodecs } from "polkadot-api" import { dot, XcmPalletQueryStatus, XcmV4Response, XcmVersionedResponse, } from "@polkadot-api/descriptors" const codecs = await getTypedCodecs(dot) const xcmQueriesCodecs = codecs.query.XcmPallet.Queries export const encodedValue = xcmQueriesCodecs.value.enc( XcmPalletQueryStatus.Ready({ at: 100000, response: XcmVersionedResponse.V4(XcmV4Response.Null()), }), ) export const encodedKey = xcmQueriesCodecs.args.enc([100n]) ``` ### Response #### Success Response (200) N/A (Code example demonstrating output) #### Response Example `encodedValue` and `encodedKey` will contain Uint8Array representations of the encoded data. ``` -------------------------------- ### Identity SDK - Get On-Chain Identities Source: https://papi.how/sdks/accounts/identity This section covers the functions for retrieving on-chain identity information using the Identity SDK. ```APIDOC ## Identity SDK - Get On-Chain Identities ### Description The Identity SDK provides functions to fetch and decode on-chain identity data for given addresses. It simplifies the retrieval of identity information, including decoded strings for various fields, judgement details, a verification status, and support for sub-identities. ### Method `getIdentity(address: SS58String): Promise` `getIdentities(addresses: SS58String[]): Promise>` ### Endpoint N/A (These are SDK functions, not direct API endpoints.) ### Parameters #### `getIdentity` Path Parameters - **address** (SS58String) - Required - The SS58 address of the identity to retrieve. #### `getIdentities` Path Parameters - **addresses** (SS58String[]) - Required - An array of SS58 addresses for which to retrieve identities. ### Request Example ```javascript // For getIdentity const identity = await identitySdk.getIdentity("13GtCixw3EZARj52CVbKLrsAzyc7dmmYhDV6quS5yeVCfnh1"); // For getIdentities const identities = await identitySdk.getIdentities([ "13GtCixw3EZARj52CVbKLrsAzyc7dmmYhDV6quS5yeVCfnh1", "14WBgUYr1scUwR5rvx7DwgMUhHtdtRyHMkurkU4AZ7wRgFxC" ]); ``` ### Response #### Success Response (Identity Object) - **info** (object) - Contains decoded identity information. - **email** (string) - The decoded email address. - **display** (string) - The decoded display name. - **github** (string) - The decoded GitHub username. - **twitter** (string) - The decoded Twitter username. - ... (other available fields) - **judgements** (array) - An array of judgement objects. - **registrar** (string) - The registrar's identifier. - **judgement** (string) - The type of judgement (e.g., "Reasonable", "KnownGood"). - **fee** (bigint) - Optional: The fee associated with the judgement. - **verified** (boolean) - True if the judgement is "Reasonable" or "KnownGood". - **subIdentity** (string) - Optional: The name of the sub-identity if the account is a sub-identity of another. #### Response Example ```json { "info": { "email": "example@example.com", "display": "RADIUMBLOCK.COM", "github": "radiumblock", "twitter": "radiumblock" }, "judgements": [ { "registrar": "0x123...", "judgement": "KnownGood", "fee": 10000000000n } ], "verified": true, "subIdentity": "03" } ``` #### Null Response - Returns `null` if no identity is found for the given address. ``` -------------------------------- ### Accessing System Version Constant Source: https://papi.how/typed/constants Demonstrates how to retrieve the 'System.Version' constant using both asynchronous and synchronous methods. ```APIDOC ## Accessing Constants (e.g., System.Version) ### Description Constants are key-value pairs embedded in the runtime metadata. They can be accessed asynchronously or synchronously. ### Method Asynchronous: `typedApi.constants.ModuleName.ConstantName()` Synchronous: `typedApi.constants.ModuleName.ConstantName(compatibilityToken)` ### Endpoint N/A (Constants are accessed directly via the API object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript // Asynchronous call const versionAsync = await typedApi.constants.System.Version(); // Synchronous call (requires compatibility token) const compatibilityToken = await typedApi.compatibilityToken; const versionSync = typedApi.constants.System.Version(compatibilityToken); ``` ### Response #### Success Response (200) - **version** (any) - The decoded value of the constant. #### Response Example ```json { "version": "1.0.0" } ``` ``` -------------------------------- ### Configure WS Provider with Options Source: https://papi.how/providers/ws Illustrates advanced configuration options for the WS provider, including setting connection timeouts, applying enhancers like `withLegacy`, and handling status changes via a callback. The `onStatusChanged` callback allows reacting to different connection events. ```javascript import { getWsProvider } from "polkadot-api/ws-provider" import { withLegacy } from "@polkadot-api/legacy-provider" const provider = getWsProvider("wss://myws.com", { timeout: 10_000, innerEnhancer: withLegacy(), onStatusChange: (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 } }, }) ``` -------------------------------- ### Entries Without Keys API Source: https://papi.how/typed/queries This section describes how to interact with storage entries that do not require keys for indexing. Examples include querying the block number. ```APIDOC ## Entries Without Keys ### Description This section describes how to interact with storage entries that do not require keys for indexing. Examples include querying the block number. ### Method N/A (This describes a data structure and its methods) ### Endpoint N/A ### Parameters #### CallOptions - **at** (string) - Optional - Specifies the block hash to query. Can be a block hash, \"finalized\", or \"best\". Defaults to \"finalized\". - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the request. #### StorageEntryWithoutKeys Methods - **isCompatible**: (Function) - Checks compatibility. - **getCompatibilityLevel**: (Function) - Gets the compatibility level. - **getValue**: (Function) - Retrieves the storage entry's value. Accepts optional `CallOptions`. - **watchValue**: (Function) - Returns an Observable that emits changes to the storage entry. Accepts an optional \"best\" or \"finalized\" argument. - **getKey**: (Function) - Builds the storage key for a query. Can optionally take a `CompatibilityToken` for synchronous retrieval. ### Request Example ```json { "example": "Calling getValue() on a StorageEntryWithoutKeys instance" } ``` ### Response #### Success Response (200) - **Payload**: The data type of the storage entry (e.g., number for block height). #### Response Example ```json { "example": "1234567" } ``` ``` -------------------------------- ### Interact with Added Solidity Contract Source: https://papi.how/sdks/ink-sdk Demonstrates how to get an instance of an added Solidity contract using its generated types and interact with its methods, such as querying a 'winningProposal'. ```typescript import { contracts } from "@polkadot-api/descriptors" const contractAddress = "0x45db12…" const ballot = inkSdk.getContract(contracts.ballot, contractAddress) const result = await ballot.query("winningProposal", { origin: ADDRESS.alice, }) if (result.success) { console.log(`Winning proposal: ${result.value.response.winningProposal_}`) } else { console.log(`request failed`, result.value) } ``` -------------------------------- ### WS Provider Initialization Source: https://papi.how/providers/ws This section covers how to initialize the WS provider, including single and multiple endpoint configurations, and the optional configuration object. ```APIDOC ## GET /ws-provider ### Description Initializes a WebSocket provider for interacting with JSON-RPC servers. ### Method GET ### Endpoint `/ws-provider` ### Parameters #### Query Parameters - **endpoints** (string | Array) - Required - One or more WebSocket URIs or objects specifying URI and protocols. - **config** (object) - Optional - Configuration object for the provider. - **onStatusChanged** (function) - Optional - Callback function to handle status changes. - **innerEnhancer** (function) - Optional - An enhancer to be applied before others. - **timeout** (number) - Optional - Connection timeout in milliseconds. - **heartbeatTimeout** (number) - Optional - Heartbeat timeout in milliseconds. - **websocketClass** (WebSocketClass) - Optional - Custom WebSocket implementation. ### Request Example ```javascript import { getWsProvider } from "polkadot-api/ws-provider" // Single endpoint const provider1 = getWsProvider("wss://myws.com") // Multiple endpoints const provider2 = getWsProvider([ "wss://myws.com", "wss://myfallbackws.com" ]) // With configuration import { withLegacy } from "@polkadot-api/legacy-provider" const provider3 = getWsProvider("wss://myws.com", { timeout: 10_000, innerEnhancer: withLegacy(), onStatusChanged: (status) => { console.log("Status changed:", status) }, heartbeatTimeout: 40_000, websocketClass: WebSocket // or a custom class }) ``` ### Response #### Success Response (200) - **WsJsonRpcProvider** (object) - An object with `switch` and `getStatus` methods. #### Response Example ```json { "switch": function(uri?: string, protocol?: string[]): void, "getStatus": function(): StatusChange } ``` ``` -------------------------------- ### Storage Entry with Keys Source: https://papi.how/typed/queries This section details the methods available for interacting with storage entries that have keys, including getting single values, multiple values, all entries, and watching for changes. ```APIDOC ## Storage Entry with Keys API This API provides methods for interacting with storage entries that utilize keys for indexing and retrieval. ### Methods - **`getValue(...args: [...Args, options?: CallOptions]) => Promise`**: Retrieves the value of a storage entry for the given arguments. Requires all keys for the storage query. - **`watchValue(...args: [...Args, bestOrFinalized?: "best" | "finalized"]) => Observable`**: Observes changes to a storage entry for the given arguments. Requires all keys for the storage query. - **`getValues(keys: Array<[...Args]>, options?: CallOptions) => Promise>`**: Retrieves multiple storage entries for the given keys. - **`getEntries(...args: [PossibleParents, options?: CallOptions]) => Promise }>>`**: Retrieves all storage entries, optionally accepting a subset of keys. - **`watchEntries(...args: [PossibleParents, options?: { at: "best" }]) => Observable<{ block: BlockInfo, deltas: null | { deleted: Array<{ args: ArgsOut, value: NonNullable }>, upserted: Array<{ args: ArgsOut, value: NonNullable }> }, entries: Array<{ args: ArgsOut, value: NonNullable }> }>`**: Watches for changes to all storage entries, optionally accepting a subset of keys. - **`getKey(...args: PossibleArgs) => Promise`**: Builds the storage key for a specific query and set of arguments. - **`getKey(...args: PossibleArgs, token: CompatibilityToken) => HexString`**: Builds the storage key synchronously if a CompatibilityToken is provided. ### Usage Examples **Getting a single value:** ```javascript typedApi.query.Pallet.Query.getValue(arg1, arg2, arg3, { at: "best" }) ``` **Getting multiple values:** ```javascript typedApi.query.Pallet.Query.getValues([[key1_arg1, key1_arg2], [key2_arg1, key2_arg2]]) ``` **Getting all entries (no keys):** ```javascript typedApi.query.Pallet.Query.getEntries({ at: "best" }) ``` **Getting entries with a subset of keys (1 out of 3):** ```javascript typedApi.query.Pallet.Query.getEntries(arg1, { at: "finalized" }) ``` **Getting entries with a subset of keys (2 out of 3):** ```javascript typedApi.query.Pallet.Query.getEntries(arg1, arg2, { at: "0x12345678" }) ``` **Watching entries with a subset of keys:** ```javascript typedApi.query.Pallet.Query.watchEntries(arg1, { at: "best" }) ``` **Getting a storage key:** ```javascript typedApi.query.Pallet.Query.getKey(arg1, arg2) ``` **Getting a storage key synchronously:** ```javascript typedApi.query.Pallet.Query.getKey(arg1, arg2, compatibilityToken) ``` ### Response Structure for `watchEntries` ```json { "block": { "hash": "string", "number": "number", "parentHash": "string" }, "deltas": { "deleted": [ { "args": "any", "value": "any" } ], "upserted": [ { "args": "any", "value": "any" } ] } | null, "entries": [ { "args": "any", "value": "any" } ] } ``` ``` -------------------------------- ### Initialize and Use Offline API with Polkadot-API Source: https://papi.how/offline Demonstrates how to initialize the offline API using metadata descriptors and access constants like SS58Prefix and version information. It also shows how to create, encode, decode, and sign transactions, including batching multiple calls and specifying mandatory signing parameters like nonce and mortality. ```typescript import { getOfflineApi } from "polkadot-api" import { dotDescriptors } from "@polkadot-api/descriptors" // you'll need them! const offline = await getOfflineApi(dotDescriptors) // it is async! // metadata constants can be easily accessed const prefix = offline.constants.System.SS58Prefix // directly the value; e.g. `0` const { spec_name, spec_version } = offline.constants.System.Version // transactions can be created and signed const tx = offline.tx.Balances.transfer_keep_alive({ dest: MultiAddress.Id(myAddr), value: amount, }) tx.encodedData // we have the encoded callData tx.decodedCall // and the decodedCall const tx2 = offline.tx.Utility.batch({ calls: [ offline.tx.System.remark({ remark: Binary.fromText("HELLO!") }).decodedCall, tx.decodedCall, ], }) // we can sign txs, but we need to add more stuff than usual! const signedTx = await tx2.sign(signer, { nonce: 24, // nonce is always compulsory mortality: { mortal: false }, // and mortality! }) ``` -------------------------------- ### TypeScript: Get Bare Transaction (getBareTx) Source: https://papi.how/typed/tx Packs a transaction into a 'Bare'/'Unsigned' format, preferring Extrinsic V5 and falling back to V4. Can be made synchronous using a compatibilityToken or asynchronous (promise-based). ```typescript interface TxBare { (): Promise (compatibilityToken: CompatibilityToken): HexString } ``` -------------------------------- ### TypeScript: Get Storage Key Source: https://papi.how/typed/queries Explains how to construct the storage key for a given query and set of arguments. The `getKey` method can optionally accept a `CompatibilityToken` to perform the operation synchronously. ```typescript typedApi.query.Pallet.Query.getKey(...args) typedApi.query.Pallet.Query.getKey(...args, token) ```