Skip to main content

Connect API

The API allows us to interact with the chain and make queries via Javascript. The basic API is implemented on the Substrate layer and is the same for all substrate-based networks.

Complete API overview and cookbook is on Polkadot documentation portal.

Below are a few entry points for interact with Gear RPC Node:

Dev mode:

ws://127.0.0.1:9944

Testnet:

wss://rpc-node.gear-tech.io:443

Installation

npm install @gear-js/api

or

yarn add @gear-js/api

Getting started

Start an API connection to a running node on localhost

import { GearApi } from '@gear-js/api';

const gearApi = await GearApi.create();

You can also connect to a different node

const gearApi = await GearApi.create({
providerAddress: 'wss://someIP:somePort',
});

Getting node info

const chain = await gearApi.chain();
const nodeName = await gearApi.nodeName();
const nodeVersion = await gearApi.nodeVersion();
const genesis = gearApi.genesisHash.toHex();

Example

This simple example describes how to subscribe to a new blocks and get chain spec:

async function connect() {
const gearApi = await GearApi.create();

const [chain, nodeName, nodeVersion] = await Promise.all([
gearApi.chain(),
gearApi.nodeName(),
gearApi.nodeVersion(),
]);

console.log(
`You are connected to chain ${chain} using ${nodeName} v${nodeVersion}`,
);

const unsub = await gearApi.gearEvents.subscribeToNewBlocks((header) => {
console.log(
`New block with number: ${header.number.toNumber()} and hash: ${header.hash.toHex()}`,
);
});
}
connect().catch(console.error);