Getting started
Gear-JS APIâ
The Gear-JS API provides a set of utilities, libraries and tools that enable JavaScript applications to interact with smart contracts running in the Gear network via queries to a Gear node.
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.
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]',
});
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.io
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.io',
});
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.