Skip to content

Instantly share code, notes, and snippets.

@ezynda3
Created July 27, 2025 13:23
Show Gist options
  • Save ezynda3/a2674e30783cdee9fe8ef1dcc1bdcd76 to your computer and use it in GitHub Desktop.
Save ezynda3/a2674e30783cdee9fe8ef1dcc1bdcd76 to your computer and use it in GitHub Desktop.
Bigmi Library - Complete Function Documentation

Bigmi Library - Complete Function Documentation

Overview

Bigmi is a TypeScript library for Bitcoin applications that provides a comprehensive set of functions for interacting with the Bitcoin blockchain. It includes actions for querying blockchain data, managing transactions, and working with various Bitcoin data providers.

Core Functions

1. getBalance

getBalance(client: Client, params: { address: string }): Promise<bigint>

Retrieves the balance of a Bitcoin address.

Parameters:

  • client: The configured client instance
  • address: The Bitcoin address to check

Returns: The balance in satoshis as a bigint

Example:

const balance = await getBalance(client, { 
  address: "bc1qpvk0kjdg0kantu9z78qz7gqk53q643auz33yaw" 
});

2. getBlock

getBlock(client: Client, params: { blockHash?: string, blockNumber?: number }): Promise<Block>

Retrieves a block by hash or number.

Parameters:

  • client: The configured client instance
  • blockHash: The block hash (optional if blockNumber provided)
  • blockNumber: The block number (optional if blockHash provided)

Returns: A bitcoinjs-lib Block object

Example:

const block = await getBlock(client, { blockNumber: 897002 });

3. getBlockCount

getBlockCount(client: Client): Promise<number>

Gets the current block height of the blockchain.

Parameters:

  • client: The configured client instance

Returns: The current block count

Example:

const blockCount = await getBlockCount(client);

4. getBlockStats

getBlockStats(client: Client, params: { 
  blockHash?: string, 
  blockNumber?: number, 
  stats?: BlockStatsKeys[] 
}): Promise<BlockStats>

Retrieves statistics about a specific block.

Parameters:

  • client: The configured client instance
  • blockHash: The block hash (optional if blockNumber provided)
  • blockNumber: The block number (optional if blockHash provided)
  • stats: Array of specific stats to retrieve (optional)

Returns: Block statistics object

Available Stats:

  • avgfee, avgfeerate, avgtxsize, blockhash, feerate_percentiles
  • height, ins, maxfee, maxfeerate, maxtxsize
  • medianfee, mediantime, mediantxsize, minfee, minfeerate
  • mintxsize, outs, subsidy, swtotal_size, swtotal_weight
  • swtxs, time, total_out, total_size, total_weight
  • totalfee, txs, utxo_increase, utxo_size_inc

5. getTransactionFee

getTransactionFee(client: Client, params: { txId: string }): Promise<bigint>

Gets the fee paid for a specific transaction.

Parameters:

  • client: The configured client instance
  • txId: The transaction ID

Returns: The transaction fee in satoshis as bigint

Example:

const fee = await getTransactionFee(client, { 
  txId: "4b6ee974f1dd179071d027562e1fd1c83965efa4a171ec84f00b6c638e36fa4e" 
});

6. getTransactions

getTransactions(client: Client, params: {
  address: string,
  offset?: number,
  limit?: number,
  lastBlock?: string,
  afterTxId?: string
}): Promise<{
  transactions: Array<Partial<UTXOTransaction>>,
  total: number,
  hasMore?: boolean
}>

Retrieves transactions for an address with pagination support.

Parameters:

  • client: The configured client instance
  • address: The Bitcoin address
  • offset: Pagination offset (optional)
  • limit: Number of transactions to return (optional)
  • lastBlock: Last block to include (optional)
  • afterTxId: Return transactions after this ID (optional)

Returns: Object containing transactions array and pagination info

7. getUTXOs

getUTXOs(client: Client, params: {
  address: string,
  minValue?: number
}): Promise<Array<UTXO>>

Gets unspent transaction outputs (UTXOs) for an address.

Parameters:

  • client: The configured client instance
  • address: The Bitcoin address
  • minValue: Minimum total value of UTXOs to retrieve (optional)

