# @cosmjs/stargate Agent Guide

> **Package**: `@cosmjs/stargate` v0.38.0 **Purpose**: High-level client for
> Cosmos SDK 0.40+ chains **Layer**: Client Layer (top-level package)

## Package Overview

The primary client library for interacting with Cosmos SDK 0.40+ (Stargate)
chains. Provides both read-only querying and transaction signing/broadcasting.

### Key Features

- **StargateClient**: Read-only queries
- **SigningStargateClient**: Sign and broadcast transactions
- **Query Extensions**: Modular query system (bank, staking, gov, etc.)
- **Gas Estimation**: Automatic fee calculation
- **Transaction Search**: Query transaction history

## Key Exports

| Export                    | Purpose                           |
| ------------------------- | --------------------------------- |
| `StargateClient`          | Read-only client                  |
| `SigningStargateClient`   | Signing client                    |
| `QueryClient`             | Base query client with extensions |
| `calculateFee()`          | Fee calculation                   |
| `GasPrice`                | Gas price representation          |
| `coin()`, `coins()`       | Coin utilities                    |
| `setupBankExtension()`    | Bank module queries               |
| `setupStakingExtension()` | Staking module queries            |
| `setupGovExtension()`     | Governance module queries         |

## Common Usage

### Read-Only Client

```typescript
import { StargateClient } from "@cosmjs/stargate";

const client = await StargateClient.connect("https://rpc.cosmos.network");

// Query balance
const balance = await client.getBalance(address, "uatom");

// Query account
const account = await client.getAccount(address);

// Get block
const block = await client.getBlock(height);

// Search transactions
const txs = await client.searchTx({ sentFromOrTo: address });
```

### Signing Client

```typescript
import { SigningStargateClient, GasPrice } from "@cosmjs/stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";

const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic);
const client = await SigningStargateClient.connectWithSigner(
  "https://rpc.cosmos.network",
  wallet,
  { gasPrice: GasPrice.fromString("0.025uatom") },
);

// Send tokens
const result = await client.sendTokens(
  senderAddress,
  recipientAddress,
  [{ denom: "uatom", amount: "1000000" }],
  "auto", // or specific fee
);

// Delegate
await client.delegateTokens(
  delegatorAddress,
  validatorAddress,
  { denom: "uatom", amount: "1000000" },
  "auto",
);

// Sign and broadcast custom message
await client.signAndBroadcast(signerAddress, [customMessage], "auto", "memo");
```

### Query Extensions

```typescript
import {
  QueryClient,
  setupBankExtension,
  setupStakingExtension,
} from "@cosmjs/stargate";
import { Tendermint37Client } from "@cosmjs/tendermint-rpc";

const tmClient = await Tendermint37Client.connect(rpcUrl);
const queryClient = QueryClient.withExtensions(
  tmClient,
  setupBankExtension,
  setupStakingExtension,
);

// Use extensions
const supply = await queryClient.bank.totalSupply();
const validators = await queryClient.staking.validators("BOND_STATUS_BONDED");
```

## Common Patterns

### Pattern: Multi-Signature Transaction

```typescript
const messages = [
  {
    typeUrl: "/cosmos.bank.v1beta1.MsgSend",
    value: { fromAddress, toAddress, amount: coins(1000, "uatom") },
  },
  {
    typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
    value: { delegatorAddress, validatorAddress, amount: coin(500, "uatom") },
  },
];

const result = await client.signAndBroadcast(signerAddress, messages, "auto");
```

### Pattern: Gas Estimation

```typescript
import { calculateFee, GasPrice } from "@cosmjs/stargate";

// Simulate transaction
const gasEstimate = await client.simulate(signerAddress, messages, memo);

// Add 20% buffer
const gasLimit = Math.round(gasEstimate * 1.2);

// Calculate fee
const gasPrice = GasPrice.fromString("0.025uatom");
const fee = calculateFee(gasLimit, gasPrice);
```

### Pattern: Transaction Polling

```typescript
const result = await client.sendTokens(sender, recipient, amount, "auto");

// Wait for transaction to be indexed
await sleep(1000);

// Query transaction
const tx = await client.getTx(result.transactionHash);
```

## Custom Protobuf Types

See `/packages/stargate/CUSTOM_PROTOBUF_CODECS.md` for detailed guide on adding
custom message types.

```typescript
import { Registry } from "@cosmjs/proto-signing";
import { defaultRegistryTypes } from "@cosmjs/stargate";

const registry = new Registry(defaultRegistryTypes);
registry.register("/my.custom.MsgCustom", MsgCustom);

const client = await SigningStargateClient.connectWithSigner(rpcUrl, wallet, {
  registry,
});
```

## Error Handling

```typescript
import { isDeliverTxFailure, isDeliverTxSuccess } from "@cosmjs/stargate";

try {
  const result = await client.sendTokens(sender, recipient, amount, "auto");

  if (isDeliverTxSuccess(result)) {
    console.log("Success:", result.transactionHash);
  }
} catch (error) {
  if (isDeliverTxFailure(error)) {
    console.error("Transaction failed:", error.code, error.rawLog);
  }
  throw error;
}
```

## Gas and Fees

```typescript
import { GasPrice, calculateFee } from "@cosmjs/stargate";

// Create gas price
const gasPrice = GasPrice.fromString("0.025uatom");

// Calculate fee for specific gas
const fee = calculateFee(200000, gasPrice);
// { amount: [{ denom: "uatom", amount: "5000" }], gas: "200000" }

// Use "auto" for automatic estimation
const result = await client.sendTokens(sender, recipient, amount, "auto");

// Use multiplier for auto estimation
const result = await client.sendTokens(
  sender,
  recipient,
  amount,
  "auto",
  "memo",
  1.3, // 30% buffer
);
```

---

**Last Updated**: January 6, 2026 **Package Version**: 0.38.0


