Polkadot.js API
Introduction
Section titled “Introduction”The Polkadot.js API uses JavaScript/TypeScript to interact with Polkadot SDK-based chains. It allows you to query nodes, read chain state, and submit transactions through a dynamic, auto-generated API interface.
Dynamic API Generation
Section titled “Dynamic API Generation”Unlike traditional static APIs, the Polkadot.js API generates its interfaces automatically when connecting to a node. Here's what happens when you connect:
- The API connects to your node.
- It retrieves the chain's metadata.
- Based on this metadata, it creates specific endpoints in this format:
api.<type>.<module>.<section>.
Available API Categories
Section titled “Available API Categories”You can access three main categories of chain interactions:
-
Runtime constants (
api.consts):- Access runtime constants directly.
- Returns values immediately without function calls.
- Example:
api.consts.balances.existentialDeposit
-
State queries (
api.query):- Read chain state.
- Example:
api.query.system.account(accountId)
-
Transactions (
api.tx):- Submit extrinsics (transactions).
- Example:
api.tx.balances.transfer(accountId, value)
The available methods and interfaces will automatically reflect what's possible on your connected chain.
Installation
Section titled “Installation”To add the Polkadot.js API to your project, use the following command to install the version 17.0.2 which supports any Polkadot SDK-based chain:
npm i @polkadot/api@17.0.2pnpm add @polkadot/api@17.0.2yarn add @polkadot/api@17.0.2For more detailed information about installation, see the Installation section in the official Polkadot.js API documentation.
Get Started
Section titled “Get Started”Creating an API Instance
Section titled “Creating an API Instance”To interact with a Polkadot SDK-based chain, you must establish a connection through an API instance. The API provides methods for querying chain state, sending transactions, and subscribing to updates.
To create an API connection:
import { ApiPromise, WsProvider } from '@polkadot/api';
// Create a WebSocket providerconst wsProvider = new WsProvider('wss://rpc.polkadot.io');
// Initialize the APIconst api = await ApiPromise.create({ provider: wsProvider });
// Verify the connection by getting the chain's genesis hashconsole.log('Genesis Hash:', api.genesisHash.toHex());Reading Chain Data
Section titled “Reading Chain Data”The API provides several ways to read data from the chain. You can access:
-
Constants: Values that are fixed in the runtime and don't change without a runtime upgrade.
// Get the minimum balance required for a new accountconst minBalance = api.consts.balances.existentialDeposit.toNumber(); -
State: Current chain state that updates with each block.
// Example addressconst address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE';// Get current timestampconst timestamp = await api.query.timestamp.now();// Get account informationconst { nonce, data: balance } = await api.query.system.account(address);console.log(`Timestamp: ${timestamp}Free Balance: ${balance.free}Nonce: ${nonce}`);
Sending Transactions
Section titled “Sending Transactions”Transactions (also called extrinsics) modify the chain state. Before sending a transaction, you need:
- A funded account with sufficient balance to pay transaction fees.
- The account's keypair for signing.
To make a transfer:
// Assuming you have an `alice` keypair from the Keyringconst recipient = 'INSERT_RECIPIENT_ADDRESS';const amount = 'INSERT_VALUE'; // Amount in the smallest unit (e.g., Planck for DOT)
// Sign and send a transferconst txHash = await api.tx.balances .transfer(recipient, amount) .signAndSend(alice);
console.log('Transaction Hash:', txHash);The alice keypair in the example comes from a Keyring object. For more details about managing keypairs, see the Keyring documentation.
Where to Go Next
Section titled “Where to Go Next”For more detailed information about the Polkadot.js API, check the official documentation.