Returns: Array of UTXO objects

UTXO Object Structure:

{
  txId: string,
  vout: number,
  value: number,
  isConfirmed?: boolean,
  confirmations?: number,
  blockHeight: number,
  scriptHex: string
}

8. getUTXOTransaction

getUTXOTransaction(client: Client, params: {
  txId: string,
  blockHash?: string
}): Promise<UTXOTransaction>

Retrieves detailed information about a specific transaction.

Parameters:

  • client: The configured client instance
  • txId: The transaction ID
  • blockHash: The block hash containing the transaction (optional)

Returns: Detailed transaction object

9. sendUTXOTransaction

sendUTXOTransaction(client: Client, params: {
  hex: string,
  maxFeeRate?: number
}): Promise<string>

Broadcasts a raw transaction to the network.

Parameters:

  • client: The configured client instance
  • hex: The hex string of the raw transaction
  • maxFeeRate: Maximum acceptable fee rate in BTC/kB (optional, default: 0.10)

Returns: The transaction ID

10. signPsbt

signPsbt(client: Client, params: {
  psbt: string,
  inputsToSign: Array<{
    sigHash?: number,
    address: string,
    signingIndexes: number[]
  }>,
  finalize?: boolean
}): Promise<string>

Signs a Partially Signed Bitcoin Transaction (PSBT).

Parameters:

  • client: The configured client instance
  • psbt: The PSBT encoded as a hexadecimal string
  • inputsToSign: Array of input signing details
  • finalize: Whether to finalize the PSBT after signing (optional)

Returns: The signed PSBT as a hex string

11. waitForTransaction

waitForTransaction(client: Client, params: {
  txId: string,
  txHex: string,
  senderAddress?: string,
  confirmations?: number,
  onReplaced?: (response: ReplacementReturnType) => void,
  pollingInterval?: number,
  retryCount?: number,
  retryDelay?: number | ((config: { count: number; error: Error }) => number),
  timeout?: number
}): Promise<UTXOTransaction>

Waits for a transaction to be confirmed on the blockchain with replacement detection support.

Parameters:

  • client: The configured client instance
  • txId: The transaction ID to wait for
  • txHex: The hex string of the raw transaction
  • senderAddress: The sender's address (optional, for replacement detection)
  • confirmations: Number of confirmations to wait for (default: 1)
  • onReplaced: Callback for transaction replacement events
  • pollingInterval: Polling frequency in ms
  • retryCount: Number of retry attempts (default: 10)
  • retryDelay: Delay between retries
  • timeout: Maximum wait time in ms

Returns: The confirmed transaction

12. watchBlockNumber

watchBlockNumber(client: Client, params: {
  onBlockNumber: (blockNumber: number, prevBlockNumber?: number) => Promise<void>,
  onError?: (error: Error) => void,
  emitMissed?: boolean,
  emitOnBegin?: boolean,
  pollingInterval?: number
}): () => void

Watches for new blocks and calls a callback when they arrive.

Parameters:

  • client: The configured client instance
  • onBlockNumber: Callback function for new blocks
  • onError: Error handler callback
  • emitMissed: Whether to emit missed block numbers
  • emitOnBegin: Whether to emit the latest block on start
  • pollingInterval: Polling frequency in ms

Returns: A function to stop watching

Transport Providers

1. Ankr Transport

ankr(config?: { baseUrl?: string, apiKey?: string })

Creates a transport using Ankr's API.

Supported Methods:

  • getBalance
  • getTransactions
  • getTransactionFee

2. Blockchair Transport

blockchair(config?: { baseUrl?: string, apiKey?: string })

Creates a transport using Blockchair's API.

Supported Methods:

  • getBalance
  • getUTXOs
  • getTransactionFee

3. Blockcypher Transport

blockcypher(config?: { baseUrl?: string, apiKey?: string })

Creates a transport using Blockcypher's API.

Supported Methods:

  • getBalance
  • getUTXOs
  • getTransactionFee

4. Mempool Transport

mempool(config?: { baseUrl?: string })

Creates a transport using Mempool.space API.

Supported Methods:

  • getBalance
  • getTransactions
  • getTransactionFee

5. HTTP Transport

http(url?: string, config?: HttpTransportConfig)

