Skip to main content

API Reference

TachiClient​

Constructor​

import { TachiClient } from "@tachibtc/tachi-sdk-ts";

const client = new TachiClient({
baseUrl: "https://rpc-regtest.tachibtc.com", // or "https://rpc-signet.tachibtc.com"
timeoutMs: 30000, // optional, default 30s
});
OptionTypeDefaultDescription
baseUrlstring—Base URL of the Tachi daemon RPC
fetchfetchglobalThis.fetchCustom fetch implementation
timeoutMsnumber30000Request timeout in ms. Set to 0 to disable
maxResponseBytesnumber67108864 (64 MiB)Reject responses larger than this. Set to 0 to disable

Errors​

Failed requests reject with the daemon's own explanation appended, not just the status line:

GET /tachi_addressVtxos failed: 400 Bad Request — address "bc1q…" is not a taproot (P2TR) address — use a raw pubkey hex or a bc1p/tb1p/bcrt1p address

Timeouts and transport failures name the endpoint and host, and keep the original error as cause:

GET /health timed out after 30000ms (rpc-regtest.tachibtc.com)
caution

A resolved promise is not always success. query(), broadcastTxAsync(), broadcastTxSync(), and bitcoinRPC() pass through protocols that report failures inside an HTTP 200 — check result.response.code / result.code (with result.log) for the CometBFT calls, and error !== null for bitcoinRPC(). Only HTTP-level failures reject.

note

Every daemon response carries an X-Tachi-Height header with the last block the answering node committed. TachiClient methods return only the body. If you need the header for freshness checks, call the endpoint with fetch.


Health & Status​

getHealth()​

Liveness probe returning daemon status and validator count.

const health = await client.getHealth();
// { status: "ok", validators: 3 }

Returns: HealthResponse

FieldTypeDescription
statusstringDaemon status
validatorsnumberNumber of validators

getStatus()​

Node info, sync status, and latest block height via CometBFT.

const status = await client.getStatus();
console.log(status.result);

Returns: CometRPCResponse


Peer Info​

getPeerInfo()​

Returns the PeerID, public key, and network addresses of this node.

const peer = await client.getPeerInfo();
// { peer_id: "abc...", pub_key_hex: "def...", host: "127.0.0.1", p2p_port: 26656, rpc_addr: "..." }

Returns: ValidatorInfo

FieldTypeDescription
peer_idstringPeer identifier
pub_key_hexstringPublic key (hex)
hoststringHost address
p2p_portnumberP2P port
rpc_addrstringRPC address

Validators​

getValidators()​

All validators from bootstrap registry merged with KDHT-discovered validators.

const { count, validators } = await client.getValidators();

Returns: ValidatorsResponse

FieldTypeDescription
countnumberTotal validator count
validatorsValidatorInfo[]Validator list

getValidatorCount()​

Number of validators in the bootstrap registry.

const { count } = await client.getValidatorCount();

Returns: ValidatorCountResponse


getLiveValidators()​

Validators whose peers are currently connected via the overlay network.

const live = await client.getLiveValidators();
console.log(`${live.count} of ${live.total_known} online`);

Returns: LiveValidatorsResponse

FieldTypeDescription
countnumberLive validator count
total_knownnumberTotal known validators
validatorsValidatorInfo[]Live validator list

waitForValidatorsReady(expected?)​

Long-polls until the expected number of validators have registered or a 60-second timeout expires.

const ready = await client.waitForValidatorsReady(3);
console.log(ready.ready); // true or false

Parameters:

ParamTypeDefaultDescription
expectednumber2Number of expected validators

Returns: ReadyResponse


VTXOs​

getVtxo(id)​

Look up a single VTXO by its 32-byte hex ID.

const vtxo = await client.getVtxo("5e43129f...");
// { id, owner, amount, script, height, spent }

Returns: VTXOResponse

FieldTypeDescription
idstringHex-encoded 32-byte VTXO identifier
ownerstringHex-encoded owner public key
amountnumberValue in satoshis
scriptstringHex-encoded locking script
heightnumberBlock height the VTXO was created at
spentbooleanTrue once consumed by a confirmed transaction

listVtxos(params?)​

Paginated list of all VTXOs (unspent and spent), sorted by height descending.

const { vtxos, total, total_pages } = await client.listVtxos({ page: 1, page_size: 50 });

Parameters: PageParams

ParamTypeDefaultDescription
pagenumber11-based page number
page_sizenumber50Entries per page (max 100)

Returns: ListVTXOsResponse — { vtxos, page, page_size, total, total_pages }


getAddressVtxos(address, includeSpent?)​

VTXOs owned by an address or public key. Unspent only by default.

const { pubkey, count, vtxos } = await client.getAddressVtxos("bcrt1p...");
const all = await client.getAddressVtxos("bcrt1p...", true); // include spent

Parameters:

ParamTypeDefaultDescription
addressstring—Taproot address (bc1p/tb1p/bcrt1p) or public key hex (32 or 33 bytes)
includeSpentbooleanfalseInclude spent VTXOs

Returns: AddressVTXOsResponse — items are VTXOItem, which adds locked and an optional vault_address (present only when locked is true).


getLockedVtxos(vault)​

All VTXOs locked to a given vault.

const { vault, count, vtxos } = await client.getLockedVtxos("bcrt1p...");

Returns: LockedVTXOsResponse


Vaults​

listVaults(user, options?)​

Paginated list of vaults owned by a user.

const { vaults, total } = await client.listVaults("bcrt1p...");

// With an API key, the reconstruction params are included
const full = await client.listVaults("bcrt1p...", { apiKey: process.env.TACHI_API_KEY });

Parameters:

ParamTypeDefaultDescription
userstring—Taproot address or public key hex
options.pagenumber11-based page number
options.page_sizenumber50Entries per page (max 100)
options.apiKeystring—Sent as X-Api-Key

Returns: ListVaultsResponse — vaults are VaultListItem:

FieldTypeDescription
vault_idstringHex VaultID = H(funding_txid || vout)
addressstringbech32m P2TR vault address; also the ?vault= websocket filter key
funding_txidstringHex L1 funding txid, internal byte order
funding_txid_displaystring?Same txid in display (explorer) order
funding_voutnumberL1 funding output index
statestringAlways "open" today
latest_state_numnumberAlways 0 today
csv_delay, threshold, quorum_keyset, user_keyoptionalReconstruction params — omitted unless a valid apiKey is supplied

state is "open", or "closed" once a TxVaultClose has committed (see Closing a vault). latest_state_num is always 0 today.

note

funding_txid is in internal byte order (the reverse of what explorers and bitcoind show). getDepositStatus takes the display txid: pass funding_txid_display.

getVault(vaultId, options?)​

One vault by its 64-char hex id, plus locked_sat and locked_count (VTXOs locked to it). The reconstruction params are redacted the same way as listVaults unless options.apiKey is a master or vault-scoped key.

const v = await client.getVault(vaultId);
if (v.locked_count > 0) console.log("cooperative refund/transfer blocked while VTXOs are locked");

Returns: VaultResponse

getVaultExits(vaultId, apiKey)​

The cooperative and unilateral exit paths for a vault, checked against the L1 funding output. Requires a master or :vault-scoped API key (401 without one). A path is available only when every prerequisite was checked. Each path has est_vsize, and est_fee_sat when bitcoind can estimate a 6-block fee rate.

Returns: VaultExitsResponse: { vault_id, state, l1_checked, funding_unspent, funding_confirmations, locked_count, cooperative, unilateral, fee_rate_sat_vb, ... }


Network​

getNetInfo()​

Listening addresses, connected peer count, and per-peer connection info via CometBFT.

const netInfo = await client.getNetInfo();

Returns: CometRPCResponse


Transactions​

broadcastTxAsync(tx)​

Broadcast a hex-encoded transaction. Returns immediately without waiting for CheckTx.

const result = await client.broadcastTxAsync("deadbeef");
caution

Transaction hex strings do not use a 0x prefix.

Parameters:

ParamTypeDescription
txstringHex-encoded transaction bytes

Returns: CometRPCResponse


broadcastTxSync(tx)​

Broadcast a hex-encoded transaction. Waits for CheckTx to complete before responding.

