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.
getBalance(client: Client, params: { address: string }): Promise<bigint>Retrieves the balance of a Bitcoin address.
Parameters:
client: The configured client instanceaddress: The Bitcoin address to check
Returns: The balance in satoshis as a bigint
Example:
const balance = await getBalance(client, {
address: "bc1qpvk0kjdg0kantu9z78qz7gqk53q643auz33yaw"
});getBlock(client: Client, params: { blockHash?: string, blockNumber?: number }): Promise<Block>Retrieves a block by hash or number.
Parameters:
client: The configured client instanceblockHash: 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 });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);getBlockStats(client: Client, params: {
blockHash?: string,
blockNumber?: number,
stats?: BlockStatsKeys[]
}): Promise<BlockStats>Retrieves statistics about a specific block.
Parameters:
client: The configured client instanceblockHash: 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_percentilesheight,ins,maxfee,maxfeerate,maxtxsizemedianfee,mediantime,mediantxsize,minfee,minfeeratemintxsize,outs,subsidy,swtotal_size,swtotal_weightswtxs,time,total_out,total_size,total_weighttotalfee,txs,utxo_increase,utxo_size_inc
getTransactionFee(client: Client, params: { txId: string }): Promise<bigint>Gets the fee paid for a specific transaction.
Parameters:
client: The configured client instancetxId: The transaction ID
Returns: The transaction fee in satoshis as bigint
Example:
const fee = await getTransactionFee(client, {
txId: "4b6ee974f1dd179071d027562e1fd1c83965efa4a171ec84f00b6c638e36fa4e"
});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 instanceaddress: The Bitcoin addressoffset: 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
getUTXOs(client: Client, params: {
address: string,
minValue?: number
}): Promise<Array<UTXO>>Gets unspent transaction outputs (UTXOs) for an address.
Parameters:
client: The configured client instanceaddress: The Bitcoin addressminValue: 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
}getUTXOTransaction(client: Client, params: {
txId: string,
blockHash?: string
}): Promise<UTXOTransaction>Retrieves detailed information about a specific transaction.
Parameters:
client: The configured client instancetxId: The transaction IDblockHash: The block hash containing the transaction (optional)
Returns: Detailed transaction object
sendUTXOTransaction(client: Client, params: {
hex: string,
maxFeeRate?: number
}): Promise<string>Broadcasts a raw transaction to the network.
Parameters:
client: The configured client instancehex: The hex string of the raw transactionmaxFeeRate: Maximum acceptable fee rate in BTC/kB (optional, default: 0.10)
Returns: The transaction ID
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 instancepsbt: The PSBT encoded as a hexadecimal stringinputsToSign: Array of input signing detailsfinalize: Whether to finalize the PSBT after signing (optional)
Returns: The signed PSBT as a hex string
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 instancetxId: The transaction ID to wait fortxHex: The hex string of the raw transactionsenderAddress: The sender's address (optional, for replacement detection)confirmations: Number of confirmations to wait for (default: 1)onReplaced: Callback for transaction replacement eventspollingInterval: Polling frequency in msretryCount: Number of retry attempts (default: 10)retryDelay: Delay between retriestimeout: Maximum wait time in ms
Returns: The confirmed transaction
watchBlockNumber(client: Client, params: {
onBlockNumber: (blockNumber: number, prevBlockNumber?: number) => Promise<void>,
onError?: (error: Error) => void,
emitMissed?: boolean,
emitOnBegin?: boolean,
pollingInterval?: number
}): () => voidWatches for new blocks and calls a callback when they arrive.
Parameters:
client: The configured client instanceonBlockNumber: Callback function for new blocksonError: Error handler callbackemitMissed: Whether to emit missed block numbersemitOnBegin: Whether to emit the latest block on startpollingInterval: Polling frequency in ms
Returns: A function to stop watching
ankr(config?: { baseUrl?: string, apiKey?: string })Creates a transport using Ankr's API.
Supported Methods:
getBalancegetTransactionsgetTransactionFee
blockchair(config?: { baseUrl?: string, apiKey?: string })Creates a transport using Blockchair's API.
Supported Methods:
getBalancegetUTXOsgetTransactionFee
blockcypher(config?: { baseUrl?: string, apiKey?: string })Creates a transport using Blockcypher's API.
Supported Methods:
getBalancegetUTXOsgetTransactionFee
mempool(config?: { baseUrl?: string })Creates a transport using Mempool.space API.
Supported Methods:
getBalancegetTransactionsgetTransactionFee
http(url?: string, config?: HttpTransportConfig)Creates a generic HTTP JSON-RPC 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()
]);createClient(config: ClientConfig): ClientCreates a client instance for interacting with Bitcoin.
Parameters:
account: Account or address to usechain: The blockchain configurationtransport: The transport providerpollingInterval: 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()
});getAddressInfo(address: string): AddressInfoParses 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(address: string, network?: Network): booleanValidates if a string is a valid Bitcoin address.
cancelTransaction(psbt: Psbt, accountAddress: string): PsbtCreates a replacement transaction that cancels the original by sending funds back to sender.
modifyFee(psbt: Psbt, newFee: bigint, accountAddress: string): PsbtModifies the fee of a transaction by adjusting the change output.
hexToBase64(hex: string): stringbase64ToHex(base64: string): stringstringToHex(value: string): stringhexToUnit8Array(value: string): Uint8ArraywithRetry<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<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<T>(fn: ({ unpoll }: { unpoll: () => void }) => Promise<T | undefined>, options: {
emitOnBegin?: boolean,
initialWaitTime?: (data: T | undefined) => Promise<number>,
interval: number
}): () => voidPolls a function at specified intervals.
The library includes specific error types for different scenarios:
InvalidAddressError: Invalid Bitcoin address formatBaseError: Base error class for all library errorsBlockNotFoundError: Block not foundTransactionNotFoundError: Transaction not foundTransactionReceiptNotFoundError: Transaction receipt not foundWaitForTransactionReceiptTimeoutError: Timeout waiting for transactionInsufficientUTXOBalanceError: Insufficient UTXO balanceHttpRequestError: HTTP request failedRpcRequestError: RPC request failedTimeoutError: Request timeoutUserRejectedRequestError: User rejected the requestMethodNotSupportedRpcError: RPC method not supported
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().