Skip to main content

Getting started

Gear-JS API

The Gear-JS API provides a set of utilities, libraries and tools that enable JavaScript applications to interact with programs running in the Gear network via queries to a Gear node.

The sections below describe tools that you can use in your JS application to implement basic functions such as managing your key pair (account), calculating gas required for network operations, uploading program in the network, sending a message to a program, reading program's state, getting messages from the user's mailbox, working with metadata and more. Some useful code snippets are provided in the Cookbook section.

The basic API is implemented on the Substrate layer and is the same for all Substrate-based networks. The Gear-JS API code is available on GitHub. Complete API overview can be found on the Polkadot documentation portal.

note

Since Vara and Vara Testnet can have different runtime versions, they may have different extrinsic signatures. If your application is operating on the Vara Network, it is more convenient to use the VaraApi class instead of GearApi and VaraTestnetApi for the Vara Testnet Network.

Installation

npm install @gear-js/api

or

yarn add @gear-js/api

Getting started

Start the API connection to the local running RPC node:

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: 'ws[s]://someIP[:somePort]',
});
note

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

For connection to local node use:

ws://127.0.0.1:9944

For connection to Vara Network Testnet use:

wss://testnet.vara.network

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({
providerAddress: 'wss://testnet.vara.network',
});

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);

Also, refer to the article that demonstrates the creation of a React application that connects to an NFT smart contract running on the blockchain.