const result = await client.broadcastTxSync("deadbeef");
console.log(result.result);

Parameters:

ParamTypeDescription
txstringHex-encoded transaction bytes

Returns: CometRPCResponse


Queries​

query(params)​

Forward a query to the CometBFT ABCI application.

const result = await client.query({
path: "/store/key",
data: "0xab", // optional, hex-encoded
height: "100", // optional
});

Parameters: QueryParams

ParamTypeRequiredDescription
pathstringYesABCI query path
datastringNoHex-encoded query data
heightstringNoBlock height to query at

Returns: CometRPCResponse


Bitcoin RPC​

bitcoinRPC(request)​

Forward a JSON-RPC 1.0 request to the underlying bitcoind. Any method exposed by the Bitcoin node is reachable.

const info = await client.bitcoinRPC({ method: "getblockchaininfo" });
console.log(info.result);

const block = await client.bitcoinRPC({
method: "getblock",
params: ["<block-hash>"],
});
warning

This proxies any Bitcoin RPC method, including privileged ones like sendtoaddress, dumpprivkey, and stop. Ensure the daemon's RPC is properly access-controlled.

Parameters: BitcoinRPCRequest

ParamTypeDefaultDescription
methodstring—Bitcoin RPC method name
paramsunknown[]Method parameters
jsonrpcstring"1.0"JSON-RPC version
idstring"tachi-sdk"Request ID

Returns: BitcoinRPCResponse<T>

FieldTypeDescription
resultTRPC result
error{code, message} | nullError if any
idstringRequest ID

Address​

getAddress(address) / getBalance(address) / getNonce(address)​

Balance, nonce, and VTXO count for a Taproot address or public key hex.

const { balance_sat, nonce, vtxo_count } = await client.getAddress("bcrt1p...");

Returns: AddressResponse / BalanceResponse / Record<string, unknown>

BalanceResponse splits the balance: available_sat (spendable now), locked_sat (escrowed by a vault or bridge lock), pending_out_sat / pending_in_sat (mempool), and balance_sat, the legacy total that includes locked sats.

note

getNonce returns both nonce and next_nonce. Sign with nonce: it's already the value your next transaction must use. next_nonce is one higher. For EVM transactions, getEvmNonce(pubKey) returns the right one as a bigint.


getAddressTransactions(address, options?)​

Transactions involving an address, newest first.

Full-chain scan

The daemon has no address index and walks every block. Measured at ~17s on a ~115k-block chain for an address with 2 matching transactions. Always pass pageSize and page with the next_before_height cursor.

let cursor: number | undefined;
do {
const page = await client.getAddressTransactions(addr, { pageSize: 25, beforeHeight: cursor });
handle(page.transactions);
cursor = page.next_before_height || undefined;
} while (cursor);
OptionTypeDescription
beforeHeightnumber?Cursor: exclusive upper bound. Pass next_before_height from the previous page
pageSizenumber?Max transactions (default 50, max 100)
afterHeightnumber?Exclusive lower bound. The scan stops there, and no cursor is returned once it is reached
typestring?Only txs of this type, e.g. "transfer", "payment_request", "evm_call"

Returns: AddressTransactionsResponse


Transactions​

getTransaction(hash, options?)​

OptionTypeDescription
hatbooleanInclude the Hash-Anchored Timestamp proof
ripbooleanInclude the RIP payload
vtxoIdstringScope the HAT proof to one VTXO
originEpoch / finalEpochnumberEpoch bounds for proof lookup

Returns: GetTransactionResponse

getRawTransaction(hash) — GetRawTransactionResponse​

listTransactions(options?) — ListTransactionsResponse (same full-chain-scan caveat)​

getMempool() / getMempoolByAddress(address) — MempoolResponse / MempoolByAddressResponse​

getFeeEstimate(options?) — FeeEstimateResponse​

Fee quote from the last 20 blocks. options.type averages only that tx type. options.gas (for example gas_used from evmCall) adds gas_fee_sat, the exact EVM gas cost at the minimum gas price.

const { recommended_fee_sat } = await client.getFeeEstimate({ type: "payment_request" });
const { gas_fee_sat } = await client.getFeeEstimate({ type: "evm_call", gas: 50_000 });

getTxStatus(hash) — TxStatusResponse​

Where a tx is on the way to finality. finality moves not_found → mempool → committed → epoch_closed → l1_anchored, or failed. Also returns block_height, epoch, epoch_root, l1_settlement_txid and settled_by_epoch. A tx is l1_anchored once an anchor of its epoch or a later one has confirmed on Bitcoin.

getWithdraw(txHash) — WithdrawResponse​

The L1 payout record for a withdraw tx: status (pending / settled), amount_sat, dest_script, recorded_height. Rejects with 404 if there is no record.

getDepositStatus(txid, vout) — DepositStatusResponse​

Progress of an L1 deposit, by display-order txid. status is l1_not_found, l1_mempool, confirming, claimable or claimed. It is vault_funding when the outpoint funds a vault (funds_vault names it, and a deposit on it is rejected), and unclaimed when the node has no bitcoind.

verifyProof(rip) — ProofVerifyResponse​

Check a RIP proof (the rip object from getTransaction(hash, { rip: true, ... })) against the node's epoch roots. valid is true only when the proof verifies against this node's root for final_epoch, reason explains a false, verified states what a valid proof establishes, and l1_settlement_txid is the anchor of final_epoch.

getSettlementInfo() — SettlementInfoResponse​

L1 settlement: the quorum-controlled settlement address, latest_settled_epoch and latest_txid (newest epoch anchored on Bitcoin), latest_closed_epoch, lag_epochs, and, after the first anchor, balance_sat / anchors_left.

decodeTransaction(tx) / validateTransaction(tx)​

Decode or validate raw hex without broadcasting.

note

These two endpoints take a hex body field, unlike the broadcast endpoints which take tx. The SDK handles this — pass the hex string either way.

decodeTransaction rejects on undecodable input (HTTP 400). validateTransaction resolves with valid: false instead — check the field, don't rely on the promise.


Blocks​

getBlockByHeight(height) — BlockResponse​

getBlock({ height | hash }) — BlockResponse​

getBlockHash(height) — GetBlockHashResponse​

getBlockHeader({ height | hash }) — GetBlockHeaderResponse​

listBlocks(params?) — ListBlocksResponse​

getBlock and getBlockHeader throw before making a request if given neither a height nor a hash.


Epochs​

getEpoch({ id | hash })​

Each epoch carries size (bytes), proposer, and a fees summary (count, total, min, max, avg, median, p90). listEpochs items carry the same fields.

Requires exactly one of id or hash — there is no "current epoch" form. Use getStats().current_epoch to find the latest id. Throws locally if given neither or both.

listEpochs(params?) — ListEpochsResponse​

note

bitcoin_block_height is null until the epoch is anchored to a Bitcoin block.


Dashboard & stats​

getStats() — StatsResponse​

getSupply() — SupplyResponse​

getNodeInfo() — NodeInfoResponse​

Includes features: the runtimes (script, evm) and gated consensus rules (withdraw_lock, lock_consent, vault_close, payment_requests), each with active and activation_height. Check it before using a feature on a network. Also includes evm_chain_id.

getConsensusState() / getValidatorsPower() — CometRPCResponse​

search(q)​

Resolve a height, hash, address, or VTXO id. Narrow on the returned type before using result.

const hit = await client.search("229917");
if (hit.type === "block") { /* hit.result is a block */ }

EVM​

Deploy and call Solidity contracts. Gas is paid in sats from your VTXOs. For a full walkthrough, see EVM Smart Contracts.

evmCall(request)​

Read-only call against committed state, like eth_call. Nothing is committed. Omit to to simulate a deploy of data and read its gas use, which is how to size gasLimit for a deploy (add headroom).

const res = await client.evmCall({ from: me, to: counter, data: "0x06661abd" }); // count()
// { status: 1, gas_used: 23466, return_data: "0x00…01", logs: [] }
FieldTypeDescription
fromstring?Caller address (msg.sender); the zero address if omitted
tostring?Contract to call. Omit to simulate a deploy
datastringCalldata, or init code when to is omitted
gasnumber?Gas limit; defaults to and is capped at 1,000,000

