fiberprobe 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ /**
2
+ * FiberClient — fully typed HTTP JSON-RPC client for Fiber Network Node (FNN).
3
+ *
4
+ * Communicates with a running FNN instance via its JSON-RPC endpoint
5
+ * (default: http://127.0.0.1:8227). Every method is typed against the
6
+ * official FNN RPC specification so callers get compile-time safety and
7
+ * inline documentation instead of raw invokeCommand() calls.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * const client = new FiberClient('http://127.0.0.1:8227')
12
+ * const info = await client.nodeInfo()
13
+ * console.log(info.pubkey, info.channel_count)
14
+ * ```
15
+ */
16
+ // ── JSON-RPC transport ────────────────────────────────────────────────────────
17
+ let requestId = 0;
18
+ /**
19
+ * Send a single JSON-RPC 2.0 request to the FNN node and return the result.
20
+ * Throws if the response contains a JSON-RPC error object.
21
+ *
22
+ * @param url - Full HTTP URL of the FNN RPC endpoint
23
+ * @param method - JSON-RPC method name
24
+ * @param params - Method parameters (passed as the first array element per FNN convention)
25
+ */
26
+ async function rpc(url, method, params = {}) {
27
+ const id = ++requestId;
28
+ const response = await fetch(url, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: JSON.stringify({ jsonrpc: '2.0', id, method, params: [params] }),
32
+ });
33
+ if (!response.ok) {
34
+ throw new Error(`FNN RPC HTTP error ${response.status}: ${response.statusText}`);
35
+ }
36
+ const json = await response.json();
37
+ if (json.error) {
38
+ throw new Error(`FNN RPC error [${json.error.code}]: ${json.error.message}`);
39
+ }
40
+ return json.result;
41
+ }
42
+ // ── FiberClient ───────────────────────────────────────────────────────────────
43
+ export class FiberClient {
44
+ rpcUrl;
45
+ /**
46
+ * @param rpcUrl - HTTP URL of the FNN RPC endpoint. Defaults to the standard
47
+ * local node address. Override for remote nodes or custom ports.
48
+ */
49
+ constructor(rpcUrl = 'http://127.0.0.1:8227') {
50
+ this.rpcUrl = rpcUrl;
51
+ }
52
+ // ── Node ───────────────────────────────────────────────────────────────────
53
+ /** Returns identifying information and operational stats for the running FNN node. */
54
+ async nodeInfo() {
55
+ return rpc(this.rpcUrl, 'node_info');
56
+ }
57
+ // ── Peers ──────────────────────────────────────────────────────────────────
58
+ /** Lists all peers currently connected to this node. */
59
+ async listPeers() {
60
+ return rpc(this.rpcUrl, 'list_peers');
61
+ }
62
+ /**
63
+ * Connects to a remote Fiber peer by multiaddr.
64
+ * @param address - Multiaddr of the remote peer
65
+ * @param save - Persist this address for reconnection on restart
66
+ */
67
+ async connectPeer(address, save = true) {
68
+ return rpc(this.rpcUrl, 'connect_peer', { address, save });
69
+ }
70
+ // ── Channels ───────────────────────────────────────────────────────────────
71
+ /**
72
+ * Lists channels on this node, optionally filtered by peer pubkey.
73
+ * @param options.pubkey - Filter to channels with a specific peer
74
+ * @param options.include_closed - Include closed channels. Defaults to false.
75
+ */
76
+ async listChannels(options = {}) {
77
+ const result = await rpc(this.rpcUrl, 'list_channels', options);
78
+ return result.channels;
79
+ }
80
+ /**
81
+ * Opens a new payment channel with a connected peer.
82
+ * @param params.pubkey - Peer pubkey to open the channel with
83
+ * @param params.funding_amount - CKB to lock in the channel (hex u128, shannon)
84
+ * @param params.public - Announce to the network graph
85
+ */
86
+ async openChannel(params) {
87
+ return rpc(this.rpcUrl, 'open_channel', params);
88
+ }
89
+ /**
90
+ * Initiates cooperative shutdown of a channel.
91
+ * @param channel_id - Channel to close
92
+ * @param force - Force-close unilaterally. Incurs a time-lock penalty.
93
+ */
94
+ async shutdownChannel(channel_id, force = false) {
95
+ return rpc(this.rpcUrl, 'shutdown_channel', { channel_id, force });
96
+ }
97
+ // ── Payments ───────────────────────────────────────────────────────────────
98
+ /**
99
+ * Sends a payment or performs a dry-run feasibility check.
100
+ * Set dry_run: true to validate routing and estimate fees without
101
+ * broadcasting the payment.
102
+ */
103
+ async sendPayment(params) {
104
+ return rpc(this.rpcUrl, 'send_payment', params);
105
+ }
106
+ /**
107
+ * Fetches current status and details of a payment by its hash.
108
+ * Poll this after sendPayment() to track Inflight → Success/Failed transitions.
109
+ */
110
+ async getPayment(payment_hash) {
111
+ return rpc(this.rpcUrl, 'get_payment', { payment_hash });
112
+ }
113
+ /**
114
+ * Builds and validates a payment route without sending.
115
+ * Use this to inspect hop details and confirm a path exists before committing.
116
+ */
117
+ async buildRouter(params) {
118
+ return rpc(this.rpcUrl, 'build_router', params);
119
+ }
120
+ // ── Invoices ───────────────────────────────────────────────────────────────
121
+ /**
122
+ * Creates a new Fiber invoice for receiving a payment.
123
+ * @param params.amount - Amount in shannon (hex u128)
124
+ * @param params.currency - Fibb (mainnet) | Fibt (testnet) | Fibd (devnet)
125
+ */
126
+ async newInvoice(params) {
127
+ return rpc(this.rpcUrl, 'new_invoice', params);
128
+ }
129
+ /** Fetches an invoice and its current payment status by payment hash. */
130
+ async getInvoice(payment_hash) {
131
+ return rpc(this.rpcUrl, 'get_invoice', { payment_hash });
132
+ }
133
+ /** Cancels an Open invoice, preventing it from being paid. */
134
+ async cancelInvoice(payment_hash) {
135
+ return rpc(this.rpcUrl, 'cancel_invoice', { payment_hash });
136
+ }
137
+ // ── Network Graph ──────────────────────────────────────────────────────────
138
+ /**
139
+ * Fetches public channels from the Fiber network graph.
140
+ * Used by PaymentChecker to score route liquidity during canPay() analysis.
141
+ * @param limit - Maximum channels to return. Defaults to 100.
142
+ */
143
+ async graphChannels(limit = 100, after) {
144
+ return rpc(this.rpcUrl, 'graph_channels', {
145
+ limit: '0x' + limit.toString(16),
146
+ ...(after !== undefined && { after }),
147
+ });
148
+ }
149
+ // ── Invoice Parsing ──────────────────────────────────────────────────────────
150
+ /**
151
+ * Parses an encoded Fiber invoice string without attempting payment.
152
+ * Extracts amount, payment_hash, and the destination pubkey (payee_public_key)
153
+ * from the attrs array. Used by PaymentChecker.canPay() to resolve the
154
+ * payment destination before running graph reachability analysis.
155
+ *
156
+ * @param invoice - The encoded invoice string (fibb.../fibt.../fibd...)
157
+ */
158
+ async parseInvoice(invoice) {
159
+ return rpc(this.rpcUrl, 'parse_invoice', { invoice });
160
+ }
161
+ }
162
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAiBH,iFAAiF;AAEjF,IAAI,SAAS,GAAG,CAAC,CAAA;AAEjB;;;;;;;GAOG;AACH,KAAK,UAAU,GAAG,CAAI,GAAW,EAAE,MAAc,EAAE,MAAM,GAAY,EAAE;IACrE,MAAM,EAAE,GAAS,EAAE,SAAS,CAAA;IAC5B,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;QAChC,MAAM,EAAG,MAAM;QACf,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;QAC/C,IAAI,EAAK,IAAI,CAAC,SAAS,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC;KAC1E,CAAC,CAAA;IAEF,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,MAAM,IAAI,KAAK,CAAC,sBAAsB,QAAQ,CAAC,MAAM,KAAK,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAA;IAClF,CAAC;IAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAA+D,CAAA;IAE/F,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,CAAC,KAAK,CAAC,IAAI,MAAM,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;IAC9E,CAAC;IAED,OAAO,IAAI,CAAC,MAAW,CAAA;AACzB,CAAC;AAED,iFAAiF;AAEjF,MAAM,OAAO,WAAW;IAKO,MAAM;IAJnC;;;OAGG;IACH,YAA6B,MA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E,CAAC;CACF"}
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Fiber Network RPC Types — derived from the official FNN RPC specification.
3
+ * All hex values are 0x-prefixed strings representing u128 amounts in shannon.
4
+ */
5
+ export type Hash256 = string;
6
+ export type Pubkey = string;
7
+ export type PeerId = string;
8
+ export type ChannelStateName = 'NegotiatingFunding' | 'CollaboratingFundingTx' | 'SigningCommitment' | 'AwaitingTxSignatures' | 'AwaitingChannelReady' | 'ChannelReady' | 'ShuttingDown' | 'Closed';
9
+ /** Channel state as returned by the RPC: an object, not a bare string. */
10
+ export interface ChannelState {
11
+ state_name: ChannelStateName;
12
+ state_flags?: string;
13
+ }
14
+ export interface Channel {
15
+ channel_id: Hash256;
16
+ is_public: boolean;
17
+ is_acceptor: boolean;
18
+ is_one_way: boolean;
19
+ channel_outpoint?: string;
20
+ pubkey: Pubkey;
21
+ funding_udt_type_script?: object;
22
+ state: ChannelState;
23
+ local_balance: string;
24
+ remote_balance: string;
25
+ offered_tlc_balance: string;
26
+ received_tlc_balance: string;
27
+ pending_tlcs: Htlc[];
28
+ latest_commitment_transaction_hash?: Hash256;
29
+ created_at: string;
30
+ enabled: boolean;
31
+ tlc_expiry_delta: number;
32
+ tlc_fee_proportional_millionths: string;
33
+ shutdown_transaction_hash?: Hash256;
34
+ failure_detail?: string | null;
35
+ }
36
+ export interface Htlc {
37
+ id: number;
38
+ amount: string;
39
+ payment_hash: Hash256;
40
+ expiry: number;
41
+ status: {
42
+ Outbound: string;
43
+ } | {
44
+ Inbound: string;
45
+ };
46
+ }
47
+ export interface ListChannelsResult {
48
+ channels: Channel[];
49
+ }
50
+ export type PaymentStatus = 'Created' | 'Inflight' | 'Success' | 'Failed';
51
+ export interface SessionRouteNode {
52
+ pubkey: Pubkey;
53
+ amount: string;
54
+ channel_outpoint: string;
55
+ }
56
+ export interface SessionRoute {
57
+ nodes: SessionRouteNode[];
58
+ }
59
+ export interface Payment {
60
+ payment_hash: Hash256;
61
+ status: PaymentStatus;
62
+ created_at: number;
63
+ last_updated_at: number;
64
+ failed_error?: string;
65
+ fee: string;
66
+ routers: SessionRoute[];
67
+ }
68
+ export interface SendPaymentParams {
69
+ invoice?: string;
70
+ target_pubkey?: Pubkey;
71
+ amount?: string;
72
+ payment_hash?: Hash256;
73
+ max_fee_amount?: string;
74
+ timeout?: number;
75
+ keysend?: boolean;
76
+ dry_run?: boolean;
77
+ allow_self_payment?: boolean;
78
+ }
79
+ export type InvoiceStatus = 'Open' | 'Cancelled' | 'Expired' | 'Received' | 'Paid';
80
+ export interface InvoiceResult {
81
+ invoice_address: string;
82
+ invoice: object;
83
+ status: InvoiceStatus;
84
+ }
85
+ export interface NewInvoiceParams {
86
+ amount: string;
87
+ currency: 'Fibb' | 'Fibt' | 'Fibd';
88
+ description?: string;
89
+ expiry?: number;
90
+ final_expiry_delta?: number;
91
+ }
92
+ export interface ChannelUpdateInfo {
93
+ timestamp: number;
94
+ enabled: boolean;
95
+ outbound_liquidity?: string;
96
+ tlc_expiry_delta: number;
97
+ tlc_minimum_value: string;
98
+ fee_rate: number;
99
+ }
100
+ export interface GraphChannel {
101
+ channel_outpoint: string;
102
+ node1: Pubkey;
103
+ node2: Pubkey;
104
+ capacity: string;
105
+ update_info_of_node1?: ChannelUpdateInfo;
106
+ update_info_of_node2?: ChannelUpdateInfo;
107
+ udt_type_script?: object;
108
+ }
109
+ export interface GraphChannelsResult {
110
+ channels: GraphChannel[];
111
+ last_cursor: string;
112
+ }
113
+ export interface NodeInfo {
114
+ version: string;
115
+ pubkey: Pubkey;
116
+ node_name?: string;
117
+ addresses: string[];
118
+ channel_count: number;
119
+ peers_count: number;
120
+ }
121
+ export interface PeerInfo {
122
+ pubkey: Pubkey;
123
+ address: string;
124
+ }
125
+ export interface ListPeersResult {
126
+ peers: PeerInfo[];
127
+ }
128
+ export interface RouterHop {
129
+ target: Pubkey;
130
+ channel_outpoint: string;
131
+ amount_received: string;
132
+ incoming_tlc_expiry: number;
133
+ }
134
+ export interface ParsedInvoiceAttr {
135
+ description?: string;
136
+ final_htlc_minimum_expiry_delta?: string;
137
+ payee_public_key?: Pubkey;
138
+ expiry?: string;
139
+ }
140
+ export interface ParsedInvoiceData {
141
+ timestamp: string;
142
+ payment_hash: Hash256;
143
+ attrs: ParsedInvoiceAttr[];
144
+ }
145
+ export interface ParsedInvoice {
146
+ currency: 'Fibb' | 'Fibt' | 'Fibd';
147
+ amount: string;
148
+ signature: string;
149
+ data: ParsedInvoiceData;
150
+ }
151
+ export interface ParseInvoiceResult {
152
+ invoice: ParsedInvoice;
153
+ }
154
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/client/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,MAAM,OAAO,GAAG,MAAM,CAAA;AAC5B,MAAM,MAAM,MAAM,GAAI,MAAM,CAAA;AAC5B,MAAM,MAAM,MAAM,GAAI,MAAM,CAAA;AAC5B,MAAM,MAAM,gBAAgB,GACxB,oBAAoB,GACpB,wBAAwB,GACxB,mBAAmB,GACnB,sBAAsB,GACtB,sBAAsB,GACtB,cAAc,GACd,cAAc,GACd,QAAQ,CAAA;AAEZ,0EAA0E;AAC1E,MAAM,WAAW,YAAY;IAC3B,UAAU,EAAI,gBAAgB,CAAA;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,MAAM,WAAW,OAAO;IACtB,UAAU,EAAkB,OAAO,CAAA;IACnC,SAAS,EAAmB,OAAO,CAAA;IACnC,WAAW,EAAiB,OAAO,CAAA;IACnC,UAAU,EAAkB,OAAO,CAAA;IACnC,gBAAgB,CAAC,EAAW,MAAM,CAAA;IAClC,MAAM,EAAsB,MAAM,CAAA;IAClC,uBAAuB,CAAC,EAAI,MAAM,CAAA;IAClC,KAAK,EAAuB,YAAY,CAAA;IACxC,aAAa,EAAe,MAAM,CAAA;IAClC,cAAc,EAAc,MAAM,CAAA;IAClC,mBAAmB,EAA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AAa,CAAA;CACvB"}
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Fiber Network RPC Types — derived from the official FNN RPC specification.
3
+ * All hex values are 0x-prefixed strings representing u128 amounts in shannon.
4
+ */
5
+ export {};
6
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/client/types.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * fnn-ts — TypeScript SDK for Fiber Network Node (FNN)
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ export { FiberClient } from './client/index.js';
7
+ export { PaymentChecker } from './payment/checker.js';
8
+ export { FiberError, RouteNotFoundError, InsufficientCapacityError, TemporaryChannelFailureError, PeerUnreachableError, PaymentTimeoutError, FeeInsufficientError, AmountBelowMinimumError, UnknownFiberError, } from './client/errors.js';
9
+ export type { Hash256, Pubkey, PeerId, Channel, ChannelState, Payment, PaymentStatus, SendPaymentParams, InvoiceResult, InvoiceStatus, NewInvoiceParams, GraphChannel, GraphChannelsResult, NodeInfo, ListPeersResult, } from './client/types.js';
10
+ export type { CanPayParams, PaymentCheckResult, ProbePayParams, ProbeResult, CanReceiveParams, ReceiveCheckResult, ChannelCapacityEntry, } from './payment/checker.js';
11
+ export { FiberEventEmitter } from './payment/events.js';
12
+ export type { WatchPaymentOptions, WatchInvoiceOptions, WatchChannelOptions, BackoffProfile, CancelFn, } from './payment/events.js';
13
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAwB,mBAAmB,CAAA;AACjE,OAAO,EAAE,cAAc,EAAE,MAAqB,sBAAsB,CAAA;AAEpE,OAAO,EACL,UAAU,EACV,kBAAkB,EAClB,yBAAyB,EACzB,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,iBAAiB,GAClB,MAA6C,oBAAoB,CAAA;AAElE,YAAY,EACV,OAAO,EAAE,MAAM,EAAE,MAAM,EACvB,OAAO,EAAE,YAAY,EACrB,OAAO,EAAE,aAAa,EAAE,iBAAiB,EACzC,aAAa,EAAE,aAAa,EAAE,gBAAgB,EAC9C,YAAY,EAAE,mBAAmB,EACjC,QAAQ,EAAE,eAAe,GAC1B,MAA6C,mBAAmB,CAAA;AAEjE,YAAY,EACV,YAAY,EAAE,kBAAkB,EAChC,cAAc,EAAE,WAAW,EAC3B,gBAAgB,EAAE,kBAAkB,EACpC,oBAAoB,GACrB,MAA6C,sBAAsB,CAAA;AAEpE,OAAO,EAAE,iBAAiB,EAAE,MAAkB,qBAAqB,CAAA;AAEnE,YAAY,EACV,mBAAmB,EACnB,mBAAmB,EACnB,mBAAmB,EACnB,cAAc,EACd,QAAQ,GACT,MAA6C,qBAAqB,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * fnn-ts — TypeScript SDK for Fiber Network Node (FNN)
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ export { FiberClient } from './client/index.js';
7
+ export { PaymentChecker } from './payment/checker.js';
8
+ export { FiberError, RouteNotFoundError, InsufficientCapacityError, TemporaryChannelFailureError, PeerUnreachableError, PaymentTimeoutError, FeeInsufficientError, AmountBelowMinimumError, UnknownFiberError, } from './client/errors.js';
9
+ export { FiberEventEmitter } from './payment/events.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAwB,mBAAmB,CAAA;AACjE,OAAO,EAAE,cAAc,EAAE,MAAqB,sBAAsB,CAAA;AAEpE,OAAO,EACL,UAAU,EACV,kBAAkB,EAClB,yBAAyB,EACzB,4BAA4B,EAC5B,oBAAoB,EACpB,mBAAmB,EACnB,oBAAoB,EACpB,uBAAuB,EACvB,iBAAiB,GAClB,MAA6C,oBAAoB,CAAA;AAkBlE,OAAO,EAAE,iBAAiB,EAAE,MAAkB,qBAAqB,CAAA"}
@@ -0,0 +1,165 @@
1
+ /**
2
+ * PaymentChecker — pre-flight payment feasibility analysis for Fiber Network.
3
+ *
4
+ * Solves two problems every Fiber application faces:
5
+ *
6
+ * 1. canPay() — Will this payment succeed before I try to send it?
7
+ * 2. canReceive() — Do I have enough inbound capacity to receive a payment?
8
+ *
9
+ * Design note: send_payment's dry_run flag was evaluated as a data source
10
+ * for canPay() and rejected. Live testnet testing confirmed dry-run payment
11
+ * sessions are never queryable via get_payment, even immediately after
12
+ * creation — the RPC returns "Payment session not found" on instant lookup.
13
+ * This means dry_run cannot supply route or fee detail synchronously or
14
+ * asynchronously.
15
+ *
16
+ * canPay() instead performs static graph reachability analysis:
17
+ * 1. parseInvoice() resolves the destination pubkey and amount
18
+ * 2. listChannels() checks for a direct channel to the destination
19
+ * 3. graphChannels() + BFS finds a multi-hop path if no direct channel exists
20
+ * 4. Each hop is scored against published outbound_liquidity, exactly as
21
+ * a live router would need to evaluate route viability
22
+ *
23
+ * canReceive() scans open ChannelReady channels and sums usable inbound
24
+ * capacity, correctly accounting for in-flight received TLCs.
25
+ */
26
+ import type { FiberClient } from '../client/index.js';
27
+ import type { Pubkey } from '../client/types.js';
28
+ import { FiberError } from '../client/errors.js';
29
+ export interface CanPayParams {
30
+ /** Fiber invoice string (fibb… / fibt… / fibd…) */
31
+ invoice: string;
32
+ /** Maximum hops to search when pathfinding through the public graph. Defaults to 5. */
33
+ maxHops?: number;
34
+ }
35
+ export interface PaymentCheckResult {
36
+ /** Whether a viable route was found through direct or public-graph channels. */
37
+ canPay: boolean;
38
+ /**
39
+ * Confidence score: 0–100.
40
+ *
41
+ * 80–100 High. Route is liquid, short, and well-capitalised.
42
+ * 60–79 Moderate. Route found but some liquidity is uncertain.
43
+ * 30–59 Low. Route exists but liquidity is thin or unverifiable.
44
+ * 0 None. No route found.
45
+ *
46
+ * This reflects known liquidity at the time of the check — actual channel
47
+ * balances can shift before a real payment is attempted. Treat this as a
48
+ * probability signal, not a guarantee.
49
+ */
50
+ confidence: number;
51
+ /** Destination pubkey resolved from the invoice. */
52
+ destinationPubkey?: Pubkey;
53
+ /** Amount requested by the invoice, in shannon (hex). */
54
+ amount?: string;
55
+ /** Number of hops in the discovered route. 0 if paid via a direct channel. */
56
+ hopCount?: number;
57
+ /** Human-readable issues identified during analysis. */
58
+ issues: string[];
59
+ /** Structured error when no route could be found. */
60
+ error?: FiberError;
61
+ }
62
+ export interface ProbePayParams {
63
+ /** Destination node pubkey to probe. */
64
+ targetPubkey: Pubkey;
65
+ /** Amount to probe for, in shannon (hex string). */
66
+ amount: string;
67
+ /** Max seconds to wait for the probe to resolve. Defaults to 15. */
68
+ timeoutSeconds?: number;
69
+ }
70
+ export interface ProbeResult {
71
+ /**
72
+ * True when the probe reached the destination and was rejected only for
73
+ * having an unrecognised (fake) payment hash — proof the entire route had
74
+ * enough live liquidity to carry this exact amount, right now.
75
+ */
76
+ isViable: boolean;
77
+ /** Raw terminal failed_error string from the RPC, for diagnostics. */
78
+ terminalError?: string;
79
+ /** Structured error when the probe failed due to a real routing/liquidity issue. */
80
+ error?: FiberError;
81
+ /** Wall-clock time the probe took to resolve, in milliseconds. */
82
+ latencyMs: number;
83
+ }
84
+ export interface CanReceiveParams {
85
+ /** Amount in shannon to check receivability for (hex string). */
86
+ amount: string;
87
+ /** Optional UDT type script hash for multi-asset capacity checks. */
88
+ udtTypeScriptHash?: string;
89
+ }
90
+ export interface ReceiveCheckResult {
91
+ canReceive: boolean;
92
+ totalInboundCapacity: bigint;
93
+ activeChannelCount: number;
94
+ channelBreakdown: ChannelCapacityEntry[];
95
+ issues: string[];
96
+ }
97
+ export interface ChannelCapacityEntry {
98
+ channelId: string;
99
+ pubkey: string;
100
+ usableInbound: bigint;
101
+ isEnabled: boolean;
102
+ }
103
+ /**
104
+ * Pre-flight payment feasibility analysis for Fiber Network applications.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const checker = new PaymentChecker(client)
109
+ *
110
+ * const result = await checker.canPay({ invoice: 'fibt...' })
111
+ * if (!result.canPay) {
112
+ * console.error(result.error?.message)
113
+ * return
114
+ * }
115
+ * console.log(`Confidence: ${result.confidence}% Hops: ${result.hopCount}`)
116
+ *
117
+ * const rx = await checker.canReceive({ amount: '0x174876e800' })
118
+ * if (!rx.canReceive) console.warn('Low inbound capacity:', rx.issues)
119
+ * ```
120
+ */
121
+ export declare class PaymentChecker {
122
+ private readonly client;
123
+ constructor(client: FiberClient);
124
+ /**
125
+ * Performs a pre-flight feasibility check for an outgoing Fiber payment.
126
+ *
127
+ * Process:
128
+ * 1. Resolves the destination pubkey and amount from the invoice.
129
+ * 2. Checks for a direct ChannelReady channel to the destination —
130
+ * if found, this is the highest-confidence path.
131
+ * 3. Otherwise, searches the public network graph via BFS to find
132
+ * the shortest multi-hop path to the destination.
133
+ * 4. Scores each hop against published outbound liquidity data and
134
+ * combines scores using weakest-link logic, since a payment fails
135
+ * if any single hop lacks capacity.
136
+ */
137
+ canPay(params: CanPayParams): Promise<PaymentCheckResult>;
138
+ /**
139
+ * Checks whether this node has sufficient inbound capacity to receive a payment.
140
+ *
141
+ * Usable inbound per channel = remote_balance − received_tlc_balance.
142
+ * Only ChannelReady + enabled channels are included.
143
+ */
144
+ canReceive(params: CanReceiveParams): Promise<ReceiveCheckResult>;
145
+ /**
146
+ * Performs a live liquidity probe against a real destination pubkey.
147
+ *
148
+ * Sends a real HTLC using a randomly generated, never-revealed preimage.
149
+ * Funds cannot be lost: since the preimage is never shared, no node along
150
+ * the route -- including the destination -- can ever claim the payment.
151
+ *
152
+ * Terminal outcomes:
153
+ * - Destination returns IncorrectOrUnknownPaymentDetails: the entire
154
+ * route had enough live liquidity right now to carry this exact
155
+ * amount. This is a genuine empirical signal, not a static estimate.
156
+ * - Any other failure (e.g. TemporaryChannelFailure): a specific hop
157
+ * lacks liquidity or is unreachable. Parsed into a typed FiberError.
158
+ *
159
+ * This is slower and costs a brief HTLC lock on every hop versus canPay(),
160
+ * so use canPay() as the fast default and probePay() when you need
161
+ * ground-truth confidence immediately before a real payment.
162
+ */
163
+ probePay(params: ProbePayParams): Promise<ProbeResult>;
164
+ }
165
+ //# sourceMappingURL=checker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checker.d.ts","sourceRoot":"","sources":["../../src/payment/checker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAe,oBAAoB,CAAA;AAC9D,OAAO,KAAK,EAAyB,MAAM,EAAE,MAAM,oBAAoB,CAAA;AACvE,OAAO,EAAE,UAAU,EAAsB,MAAM,qBAAqB,CAAA;AAKpE,MAAM,WAAW,YAAY;IAC3B,mDAAmD;IACnD,OAAO,EAAE,MAAM,CAAA;IACf,uFAAuF;IACvF,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED,MAAM,WAAW,kBAAkB;IACjC,gFAAgF;IAChF,MAAM,EAAE,OAAO,CAAA;IACf;;;;;;;;;;;OAWG;IACH,UAAU,EAAE,MAAM,CAAA;IAClB,oDAAoD;IACpD,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,yDAAyD;IACzD,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,8EAA8E;IAC9E,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,wDAAwD;IACxD,MAAM,EAAE,MAAM,EAAE,CAAA;IAChB,qDAAqD;IACrD,KAAK,CAAC,EAAE,UAAU,CAAA;CACnB;AAGD,MAAM,WAAW,cAAc;IAC7B,wCAAwC;IACxC,YAAY,EAAE,MAAM,CAAA;IACpB,oDAAoD;IACpD,MAAM,EAAE,MAAM,CAAA;IACd,oEAAoE;IACpE,cAAc,CAAC,EAAE,MAAM,CAAA;CACx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