Core client classes for connecting to and interacting with Cosmos SDK blockchains. The package provides two main client types: read-only querying and transaction signing capabilities.
Read-only client for querying blockchain state and broadcasting pre-signed transactions.
/**
* Read-only client for interacting with Cosmos SDK chains
*/
class StargateClient {
/** Connect to a blockchain endpoint */
static async connect(endpoint: string | HttpEndpoint, options?: StargateClientOptions): Promise<StargateClient>;
/** Create client from existing CometBFT client */
static create(cometClient: CometClient, options?: StargateClientOptions): StargateClient;
/** Get the chain identifier */
async getChainId(): Promise<string>;
/** Get current block height */
async getHeight(): Promise<number>;
/** Get account information by address */
async getAccount(searchAddress: string): Promise<Account | null>;
/** Get account sequence information */
async getSequence(address: string): Promise<SequenceResponse>;
/** Get block by height (latest if not specified) */
async getBlock(height?: number): Promise<Block>;
/** Get single token balance for an address */
async getBalance(address: string, searchDenom: string): Promise<Coin>;
/** Get all token balances for an address */
async getAllBalances(address: string): Promise<readonly Coin[]>;
/** Get staked balance for an address */
async getBalanceStaked(address: string): Promise<Coin | null>;
/** Get delegation amount between delegator and validator */
async getDelegation(delegatorAddress: string, validatorAddress: string): Promise<Coin | null>;
/** Get transaction by hash */
async getTx(id: string): Promise<IndexedTx | null>;
/** Search transactions by query */
async searchTx(query: SearchTxQuery): Promise<IndexedTx[]>;
/** Broadcast transaction and wait for inclusion in a block */
async broadcastTx(tx: Uint8Array, timeoutMs?: number, pollIntervalMs?: number): Promise<DeliverTxResponse>;
/** Broadcast transaction synchronously (returns immediately) */
async broadcastTxSync(tx: Uint8Array): Promise<string>;
/** Disconnect from the endpoint */
disconnect(): void;
}
interface StargateClientOptions {
/** Custom account parser for non-standard account types */
readonly accountParser?: AccountParser;
}Usage Examples:
import { StargateClient } from "@cosmjs/stargate";
// Connect to mainnet
const client = await StargateClient.connect("https://rpc.cosmos.network:443");
// Query basic information
const chainId = await client.getChainId(); // "cosmoshub-4"
const height = await client.getHeight(); // 12345678
// Query account data
const account = await client.getAccount("cosmos1abc123...");
const balances = await client.getAllBalances("cosmos1abc123...");
// Query specific balance
const atomBalance = await client.getBalance("cosmos1abc123...", "uatom");
// Search transactions
const txs = await client.searchTx({
sentFromOrTo: "cosmos1abc123..."
});
// Clean up
client.disconnect();Client with transaction signing capabilities for wallets and applications that need to submit transactions.
/**
* Client with transaction signing capabilities
*/
class SigningStargateClient extends StargateClient {
/** Connect to endpoint with a signer */
static async connectWithSigner(
endpoint: string | HttpEndpoint,
signer: OfflineSigner,
options?: SigningStargateClientOptions
): Promise<SigningStargateClient>;
/** Create client from existing CometBFT client with signer */
static createWithSigner(
cometClient: CometClient,
signer: OfflineSigner,
options?: SigningStargateClientOptions
): SigningStargateClient;
/** Create offline signer (for transaction preparation) */
static async offline(signer: OfflineSigner, options?: SigningStargateClientOptions): Promise<SigningStargateClient>;
/** Simulate transaction execution to estimate gas */
async simulate(signerAddress: string, messages: readonly EncodeObject[], memo: string | undefined): Promise<number>;
/** Send tokens between addresses */
async sendTokens(
senderAddress: string,
recipientAddress: string,
amount: readonly Coin[],
fee: StdFee | "auto" | number,
memo?: string
): Promise<DeliverTxResponse>;
/**
* Send IBC tokens to another chain
* @deprecated This API does not support setting the memo field of MsgTransfer.
* Use signAndBroadcast with MsgTransferEncodeObject instead.
*/
async sendIbcTokens(
senderAddress: string,
recipientAddress: string,
transferAmount: Coin,
sourcePort: string,
sourceChannel: string,
timeoutHeight: Height | undefined,
timeoutTimestamp: number | undefined,
fee: StdFee | "auto" | number,
memo?: string
): Promise<DeliverTxResponse>;
/** Delegate tokens to a validator */
async delegateTokens(
delegatorAddress: string,
validatorAddress: string,
amount: Coin,
fee: StdFee | "auto" | number,
memo?: string
): Promise<DeliverTxResponse>;
/** Undelegate tokens from a validator */
async undelegateTokens(
delegatorAddress: string,
validatorAddress: string,
amount: Coin,
fee: StdFee | "auto" | number,
memo?: string
): Promise<DeliverTxResponse>;
/** Withdraw staking rewards */
async withdrawRewards(
delegatorAddress: string,
validatorAddress: string,
fee: StdFee | "auto" | number,
memo?: string
): Promise<DeliverTxResponse>;
/** Sign and broadcast multiple messages */
async signAndBroadcast(
signerAddress: string,
messages: readonly EncodeObject[],
fee: StdFee | "auto" | number,
memo?: string,
timeoutHeight?: bigint
): Promise<DeliverTxResponse>;
/** Sign and broadcast synchronously (returns immediately) */
async signAndBroadcastSync(
signerAddress: string,
messages: readonly EncodeObject[],
fee: StdFee | "auto" | number,
memo?: string,
timeoutHeight?: bigint
): Promise<string>;
/** Sign transaction without broadcasting */
async sign(
signerAddress: string,
messages: readonly EncodeObject[],
fee: StdFee,
memo: string,
explicitSignerData?: SignerData,
timeoutHeight?: bigint
): Promise<TxRaw>;
/** Protocol buffer type registry */
readonly registry: Registry;
/** Broadcast timeout in milliseconds */
readonly broadcastTimeoutMs: number | undefined;
/** Broadcast polling interval in milliseconds */
readonly broadcastPollIntervalMs: number | undefined;
}
interface SigningStargateClientOptions extends StargateClientOptions {
/** Custom protocol buffer type registry */
readonly registry?: Registry;
/** Custom amino type converters */
readonly aminoTypes?: AminoTypes;
/** Transaction broadcast timeout */
readonly broadcastTimeoutMs?: number;
/** Transaction broadcast polling interval */
readonly broadcastPollIntervalMs?: number;
/** Gas price for automatic fee calculation */
readonly gasPrice?: GasPrice;
}
interface SignerData {
/** Account number from the blockchain */
readonly accountNumber: number;
/** Current sequence number */
readonly sequence: number;
/** Chain identifier */
readonly chainId: string;
}Usage Examples:
import { SigningStargateClient, GasPrice } from "@cosmjs/stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
// Create wallet from mnemonic
const wallet = await DirectSecp256k1HdWallet.fromMnemonic(
"surround miss nominee dream gap cross assault thank captain prosper drop duty group candy wealth weather scale put"
);
// Get first account
const [account] = await wallet.getAccounts();
// Connect with signer
const client = await SigningStargateClient.connectWithSigner(
"https://rpc.cosmos.network:443",
wallet,
{
gasPrice: GasPrice.fromString("0.025uatom"),
broadcastTimeoutMs: 60000
}
);
// Send tokens
const sendResult = await client.sendTokens(
account.address,
"cosmos1recipient...",
[{ denom: "uatom", amount: "1000000" }], // 1 ATOM
"auto", // Calculate fee automatically
"Payment for services"
);
// Delegate to validator
const delegateResult = await client.delegateTokens(
account.address,
"cosmosvaloper1validator...",
{ denom: "uatom", amount: "5000000" }, // 5 ATOM
"auto"
);
// Custom message transaction
import { MsgVote } from "cosmjs-types/cosmos/gov/v1beta1/tx";
const voteMsg = {
typeUrl: "/cosmos.gov.v1beta1.MsgVote",
value: MsgVote.fromPartial({
proposalId: Long.fromNumber(1),
voter: account.address,
option: VoteOption.VOTE_OPTION_YES,
}),
};
const voteResult = await client.signAndBroadcast(
account.address,
[voteMsg],
"auto",
"Voting yes on proposal 1"
);The package provides default configurations for common use cases.
/** Default protocol buffer types for all supported Cosmos SDK modules */
const defaultRegistryTypes: ReadonlyArray<[string, GeneratedType]>;
/** Creates default amino converters for all supported modules */
function createDefaultAminoConverters(): AminoConverters;interface SequenceResponse {
/** Account number on the blockchain */
readonly accountNumber: number;
/** Current sequence number for transactions */
readonly sequence: number;
}
interface Block {
/** Block hash (uppercase hex) */
readonly id: string;
/** Block header information */
readonly header: BlockHeader;
/** Raw transaction bytes in the block */
readonly txs: readonly Uint8Array[];
}
interface BlockHeader {
/** Block and app version information */
readonly version: {
readonly block: string;
readonly app: string;
};
/** Block height */
readonly height: number;
/** Chain identifier */
readonly chainId: string;
/** Block timestamp (RFC 3339) */
readonly time: string;
}
interface IndexedTx {
/** Block height containing the transaction */
readonly height: number;
/** Transaction index within the block */
readonly txIndex: number;
/** Transaction hash */
readonly hash: string;
/** Result code (0 = success) */
readonly code: number;
/** Transaction events */
readonly events: readonly Event[];
/** Raw log string (deprecated in Cosmos SDK 0.50+) */
readonly rawLog: string;
/** Raw transaction bytes */
readonly tx: Uint8Array;
/** Typed message responses */
readonly msgResponses: Array<{
readonly typeUrl: string;
readonly value: Uint8Array;
}>;
/** Gas consumed by transaction */
readonly gasUsed: bigint;
/** Gas requested for transaction */
readonly gasWanted: bigint;
}
interface DeliverTxResponse {
/** Block height containing the transaction */
readonly height: number;
/** Transaction index within the block */
readonly txIndex: number;
/** Result code (0 = success) */
readonly code: number;
/** Transaction hash */
readonly transactionHash: string;
/** Transaction events */
readonly events: readonly Event[];
/** Raw log string (deprecated in Cosmos SDK 0.50+) */
readonly rawLog?: string;
/** Message data (deprecated) */
readonly data?: readonly MsgData[];
/** Typed message responses */
readonly msgResponses: Array<{
readonly typeUrl: string;
readonly value: Uint8Array;
}>;
/** Gas consumed by transaction */
readonly gasUsed: bigint;
/** Gas requested for transaction */
readonly gasWanted: bigint;
}
interface Height {
/** IBC revision number */
readonly revisionNumber: bigint;
/** IBC revision height */
readonly revisionHeight: bigint;
}