or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

amino-types.mdclient.mdindex.mdmessages.mdquery-extensions.mdutilities.md
tile.json

utilities.mddocs/

Utilities and Error Handling

Fee calculation, transaction utilities, multisignature support, and comprehensive error handling for robust blockchain applications.

Capabilities

Fee Calculation

Utilities for calculating transaction fees and gas prices.

/**
 * Gas price calculator for transaction fees
 */
class GasPrice {
  /** Gas price amount */
  public readonly amount: Decimal;
  
  /** Token denomination */
  public readonly denom: string;
  
  /** Create gas price from amount and denomination */
  constructor(amount: Decimal, denom: string);
  
  /** Parse gas price from string (e.g., "0.025uatom") */
  static fromString(gasPrice: string): GasPrice;
  
  /** Convert to string representation */
  toString(): string;
}

/**
 * Calculate transaction fee from gas limit and gas price
 * @param gasLimit - Gas limit for the transaction
 * @param gasPrice - Gas price (GasPrice object or string)
 * @returns Standard fee object
 */
function calculateFee(gasLimit: number, gasPrice: GasPrice | string): StdFee;

Usage Examples:

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

// Create gas price
const gasPrice = GasPrice.fromString("0.025uatom");
console.log(gasPrice.amount); // Decimal("0.025")
console.log(gasPrice.denom);  // "uatom"

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

// Or use string directly
const fee2 = calculateFee(200000, "0.025uatom");

Error Classes

Specialized error classes for different failure scenarios.

/**
 * Error thrown when transaction times out
 */
class TimeoutError extends Error {
  /** Transaction ID that timed out */
  public readonly txId: string;
  
  constructor(message: string, txId: string);
}

/**
 * Error thrown when transaction broadcast fails
 */
class BroadcastTxError extends Error {
  /** Error code from the blockchain */
  public readonly code: number;
  
  /** Error codespace */
  public readonly codespace: string;
  
  /** Error log message */
  public readonly log: string | undefined;
  
  constructor(code: number, codespace: string, log: string | undefined);
}

Usage Examples:

import { SigningStargateClient, TimeoutError, BroadcastTxError } from "@cosmjs/stargate";

try {
  const result = await client.signAndBroadcast(address, messages, "auto");
} catch (error) {
  if (error instanceof TimeoutError) {
    console.log(`Transaction ${error.txId} timed out`);
  } else if (error instanceof BroadcastTxError) {
    console.log(`Transaction failed: ${error.code} - ${error.log}`);
  }
}

Transaction Result Utilities

Functions to check and assert transaction success or failure.

/**
 * Check if transaction delivery failed
 * @param result - Transaction delivery response
 * @returns true if transaction failed (code !== 0)
 */
function isDeliverTxFailure(result: DeliverTxResponse): boolean;

/**
 * Check if transaction delivery succeeded
 * @param result - Transaction delivery response
 * @returns true if transaction succeeded (code === 0) 
 */
function isDeliverTxSuccess(result: DeliverTxResponse): boolean;

/**
 * Assert that transaction delivery succeeded, throw if not
 * @param result - Transaction delivery response
 * @throws Error if transaction failed
 */
function assertIsDeliverTxSuccess(result: DeliverTxResponse): void;

/**
 * Assert that transaction delivery failed, throw if not
 * @param result - Transaction delivery response
 * @throws Error if transaction succeeded
 */
function assertIsDeliverTxFailure(result: DeliverTxResponse): void;

Usage Examples:

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

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

// Check success/failure
if (isDeliverTxSuccess(result)) {
  console.log("Transaction succeeded!");
  console.log(`Gas used: ${result.gasUsed}`);
} else if (isDeliverTxFailure(result)) {
  console.log("Transaction failed!");
  console.log(`Error code: ${result.code}`);
}

// Assert success (throws if failed)
assertIsDeliverTxSuccess(result);
console.log("This line only runs if transaction succeeded");

Multisignature Utilities

Functions for creating and managing multisignature transactions.