Creates a generic HTTP JSON-RPC transport.

6. Fallback Transport

fallback(transports: Transport[], config?: FallbackTransportConfig)

Creates a transport that falls back to other transports on failure.

Example:

const transport = fallback([
  blockcypher({ apiKey: 'your-key' }),
  blockchair({ apiKey: 'your-key' }),
  mempool()
]);

Client Creation

createClient

createClient(config: ClientConfig): Client

Creates a client instance for interacting with Bitcoin.

Parameters:

  • account: Account or address to use
  • chain: The blockchain configuration
  • transport: The transport provider
  • pollingInterval: Default polling interval in ms (default: 4000)
  • cacheTime: Cache duration in ms (default: 4000)

Example:

import { createClient, bitcoin, mempool } from '@bigmi/core';

const client = createClient({
  chain: bitcoin,
  transport: mempool()
});

Utility Functions

Address Utilities

getAddressInfo

getAddressInfo(address: string): AddressInfo

Parses and validates a Bitcoin address.

Returns:

{
  bech32: boolean,
  network: 'mainnet' | 'testnet' | 'regtest',
  address: string,
  type: 'p2pkh' | 'p2sh' | 'p2wpkh' | 'p2wsh' | 'p2tr',
  purpose: 'payment' | 'ordinals' | 'stacks'
}

isUTXOAddress

isUTXOAddress(address: string, network?: Network): boolean

Validates if a string is a valid Bitcoin address.

Transaction Utilities

cancelTransaction

cancelTransaction(psbt: Psbt, accountAddress: string): Psbt

Creates a replacement transaction that cancels the original by sending funds back to sender.

modifyFee

modifyFee(psbt: Psbt, newFee: bigint, accountAddress: string): Psbt

Modifies the fee of a transaction by adjusting the change output.

Conversion Utilities

hexToBase64

hexToBase64(hex: string): string

base64ToHex

base64ToHex(base64: string): string

stringToHex

stringToHex(value: string): string

hexToUnit8Array

hexToUnit8Array(value: string): Uint8Array

Async Utilities

withRetry

withRetry<T>(fn: () => Promise<T>, options?: {
  delay?: number | ((config: { count: number; error: Error }) => number),
  retryCount?: number,
  shouldRetry?: (config: { count: number; error: Error }) => boolean | Promise<boolean>
}): Promise<T>

Retries an async function with configurable delay and retry logic.

withTimeout

withTimeout<T>(fn: ({ signal }: { signal: AbortSignal | null }) => Promise<T>, options: {
  errorInstance?: Error,
  timeout: number,
  signal?: boolean
}): Promise<T>

Adds a timeout to an async function.

poll

poll<T>(fn: ({ unpoll }: { unpoll: () => void }) => Promise<T | undefined>, options: {
  emitOnBegin?: boolean,
  initialWaitTime?: (data: T | undefined) => Promise<number>,
  interval: number
}): () => void

Polls a function at specified intervals.

Error Types

The library includes specific error types for different scenarios:

  • InvalidAddressError: Invalid Bitcoin address format
  • BaseError: Base error class for all library errors
  • BlockNotFoundError: Block not found
  • TransactionNotFoundError: Transaction not found
  • TransactionReceiptNotFoundError: Transaction receipt not found
  • WaitForTransactionReceiptTimeoutError: Timeout waiting for transaction
  • InsufficientUTXOBalanceError: Insufficient UTXO balance
  • HttpRequestError: HTTP request failed
  • RpcRequestError: RPC request failed
  • TimeoutError: Request timeout
  • UserRejectedRequestError: User rejected the request
  • MethodNotSupportedRpcError: RPC method not supported

Chain Configuration

The library includes a pre-configured Bitcoin mainnet chain:

const bitcoin = {
  id: 20000000000001,
  name: 'Bitcoin',
  nativeCurrency: { name: 'Bitcoin', symbol: 'BTC', decimals: 8 },
  rpcUrls: {
    default: {
      http: ['https://node-router.thorswap.net/bitcoin'],
    },
  },
  blockExplorers: {
    default: {
      name: 'Mempool',
      url: 'https://mempool.space/',
    },
  },
}

You can also define custom chains using defineChain().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment