/** * Fiber Network Node RPC Types (Fiber v0.9.0) * * The types in this file are intended to align with the upstream RPC spec: * https://github.com/nervosnetwork/fiber/blob/v0.9.0/crates/fiber-lib/src/rpc/README.md */ /** Hex-encoded string (prefixed with 0x). The RPC serializes most numeric values as hex strings. */ type HexString = `0x${string}`; /** A 256-bit hash digest (Hash256 in the RPC spec). */ type Hash256 = HexString; /** Public key for a node (Pubkey in the RPC spec). */ type Pubkey = HexString; /** Private key (Privkey in the RPC spec). */ type Privkey = HexString; /** Peer ID in libp2p format. */ type PeerId = string; /** Multiaddr format for network addresses. */ type Multiaddr = string; /** * Transport type for multiaddr filtering. * Used by `connect_peer` to select addresses by transport protocol. * @since Fiber v0.8.1 */ type TransportType = 'tcp' | 'ws' | 'wss'; /** Channel ID (Hash256). */ type ChannelId = Hash256; /** Payment hash (Hash256). */ type PaymentHash = Hash256; /** Script structure for CKB. */ interface Script$1 { code_hash: HexString; hash_type: 'type' | 'data' | 'data1' | 'data2'; args: HexString; } /** Transaction out point. */ interface OutPoint { tx_hash: Hash256; index: HexString; } /** Cell dependency reference for transaction construction. */ interface CellDep { out_point: OutPoint; dep_type: 'code' | 'dep_group'; } /** * JSON representation of a CKB transaction used by Fiber RPC. * * The upstream uses `ckb_jsonrpc_types::Transaction` here. We keep this type * intentionally structural to preserve compatibility across Fiber releases. */ type CkbTransaction = Record; /** UDT (User Defined Token) script (UdtScript in the RPC spec). */ type UdtScript = Script$1; type Currency = 'Fibb' | 'Fibt' | 'Fibd'; type HashAlgorithm = 'ckb_hash' | 'sha256'; /** Recoverable signature (InvoiceSignature in the RPC spec). */ type InvoiceSignature = HexString; /** * Invoice attribute types as returned by the RPC. * Each attribute is an object with a single key indicating the attribute type. */ type Attribute = /** Deprecated since v0.6.0, preserved for compatibility. */ { final_htlc_timeout: HexString; } /** Final TLC minimum expiry delta in milliseconds. */ | { final_htlc_minimum_expiry_delta: HexString; } /** Invoice expiry time in seconds. */ | { expiry_time: HexString; } /** Human-readable invoice description. */ | { description: string; } /** Fallback address for on-chain settlement. */ | { fallback_addr: string; } /** UDT script for token invoices. */ | { udt_script: HexString; } /** Payee public key. */ | { payee_public_key: Pubkey; } /** Hash algorithm used in the payment hash lock. */ | { hash_algorithm: HashAlgorithm; } /** Feature flags list. */ | { feature: string[]; } /** Payment secret. */ | { payment_secret: Hash256; }; interface InvoiceData { timestamp: HexString; payment_hash: PaymentHash; attrs: Attribute[]; } interface CkbInvoice { currency: Currency; amount?: HexString; signature?: InvoiceSignature; data: InvoiceData; } type CkbInvoiceStatus = 'Open' | 'Cancelled' | 'Expired' | 'Received' | 'Paid'; declare enum ChannelState { NegotiatingFunding = "NEGOTIATING_FUNDING", CollaboratingFundingTx = "COLLABORATING_FUNDING_TX", SigningCommitment = "SIGNING_COMMITMENT", AwaitingTxSignatures = "AWAITING_TX_SIGNATURES", AwaitingChannelReady = "AWAITING_CHANNEL_READY", ChannelReady = "CHANNEL_READY", ShuttingDown = "SHUTTING_DOWN", Closed = "CLOSED", /** * The channel state is potentially outdated (e.g., after a database restore). * fnn v0.9.0+ performs a passive audit with the peer before resuming operations. */ Stale = "STALE" } /** Channel state flags are serialized as a pipe-delimited SCREAMING_SNAKE_CASE string. */ type ChannelStateFlags = string; /** TLC status. The upstream spec defines OutboundTlcStatus / InboundTlcStatus, which may evolve. */ type TlcStatus = { Outbound: unknown; } | { Inbound: unknown; }; interface Htlc { id: HexString; amount: HexString; payment_hash: PaymentHash; expiry: HexString; forwarding_channel_id?: Hash256; forwarding_tlc_id?: HexString; status: TlcStatus; } interface Channel { channel_id: ChannelId; is_public: boolean; is_acceptor: boolean; is_one_way: boolean; channel_outpoint: OutPoint | null; pubkey: Pubkey; funding_udt_type_script: Script$1 | null; state: { state_name: ChannelState; state_flags?: ChannelStateFlags | string[]; }; local_balance: HexString; offered_tlc_balance: HexString; remote_balance: HexString; received_tlc_balance: HexString; pending_tlcs: Htlc[]; latest_commitment_transaction_hash: Hash256 | null; created_at: HexString; enabled: boolean; tlc_expiry_delta: HexString; tlc_fee_proportional_millionths: HexString; shutdown_transaction_hash: Hash256 | null; failure_detail?: string; } interface PeerInfo { pubkey: Pubkey; address: Multiaddr; } type PaymentStatus = 'Created' | 'Inflight' | 'Success' | 'Failed'; /** * Custom records for payments. * * Keys are hex-encoded u32 values (e.g. `0x1`, range 0..=65535), * values are hex-encoded byte arrays (0x-prefixed). */ type PaymentCustomRecords = Record; interface SessionRouteNode { pubkey: Pubkey; amount: HexString; channel_outpoint: OutPoint; } interface SessionRoute { nodes: SessionRouteNode[]; } interface PaymentInfo { payment_hash: PaymentHash; /** The preimage learned from a successful payment attempt (fnn v0.9.0+). */ payment_preimage?: Hash256; status: PaymentStatus; created_at: HexString; last_updated_at: HexString; failed_error?: string; fee: HexString; custom_records?: PaymentCustomRecords; routers?: SessionRoute[]; } interface ListPaymentsParams { payment_hash?: PaymentHash; limit?: HexString; after?: HexString; } interface ListPaymentsResult { payments: PaymentInfo[]; last_cursor: HexString; } interface HopHint { pubkey: Pubkey; channel_outpoint: OutPoint; fee_rate: HexString; tlc_expiry_delta: HexString; } type UdtCellDep = CellDep; interface UdtDep { cell_dep?: UdtCellDep | null; type_id?: Script$1 | null; } interface UdtArgInfo { name: string; script: UdtScript; auto_accept_amount?: HexString; cell_deps: UdtDep[]; } type UdtCfgInfos = UdtArgInfo[]; interface NodeInfo { version: string; commit_hash: string; pubkey: Pubkey; features: string[]; node_name: string | null; addresses: Multiaddr[]; chain_hash: Hash256; open_channel_auto_accept_min_ckb_funding_amount: HexString; auto_accept_channel_ckb_funding_amount: HexString; default_funding_lock_script: Script$1; tlc_expiry_delta: HexString; tlc_min_value: HexString; tlc_fee_proportional_millionths: HexString; channel_count: HexString; pending_channel_count: HexString; peers_count: HexString; udt_cfg_infos: UdtCfgInfos; } interface ChannelUpdateInfo { timestamp: HexString; enabled: boolean; outbound_liquidity?: HexString; tlc_expiry_delta: HexString; tlc_minimum_value: HexString; fee_rate: HexString; } interface GraphNodeInfo { node_name: string; version: string; addresses: Multiaddr[]; features: string[]; pubkey: Pubkey; timestamp: HexString; chain_hash: Hash256; auto_accept_min_ckb_funding_amount: HexString; udt_cfg_infos: UdtCfgInfos; } interface GraphChannelInfo { channel_outpoint: OutPoint; node1: Pubkey; node2: Pubkey; created_timestamp: HexString; update_info_of_node1?: ChannelUpdateInfo | null; update_info_of_node2?: ChannelUpdateInfo | null; capacity: HexString; chain_hash: Hash256; udt_type_script?: Script$1 | null; } interface ConnectPeerParams { address?: string; pubkey?: Pubkey; save?: boolean; /** * Filter peer addresses by transport type before random selection. * Only applies when connecting via pubkey (no explicit address). * Useful in WASM environments that only support WSS. * @since Fiber v0.8.1 */ addr_type?: TransportType; } /** connect_peer returns null. */ type ConnectPeerResult = null; interface DisconnectPeerParams { pubkey: Pubkey; } interface ListPeersResult { peers: PeerInfo[]; } interface OpenChannelParams { pubkey: Pubkey; funding_amount: HexString; public?: boolean; one_way?: boolean; funding_udt_type_script?: Script$1; shutdown_script?: Script$1; commitment_delay_epoch?: HexString; commitment_fee_rate?: HexString; funding_fee_rate?: HexString; tlc_expiry_delta?: HexString; tlc_min_value?: HexString; tlc_fee_proportional_millionths?: HexString; max_tlc_value_in_flight?: HexString; max_tlc_number_in_flight?: HexString; } interface OpenChannelResult { temporary_channel_id: ChannelId; } interface OpenChannelWithExternalFundingParams { pubkey: Pubkey; funding_amount: HexString; public?: boolean; funding_udt_type_script?: Script$1; shutdown_script?: Script$1; funding_lock_script: Script$1; funding_lock_script_cell_deps?: CellDep[]; commitment_delay_epoch?: HexString; commitment_fee_rate?: HexString; funding_fee_rate?: HexString; tlc_expiry_delta?: HexString; tlc_min_value?: HexString; tlc_fee_proportional_millionths?: HexString; max_tlc_value_in_flight?: HexString; max_tlc_number_in_flight?: HexString; } interface OpenChannelWithExternalFundingResult { channel_id: ChannelId; unsigned_funding_tx: CkbTransaction; } interface SubmitSignedFundingTxParams { channel_id: ChannelId; signed_funding_tx: CkbTransaction; } interface SubmitSignedFundingTxResult { channel_id: ChannelId; funding_tx_hash: Hash256; } interface AcceptChannelParams { temporary_channel_id: ChannelId; funding_amount: HexString; shutdown_script?: Script$1; max_tlc_value_in_flight?: HexString; max_tlc_number_in_flight?: HexString; tlc_min_value?: HexString; tlc_fee_proportional_millionths?: HexString; tlc_expiry_delta?: HexString; } interface AcceptChannelResult { channel_id: ChannelId; } interface ListChannelsParams { pubkey?: Pubkey; include_closed?: boolean; only_pending?: boolean; } interface ListChannelsResult { channels: Channel[]; } interface ShutdownChannelParams { channel_id: ChannelId; close_script?: Script$1; fee_rate?: HexString; force?: boolean; } interface AbandonChannelParams { channel_id: ChannelId; } interface UpdateChannelParams { channel_id: ChannelId; enabled?: boolean; tlc_expiry_delta?: HexString; tlc_minimum_value?: HexString; tlc_fee_proportional_millionths?: HexString; } interface SendPaymentParams { target_pubkey?: Pubkey; amount?: HexString; payment_hash?: PaymentHash; final_tlc_expiry_delta?: HexString; tlc_expiry_limit?: HexString; invoice?: string; timeout?: HexString; max_fee_amount?: HexString; max_fee_rate?: HexString; max_parts?: HexString; trampoline_hops?: Pubkey[]; keysend?: boolean; udt_type_script?: Script$1; allow_self_payment?: boolean; custom_records?: PaymentCustomRecords; hop_hints?: HopHint[]; dry_run?: boolean; } interface SendPaymentResult extends PaymentInfo { } interface GetPaymentParams { payment_hash: PaymentHash; } interface GetPaymentResult extends PaymentInfo { } interface NewInvoiceParams { amount: HexString; description?: string; currency: Currency; payment_preimage?: Hash256; payment_hash?: PaymentHash; expiry?: HexString; fallback_address?: string; final_expiry_delta?: HexString; udt_type_script?: Script$1; hash_algorithm?: HashAlgorithm; allow_mpp?: boolean; allow_trampoline_routing?: boolean; } interface NewInvoiceResult { invoice_address: string; invoice: CkbInvoice; } interface ParseInvoiceParams { invoice: string; } interface ParseInvoiceResult { invoice: CkbInvoice; } interface GetInvoiceParams { payment_hash: PaymentHash; } interface GetInvoiceResult { invoice_address: string; invoice: CkbInvoice; status: CkbInvoiceStatus; } interface CancelInvoiceParams { payment_hash: PaymentHash; } interface CancelInvoiceResult { invoice_address: string; invoice: CkbInvoice; status: CkbInvoiceStatus; } interface SettleInvoiceParams { payment_hash: PaymentHash; payment_preimage: Hash256; } interface HopRequire { pubkey: Pubkey; channel_outpoint?: OutPoint | null; } interface BuildRouterParams { amount?: HexString; udt_type_script?: Script$1; hops_info: HopRequire[]; final_tlc_expiry_delta?: HexString; } interface RouterHop { target: Pubkey; channel_outpoint: OutPoint; amount_received: HexString; incoming_tlc_expiry: HexString; } interface BuildRouterResult { router_hops: RouterHop[]; } interface SendPaymentWithRouterParams { payment_hash?: PaymentHash; router: RouterHop[]; invoice?: string; custom_records?: PaymentCustomRecords; keysend?: boolean; allow_self_payment?: boolean; udt_type_script?: Script$1; dry_run?: boolean; } interface GraphNodesParams { limit?: HexString; after?: HexString; } interface GraphNodesResult { nodes: GraphNodeInfo[]; last_cursor: HexString; } interface GraphChannelsParams { limit?: HexString; after?: HexString; } interface GraphChannelsResult { channels: GraphChannelInfo[]; last_cursor: HexString; } /** Cross-chain hub invoice variant. */ type CchInvoice = { Fiber: string; } | { Lightning: string; }; /** Cross-chain hub order status. */ type CchOrderStatus = 'Pending' | 'IncomingAccepted' | 'OutgoingInFlight' | 'OutgoingSuccess' | 'Success' | 'Failed'; /** Reason for removing a TLC in Dev module APIs. */ type RemoveTlcReason = { RemoveTlcFulfill: Hash256; } | { RemoveTlcFail: HexString; }; /** TLC id wrapper in watchtower-related types. */ type TLCId = { Offered: HexString; } | { Received: HexString; }; /** Minimal CKB cell output representation used by watchtower revocation data. */ interface CellOutput { capacity: HexString; lock: Script$1; type?: Script$1 | null; } /** Settlement TLC data used by watchtower operations. */ interface SettlementTlc { tlc_id: TLCId; hash_algorithm: HashAlgorithm; payment_amount: HexString; payment_hash: Hash256; expiry: HexString; local_key: Privkey; remote_key: Pubkey; } /** Settlement data used by watchtower operations. */ interface SettlementData { local_amount: HexString; remote_amount: HexString; tlcs: SettlementTlc[]; } /** Revocation data used by watchtower operations. */ interface RevocationData { commitment_number: HexString; aggregated_signature: HexString; output: CellOutput; output_data: HexString; } interface NodeInfoResult extends NodeInfo { } interface JsonRpcRequest { jsonrpc: '2.0'; id: number | string; method: string; params: T[]; } interface JsonRpcResponse { jsonrpc: '2.0'; id: number | string; result?: T; error?: JsonRpcError; } interface JsonRpcError { code: number; message: string; data?: unknown; } /** * IFiberClient — Shared interface for Fiber node clients * * Both `FiberRpcClient` (JSON-RPC over HTTP) and `FiberBrowserNode` * (WASM in-browser) implement this interface, enabling dual-mode apps * to switch backends without adapter glue code. * * @example * ```ts * import type { IFiberClient } from '@fiber-pay/sdk'; * * async function getBalance(client: IFiberClient) { * const info = await client.nodeInfo(); * const channels = await client.listChannels(); * // Works identically regardless of RPC vs browser node * return channels; * } * ``` */ /** * Common client interface shared by FiberRpcClient and FiberBrowserNode. * * Method names mirror the Fiber RPC spec (`node_info` → `nodeInfo`, etc.). * Mutation methods that return nothing in practice use `Promise` * for ergonomic TypeScript usage. */ interface IFiberClient { /** Get local node information. */ nodeInfo(): Promise; /** Connect to a peer. */ connectPeer(params: ConnectPeerParams): Promise; /** Disconnect from a peer. */ disconnectPeer(params: DisconnectPeerParams): Promise; /** List all connected peers. */ listPeers(): Promise; /** Open a new channel with a peer. */ openChannel(params: OpenChannelParams): Promise; /** Open a channel where the funding transaction is signed externally by user wallet. */ openChannelWithExternalFunding(params: OpenChannelWithExternalFundingParams): Promise; /** Submit the externally signed funding transaction for an externally funded channel. */ submitSignedFundingTx(params: SubmitSignedFundingTxParams): Promise; /** Accept a channel opening request. */ acceptChannel(params: AcceptChannelParams): Promise; /** List all channels. */ listChannels(params?: ListChannelsParams): Promise; /** Shutdown (close) a channel. */ shutdownChannel(params: ShutdownChannelParams): Promise; /** Abandon a pending channel. */ abandonChannel(params: AbandonChannelParams): Promise; /** Update channel parameters. */ updateChannel(params: UpdateChannelParams): Promise; /** Send a payment. */ sendPayment(params: SendPaymentParams): Promise; /** Get payment status. */ getPayment(params: GetPaymentParams): Promise; /** List payments. */ listPayments(params?: ListPaymentsParams): Promise; /** Build a custom route for payment. */ buildRouter(params: BuildRouterParams): Promise; /** Send a payment using a pre-built route. */ sendPaymentWithRouter(params: SendPaymentWithRouterParams): Promise; /** Create a new invoice. */ newInvoice(params: NewInvoiceParams): Promise; /** Parse an invoice string. */ parseInvoice(params: ParseInvoiceParams): Promise; /** Get invoice by payment hash. */ getInvoice(params: GetInvoiceParams): Promise; /** Cancel an open invoice. */ cancelInvoice(params: CancelInvoiceParams): Promise; /** Settle a hold invoice with the preimage. */ settleInvoice(params: SettleInvoiceParams): Promise; /** List nodes in the network graph. */ graphNodes(params?: GraphNodesParams): Promise; /** List channels in the network graph. */ graphChannels(params?: GraphChannelsParams): Promise; /** Wait for a payment to reach a terminal state (Success or Failed). */ waitForPayment(paymentHash: PaymentHash, options?: { timeout?: number; interval?: number; }): Promise; /** Wait for a channel to reach ChannelReady state. */ waitForChannelReady(channelId: ChannelId, options?: { timeout?: number; interval?: number; }): Promise; /** Wait for an invoice to reach a specific status. */ waitForInvoiceStatus(paymentHash: PaymentHash, targetStatus: CkbInvoiceStatus | CkbInvoiceStatus[], options?: { timeout?: number; interval?: number; }): Promise; } /** * CKB Address Encoding (Bech32m) * Encode CKB lock scripts to human-readable addresses */ interface Script { code_hash: string; hash_type: 'type' | 'data' | 'data1' | 'data2'; args: string; } /** * Convert a CKB lock script to a bech32m-encoded address * @param script - The lock script to encode * @param network - The CKB network ('testnet' or 'mainnet') * @returns Bech32m-encoded CKB address */ declare function scriptToAddress(script: Script, network: 'testnet' | 'mainnet'): string; /** * Utility Functions * Common utilities for hex conversion, CKB amount calculation, and random generation */ /** * Convert number to hex string */ declare function toHex(value: number | bigint): HexString; /** * Ensure a string has a `0x` hex prefix. If missing, prepend it. * Handles case-insensitive prefixes (e.g. `0X`) to avoid double-prefixing. */ declare function ensureHexPrefix(value: string): HexString; /** * Convert hex string to bigint */ declare function fromHex(hex: HexString): bigint; /** * Convert CKB amount (in CKB units) to shannons (hex) */ declare function ckbToShannons(ckb: number | string): HexString; /** * Convert shannons (hex) to CKB amount */ declare function shannonsToCkb(shannons: HexString): number; /** * Generate a random 32-byte hex string (for payment preimage) */ declare function randomBytes32(): HexString; /** * Convert a Fiber node id (hex-encoded compressed secp256k1 pubkey, 33 bytes) * to a libp2p peer id (base58btc encoded sha2-256 multihash). */ declare function nodeIdToPeerId(nodeId: string): Promise; /** * Build a canonical multiaddr by appending/replacing /p2p/. */ declare function buildMultiaddr(address: string, peerId: string): string; /** * Build a canonical multiaddr from a node id and base address. */ declare function buildMultiaddrFromNodeId(address: string, nodeId: string): Promise; /** * Build a best-effort local multiaddr from an RPC URL and peer id. * Uses rpcPort + 1 as inferred P2P port when advertised addresses are unavailable. */ declare function buildMultiaddrFromRpcUrl(rpcUrl: string, peerId: string): string; /** * Fiber RPC Client * Type-safe JSON-RPC client for Fiber Network Node */ interface RpcClientConfig { /** RPC endpoint URL */ url: string; /** Request timeout in milliseconds */ timeout?: number; /** Custom headers */ headers?: Record; /** * Biscuit token for authentication. * * Prefer server-side usage. In browser apps, avoid embedding long-lived * privileged tokens and use a trusted backend/proxy where possible. */ biscuitToken?: string; } declare class FiberRpcError extends Error { code: number; data?: unknown | undefined; constructor(code: number, message: string, data?: unknown | undefined); static fromJsonRpcError(error: JsonRpcError): FiberRpcError; } declare class FiberRpcClient implements IFiberClient { private requestId; private config; constructor(config: RpcClientConfig); /** * Make a raw JSON-RPC call * * Useful for advanced/experimental RPCs not wrapped by convenience methods. * * @example * ```ts * const result = await client.call('some_method', [{ foo: 'bar' }]); * ``` */ call(method: string, params?: unknown[]): Promise; /** * Connect to a peer */ connectPeer(params: ConnectPeerParams): Promise; /** * Disconnect from a peer */ disconnectPeer(params: DisconnectPeerParams): Promise; /** * List all connected peers */ listPeers(): Promise; /** * Open a new channel with a peer */ openChannel(params: OpenChannelParams): Promise; /** * Open a channel with external funding. * The returned unsigned funding transaction must be signed externally and * submitted via `submitSignedFundingTx`. */ openChannelWithExternalFunding(params: OpenChannelWithExternalFundingParams): Promise; /** * Submit the externally signed funding transaction. */ submitSignedFundingTx(params: SubmitSignedFundingTxParams): Promise; /** * Accept a channel opening request */ acceptChannel(params: AcceptChannelParams): Promise; /** * List all channels */ listChannels(params?: ListChannelsParams): Promise; /** * Shutdown (close) a channel */ shutdownChannel(params: ShutdownChannelParams): Promise; /** * Abandon a pending channel */ abandonChannel(params: AbandonChannelParams): Promise; /** * Update channel parameters */ updateChannel(params: UpdateChannelParams): Promise; /** * Send a payment */ sendPayment(params: SendPaymentParams): Promise; /** * Get payment status */ getPayment(params: GetPaymentParams): Promise; /** * List payments */ listPayments(params?: ListPaymentsParams): Promise; /** Create a new invoice. */ newInvoice(params: NewInvoiceParams): Promise; /** * Parse an invoice string */ parseInvoice(params: ParseInvoiceParams): Promise; /** * Get invoice by payment hash */ getInvoice(params: GetInvoiceParams): Promise; /** * Cancel an open invoice */ cancelInvoice(params: CancelInvoiceParams): Promise; /** * Settle a hold invoice with the preimage * Used for conditional/escrow payments where the invoice was created * with a payment_hash (no preimage provided upfront) */ settleInvoice(params: SettleInvoiceParams): Promise; /** * Build a custom route for payment * Useful for channel rebalancing (circular payments) and advanced routing */ buildRouter(params: BuildRouterParams): Promise; /** * Send a payment using a pre-built route from buildRouter() * Use with allow_self_payment for channel rebalancing */ sendPaymentWithRouter(params: SendPaymentWithRouterParams): Promise; /** * List nodes in the network graph */ graphNodes(params?: GraphNodesParams): Promise; /** * List channels in the network graph */ graphChannels(params?: GraphChannelsParams): Promise; /** * Get local node information */ nodeInfo(): Promise; /** * Backup the node database (fnn v0.9.0+). * * Writes a backup of the node store to disk on the node host. After a * restore, channels enter the `STALE` state until a passive audit with the * peer completes. * * RPC-client-only capability: writing to the node host's disk is meaningless * for `FiberBrowserNode` (in-browser WASM node), so this method is * deliberately not part of the shared `IFiberClient` interface. * * Known upstream limitation (fnn v0.9.0): the Biscuit auth rule is registered * under the key `backup_now` while the RPC method is named `backup`, so on * nodes with authentication enabled the call is fail-closed rejected with * "no rules for method". Use against a local (unauthenticated) RPC, or wait * for the upstream fix. */ backup(): Promise; /** * Check if the node is reachable */ ping(): Promise; /** * Wait for the node to be ready */ waitForReady(options?: { timeout?: number; interval?: number; }): Promise; /** * Wait for a payment to reach a terminal state (Success or Failed) * Polls get_payment at the specified interval. * * @returns The final payment result * @throws FiberRpcError on timeout */ waitForPayment(paymentHash: PaymentHash, options?: { timeout?: number; interval?: number; }): Promise; /** * Wait for a channel to reach ChannelReady state. * Polls list_channels at the specified interval. * * @returns The channel info once ready * @throws FiberRpcError on timeout or if channel disappears */ waitForChannelReady(channelId: ChannelId, options?: { timeout?: number; interval?: number; }): Promise; /** * Wait for an invoice to reach a specific status. * Useful for hold invoice workflows: wait for 'Received' before settling. * * @returns The invoice info once the target status is reached * @throws FiberRpcError on timeout */ waitForInvoiceStatus(paymentHash: PaymentHash, targetStatus: CkbInvoiceStatus | CkbInvoiceStatus[], options?: { timeout?: number; interval?: number; }): Promise; /** * Watch for incoming payments on specified invoices. * Polls invoice statuses and calls the callback when a status changes. * Use an AbortSignal to stop watching. * * @example * ```typescript * const controller = new AbortController(); * client.watchIncomingPayments({ * paymentHashes: [hash1, hash2], * onPayment: (invoice) => console.log('Payment received!', invoice), * signal: controller.signal, * }); * // Later: controller.abort(); to stop watching * ``` */ watchIncomingPayments(options: { /** Payment hashes of invoices to watch */ paymentHashes: PaymentHash[]; /** Callback when an invoice status changes to Received or Paid */ onPayment: (invoice: GetInvoiceResult) => void; /** Polling interval in ms (default: 3000) */ interval?: number; /** AbortSignal to stop watching */ signal?: AbortSignal; }): Promise; } /** * Channel normalization helpers. * * The Fiber node may return channel `state_name` in different casings depending * on the transport (JSON-RPC over HTTP vs WASM adapter). These helpers normalize * the value to the canonical SCREAMING_SNAKE_CASE `ChannelState` enum so that * consumers can rely on `=== ChannelState.X` comparisons regardless of which * client they use. */ /** * Normalize a channel state name to the canonical `ChannelState` enum value. * * Accepts SCREAMING_SNAKE_CASE (e.g. `"CHANNEL_READY"`), PascalCase * (e.g. `"ChannelReady"`), and other variants by stripping non-alphanumeric * characters and comparing case-insensitively. * * Falls back to returning the input unchanged (cast to `ChannelState`) if no * match is found, so unknown future states do not throw. */ declare function normalizeChannelStateName(stateName: string): ChannelState; /** * Return a copy of `channel` with its `state.state_name` normalized. */ declare function normalizeChannel(channel: Channel): Channel; /** * Crypto Utilities * Pure cryptographic functions for key operations. * Browser-compatible — uses Web Crypto API and @noble/hashes. */ declare const SCRYPT_N: number; declare const SCRYPT_R = 8; declare const SCRYPT_P = 1; declare const KEY_LENGTH = 32; declare const SALT_LENGTH = 32; declare const IV_LENGTH = 16; declare const AUTH_TAG_LENGTH = 16; /** Magic bytes: ASCII 'FIBERENC' */ declare const ENCRYPTED_MAGIC: Uint8Array; /** * Check if key data is encrypted (starts with FIBERENC magic bytes) */ declare function isEncryptedKey(data: Uint8Array): boolean; /** * Decrypt an encrypted key using scrypt + AES-256-GCM */ declare function decryptKey(data: Uint8Array, password: string): Promise; /** * Derive a public key hash from a private key (SHA-256) */ declare function derivePublicKey(privateKey: Uint8Array): Promise; /** * Generate a random 32-byte private key */ declare function generatePrivateKey(): Uint8Array; /** * Generate a random preimage for hold invoice * @returns Hex-encoded random 32-byte preimage */ declare function generatePreimage(): HexString; /** * Compute CKB hash (blake2b-256 with "ckb-default-hash" personalization) */ declare function ckbHash(data: Uint8Array): Uint8Array; /** * Compute SHA-256 hash */ declare function sha256Hash(data: Uint8Array): Uint8Array; /** * Compute payment hash from preimage using specified algorithm * @param preimageHex - Hex-encoded preimage (0x-prefixed) * @param algorithm - Hash algorithm: 'ckb_hash' or 'sha256' * @returns Hex-encoded payment hash (0x-prefixed, 64 hex chars) */ declare function hashPreimage(preimageHex: HexString, algorithm: HashAlgorithm): Hash256; /** * Verify that a preimage matches the given payment hash * @param preimageHex - Hex-encoded preimage * @param paymentHash - Expected payment hash * @param algorithm - Hash algorithm used * @returns true if preimage hashes to paymentHash */ declare function verifyPreimageHash(preimageHex: HexString, paymentHash: Hash256, algorithm: HashAlgorithm): boolean; type UdtTypeScript = { code_hash: HexString; hash_type: 'type' | 'data' | 'data1' | 'data2'; args: HexString; }; type UdtAsset = { kind: 'ckb'; } | { kind: 'udt'; script: UdtTypeScript; name?: string; }; declare const DEFAULT_CKB_ASSET: UdtAsset; type FormattedChannelBalances = { kind: 'ckb'; local: number; remote: number; capacity: number; fundingUdtTypeScript: undefined; } | { kind: 'udt'; local: string; remote: string; capacity: string; fundingUdtTypeScript: Script$1; }; /** * Format channel balances for display, choosing raw UDT units or CKB conversion. * * @param channel - Channel data from `list_channels`. * @returns Display-ready balance fields and unit label. */ declare function formatChannelBalances(channel: Channel): FormattedChannelBalances; /** * Return a human-readable unit name for an asset. * * @param asset - Asset descriptor (CKB or UDT). * @returns 'CKB' for CKB assets, or the trimmed UDT name with 'UDT' fallback. */ declare function formatAssetName(asset: UdtAsset): string; /** * Validate a UDT type script object at runtime. * * @param value - Unknown value to validate. * @param optionName - Name of the option for error messages. * @returns Validated UdtTypeScript. */ declare function validateUdtTypeScript(value: unknown, optionName?: string): UdtTypeScript; /** * Serialize a UDT type script to the Molecule bytes used by Fiber invoice attributes. */ declare function serializeUdtTypeScript(value: unknown): HexString; /** Compare UDT scripts by their canonical fields, ignoring hex letter casing. */ declare function areUdtTypeScriptsEqual(left: unknown, right: unknown): boolean; /** * Parse a UDT type script from a JSON string. * * @param value - Raw JSON object string representing a CKB Script. * @param optionName - Name of the option for error messages. * @returns Parsed UdtTypeScript, or undefined if value is undefined. */ declare function parseUdtTypeScript(value: string | undefined, optionName?: string): UdtTypeScript | undefined; /** * Parse a payment amount for either CKB or UDT. * * CKB amounts are decimal numbers with up to 8 decimal places and returned in shannons. * UDT amounts are plain integers in the smallest UDT unit. * * @param value - Human-readable amount string. * @param asset - Asset descriptor (CKB or UDT). * @returns Amount in raw on-chain units. */ declare function parsePaymentAmount(value: string, asset: UdtAsset): bigint; /** * Parse a funding amount for either CKB or UDT. * * Unlike payment amounts, funding amounts may be zero (e.g., one-way channels). * * @param value - Human-readable amount string. * @param asset - Asset descriptor (CKB or UDT). * @returns Amount in raw on-chain units. */ declare function parseFundingAmount(value: string, asset: UdtAsset): bigint; interface ResolveUdtAssetOptions { rawScript?: string; name?: string; scriptOptionName?: string; rpc?: { nodeInfo(): Promise<{ udt_cfg_infos: UdtCfgInfos; }>; }; } /** * Resolve a UDT asset from a raw script string, a configured name, or default to CKB. * * @param options - Resolution options. * @returns A `UdtAsset` describing CKB or a resolved UDT. */ declare function resolveUdtAsset(options: ResolveUdtAssetOptions): Promise; export { KEY_LENGTH as $, AUTH_TAG_LENGTH as A, type BuildRouterParams as B, type Currency as C, DEFAULT_CKB_ASSET as D, ENCRYPTED_MAGIC as E, FiberRpcClient as F, type GetInvoiceParams as G, type GetPaymentResult as H, type GraphChannelInfo as I, type GraphChannelsParams as J, type GraphChannelsResult as K, type GraphNodeInfo as L, type GraphNodesParams as M, type GraphNodesResult as N, type Hash256 as O, type HashAlgorithm as P, type HexString as Q, type HopHint as R, type HopRequire as S, type Htlc as T, type IFiberClient as U, IV_LENGTH as V, type InvoiceData as W, type InvoiceSignature as X, type JsonRpcError as Y, type JsonRpcRequest as Z, type JsonRpcResponse as _, type AbandonChannelParams as a, derivePublicKey as a$, type ListChannelsParams as a0, type ListChannelsResult as a1, type ListPaymentsParams as a2, type ListPaymentsResult as a3, type ListPeersResult as a4, type Multiaddr as a5, type NewInvoiceParams as a6, type NewInvoiceResult as a7, type NodeInfo as a8, type NodeInfoResult as a9, type SendPaymentWithRouterParams as aA, type SessionRoute as aB, type SessionRouteNode as aC, type SettleInvoiceParams as aD, type SettlementData as aE, type SettlementTlc as aF, type ShutdownChannelParams as aG, type SubmitSignedFundingTxParams as aH, type SubmitSignedFundingTxResult as aI, type TLCId as aJ, type TlcStatus as aK, type TransportType as aL, type UdtArgInfo as aM, type UdtAsset as aN, type UdtCellDep as aO, type UdtCfgInfos as aP, type UdtDep as aQ, type UdtScript as aR, type UdtTypeScript as aS, type UpdateChannelParams as aT, areUdtTypeScriptsEqual as aU, buildMultiaddr as aV, buildMultiaddrFromNodeId as aW, buildMultiaddrFromRpcUrl as aX, ckbHash as aY, ckbToShannons as aZ, decryptKey as a_, type OpenChannelParams as aa, type OpenChannelResult as ab, type OpenChannelWithExternalFundingParams as ac, type OpenChannelWithExternalFundingResult as ad, type OutPoint as ae, type ParseInvoiceParams as af, type ParseInvoiceResult as ag, type PaymentCustomRecords as ah, type PaymentHash as ai, type PaymentInfo as aj, type PaymentStatus as ak, type PeerId as al, type PeerInfo as am, type Privkey as an, type Pubkey as ao, type RemoveTlcReason as ap, type ResolveUdtAssetOptions as aq, type RevocationData as ar, type RouterHop as as, SALT_LENGTH as at, SCRYPT_N as au, SCRYPT_P as av, SCRYPT_R as aw, type Script as ax, type SendPaymentParams as ay, type SendPaymentResult as az, type AcceptChannelParams as b, ensureHexPrefix as b0, formatAssetName as b1, formatChannelBalances as b2, fromHex as b3, generatePreimage as b4, generatePrivateKey as b5, hashPreimage as b6, isEncryptedKey as b7, nodeIdToPeerId as b8, normalizeChannel as b9, normalizeChannelStateName as ba, parseFundingAmount as bb, parsePaymentAmount as bc, parseUdtTypeScript as bd, randomBytes32 as be, resolveUdtAsset as bf, scriptToAddress as bg, serializeUdtTypeScript as bh, sha256Hash as bi, shannonsToCkb as bj, toHex as bk, validateUdtTypeScript as bl, verifyPreimageHash as bm, type Script$1 as bn, type RpcClientConfig as bo, type AcceptChannelResult as c, type Attribute as d, type BuildRouterResult as e, type CancelInvoiceParams as f, type CancelInvoiceResult as g, type CchInvoice as h, type CchOrderStatus as i, type CellDep as j, type CellOutput as k, type Channel as l, type ChannelId as m, ChannelState as n, type ChannelStateFlags as o, type ChannelUpdateInfo as p, type CkbInvoice as q, type CkbInvoiceStatus as r, type CkbTransaction as s, type ConnectPeerParams as t, type ConnectPeerResult as u, type DisconnectPeerParams as v, FiberRpcError as w, type FormattedChannelBalances as x, type GetInvoiceResult as y, type GetPaymentParams as z };