/**
 * Create compact bit array from boolean array
 * @param bits - Array of boolean values
 * @returns CompactBitArray for multisig
 */
function makeCompactBitArray(bits: readonly boolean[]): CompactBitArray;

/**
 * Create multisigned transaction
 * @param multisigPubkey - Multisig threshold public key
 * @param sequence - Account sequence number
 * @param fee - Transaction fee
 * @param bodyBytes - Transaction body bytes
 * @param signatures - Map of signer addresses to signatures
 * @returns Complete multisigned transaction
 */
function makeMultisignedTx(
  multisigPubkey: MultisigThresholdPubkey,
  sequence: number,
  fee: StdFee,
  bodyBytes: Uint8Array,
  signatures: Map<string, Uint8Array>
): TxRaw;

/**
 * Create multisigned transaction bytes
 * @param multisigPubkey - Multisig threshold public key
 * @param sequence - Account sequence number
 * @param fee - Transaction fee
 * @param bodyBytes - Transaction body bytes
 * @param signatures - Map of signer addresses to signatures
 * @returns Serialized multisigned transaction bytes
 */
function makeMultisignedTxBytes(
  multisigPubkey: MultisigThresholdPubkey,
  sequence: number,
  fee: StdFee,
  bodyBytes: Uint8Array,
  signatures: Map<string, Uint8Array>
): Uint8Array;

Usage Examples:

import { 
  makeMultisignedTx, 
  makeCompactBitArray 
} from "@cosmjs/stargate";
import { MultisigThresholdPubkey } from "@cosmjs/amino";

// Create multisig transaction
const multisigPubkey: MultisigThresholdPubkey = {
  type: "tendermint/PubKeyMultisigThreshold",
  value: {
    threshold: "2",
    pubkeys: [pubkey1, pubkey2, pubkey3]
  }
};

const signatures = new Map([
  ["cosmos1signer1...", signature1Bytes],
  ["cosmos1signer2...", signature2Bytes]
]);

const multisignedTx = makeMultisignedTx(
  multisigPubkey,
  sequence,
  fee,
  bodyBytes,
  signatures
);

// Broadcast the multisigned transaction
const result = await client.broadcastTx(TxRaw.encode(multisignedTx).finish());

Log Parsing Utilities

Functions for parsing and working with transaction logs and events.

/**
 * Transaction log entry
 */
interface Log {
  /** Message index in transaction */
  readonly msg_index: number;
  
  /** Log message string */
  readonly log: string;
  
  /** Events in this log */
  readonly events: readonly Event[];
}

/**
 * Parse attribute from unknown input
 * @param input - Raw attribute data
 * @returns Parsed attribute
 */
function parseAttribute(input: unknown): Attribute;

/**
 * Parse event from unknown input
 * @param input - Raw event data
 * @returns Parsed event
 */
function parseEvent(input: unknown): Event;

/**
 * Parse log entry from unknown input
 * @param input - Raw log data
 * @returns Parsed log
 */
function parseLog(input: unknown): Log;

/**
 * Parse logs array from unknown input
 * @param input - Raw logs data
 * @returns Array of parsed logs
 */
function parseLogs(input: unknown): readonly Log[];

/**
 * Parse raw log string into structured logs
 * @param input - Raw log string from transaction
 * @returns Parsed logs array
 */
function parseRawLog(input: string | undefined): readonly Log[];

/**
 * Find specific attribute in transaction logs
 * @param logs - Transaction logs to search
 * @param eventType - Event type to look for
 * @param attrKey - Attribute key to find
 * @returns First matching attribute or undefined
 */
function findAttribute(logs: readonly Log[], eventType: string, attrKey: string): Attribute | undefined;

Usage Examples:

import { 
  parseRawLog, 
  findAttribute,
  parseLogs 
} from "@cosmjs/stargate";

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

// Parse raw logs (for older SDK versions)
if (result.rawLog) {
  const logs = parseRawLog(result.rawLog);
  console.log(`Transaction had ${logs.length} message(s)`);
}