Returns: EVMCallResult: status (1 or 0), gas_used, return_data, logs, error

note

A reverted call resolves with status: 0. The promise only rejects on an HTTP-level failure or a malformed request. The endpoint is rate limited per client IP.

getEvmCode(address)​

Runtime bytecode at an EVM address, or "0x" if there's no contract there.

Returns: EVMCodeResponse: { address, code }

getEvmReceipt(hash)​

Receipt of a deploy or call, by transaction hash (from evmTxHash). Rejects until the transaction is in a block.

const receipt = await client.getEvmReceipt(await evmTxHash(signed));
if (receipt.status !== 1) throw new Error(receipt.error);

Returns: EVMReceipt

FieldTypeDescription
status0 | 11 success. 0 means it failed but still applied: inputs spent, gas charged, nonce used
gas_usednumberGas charged, after refunds
contract_addressstring?The deployed contract, for a deploy. Set even when the deploy failed
return_datastring?Return data, or the revert payload
logsEVMLog[]Events emitted (address, topics, data); empty when status is 0
errorstring?Why execution failed

The node also returns tx_hash, height, tx_index, block_time, from, to, gas_limit, gas_price, fee_sats, refund_sats and refund_vtxo_id.

getEvmNonce(pubKey)​

The nonce your next EVM transaction must use, as a bigint. This is the nonce field of /tachi_nonce, not next_nonce, which is one too high for signing.

sendEvmTx(tx)​

Broadcast a signed deploy or call and wait for CheckTx. result.code 0 means it entered the mempool. Read the outcome from getEvmReceipt once it's in a block.

Returns: CometRPCResponse

Building and signing​

These are standalone functions, not client methods. They have no runtime dependencies, and signing is up to you: pass any BIP-340 Schnorr signer.

FunctionDescription
buildDeployTx(params)Unsigned deploy. params: inputs, outputs?, pubKey, nonce, gasLimit, gasPrice?, initCode
buildCallTx(params)Unsigned call. Same as above, with to and data instead of initCode
signEVMTx(tx, signer)Returns a signed copy. signer gets the 32-byte digest and returns a 64-byte signature
evmTxHash(tx)Transaction hash, for getEvmReceipt
evmTxHex(tx)Hex of a signed transaction, for broadcastTxSync / validateTransaction
maxGasFeeSats(tx)Sats set aside for gas: gasLimit × gasPrice / 1000, rounded up. Inputs must cover this plus the outputs
gasFeeSats(gas, gasPrice)Sats that gas units cost
refundVtxoId(tx)ID of the VTXO that returns unused gas (output index right after yours)
vtxoId(tx, index)ID of any VTXO the transaction creates
evmAddressFromPubKey(pubKey)Your EVM address (msg.sender), from an x-only, compressed or uncompressed key
contractAddress(deployer, nonce)Address a deploy will get (standard CREATE rule)
encodeEVMTx(tx) / evmSigHash(tx)Wire bytes / signing digest, for custom signers
keccak256(bytes)Ethereum Keccak-256
import { schnorr } from "@noble/curves/secp256k1.js";
import { buildCallTx, signEVMTx, maxGasFeeSats } from "@tachibtc/tachi-sdk-ts";

const tx = buildCallTx({ inputs, outputs: [{ owner: pubKey, amount: change }], pubKey, nonce, gasLimit, to, data });
const signed = await signEVMTx(tx, (digest) => schnorr.sign(digest, privateKey));
await client.sendEvmTx(signed);
ConstantValue
EVM_CHAIN_ID0x54434849n ("TCHI"), for EIP-712 domains
MIN_GAS_PRICE1n millisat per gas
GAS_PRICE_UNIT1000n millisats per sat
MAX_GAS_PER_EVM_CALL1_000_000n
MAX_EVM_INIT_CODE_SIZE49152 bytes

getEvmAccount(address) — EVMAccountResponse​

Nonce and code summary of an EVM address. A pubkey is mapped to its EVM address.

getEvmStorage(address, slot) — EVMStorageResponse​

One 32-byte storage slot. slot is hex and is left-padded.

