What is @cosmjs/stargate?
@cosmjs/stargate is a JavaScript library for interacting with Cosmos SDK-based blockchains. It provides tools for connecting to nodes, querying blockchain data, and creating and signing transactions.
Connecting to a Blockchain
This feature allows you to connect to a Cosmos SDK-based blockchain using an RPC endpoint. The code sample demonstrates how to establish a connection and retrieve the chain ID.
const { StargateClient } = require('@cosmjs/stargate');
async function connect() {
const rpcEndpoint = 'https://rpc.cosmos.network';
const client = await StargateClient.connect(rpcEndpoint);
console.log('Connected to chain:', await client.getChainId());
}
connect();
Querying Blockchain Data
This feature allows you to query blockchain data such as account information. The code sample demonstrates how to retrieve account data for a given address.
const { StargateClient } = require('@cosmjs/stargate');
async function queryAccount(address) {
const rpcEndpoint = 'https://rpc.cosmos.network';
const client = await StargateClient.connect(rpcEndpoint);
const account = await client.getAccount(address);
console.log('Account data:', account);
}
queryAccount('cosmos1...');
Creating and Signing Transactions
This feature allows you to create and sign transactions. The code sample demonstrates how to send tokens from one account to another, including setting up the wallet, connecting to the blockchain, and broadcasting the transaction.
const { DirectSecp256k1HdWallet } = require('@cosmjs/proto-signing');
const { assertIsBroadcastTxSuccess, SigningStargateClient } = require('@cosmjs/stargate');
async function sendTokens() {
const mnemonic = 'your mnemonic here';
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic);
const [firstAccount] = await wallet.getAccounts();
const rpcEndpoint = 'https://rpc.cosmos.network';
const client = await SigningStargateClient.connectWithSigner(rpcEndpoint, wallet);
const amountFinal = {
denom: 'uatom',
amount: '1000',
};
const fee = {
amount: [{ denom: 'uatom', amount: '500' }],
gas: '200000',
};
const result = await client.sendTokens(firstAccount.address, 'cosmos1...', [amountFinal], fee, 'Test transaction');
assertIsBroadcastTxSuccess(result);
console.log('Transaction successful:', result);
}
sendTokens();