// Find specific attribute
const transferAmount = findAttribute(
  logs, 
  "transfer", 
  "amount"
);
if (transferAmount) {
  console.log(`Transfer amount: ${transferAmount.value}`);
}

// Work with events directly (newer SDK versions)
result.events.forEach(event => {
  console.log(`Event type: ${event.type}`);
  event.attributes.forEach(attr => {
    console.log(`  ${attr.key}: ${attr.value}`);
  });
});

Account Utilities

Functions for working with account information.

/**
 * Account parser function type
 */
type AccountParser = (any: Any) => Account;

/**
 * Parse Any protobuf type to Account
 * @param input - Any protobuf containing account data
 * @returns Parsed account information
 */
function accountFromAny(input: Any): Account;

Usage Examples:

import { accountFromAny } from "@cosmjs/stargate";

const client = QueryClient.withExtensions(tmClient, setupAuthExtension);

// Get raw account data
const accountAny = await client.auth.account("cosmos1abc...");

if (accountAny) {
  // Parse to structured account
  const account = accountFromAny(accountAny);
  console.log(`Account: ${account.address}`);
  console.log(`Number: ${account.accountNumber}`);
  console.log(`Sequence: ${account.sequence}`);
}

Event Utilities

Functions for working with transaction events.

/**
 * Convert Tendermint event to standard Event format
 * @param event - Tendermint event (v34 or v37)
 * @returns Standardized event
 */
function fromTendermintEvent(event: tendermint34.Event | tendermint37.Event): Event;

Usage Examples:

import { fromTendermintEvent } from "@cosmjs/stargate";

// Convert raw Tendermint events
tendermintEvents.forEach(tmEvent => {
  const event = fromTendermintEvent(tmEvent);
  console.log(`Event: ${event.type}`);
  event.attributes.forEach(attr => {
    console.log(`  ${attr.key}: ${attr.value}`);
  });
});

Complete Error Handling Example

import { 
  SigningStargateClient,
  TimeoutError,
  BroadcastTxError,
  isDeliverTxSuccess,
  isDeliverTxFailure
} from "@cosmjs/stargate";

async function safeSendTokens(
  client: SigningStargateClient,
  senderAddress: string,
  recipientAddress: string,
  amount: Coin[],
  memo: string = ""
) {
  try {
    // Attempt to send tokens
    const result = await client.sendTokens(
      senderAddress,
      recipientAddress,
      amount,
      "auto",
      memo
    );

    // Check if transaction succeeded
    if (isDeliverTxSuccess(result)) {
      console.log(`βœ… Transfer successful!`);
      console.log(`Transaction hash: ${result.transactionHash}`);
      console.log(`Block height: ${result.height}`);
      console.log(`Gas used: ${result.gasUsed}/${result.gasWanted}`);
      return result;
    } else if (isDeliverTxFailure(result)) {
      console.log(`❌ Transfer failed on chain`);
      console.log(`Error code: ${result.code}`);
      console.log(`Raw log: ${result.rawLog}`);
      throw new Error(`Transaction failed with code ${result.code}`);
    }

  } catch (error) {
    if (error instanceof TimeoutError) {
      console.log(`⏰ Transfer timed out`);
      console.log(`Transaction ID: ${error.txId}`);
      throw error;
    } else if (error instanceof BroadcastTxError) {
      console.log(`πŸ“‘ Broadcast failed`);
      console.log(`Code: ${error.code}`);
      console.log(`Codespace: ${error.codespace}`);
      console.log(`Log: ${error.log}`);
      throw error;
    } else {
      console.log(`πŸ”₯ Unexpected error:`, error);
      throw error;
    }
  }
}

// Usage
try {
  await safeSendTokens(
    client,
    "cosmos1sender...",
    "cosmos1recipient...",
    [{ denom: "uatom", amount: "1000000" }],
    "Safe transfer with error handling"
  );
} catch (error) {
  console.log("Transfer failed:", error.message);
}