/** Account derived from a local private key (mnemonic or raw key). */ type LocalAccount = { type: "local" address: string /** Compressed public key (hex) */ publicKey: string /** Raw ECDSA sign over a hash */ sign(hash: Uint8Array): Uint8Array /** Sign a raw UTF-8 / byte message (`sha256(bytes)`). Not SIP-018. */ signMessage(message: string | Uint8Array): string }; /** Account with a user-provided signing function (sync or async). */ type CustomAccount = { type: "custom" address: string publicKey: string sign(hash: Uint8Array): Promise | Uint8Array }; /** Browser wallet provider interface (e.g. Leather, Xverse). */ type StacksProvider = { request(method: string, params?: any): Promise }; /** Account backed by a browser wallet {@link StacksProvider}. */ type ProviderAccount = { type: "provider" address: string publicKey: string provider: StacksProvider }; type IntCV = { readonly type: "int" readonly value: bigint }; type UIntCV = { readonly type: "uint" readonly value: bigint }; type BooleanCV = TrueCV | FalseCV; type TrueCV = { readonly type: "true" }; type FalseCV = { readonly type: "false" }; type BufferCV = { readonly type: "buffer" readonly value: string }; type NoneCV = { readonly type: "none" }; type SomeCV = { readonly type: "some" readonly value: ClarityValue }; type ResponseOkCV = { readonly type: "ok" readonly value: ClarityValue }; type ResponseErrorCV = { readonly type: "err" readonly value: ClarityValue }; type StandardPrincipalCV = { readonly type: "address" readonly value: string }; type ContractPrincipalCV = { readonly type: "contract" readonly value: string }; type ListCV = { type: "list" value: ClarityValue[] }; type TupleData = { [key: string]: ClarityValue }; type TupleCV = { type: "tuple" value: TupleData }; type StringAsciiCV = { readonly type: "ascii" readonly value: string }; type StringUtf8CV = { readonly type: "utf8" readonly value: string }; type ClarityValue = IntCV | UIntCV | BooleanCV | BufferCV | NoneCV | SomeCV | ResponseOkCV | ResponseErrorCV | StandardPrincipalCV | ContractPrincipalCV | ListCV | TupleCV | StringAsciiCV | StringUtf8CV; declare const AuthType: { readonly Standard: 0x04 readonly Sponsored: 0x05 }; type AuthType = (typeof AuthType)[keyof typeof AuthType]; declare const PayloadType: { readonly TokenTransfer: 0x00 readonly SmartContract: 0x01 readonly ContractCall: 0x02 readonly PoisonMicroblock: 0x03 readonly Coinbase: 0x04 readonly CoinbaseToAltRecipient: 0x05 readonly VersionedSmartContract: 0x06 readonly TenureChange: 0x07 readonly NakamotoCoinbase: 0x08 }; type PayloadType = (typeof PayloadType)[keyof typeof PayloadType]; declare const ClarityVersion: { readonly Clarity1: 1 readonly Clarity2: 2 readonly Clarity3: 3 readonly Clarity4: 4 readonly Clarity5: 5 readonly Clarity6: 6 }; type ClarityVersion = (typeof ClarityVersion)[keyof typeof ClarityVersion]; declare const AnchorMode: { readonly OnChainOnly: 0x01 readonly OffChainOnly: 0x02 readonly Any: 0x03 }; type AnchorMode = (typeof AnchorMode)[keyof typeof AnchorMode]; declare const PostConditionModeWire: { readonly Allow: 0x01 readonly Deny: 0x02 readonly Originator: 0x03 }; type PostConditionModeWire = (typeof PostConditionModeWire)[keyof typeof PostConditionModeWire]; declare const AddressHashMode: { readonly P2PKH: 0x00 readonly P2SH: 0x01 readonly P2WPKH: 0x02 readonly P2WSH: 0x03 readonly P2SH_NonSequential: 0x05 readonly P2WSH_P2SH_NonSequential: 0x07 }; type AddressHashMode = (typeof AddressHashMode)[keyof typeof AddressHashMode]; declare const PubKeyEncoding: { readonly Compressed: 0x00 readonly Uncompressed: 0x01 }; type PubKeyEncoding = (typeof PubKeyEncoding)[keyof typeof PubKeyEncoding]; declare const PoxConditionCode: { readonly WillNotPerform: 0x30 readonly MayPerform: 0x31 readonly WillPerform: 0x32 }; type PoxConditionCode = (typeof PoxConditionCode)[keyof typeof PoxConditionCode]; declare const TenureChangeCause: { readonly BlockFound: 0x00 readonly Extended: 0x01 readonly ExtendedRuntime: 0x02 readonly ExtendedReadCount: 0x03 readonly ExtendedReadLength: 0x04 readonly ExtendedWriteCount: 0x05 readonly ExtendedWriteLength: 0x06 }; type TenureChangeCause = (typeof TenureChangeCause)[keyof typeof TenureChangeCause]; type TokenTransferPayload = { payloadType: typeof PayloadType.TokenTransfer recipient: ClarityValue amount: bigint memo: string }; type ContractCallPayload = { payloadType: typeof PayloadType.ContractCall contractAddress: string contractName: string functionName: string functionArgs: ClarityValue[] }; type SmartContractPayload = { payloadType: typeof PayloadType.SmartContract | typeof PayloadType.VersionedSmartContract clarityVersion?: ClarityVersion contractName: string codeBody: string }; type CoinbasePayload = { payloadType: typeof PayloadType.Coinbase coinbaseBuffer: string }; type CoinbaseToAltRecipientPayload = { payloadType: typeof PayloadType.CoinbaseToAltRecipient coinbaseBuffer: string recipient: ClarityValue }; type PoisonMicroblockPayload = { payloadType: typeof PayloadType.PoisonMicroblock header1: string header2: string }; type TenureChangePayload = { payloadType: typeof PayloadType.TenureChange tenureConsensusHash: string prevTenureConsensusHash: string burnViewConsensusHash: string previousTenureEnd: string previousTenureBlocks: number cause: TenureChangeCause pubkeyHash: string }; type NakamotoCoinbasePayload = { payloadType: typeof PayloadType.NakamotoCoinbase coinbaseBuffer: string recipient: ClarityValue | null vrfProof: string }; type TransactionPayload = TokenTransferPayload | ContractCallPayload | SmartContractPayload | CoinbasePayload | CoinbaseToAltRecipientPayload | PoisonMicroblockPayload | TenureChangePayload | NakamotoCoinbasePayload; type SingleSigSpendingCondition = { hashMode: typeof AddressHashMode.P2PKH | typeof AddressHashMode.P2WPKH signer: string nonce: bigint fee: bigint keyEncoding: PubKeyEncoding signature: string }; type TransactionAuthField = { pubKeyEncoding: PubKeyEncoding type: "publicKey" | "signature" data: string }; type MultiSigHashMode = typeof AddressHashMode.P2SH | typeof AddressHashMode.P2WSH | typeof AddressHashMode.P2SH_NonSequential | typeof AddressHashMode.P2WSH_P2SH_NonSequential; type MultiSigSpendingCondition = { hashMode: MultiSigHashMode signer: string nonce: bigint fee: bigint fields: TransactionAuthField[] signaturesRequired: number }; type SpendingCondition = SingleSigSpendingCondition | MultiSigSpendingCondition; type StandardAuthorization = { authType: typeof AuthType.Standard spendingCondition: SpendingCondition }; type SponsoredAuthorization = { authType: typeof AuthType.Sponsored spendingCondition: SpendingCondition sponsorSpendingCondition: SpendingCondition }; type Authorization = StandardAuthorization | SponsoredAuthorization; type StacksTransaction = { version: number chainId: number auth: Authorization anchorMode: AnchorMode postConditionMode: PostConditionModeWire postConditions: PostConditionWire[] payload: TransactionPayload /** Multi-sig signer metadata — not part of the wire format, preserved * through serialize/deserialize round-trip for auto-detection. */ _multisig?: { publicKeys: string[] } }; type PostConditionWire = StxPostConditionWire | FtPostConditionWire | NftPostConditionWire | StakingPostConditionWire | PoxPostConditionWire; type StxPostConditionWire = { type: "stx" principal: PostConditionPrincipalWire conditionCode: number amount: bigint }; type FtPostConditionWire = { type: "ft" principal: PostConditionPrincipalWire asset: AssetInfoWire conditionCode: number amount: bigint }; type NftPostConditionWire = { type: "nft" principal: PostConditionPrincipalWire asset: AssetInfoWire conditionCode: number assetId: ClarityValue }; type StakingPostConditionWire = { type: "staking" principal: PostConditionPrincipalWire conditionCode: number amount: bigint }; type PoxPostConditionWire = { type: "pox" principal: PostConditionPrincipalWire conditionCode: PoxConditionCode }; type PostConditionPrincipalWire = { type: "origin" } | { type: "standard" address: string } | { type: "contract" address: string contractName: string }; type AssetInfoWire = { address: string contractName: string assetName: string }; /** Allocates mempool-safe sequential nonces across rapid broadcasts from one account. */ type NonceManager = { consume(params: { client: Client address: string }): Promise reset(params: { client: Client address: string }): void | Promise /** * Give back a nonce from {@link NonceManager.consume} whose transaction * was never accepted by the node. No-op unless it is the latest issued. */ release(params: { client: Client address: string nonce: bigint }): void | Promise /** Next nonce that {@link NonceManager.consume} would return without consuming it, or `undefined` if untracked. */ peek(params: { client: Client address: string }): Promise }; /** Full chain descriptor used by clients and transports for network-aware operations. */ type StacksChain = { /** Chain ID (e.g. 0x00000001 for mainnet) */ id: number /** Human-readable name */ name: string /** Network type */ network: "mainnet" | "testnet" /** Transaction version byte for serialization */ transactionVersion: number /** Peer network ID for P2P broadcasting */ peerNetworkId: number /** Address version bytes */ addressVersion: { singleSig: number multiSig: number } /** Magic bytes for network identification */ magicBytes: string /** Boot address (system contracts deployer) */ bootAddress: string /** Native currency info */ nativeCurrency: { name: string symbol: string decimals: number } /** Default RPC URLs */ rpcUrls: { default: { http: string[] ws?: string[] } } /** Block explorer URLs */ blockExplorers?: { default: { name: string url: string } } }; /** Function that sends an HTTP request to a Stacks node API path. */ type RequestFn = (path: string, options?: RequestOptions) => Promise; /** Options for a transport-level HTTP request. */ type RequestOptions = { method?: "GET" | "POST" | "PUT" | "DELETE" body?: unknown headers?: Record /** * Cancel the request from the caller's side. An aborted signal rejects * with the signal's reason immediately and never retries; it is combined * with the transport's own per-attempt timeout. */ signal?: AbortSignal /** * Override the transport's retry budget for this one request. Broadcasts * pass `0`: re-sending a transaction the node may already hold trades a * transient failure for a confusing nonce conflict. */ retryCount?: number }; /** Shared configuration for all transport types. */ type TransportConfig = { url?: string /** * Per-attempt deadline in ms covering headers AND body. A stalled body * rejects with `TimeoutError` instead of hanging. Default 30_000. */ timeout?: number retryCount?: number retryDelay?: number fetchOptions?: RequestInit /** Sent as `x-api-key`. Held in the request closure and stripped from * `Transport.config` so it never prints with the client. */ apiKey?: string }; /** A resolved transport instance with a bound request function. */ type Transport = { type: string request: RequestFn config: TransportConfig destroy?: () => void }; /** Union of all supported account types (local key, custom signer, or browser provider). */ type Account = LocalAccount | CustomAccount | ProviderAccount; /** * Core client instance that holds chain context, transport, and extensible actions. * Created via {@link createClient}, {@link createPublicClient}, or {@link createWalletClient}. */ type Client = Record> = { chain?: StacksChain account?: Account transport: Transport request: RequestFn /** Optional nonce manager for mempool-safe sequential nonces across rapid broadcasts. */ nonceManager?: NonceManager extend: >(fn: (client: Client) => TNew) => Client & TNew } & TExtended; type GetNonceParams = { address: string }; declare function getNonce(client: Client, params: GetNonceParams): Promise; type GetBalanceParams = { address: string }; declare function getBalance(client: Client, params: GetBalanceParams): Promise; type GetAccountInfoParams = { address: string }; type AccountInfo = { balance: bigint nonce: bigint balanceProof: string nonceProof: string }; declare function getAccountInfo(client: Client, params: GetAccountInfoParams): Promise; type GetBlockParams = { height?: number hash?: string }; /** * Fetch one block by hash or height, or the chain tip when both are omitted. * Every path resolves to a single block object: the tip read unwraps the * list envelope the extended API returns for `?limit=1`. */ declare function getBlock(client: Client, params?: GetBlockParams): Promise; type GetRawBlockParams = { height: number }; /** * Raw node RPC block shape (`/v2/blocks/{height}`) — distinct from * {@link getBlock}'s Hiro extended-API shape. Carries consensus/identity * fields (`index_block_hash`, `miner_txid`, ...) that the indexed API doesn't * expose, for trust-minimized use cases (e.g. block-header proofs) that can't * rely on a third-party indexer. */ type RawBlockResponse = { hash: string height: number parent_block_hash: string burn_block_height: number burn_block_hash: string burn_block_time: number index_block_hash: string parent_index_block_hash: string miner_txid: string txs: string[] }; /** * Fetch a block by height directly from a stacks-node (not Hiro's extended * API — see {@link getBlock} for that). Returns `null` when the node has no * block at that height. */ declare function getRawBlock(client: Client, params: GetRawBlockParams): Promise; declare function getBlockHeight(client: Client): Promise; type ReadContractParams = { contract: string functionName: string args?: ClarityValue[] sender?: string /** * Nakamoto StacksBlockId to evaluate against. Without it the node answers * at its own moving tip, which makes a read non-deterministic — the same * reindex of the same block can return a different value. */ tip?: string }; declare function readContract(client: Client, params: ReadContractParams): Promise; type GetContractAbiParams = { contract: string }; declare function getContractAbi(client: Client, params: GetContractAbiParams): Promise; type GetContractSourceParams = { contract: string }; type ContractSourceResponse = { source: string publish_height: number marf_proof?: string }; /** * Fetch a deployed contract's Clarity source. Node-RPC only (`/v2/contracts/source`) * — not available through Hiro's extended API or a tenant proxy, so `client` * must be configured against a direct node transport. Returns `null` when the * node has no source for the contract. */ declare function getContractSource(client: Client, params: GetContractSourceParams): Promise; type GetDataVarParams = { contract: string varName: string }; declare function getDataVar(client: Client, params: GetDataVarParams): Promise; type GetMapEntryParams = { contract: string mapName: string key: ClarityValue }; declare function getMapEntry(client: Client, params: GetMapEntryParams): Promise; type EstimateFeeParams = { transaction: StacksTransaction }; type FeeEstimation = { feeRate: number fee: number }; declare function estimateFee(client: Client, params: EstimateFeeParams): Promise; type MulticallCall = { contract: string functionName: string args?: ClarityValue[] sender?: string }; type MulticallParams = { calls: readonly MulticallCall[] allowFailure?: TAllowFailure /** * Reads in flight at once. Default 8. Each call is its own * `/v2/contracts/call-read` request (Stacks nodes have no batch RPC), so * an uncapped fan-out turns one multicall into a burst that trips rate * limits and then retries in lockstep. */ concurrency?: number }; type MulticallSuccessResult = { status: "success" result: ClarityValue }; type MulticallFailureResult = { status: "failure" error: Error }; type MulticallResult = T extends true ? (MulticallSuccessResult | MulticallFailureResult)[] : ClarityValue[]; declare function multicall(client: Client, params: MulticallParams): Promise>; declare class BaseError extends Error { private; name: string; shortMessage: string; details?: string; constructor(shortMessage: string, options?: { cause?: Error details?: string code?: string }); /** * Stable identifier for programmatic handling; survives message * rewording and minification. An explicit `code` option wins, else it * is derived from `name` (`TimeoutError` gives `TIMEOUT_ERROR`). */ get code(): string; set code(value: string); toJSON(): { name: string code: string message: string shortMessage: string details: string | undefined cause: string | undefined }; } declare class SimulationError extends BaseError { name: string; writesDetected: boolean; constructor(message: string, options: { writesDetected: boolean details?: string }); } type SimulateCallParams = { contract: string functionName: string args?: ClarityValue[] sender?: string tip?: string }; type SimulateCallSuccess = { success: true result: ClarityValue }; type SimulateCallFailure = { success: false error: SimulationError }; type SimulateCallResult = SimulateCallSuccess | SimulateCallFailure; declare function simulateCall(client: Client, params: SimulateCallParams): Promise; type SimulateTransactionParams = { transaction: StacksTransaction sender?: string tip?: string }; type SimulateContractCallResult = { type: "contract-call" execution: SimulateCallResult fees: FeeEstimation[] }; type SimulateTransferResult = { type: "token-transfer" fees: FeeEstimation[] }; type SimulateDeployResult = { type: "contract-deploy" fees: FeeEstimation[] }; type SimulateTransactionResult = SimulateContractCallResult | SimulateTransferResult | SimulateDeployResult; declare function simulateTransaction(client: Client, params: SimulateTransactionParams): Promise; /** * Pluggable transaction-status sources for {@link getTransaction} / * `waitForTransactionReceipt`. * * A bare stacks-node has no confirmed-transaction endpoint, so status reads * need a host that indexes transactions. Where that data comes from is * pluggable, mirroring the nonce sources: * * - {@link extendedApiSource} — default; `/extended/v1/tx/{txid}` on the * client's transport host (Hiro API or any extended-API-compatible host). * - {@link indexTxSource}: a Secondlayer instance's * `/v1/index/transactions/{txid}`; returns the chain tip in the same * response, so N-confirmation waits need no second request. */ type TransactionStatus = "pending" | "success" | "abort_by_response" | "abort_by_post_condition" | "dropped"; type TransactionReceipt = { txid: string status: TransactionStatus /** Anchor block height; absent while pending. */ blockHeight?: number blockHash?: string /** Decoded Clarity result; absent while pending or when the source omits it. */ result?: ClarityValue resultHex?: string events: unknown[] /** The source's unnormalized response, for fields the receipt doesn't model. */ raw: unknown }; type TransactionSnapshot = { /** `null` when the source has no record of the tx (mempool + chain). */ receipt: TransactionReceipt | null /** Chain tip height, when the source knows it (saves a round-trip). */ tip?: number }; type TransactionStatusSource = { get(args: { client: Client txid: string }): Promise /** * True when the source only knows mined transactions and reports * `receipt: null` for the whole mempool life of a tx. The wait action * then stretches its dropped-grace window to the full timeout, since * "unknown" cannot mean "dropped" until the deadline. */ canonicalOnly?: boolean }; /** * Default source: `GET /extended/v1/tx/{txid}` via the client's transport. * Requires a host that serves Hiro's extended API (a bare stacks-node does * not). Does not report the chain tip — the wait action fetches it separately * when `confirmations > 1`. */ declare function extendedApiSource(): TransactionStatusSource; type IndexTxSourceParams = { /** * URL of your Secondlayer instance. Without it the client's transport * URL is assumed to be the instance: a transport on a Hiro host throws * up front, and a host that answers `/v1/index` with a non-JSON 404 * (a bare stacks-node) throws on the first read. Pass it whenever the * transport is not the instance. */ baseUrl?: string /** Instance token, sent as `Authorization: Bearer`. */ apiKey?: string }; /** * Source backed by a Secondlayer instance's `/v1/index/transactions/{txid}`. * The response embeds the chain tip, so N-confirmation math needs no extra * request. Requests go through the transport layer: same retries, timeout * and typed errors as every other read. The index only returns canonical * (mined) transactions; while a tx is in the mempool this source reports * `receipt: null`, and the wait action's grace window carries it until * inclusion. */ declare function indexTxSource(params?: IndexTxSourceParams): TransactionStatusSource; type GetTransactionParams = { txid: string /** Where to read status from. Defaults to {@link extendedApiSource}. */ source?: TransactionStatusSource }; /** * Fetch a transaction's receipt (status, block info, decoded result). * Returns `null` when the source has no record of the transaction. */ declare function getTransaction(client: Client, params: GetTransactionParams): Promise; type GetAccountHistoryParams = { address: string /** Capped at 50. Default 20. */ limit?: number }; type AccountHistoryResponse = { results: unknown[] total: number }; /** Paginated transaction history for a principal (Hiro extended API). */ declare function getAccountHistory(client: Client, params: GetAccountHistoryParams): Promise; /** * Current mempool statistics: pending count, fee distribution, age buckets * (Hiro extended API). */ declare function getMempoolStats(client: Client): Promise; type GetNftHoldingsParams = { address: string /** Capped at 50. Default 20. */ limit?: number }; type NftHoldingsResponse = { results: unknown[] total: number }; /** NFT holdings for a principal across all collections (Hiro extended API). */ declare function getNftHoldings(client: Client, params: GetNftHoldingsParams): Promise; type WaitForTransactionReceiptParams = { txid: string /** Anchor-block confirmations to wait for. Default 1 (mined). */ confirmations?: number /** Give up after this many ms. Default 180_000 (3 min). */ timeout?: number /** Delay between status polls, ms. Default 3_000. */ pollingInterval?: number /** * How long a tx may be unknown to the source before it counts as dropped, * ms. Covers broadcast propagation lag. Default 30_000, or the full * `timeout` for a canonical-only source (one that cannot see the * mempool, so "unknown" means "not mined yet" until the deadline). */ droppedGracePeriod?: number /** Where to read status from. Defaults to {@link extendedApiSource}. */ source?: TransactionStatusSource }; /** * Poll until a transaction is mined with N confirmations, then return its * receipt. * * Rejects with {@link TransactionAbortedError} when the tx mines but aborts * (`abort_by_response` / `abort_by_post_condition`) — the receipt is attached. * Rejects with {@link TransactionDroppedError} when the tx leaves the mempool * unmined or stays unknown past `droppedGracePeriod`, and * {@link WaitForTransactionTimeoutError} at `timeout`. * * Reorg-tolerant: every cycle re-reads the receipt (block height may change) * and recomputes confirmations from the current tip. */ declare function waitForTransactionReceipt(client: Client, params: WaitForTransactionReceiptParams): Promise; /** Handle returned by WebSocket subscription methods; call `unsubscribe()` to stop. */ type Subscription = { unsubscribe: () => void }; type BlockNotification = { canonical: boolean height: number hash: string index_block_hash: string parent_block_hash: string burn_block_height: number burn_block_hash: string parent_burn_block_hash: string parent_burn_block_height: number parent_index_block_hash: string txs: string[] }; type MempoolNotification = { tx_id: string tx_type: string tx_status: string receipt_time: number receipt_time_iso: string fee_rate: string sender_address: string sponsor_address?: string nonce: number contract_call?: { contract_id: string function_name: string function_signature: string } token_transfer?: { recipient_address: string amount: string memo: string } }; type TxUpdateNotification = { tx_id: string tx_type: string tx_status: string block_hash?: string block_height?: number burn_block_height?: number burn_block_time?: number tx_result?: { hex: string repr: string } }; type AddressTxNotification = { address: string tx_id: string tx_type: string tx_status: string stx_sent: string stx_received: string stx_transfers: Array<{ amount: string sender: string recipient: string }> ft_transfers: Array<{ amount: string asset_identifier: string sender: string recipient: string }> nft_transfers: Array<{ asset_identifier: string sender: string recipient: string value: { hex: string repr: string } }> }; type AddressBalanceNotification = { address: string balance: string total_sent: string total_received: string total_fees_sent: string total_miner_rewards_received: string lock_tx_id: string locked: string lock_height: number burnchain_lock_height: number burnchain_unlock_height: number }; type NftEventNotification = { sender: string recipient: string asset_identifier: string asset_event_type: string value: { hex: string repr: string } tx_id: string block_height: number }; type WatchBlocksParams = { onBlock: (block: BlockNotification) => void }; declare function watchBlocks(client: Client, params: WatchBlocksParams): Promise; type WatchMempoolParams = { onTransaction: (tx: MempoolNotification) => void }; declare function watchMempool(client: Client, params: WatchMempoolParams): Promise; type WatchTransactionParams = { txId: string onUpdate: (update: TxUpdateNotification) => void }; declare function watchTransaction(client: Client, params: WatchTransactionParams): Promise; type WatchAddressParams = { address: string onTransaction: (tx: AddressTxNotification) => void }; declare function watchAddress(client: Client, params: WatchAddressParams): Promise; type WatchAddressBalanceParams = { address: string onBalance: (balance: AddressBalanceNotification) => void }; declare function watchAddressBalance(client: Client, params: WatchAddressBalanceParams): Promise; type WatchNftEventParams = { onEvent: (event: NftEventNotification) => void assetIdentifier?: string value?: string }; declare function watchNftEvent(client: Client, params: WatchNftEventParams): Promise; type SendTransactionParams = { transaction: StacksTransaction attachment?: Uint8Array | string /** * Wait for the transaction to be mined before returning. `true` waits for * 1 confirmation; a number waits for that many. The receipt lands on the * result. Rejects if the tx aborts, is dropped, or the wait times out. */ wait?: boolean | number }; type SendTransactionResult = { txid: string /** Present when `wait` was requested. */ receipt?: TransactionReceipt }; /** Broadcast a signed transaction to the network */ declare function sendTransaction(client: Client, params: SendTransactionParams): Promise; type SignTransactionParams = { transaction: StacksTransaction /** Public keys for multi-sig signing (auto-detected from _multisig metadata if omitted) */ signers?: string[] }; /** Sign a transaction using the client's account */ declare function signTransactionAction(client: Client, params: SignTransactionParams): Promise; type FungibleComparator = "eq" | "gt" | "gte" | "lt" | "lte"; type NonFungibleComparator = "sent" | "not-sent" | "maybe-sent"; type StxPostCondition = { type: "stx-postcondition" address: string condition: FungibleComparator amount: string | bigint | number }; type FtPostCondition = { type: "ft-postcondition" address: string condition: FungibleComparator asset: string amount: string | bigint | number }; type NftPostCondition = { type: "nft-postcondition" address: string condition: NonFungibleComparator asset: string assetId: ClarityValue }; type StakingPostCondition = { type: "staking-postcondition" address: string condition: FungibleComparator amount: string | bigint | number }; type PoxComparator = "will-not-perform" | "may-perform" | "will-perform"; type PoxPostCondition = { type: "pox-postcondition" address: string condition: PoxComparator }; type PostCondition = StxPostCondition | FtPostCondition | NftPostCondition | StakingPostCondition | PoxPostCondition; /** Serialized PC hex is accepted anywhere a `PostCondition` object is. */ type PostConditionInput = PostCondition | string; type PostConditionMode = "allow" | "deny" | "originator"; type IntegerType = number | string | bigint | Uint8Array; declare function isProviderAccount(account: Account): account is ProviderAccount; /** * Named fee tiers. `'low' | 'mid' | 'high'` map to the node's three fee * estimations; `'min'` is the node's minimum relay fee — 1 uSTX per byte of * the serialized transaction, computable offline. */ type FeeTier = "min" | "low" | "mid" | "high"; /** Fee input accepted by wallet actions: an explicit amount or a named tier. */ type FeeParam = IntegerType | FeeTier; declare function isFeeTier(fee: FeeParam | undefined): fee is FeeTier; /** * Minimum relay fee: 1 uSTX per byte of the serialized transaction. The fee * field is fixed-width (8 bytes), so the size — and therefore this floor — is * stable regardless of the fee value later set on the spending condition. */ declare function minimumFee(transaction: StacksTransaction): bigint; /** Outcome of {@link resolveFee}: the amount and which tier produced it. */ type ResolvedFee = { fee: bigint /** * Tier the amount came from. `'min'` when the estimator had no estimate * and the relay floor was used instead. Absent when the caller passed an * exact amount. */ tier?: FeeTier }; /** * True when the node answered `POST /v2/fees/transaction` with 400 * `NoEstimateAvailable`: it is healthy but has no fee history for this * payload (fresh devnet, quiet chain). Every other failure means the * estimate was never obtained and must surface to the caller. */ declare function isNoEstimateAvailable(error: unknown): boolean; /** * Resolve a fee param to a concrete amount. Numeric input passes through. * Tiers `'low' | 'mid' | 'high'` index the node's estimations (nearest * available when fewer than three are returned); `'min'` resolves to * {@link minimumFee}, which needs no network round-trip. * * The relay floor is the fallback ONLY when the node reports * `NoEstimateAvailable` or returns no estimations. A transport timeout, 5xx, * or auth failure rethrows: silently under-paying because the node was * unreachable would strand the transaction in the mempool. */ declare function resolveFee(client: Client, transaction: StacksTransaction, fee: FeeParam | undefined): Promise; type TransferStxParams = { to: string amount: IntegerType memo?: string fee?: FeeParam nonce?: IntegerType postConditionMode?: PostConditionMode postConditions?: PostConditionInput[] }; /** Build, sign, and broadcast an STX transfer */ declare function transferStx(client: Client, params: TransferStxParams): Promise; type CallContractParams = { contract: string functionName: string functionArgs?: ClarityValue[] fee?: FeeParam nonce?: IntegerType postConditionMode?: PostConditionMode postConditions?: PostConditionInput[] }; /** Build, sign, and broadcast a contract call */ declare function callContract(client: Client, params: CallContractParams): Promise; type DeployContractParams = { contractName: string codeBody: string clarityVersion?: ClarityVersion fee?: FeeParam nonce?: IntegerType postConditionMode?: PostConditionMode postConditions?: PostConditionInput[] }; /** Build, sign, and broadcast a contract deploy */ declare function deployContract(client: Client, params: DeployContractParams): Promise; type SignMessageParams = { message: string | ClarityValue domain?: { name: string version: string chainId: number } }; /** Sign a message. With `domain`, hashes per SIP-018; without, hashes the serialized CV. */ declare function signMessage2(client: Client, params: SignMessageParams): Promise; type SponsorTransactionParams = { transaction: StacksTransaction fee?: FeeParam nonce?: IntegerType }; /** Sponsor a transaction: set sponsor spending condition, sign as sponsor */ declare function sponsorTransaction(client: Client, params: SponsorTransactionParams): Promise; type AbiUInt128 = "uint128"; type AbiInt128 = "int128"; type AbiBool = "bool"; type AbiPrincipal = "principal"; type AbiTraitReference = "trait_reference"; type AbiNone = "none"; type AbiStringAscii = { "string-ascii": { length: L } }; type AbiStringUtf8 = { "string-utf8": { length: L } }; type AbiBuffer = { buff: { length: L } }; type AbiPrimitiveType = AbiUInt128 | AbiInt128 | AbiBool | AbiPrincipal | AbiTraitReference | AbiNone | AbiStringAscii | AbiStringUtf8 | AbiBuffer; interface AbiListType { list: { type: AbiType length: number }; } interface AbiTupleType { tuple: ReadonlyArray<{ name: string type: AbiType }>; } interface AbiOptionalType { optional: AbiType; } interface AbiResponseType { response: { ok: AbiType error: AbiType }; } /** Discriminated union of all Clarity value types (primitives, buffers, lists, tuples, optionals, responses). */ type AbiType = AbiPrimitiveType | AbiListType | AbiTupleType | AbiOptionalType | AbiResponseType; type CamelCaseInner = S extends `${infer P1}-${infer P2}${infer P3}` ? `${P1}${Capitalize>}` : S; type ToCamelCase = CamelCaseInner extends `${number}${string}` ? `_${CamelCaseInner}` : CamelCaseInner; type TupleToObject> = { [K in T[number]["name"] as ToCamelCase] : AbiToTS["type"]> }; type AbiToTS = T extends "none" ? never : T extends "uint128" ? bigint : T extends "int128" ? bigint : T extends "bool" ? boolean : T extends "principal" ? string : T extends "trait_reference" ? string : T extends { "string-ascii": any } ? string : T extends { "string-utf8": any } ? string : T extends { buff: any } ? Uint8Array : T extends { list: { type: infer U extends AbiType } } ? Array> : T extends { optional: infer U extends AbiType } ? AbiToTS | null : T extends { response: { ok: infer O extends AbiType error: infer E extends AbiType } } ? { ok: AbiToTS } | { err: AbiToTS } : T extends { tuple: infer Fields extends ReadonlyArray<{ name: string type: AbiType }> } ? TupleToObject : never; type FunctionAccess = "public" | "read-only" | "private"; interface FunctionArg { name: string; type: AbiType; } /** A single Clarity function definition with name, access level, arguments, and return type. */ interface AbiFunction { name: string; access: FunctionAccess; args: ReadonlyArray; outputs: AbiType; } type VariableAccess = "constant" | "variable"; interface AbiVariable { name: string; type: AbiType; access: VariableAccess; } interface AbiMap { name: string; key: AbiType; value: AbiType; } interface AbiFungibleToken { name: string; } interface AbiNonFungibleToken { name: string; type: AbiType; } type TraitFunctionAccess = Exclude; interface AbiTraitFunction { name: string; access: TraitFunctionAccess; args: ReadonlyArray; outputs: AbiType; } interface AbiTraitDefinition { name: string; functions: ReadonlyArray; } /** Full Clarity contract ABI including functions, maps, variables, and token definitions. */ interface AbiContract { functions: ReadonlyArray; maps?: ReadonlyArray; variables?: ReadonlyArray; fungible_tokens?: ReadonlyArray; non_fungible_tokens?: ReadonlyArray; implemented_traits?: ReadonlyArray; defined_traits?: ReadonlyArray; } declare const abiTypes: unique symbol; /** * Phantom type bundle a codegen tool can fuse onto an as-const ABI literal. * * Function/map keys are camelCase (matching the runtime client's method names) * and `args` is the named-args object each method accepts. `ret` is the raw * output type before any response unwrapping. */ type ContractTypes = { functions: Record maps?: Record }; /** * Resolve the brand off an ABI type. `never` for un-branded ABIs, which lets * consumers fall back to structural inference. */ type AbiTypesOf = C extends { readonly [abiTypes]?: infer T } ? NonNullable extends ContractTypes ? NonNullable : never : never; type ExtractFunctionNames< C extends AbiContract, Access extends FunctionAccess = FunctionAccess > = Extract["name"]; type ExtractFunction< C extends AbiContract, N extends ExtractFunctionNames > = Extract; type ExtractFunctionArgs< C extends AbiContract, N extends ExtractFunctionNames > = ExtractFunction extends { args: infer Args extends ReadonlyArray<{ name: string type: any }> } ? { [K in Args[number]["name"] as ToCamelCase] : AbiToTS["type"]> } : never; type ExtractFunctionOutput< C extends AbiContract, N extends ExtractFunctionNames > = ExtractFunction extends { outputs: infer O extends AbiType } ? AbiToTS : never; type ExtractPublicFunctions = ExtractFunctionNames; type ExtractReadOnlyFunctions = ExtractFunctionNames; type ExtractMapNames = C["maps"] extends ReadonlyArray<{ name: infer N extends string }> ? N : never; type ExtractMap< C extends AbiContract, N extends ExtractMapNames > = C["maps"] extends ReadonlyArray ? Extract : never; type ExtractMapKey< C extends AbiContract, N extends ExtractMapNames > = ExtractMap extends { key: infer K extends AbiType } ? AbiToTS : never; type ExtractMapValue< C extends AbiContract, N extends ExtractMapNames > = ExtractMap extends { value: infer V extends AbiType } ? AbiToTS : never; /** * Unwrap `(response ok err)` → just the `ok` branch type. Distributes over the * `{ ok } | { err }` union: the `err` branch maps to `never` (it throws * `ContractResponseError` at runtime, so it never reaches the caller). */ type UnwrapResponse = T extends { ok: infer O } ? O : T extends { err: unknown } ? never : T; /** * True for a structural empty mapped type (`{}`) and for codegen's * `Record`. `keyof Record` is `string`, so the * first check alone is not enough. */ type IsEmptyArgs = [keyof A & string] extends [never] ? true : Record extends A ? true : false; /** No-arg ABI functions may omit the dummy `{}`. Functions with args stay required. */ type ContractMethod< A, R, Extra extends unknown[] = [] > = IsEmptyArgs extends true ? (args?: A, ...extra: Extra) => R : (args: A, ...extra: Extra) => R; type ReadMethodReturn< C extends AbiContract, N extends ExtractReadOnlyFunctions > = UnwrapResponse>; /** * When the ABI carries a codegen brand (`TypedAbi`), method types resolve to * the generated named aliases — cleaner hovers and error messages. Un-branded * ABIs fall back to structural inference over the as-const literal. */ type TypedReadMethods = { [K in keyof T["functions"] as T["functions"][K]["access"] extends "read-only" ? K : never] : ContractMethod>> }; type TypedCallMethods = { [K in keyof T["functions"] as T["functions"][K]["access"] extends "public" ? K : never] : ContractMethod, [options?: ContractCallOptions]> }; type TypedMapMethods = { [K in keyof NonNullable] : (key: NonNullable[K]["key"]) => Promise[K]["value"] | null> }; type ReadMethods = [AbiTypesOf] extends [never] ? { [N in ExtractReadOnlyFunctions as ToCamelCase] : ContractMethod, Promise>> } : TypedReadMethods>; type CallMethods = [AbiTypesOf] extends [never] ? { [N in ExtractPublicFunctions as ToCamelCase] : ContractMethod, Promise, [options?: ContractCallOptions]> } : TypedCallMethods>; type MapMethods = [AbiTypesOf] extends [never] ? { [N in ExtractMapNames as ToCamelCase] : (key: ExtractMapKey) => Promise | null> } : TypedMapMethods>; type ContractCallOptions = { fee?: IntegerType nonce?: IntegerType postConditionMode?: PostConditionMode postConditions?: PostConditionInput[] }; /** * Options for `buildCall.*`, building an unsigned transaction for * wallet-signs-later flows. `publicKey` defaults to the client account's * public key. When omitted, `nonce` is the confirmed on-chain nonce read * straight from the node (the client's nonce manager is never consumed for * a transaction that may never be sent) and `fee` is the mid estimate, * falling back to the relay floor only on `NoEstimateAvailable`. */ type ContractBuildCallOptions = ContractCallOptions & { publicKey?: string sponsored?: boolean }; type TypedBuildCallMethods = { [K in keyof T["functions"] as T["functions"][K]["access"] extends "public" ? K : never] : ContractMethod, [options?: ContractBuildCallOptions]> }; type BuildCallMethods = [AbiTypesOf] extends [never] ? { [N in ExtractPublicFunctions as ToCamelCase] : ContractMethod, Promise, [options?: ContractBuildCallOptions]> } : TypedBuildCallMethods>; type ContractInstance = { read: ReadMethods call: CallMethods /** Build unsigned transactions (wallet-signs-later) — never broadcasts. */ buildCall: BuildCallMethods maps: MapMethods }; type GetContractParams = { client: Client address: string name: string abi: C }; declare function getContract(params: GetContractParams): ContractInstance; /** * Encode an ABI function's named args into positional ClarityValues. Exported * so a caller that needs the raw ClarityValue result (to cache or re-serialize * it) can reuse the same encoding this module's read methods use, instead of * maintaining a second one that drifts. */ declare function buildFunctionArgs(fn: AbiFunction, args?: Record): ClarityValue[]; /** True when an ABI output is a `(response ok err)` and needs unwrapping. */ declare function isResponseOutput(type: AbiType): boolean; declare class ContractResponseError extends Error { readonly errorValue: unknown; name: string; constructor(message: string, errorValue: unknown); } export { watchTransaction, watchNftEvent, watchMempool, watchBlocks, watchAddressBalance, watchAddress, waitForTransactionReceipt, transferStx, sponsorTransaction, simulateTransaction, simulateCall, signTransactionAction, signMessage2 as signMessage, sendTransaction, resolveFee, readContract, multicall, minimumFee, isResponseOutput, isProviderAccount, isNoEstimateAvailable, isFeeTier, indexTxSource, getTransaction, getRawBlock, getNonce, getNftHoldings, getMempoolStats, getMapEntry, getDataVar, getContractSource, getContractAbi, getContract, getBlockHeight, getBlock, getBalance, getAccountInfo, getAccountHistory, extendedApiSource, estimateFee, deployContract, callContract, buildFunctionArgs, WatchTransactionParams, WatchNftEventParams, WatchMempoolParams, WatchBlocksParams, WatchAddressParams, WatchAddressBalanceParams, WaitForTransactionReceiptParams, UnwrapResponse, TransferStxParams, TransactionStatusSource, TransactionStatus, TransactionSnapshot, TransactionReceipt, SponsorTransactionParams, SimulateTransferResult, SimulateTransactionResult, SimulateTransactionParams, SimulateDeployResult, SimulateContractCallResult, SimulateCallSuccess, SimulateCallResult, SimulateCallParams, SimulateCallFailure, SignTransactionParams, SignMessageParams, SendTransactionResult, SendTransactionParams, ResolvedFee, ReadContractParams, RawBlockResponse, NftHoldingsResponse, MulticallSuccessResult, MulticallResult, MulticallParams, MulticallFailureResult, MulticallCall, IndexTxSourceParams, GetTransactionParams, GetRawBlockParams, GetNonceParams, GetNftHoldingsParams, GetMapEntryParams, GetDataVarParams, GetContractSourceParams, GetContractParams, GetContractAbiParams, GetBlockParams, GetBalanceParams, GetAccountInfoParams, GetAccountHistoryParams, FeeTier, FeeParam, FeeEstimation, EstimateFeeParams, DeployContractParams, ContractSourceResponse, ContractResponseError, ContractInstance, ContractCallOptions, ContractBuildCallOptions, CallContractParams, AccountInfo, AccountHistoryResponse };