getEvmPubkey(address) — EVMPubkeyResponse​

The pubkey and Bitcoin (P2TR) address an EVM address derives from: { address, pubkey, bitcoin_address }. Only addresses that signed a tx or owned a VTXO are known. Others, such as contracts, reject with 404, which does not mean the address never appeared on chain. Receipts and tx.evm also carry bitcoin_address.

getEvmLogs(filter) — EVMLogsResponse​

Event logs, like eth_getLogs.

const { logs, truncated, scanned_to } = await client.getEvmLogs({
fromHeight: 1_938_000,
toHeight: 1_939_000, // at most 2,000 blocks past fromHeight
address: token,
topic0: TRANSFER_TOPIC,
});
// If truncated, call again with fromHeight: scanned_to + 1.
FieldTypeDescription
fromHeightnumberFirst height, inclusive
toHeightnumber?Last height, inclusive. At most 2,000 blocks past fromHeight
addressstring?Contract address
topic0 … topic3string?Exact topic match per position

Each log has address, topics, data, height, tx_hash, tx_index and log_index.


Watchtower​

getWatchtowerStatus() — WatchtowerStatus​

getWatchtowerReceipts({ vault?, state? }) — observed L1 spends of vault funding outpoints​


Vault refund and transfer signing​

signTransaction(refund)​

Ask the daemon's quorum to co-sign a vault refund transaction.

Parameters: RefundTx — the refund carrying the user's signature Returns: SignTransactionResponse — { refund, signatures }

signTransfer(transfer)​

Ask the quorum to co-sign a cooperative transfer of a vault's L1 coins to any destination. Used to empty a vault before closing it. Same PSBT-shaped body as signTransaction, including the top-level userSig: the owner's 64-byte BIP-340 signature (hex) over the cooperative-leaf sighash. Every output must be at least 330 sats, and the vault must be open with no VTXOs locked to it.

Returns: TransferCosignResponse — { transfer, signatures }


Payment requests​

On-chain payment requests (tx types payment_request, payment_request_pay, payment_request_cancel). Build them with @tachibtc/taurus-vault-core. See Payment Requests.

getPaymentRequest(id) — PaymentRequest​

One request by ID (the hash of its create tx). status is open, paid, cancelled or expired as of the next block. paid_tx, payer and paid_amount are set once it is paid. memo is untrusted. Rejects with 404 for an unknown ID.

listPaymentRequests({ payee, limit?, offset? }) — ListPaymentRequestsResponse​

A payee's requests, oldest first: { payment_requests, total }. payee is a pubkey hex or taproot address. limit defaults to 50, max 500.

note

This endpoint pages with limit/offset, not page_size.


Live events​

watch(filters, options?)​

Async generator over the daemon's WebSocket push stream.

const ac = new AbortController();
for await (const ev of client.watch({ blocks: true }, { signal: ac.signal })) {
console.log(ev.event, ev);
}
FilterTypePushes
addressstringTransactions crediting the address
vaultstringTransactions locking funds into the vault
vaultIdstringWatchtower-observed L1 spends of the vault's funding outpoint
blocksbooleanEvery durably-committed block
validatorsbooleanEvery new validator registration

At least one filter is required; watch() throws before opening a socket otherwise.

Transaction alerts arrive twice — state: "pending" on CheckTx acceptance, then state: "committed" once the block commits. The stream is push-only; the daemon never expects client messages.

Leaving the loop by any means closes the socket — no separate teardown call.

OptionTypeDefaultDescription
signalAbortSignal—Abort to stop the stream and close the socket
WebSockettypeof WebSocketglobalThis.WebSocketCustom implementation
maxQueuedEventsnumber10000Buffer bound while the consumer is busy; 0 disables
Node 22+

Uses the global WebSocket, native in Node from v22 (this package's engines floor). Pass options.WebSocket to supply your own implementation for older runtimes, browsers, or tests.

Backpressure

Events arriving between iterations are buffered up to maxQueuedEvents. Past that the stream throws rather than growing without bound — mirroring maxResponseBytes for HTTP responses. Already-buffered events are delivered before the error surfaces, so nothing legitimately received is discarded.