Promise and RxJS wrappers around the Polkadot JS RPC for interacting with Polkadot and Substrate-based blockchains
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core API creation and connection management for both Promise and RxJS patterns. The @polkadot/api package provides two main API classes that share the same underlying functionality but differ in their async patterns.
Promise-based API implementation for standard async/await patterns.
class ApiPromise {
/**
* Create API instance and connect to provider
* @param options - Configuration options
* @returns Promise resolving to connected API instance
*/
static create(options?: ApiOptions): Promise<ApiPromise>;
/**
* Create API instance (requires manual ready check)
* @param options - Configuration options
*/
constructor(options?: ApiOptions);
/**
* Promise that resolves when API is connected and ready
*/
get isReady(): Promise<ApiPromise>;
/**
* Promise that resolves or rejects based on connection status
*/
get isReadyOrError(): Promise<ApiPromise>;
/**
* Create a new API instance with the same configuration
*/
clone(): ApiPromise;
/**
* Combine multiple subscription functions into a single callback
*/
combineLatest<T>(
fns: (CombinatorFunction | [CombinatorFunction, ...any[]])[],
callback: CombinatorCallback<T>
): Promise<() => void>;
/**
* Connect to the underlying provider
*/
connect(): Promise<void>;
/**
* Disconnect from the underlying provider
*/
disconnect(): Promise<void>;
/**
* Set external signer for transactions
*/
setSigner(signer?: Signer): void;
}RxJS Observable-based API implementation for reactive programming patterns.
class ApiRx {
/**
* Create API instance and return Observable of connected instance
* @param options - Configuration options
* @returns Observable emitting connected API instance
*/
static create(options?: ApiOptions): Observable<ApiRx>;
/**
* Create API instance (requires manual ready check)
* @param options - Configuration options
*/
constructor(options?: ApiOptions);
/**
* Observable that emits when API is connected and ready
*/
get isReady(): Observable<ApiRx>;
/**
* Create a new API instance with the same configuration
*/
clone(): ApiRx;
/**
* Connect to the underlying provider
*/
connect(): Promise<void>;
/**
* Disconnect from the underlying provider
*/
disconnect(): Promise<void>;
/**
* Set external signer for transactions
*/
setSigner(signer?: Signer): void;
}Complete configuration interface for API initialization.
interface ApiOptions {
/** Provider instance for blockchain connection */
provider?: ProviderInterface;
/** Custom type definitions for runtime types */
types?: RegistryTypes;
/** User-defined RPC methods */
rpc?: Record<string, Record<string, DefinitionRpc | DefinitionRpcSub>>;
/** Custom derive functions */
derives?: DeriveCustom;
/** Pre-bundled metadata by genesis hash and spec version */
metadata?: Record<string, HexString>;
/** Disable initialization warnings */
noInitWarn?: boolean;
/** Throw error on connection failure */
throwOnConnect?: boolean;
/** Throw error on unknown types */
throwOnUnknown?: boolean;
/** External transaction signer */
signer?: Signer;
/** Type registry instance */
registry?: Registry;
/** Chain-specific signed extensions */
signedExtensions?: ExtDef;
/** Source API for cloning */
source?: ApiBase<any>;
/** Initialize WASM libraries */
initWasm?: boolean;
/** Enable pedantic storage checking */
isPedantic?: boolean;
/** RPC cache capacity */
rpcCacheCapacity?: number;
/** Runtime call overrides */
runtime?: DefinitionsCall;
}
interface RegistryTypes {
[typeName: string]: string | object | any;
}
type CombinatorCallback<T> = (...args: T) => void;
type CombinatorFunction = (callback: (value: any) => void) => UnsubscribePromise;
type UnsubscribePromise = Promise<() => void>;import { ApiPromise, WsProvider } from "@polkadot/api";
// Simple initialization with default provider
const api = await ApiPromise.create();
// With custom WebSocket provider
const provider = new WsProvider("wss://rpc.polkadot.io");
const api = await ApiPromise.create({ provider });
// With error handling
try {
const api = await ApiPromise.create({
provider: new WsProvider("wss://rpc.polkadot.io"),
throwOnConnect: true
});
console.log("Connected successfully");
} catch (error) {
console.error("Connection failed:", error);
}import { ApiRx, WsProvider } from "@polkadot/api";
import { switchMap } from "rxjs";
// Create and use API in RxJS chain
ApiRx.create({ provider: new WsProvider("wss://rpc.polkadot.io") })
.pipe(
switchMap((api) => api.rpc.chain.subscribeNewHeads())
)
.subscribe((header) => {
console.log(`New block #${header.number}`);
});import { ApiPromise, WsProvider } from "@polkadot/api";
const api = await ApiPromise.create({
provider: new WsProvider("wss://rpc.polkadot.io"),
types: {
// Custom type definitions
CustomStruct: {
id: "u32",
data: "Vec<u8>",
owner: "AccountId"
}
},
rpc: {
// Custom RPC methods
custom: {
getCustomData: {
description: "Get custom data",
params: [
{ name: "id", type: "u32" }
],
type: "CustomStruct"
}
}
},
derives: {
// Custom derive functions
custom: {
processedData: (instanceId, api) => (id) =>
api.rpc.custom.getCustomData(id).pipe(
map(data => ({ ...data, processed: true }))
)
}
}
});import { ApiPromise, WsProvider } from "@polkadot/api";
// Create instance without auto-connection
const api = new ApiPromise({ provider: new WsProvider("wss://rpc.polkadot.io") });
// Wait for ready state
await api.isReady;
console.log("API is ready");
// Or handle errors
try {
await api.isReadyOrError;
console.log("API connected successfully");
} catch (error) {
console.error("API connection failed:", error);
}import { ApiPromise, WsProvider } from "@polkadot/api";
const api = await ApiPromise.create({
provider: new WsProvider("wss://rpc.polkadot.io")
});
// Check connection status
console.log("Connected:", api.isConnected);
// Manually disconnect
await api.disconnect();
console.log("Disconnected");
// Reconnect
await api.connect();
console.log("Reconnected");import { ApiPromise } from "@polkadot/api";
const api = await ApiPromise.create();
// Combine multiple subscriptions
const unsubscribe = await api.combineLatest([
api.rpc.chain.subscribeNewHeads,
(callback) => api.query.timestamp.now(callback)
], ([header, timestamp]) => {
console.log(`Block #${header.number} at ${timestamp}`);
});
// Stop subscriptions
unsubscribe();Install with Tessl CLI
npx tessl i tessl/npm-polkadot--api