@fiber-pay/sdk 0.1.0-rc.1

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,895 @@
1
+ import { z } from 'zod';
2
+
3
+ /**
4
+ * CKB Address Encoding (Bech32m)
5
+ * Encode CKB lock scripts to human-readable addresses
6
+ */
7
+ interface Script$1 {
8
+ code_hash: string;
9
+ hash_type: 'type' | 'data' | 'data1' | 'data2';
10
+ args: string;
11
+ }
12
+ /**
13
+ * Convert a CKB lock script to a bech32m-encoded address
14
+ * @param script - The lock script to encode
15
+ * @param network - The CKB network ('testnet' or 'mainnet')
16
+ * @returns Bech32m-encoded CKB address
17
+ */
18
+ declare function scriptToAddress(script: Script$1, network: 'testnet' | 'mainnet'): string;
19
+
20
+ /**
21
+ * Fiber Network Node RPC Types (Fiber v0.6.1)
22
+ *
23
+ * The types in this file are intended to align with the upstream RPC spec:
24
+ * https://github.com/nervosnetwork/fiber/blob/v0.6.1/crates/fiber-lib/src/rpc/README.md
25
+ */
26
+ /** Hex-encoded string (prefixed with 0x). The RPC serializes most numeric values as hex strings. */
27
+ type HexString = `0x${string}`;
28
+ /** A 256-bit hash digest (Hash256 in the RPC spec). */
29
+ type Hash256 = HexString;
30
+ /** Public key for a node (Pubkey in the RPC spec). */
31
+ type Pubkey = HexString;
32
+ /** Private key (Privkey in the RPC spec). */
33
+ type Privkey = HexString;
34
+ /** Peer ID in libp2p format. */
35
+ type PeerId = string;
36
+ /** Multiaddr format for network addresses. */
37
+ type Multiaddr = string;
38
+ /** Channel ID (Hash256). */
39
+ type ChannelId = Hash256;
40
+ /** Payment hash (Hash256). */
41
+ type PaymentHash = Hash256;
42
+ /** Script structure for CKB. */
43
+ interface Script {
44
+ code_hash: HexString;
45
+ hash_type: 'type' | 'data' | 'data1' | 'data2';
46
+ args: HexString;
47
+ }
48
+ /** Transaction out point. */
49
+ interface OutPoint {
50
+ tx_hash: Hash256;
51
+ index: HexString;
52
+ }
53
+ /** UDT (User Defined Token) script (UdtScript in the RPC spec). */
54
+ type UdtScript = Script;
55
+ type Currency = 'Fibb' | 'Fibt' | 'Fibd';
56
+ type HashAlgorithm = 'CkbHash' | 'Sha256';
57
+ /** Recoverable signature (InvoiceSignature in the RPC spec). */
58
+ type InvoiceSignature = HexString;
59
+ /**
60
+ * Invoice attribute types as returned by the RPC.
61
+ * Each attribute is an object with a single key indicating the attribute type.
62
+ */
63
+ type Attribute =
64
+ /** Deprecated since v0.6.0, preserved for compatibility. */
65
+ {
66
+ FinalHtlcTimeout: HexString;
67
+ }
68
+ /** Final TLC minimum expiry delta in milliseconds. */
69
+ | {
70
+ FinalHtlcMinimumExpiryDelta: HexString;
71
+ }
72
+ /** Invoice expiry time in seconds. */
73
+ | {
74
+ ExpiryTime: HexString;
75
+ }
76
+ /** Human-readable invoice description. */
77
+ | {
78
+ Description: string;
79
+ }
80
+ /** Fallback address for on-chain settlement. */
81
+ | {
82
+ FallbackAddr: string;
83
+ }
84
+ /** UDT script for token invoices. */
85
+ | {
86
+ UdtScript: UdtScript;
87
+ }
88
+ /** Payee public key. */
89
+ | {
90
+ PayeePublicKey: Pubkey;
91
+ }
92
+ /** Hash algorithm used in the payment hash lock. */
93
+ | {
94
+ HashAlgorithm: HashAlgorithm;
95
+ }
96
+ /** Feature flags list. */
97
+ | {
98
+ Feature: string[];
99
+ }
100
+ /** Payment secret. */
101
+ | {
102
+ PaymentSecret: Hash256;
103
+ };
104
+ interface InvoiceData {
105
+ timestamp: HexString;
106
+ payment_hash: PaymentHash;
107
+ attrs: Attribute[];
108
+ }
109
+ interface CkbInvoice {
110
+ currency: Currency;
111
+ amount?: HexString;
112
+ signature?: InvoiceSignature;
113
+ data: InvoiceData;
114
+ }
115
+ type CkbInvoiceStatus = 'Open' | 'Cancelled' | 'Expired' | 'Received' | 'Paid';
116
+ declare enum ChannelState {
117
+ NegotiatingFunding = "NEGOTIATING_FUNDING",
118
+ CollaboratingFundingTx = "COLLABORATING_FUNDING_TX",
119
+ SigningCommitment = "SIGNING_COMMITMENT",
120
+ AwaitingTxSignatures = "AWAITING_TX_SIGNATURES",
121
+ AwaitingChannelReady = "AWAITING_CHANNEL_READY",
122
+ ChannelReady = "CHANNEL_READY",
123
+ ShuttingDown = "SHUTTING_DOWN",
124
+ Closed = "CLOSED"
125
+ }
126
+ /** Channel state flags are serialized as flag names by upstream RPC and may evolve. */
127
+ type ChannelStateFlags = string[];
128
+ /** TLC status. The upstream spec defines OutboundTlcStatus / InboundTlcStatus, which may evolve. */
129
+ type TlcStatus = {
130
+ Outbound: unknown;
131
+ } | {
132
+ Inbound: unknown;
133
+ };
134
+ interface Htlc {
135
+ id: HexString;
136
+ amount: HexString;
137
+ payment_hash: PaymentHash;
138
+ expiry: HexString;
139
+ forwarding_channel_id?: Hash256;
140
+ forwarding_tlc_id?: HexString;
141
+ status: TlcStatus;
142
+ }
143
+ interface Channel {
144
+ channel_id: ChannelId;
145
+ is_public: boolean;
146
+ channel_outpoint: OutPoint | null;
147
+ peer_id: PeerId;
148
+ funding_udt_type_script: Script | null;
149
+ state: {
150
+ state_name: ChannelState;
151
+ state_flags?: ChannelStateFlags;
152
+ };
153
+ local_balance: HexString;
154
+ offered_tlc_balance: HexString;
155
+ remote_balance: HexString;
156
+ received_tlc_balance: HexString;
157
+ pending_tlcs: Htlc[];
158
+ latest_commitment_transaction_hash: Hash256 | null;
159
+ created_at: HexString;
160
+ enabled: boolean;
161
+ tlc_expiry_delta: HexString;
162
+ tlc_fee_proportional_millionths: HexString;
163
+ shutdown_transaction_hash: Hash256 | null;
164
+ }
165
+ interface PeerInfo {
166
+ pubkey: Pubkey;
167
+ peer_id: PeerId;
168
+ address: Multiaddr;
169
+ }
170
+ type PaymentStatus = 'Created' | 'Inflight' | 'Success' | 'Failed';
171
+ /**
172
+ * Custom records for payments.
173
+ *
174
+ * Keys are hex-encoded u32 values (e.g. `0x1`, range 0..=65535),
175
+ * values are hex-encoded byte arrays (0x-prefixed).
176
+ */
177
+ type PaymentCustomRecords = Record<string, HexString>;
178
+ interface SessionRouteNode {
179
+ pubkey: Pubkey;
180
+ amount: HexString;
181
+ channel_outpoint: OutPoint;
182
+ }
183
+ interface SessionRoute {
184
+ nodes: SessionRouteNode[];
185
+ }
186
+ interface PaymentInfo {
187
+ payment_hash: PaymentHash;
188
+ status: PaymentStatus;
189
+ created_at: HexString;
190
+ last_updated_at: HexString;
191
+ failed_error?: string;
192
+ fee: HexString;
193
+ custom_records?: PaymentCustomRecords;
194
+ routers?: SessionRoute[];
195
+ }
196
+ interface HopHint {
197
+ pubkey: Pubkey;
198
+ channel_outpoint: OutPoint;
199
+ fee_rate: HexString;
200
+ tlc_expiry_delta: HexString;
201
+ }
202
+ interface UdtCellDep {
203
+ out_point: OutPoint;
204
+ dep_type: 'code' | 'dep_group';
205
+ }
206
+ interface UdtDep {
207
+ cell_dep?: UdtCellDep | null;
208
+ type_id?: Script | null;
209
+ }
210
+ interface UdtArgInfo {
211
+ name: string;
212
+ script: UdtScript;
213
+ auto_accept_amount?: HexString;
214
+ cell_deps: UdtDep[];
215
+ }
216
+ type UdtCfgInfos = UdtArgInfo[];
217
+ interface NodeInfo {
218
+ version: string;
219
+ commit_hash: string;
220
+ node_id: Pubkey;
221
+ features: string[];
222
+ node_name: string | null;
223
+ addresses: Multiaddr[];
224
+ chain_hash: Hash256;
225
+ open_channel_auto_accept_min_ckb_funding_amount: HexString;
226
+ auto_accept_channel_ckb_funding_amount: HexString;
227
+ default_funding_lock_script: Script;
228
+ tlc_expiry_delta: HexString;
229
+ tlc_min_value: HexString;
230
+ tlc_fee_proportional_millionths: HexString;
231
+ channel_count: HexString;
232
+ pending_channel_count: HexString;
233
+ peers_count: HexString;
234
+ udt_cfg_infos: UdtCfgInfos;
235
+ }
236
+ interface ChannelUpdateInfo {
237
+ timestamp: HexString;
238
+ enabled: boolean;
239
+ outbound_liquidity?: HexString;
240
+ tlc_expiry_delta: HexString;
241
+ tlc_minimum_value: HexString;
242
+ fee_rate: HexString;
243
+ }
244
+ interface GraphNodeInfo {
245
+ node_name: string;
246
+ version: string;
247
+ addresses: Multiaddr[];
248
+ features: string[];
249
+ node_id: Pubkey;
250
+ timestamp: HexString;
251
+ chain_hash: Hash256;
252
+ auto_accept_min_ckb_funding_amount: HexString;
253
+ udt_cfg_infos: UdtCfgInfos;
254
+ }
255
+ interface GraphChannelInfo {
256
+ channel_outpoint: OutPoint;
257
+ node1: Pubkey;
258
+ node2: Pubkey;
259
+ created_timestamp: HexString;
260
+ update_info_of_node1?: ChannelUpdateInfo | null;
261
+ update_info_of_node2?: ChannelUpdateInfo | null;
262
+ capacity: HexString;
263
+ chain_hash: Hash256;
264
+ udt_type_script?: Script | null;
265
+ }
266
+ interface ConnectPeerParams {
267
+ address: Multiaddr;
268
+ save?: boolean;
269
+ }
270
+ /** connect_peer returns None in v0.6.1 */
271
+ type ConnectPeerResult = null;
272
+ interface DisconnectPeerParams {
273
+ peer_id: PeerId;
274
+ }
275
+ interface ListPeersResult {
276
+ peers: PeerInfo[];
277
+ }
278
+ interface OpenChannelParams {
279
+ peer_id: PeerId;
280
+ funding_amount: HexString;
281
+ public?: boolean;
282
+ funding_udt_type_script?: Script;
283
+ shutdown_script?: Script;
284
+ commitment_delay_epoch?: HexString;
285
+ commitment_fee_rate?: HexString;
286
+ funding_fee_rate?: HexString;
287
+ tlc_expiry_delta?: HexString;
288
+ tlc_min_value?: HexString;
289
+ tlc_fee_proportional_millionths?: HexString;
290
+ max_tlc_value_in_flight?: HexString;
291
+ max_tlc_number_in_flight?: HexString;
292
+ }
293
+ interface OpenChannelResult {
294
+ temporary_channel_id: ChannelId;
295
+ }
296
+ interface AcceptChannelParams {
297
+ temporary_channel_id: ChannelId;
298
+ funding_amount: HexString;
299
+ shutdown_script?: Script;
300
+ max_tlc_value_in_flight?: HexString;
301
+ max_tlc_number_in_flight?: HexString;
302
+ tlc_min_value?: HexString;
303
+ tlc_fee_proportional_millionths?: HexString;
304
+ tlc_expiry_delta?: HexString;
305
+ }
306
+ interface AcceptChannelResult {
307
+ channel_id: ChannelId;
308
+ }
309
+ interface ListChannelsParams {
310
+ peer_id?: PeerId;
311
+ include_closed?: boolean;
312
+ }
313
+ interface ListChannelsResult {
314
+ channels: Channel[];
315
+ }
316
+ interface ShutdownChannelParams {
317
+ channel_id: ChannelId;
318
+ close_script?: Script;
319
+ fee_rate?: HexString;
320
+ force?: boolean;
321
+ }
322
+ interface AbandonChannelParams {
323
+ channel_id: ChannelId;
324
+ }
325
+ interface UpdateChannelParams {
326
+ channel_id: ChannelId;
327
+ enabled?: boolean;
328
+ tlc_expiry_delta?: HexString;
329
+ tlc_minimum_value?: HexString;
330
+ tlc_fee_proportional_millionths?: HexString;
331
+ }
332
+ interface SendPaymentParams {
333
+ target_pubkey?: Pubkey;
334
+ amount?: HexString;
335
+ payment_hash?: PaymentHash;
336
+ final_tlc_expiry_delta?: HexString;
337
+ tlc_expiry_limit?: HexString;
338
+ invoice?: string;
339
+ timeout?: HexString;
340
+ max_fee_amount?: HexString;
341
+ max_parts?: HexString;
342
+ keysend?: boolean;
343
+ udt_type_script?: Script;
344
+ allow_self_payment?: boolean;
345
+ custom_records?: PaymentCustomRecords;
346
+ hop_hints?: HopHint[];
347
+ dry_run?: boolean;
348
+ }
349
+ interface SendPaymentResult extends PaymentInfo {
350
+ }
351
+ interface GetPaymentParams {
352
+ payment_hash: PaymentHash;
353
+ }
354
+ interface GetPaymentResult extends PaymentInfo {
355
+ }
356
+ interface NewInvoiceParams {
357
+ amount: HexString;
358
+ description?: string;
359
+ currency: Currency;
360
+ payment_preimage?: Hash256;
361
+ payment_hash?: PaymentHash;
362
+ expiry?: HexString;
363
+ fallback_address?: string;
364
+ final_expiry_delta?: HexString;
365
+ udt_type_script?: Script;
366
+ hash_algorithm?: HashAlgorithm;
367
+ allow_mpp?: boolean;
368
+ }
369
+ interface NewInvoiceResult {
370
+ invoice_address: string;
371
+ invoice: CkbInvoice;
372
+ }
373
+ interface ParseInvoiceParams {
374
+ invoice: string;
375
+ }
376
+ interface ParseInvoiceResult {
377
+ invoice: CkbInvoice;
378
+ }
379
+ interface GetInvoiceParams {
380
+ payment_hash: PaymentHash;
381
+ }
382
+ interface GetInvoiceResult {
383
+ invoice_address: string;
384
+ invoice: CkbInvoice;
385
+ status: CkbInvoiceStatus;
386
+ }
387
+ interface CancelInvoiceParams {
388
+ payment_hash: PaymentHash;
389
+ }
390
+ interface CancelInvoiceResult {
391
+ invoice_address: string;
392
+ invoice: CkbInvoice;
393
+ status: CkbInvoiceStatus;
394
+ }
395
+ interface SettleInvoiceParams {
396
+ payment_hash: PaymentHash;
397
+ payment_preimage: Hash256;
398
+ }
399
+ interface HopRequire {
400
+ pubkey: Pubkey;
401
+ channel_outpoint?: OutPoint | null;
402
+ }
403
+ interface BuildRouterParams {
404
+ amount?: HexString;
405
+ udt_type_script?: Script;
406
+ hops_info: HopRequire[];
407
+ final_tlc_expiry_delta?: HexString;
408
+ }
409
+ interface RouterHop {
410
+ target: Pubkey;
411
+ channel_outpoint: OutPoint;
412
+ amount_received: HexString;
413
+ incoming_tlc_expiry: HexString;
414
+ }
415
+ interface BuildRouterResult {
416
+ router_hops: RouterHop[];
417
+ }
418
+ interface SendPaymentWithRouterParams {
419
+ payment_hash?: PaymentHash;
420
+ router: RouterHop[];
421
+ invoice?: string;
422
+ custom_records?: PaymentCustomRecords;
423
+ keysend?: boolean;
424
+ udt_type_script?: Script;
425
+ dry_run?: boolean;
426
+ }
427
+ interface GraphNodesParams {
428
+ limit?: HexString;
429
+ after?: HexString;
430
+ }
431
+ interface GraphNodesResult {
432
+ nodes: GraphNodeInfo[];
433
+ last_cursor: HexString;
434
+ }
435
+ interface GraphChannelsParams {
436
+ limit?: HexString;
437
+ after?: HexString;
438
+ }
439
+ interface GraphChannelsResult {
440
+ channels: GraphChannelInfo[];
441
+ last_cursor: HexString;
442
+ }
443
+ /** Cross-chain hub invoice variant. */
444
+ type CchInvoice = {
445
+ Fiber: string;
446
+ } | {
447
+ Lightning: string;
448
+ };
449
+ /** Cross-chain hub order status. */
450
+ type CchOrderStatus = 'Pending' | 'IncomingAccepted' | 'OutgoingInFlight' | 'OutgoingSettled' | 'Succeeded' | 'Failed';
451
+ /** Reason for removing a TLC in Dev module APIs. */
452
+ type RemoveTlcReason = {
453
+ RemoveTlcFulfill: Hash256;
454
+ } | {
455
+ RemoveTlcFail: HexString;
456
+ };
457
+ /** TLC id wrapper in watchtower-related types. */
458
+ type TLCId = {
459
+ Offered: HexString;
460
+ } | {
461
+ Received: HexString;
462
+ };
463
+ /** Minimal CKB cell output representation used by watchtower revocation data. */
464
+ interface CellOutput {
465
+ capacity: HexString;
466
+ lock: Script;
467
+ type?: Script | null;
468
+ }
469
+ /** Settlement TLC data used by watchtower operations. */
470
+ interface SettlementTlc {
471
+ tlc_id: TLCId;
472
+ hash_algorithm: HashAlgorithm;
473
+ payment_amount: HexString;
474
+ payment_hash: Hash256;
475
+ expiry: HexString;
476
+ local_key: Privkey;
477
+ remote_key: Pubkey;
478
+ }
479
+ /** Settlement data used by watchtower operations. */
480
+ interface SettlementData {
481
+ local_amount: HexString;
482
+ remote_amount: HexString;
483
+ tlcs: SettlementTlc[];
484
+ }
485
+ /** Revocation data used by watchtower operations. */
486
+ interface RevocationData {
487
+ commitment_number: HexString;
488
+ aggregated_signature: HexString;
489
+ output: CellOutput;
490
+ output_data: HexString;
491
+ }
492
+ interface NodeInfoResult extends NodeInfo {
493
+ }
494
+ interface JsonRpcRequest<T = unknown> {
495
+ jsonrpc: '2.0';
496
+ id: number | string;
497
+ method: string;
498
+ params: T[];
499
+ }
500
+ interface JsonRpcResponse<T = unknown> {
501
+ jsonrpc: '2.0';
502
+ id: number | string;
503
+ result?: T;
504
+ error?: JsonRpcError;
505
+ }
506
+ interface JsonRpcError {
507
+ code: number;
508
+ message: string;
509
+ data?: unknown;
510
+ }
511
+
512
+ /**
513
+ * Security Policy Types
514
+ * Configuration for AI agent spending limits and guardrails
515
+ */
516
+
517
+ declare const SpendingLimitSchema: z.ZodObject<{
518
+ maxPerTransaction: z.ZodString;
519
+ maxPerWindow: z.ZodString;
520
+ windowSeconds: z.ZodNumber;
521
+ currentSpent: z.ZodOptional<z.ZodString>;
522
+ windowStart: z.ZodOptional<z.ZodNumber>;
523
+ }, z.core.$strip>;
524
+ type SpendingLimit = z.infer<typeof SpendingLimitSchema>;
525
+ declare const RecipientPolicySchema: z.ZodObject<{
526
+ allowlist: z.ZodOptional<z.ZodArray<z.ZodString>>;
527
+ blocklist: z.ZodOptional<z.ZodArray<z.ZodString>>;
528
+ allowUnknown: z.ZodDefault<z.ZodBoolean>;
529
+ }, z.core.$strip>;
530
+ type RecipientPolicy = z.infer<typeof RecipientPolicySchema>;
531
+ declare const RateLimitSchema: z.ZodObject<{
532
+ maxTransactions: z.ZodNumber;
533
+ windowSeconds: z.ZodNumber;
534
+ cooldownSeconds: z.ZodDefault<z.ZodNumber>;
535
+ currentCount: z.ZodOptional<z.ZodNumber>;
536
+ windowStart: z.ZodOptional<z.ZodNumber>;
537
+ lastTransaction: z.ZodOptional<z.ZodNumber>;
538
+ }, z.core.$strip>;
539
+ type RateLimit = z.infer<typeof RateLimitSchema>;
540
+ declare const ChannelPolicySchema: z.ZodObject<{
541
+ allowOpen: z.ZodDefault<z.ZodBoolean>;
542
+ allowClose: z.ZodDefault<z.ZodBoolean>;
543
+ allowForceClose: z.ZodDefault<z.ZodBoolean>;
544
+ maxFundingAmount: z.ZodOptional<z.ZodString>;
545
+ minFundingAmount: z.ZodOptional<z.ZodString>;
546
+ maxChannels: z.ZodOptional<z.ZodNumber>;
547
+ }, z.core.$strip>;
548
+ type ChannelPolicy = z.infer<typeof ChannelPolicySchema>;
549
+ declare const SecurityPolicySchema: z.ZodObject<{
550
+ name: z.ZodString;
551
+ version: z.ZodDefault<z.ZodString>;
552
+ enabled: z.ZodDefault<z.ZodBoolean>;
553
+ spending: z.ZodOptional<z.ZodObject<{
554
+ maxPerTransaction: z.ZodString;
555
+ maxPerWindow: z.ZodString;
556
+ windowSeconds: z.ZodNumber;
557
+ currentSpent: z.ZodOptional<z.ZodString>;
558
+ windowStart: z.ZodOptional<z.ZodNumber>;
559
+ }, z.core.$strip>>;
560
+ recipients: z.ZodOptional<z.ZodObject<{
561
+ allowlist: z.ZodOptional<z.ZodArray<z.ZodString>>;
562
+ blocklist: z.ZodOptional<z.ZodArray<z.ZodString>>;
563
+ allowUnknown: z.ZodDefault<z.ZodBoolean>;
564
+ }, z.core.$strip>>;
565
+ rateLimit: z.ZodOptional<z.ZodObject<{
566
+ maxTransactions: z.ZodNumber;
567
+ windowSeconds: z.ZodNumber;
568
+ cooldownSeconds: z.ZodDefault<z.ZodNumber>;
569
+ currentCount: z.ZodOptional<z.ZodNumber>;
570
+ windowStart: z.ZodOptional<z.ZodNumber>;
571
+ lastTransaction: z.ZodOptional<z.ZodNumber>;
572
+ }, z.core.$strip>>;
573
+ channels: z.ZodOptional<z.ZodObject<{
574
+ allowOpen: z.ZodDefault<z.ZodBoolean>;
575
+ allowClose: z.ZodDefault<z.ZodBoolean>;
576
+ allowForceClose: z.ZodDefault<z.ZodBoolean>;
577
+ maxFundingAmount: z.ZodOptional<z.ZodString>;
578
+ minFundingAmount: z.ZodOptional<z.ZodString>;
579
+ maxChannels: z.ZodOptional<z.ZodNumber>;
580
+ }, z.core.$strip>>;
581
+ confirmationThreshold: z.ZodOptional<z.ZodString>;
582
+ auditLogging: z.ZodDefault<z.ZodBoolean>;
583
+ metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
584
+ }, z.core.$strip>;
585
+ type SecurityPolicy = z.infer<typeof SecurityPolicySchema>;
586
+ type ViolationType = 'SPENDING_LIMIT_PER_TX' | 'SPENDING_LIMIT_PER_WINDOW' | 'RATE_LIMIT_EXCEEDED' | 'RATE_LIMIT_COOLDOWN' | 'RECIPIENT_NOT_ALLOWED' | 'RECIPIENT_BLOCKED' | 'CHANNEL_OPEN_NOT_ALLOWED' | 'CHANNEL_CLOSE_NOT_ALLOWED' | 'CHANNEL_FORCE_CLOSE_NOT_ALLOWED' | 'CHANNEL_FUNDING_EXCEEDS_MAX' | 'CHANNEL_FUNDING_BELOW_MIN' | 'MAX_CHANNELS_REACHED' | 'REQUIRES_CONFIRMATION';
587
+ interface PolicyViolation {
588
+ type: ViolationType;
589
+ message: string;
590
+ details: {
591
+ requested?: string;
592
+ limit?: string;
593
+ recipient?: string;
594
+ remaining?: string;
595
+ cooldownRemaining?: number;
596
+ };
597
+ }
598
+ interface PolicyCheckResult {
599
+ allowed: boolean;
600
+ violations: PolicyViolation[];
601
+ requiresConfirmation: boolean;
602
+ }
603
+ type AuditAction = 'PAYMENT_SENT' | 'PAYMENT_RECEIVED' | 'INVOICE_CREATED' | 'INVOICE_VALIDATED' | 'HOLD_INVOICE_CREATED' | 'HOLD_INVOICE_SETTLED' | 'CHANNEL_OPENED' | 'CHANNEL_CLOSED' | 'POLICY_VIOLATION' | 'POLICY_UPDATED' | 'NODE_STARTED' | 'NODE_STOPPED';
604
+ interface AuditLogEntry {
605
+ timestamp: number;
606
+ action: AuditAction;
607
+ success: boolean;
608
+ details: Record<string, unknown>;
609
+ policyViolations?: PolicyViolation[];
610
+ sessionId?: string;
611
+ agentId?: string;
612
+ }
613
+ interface KeyConfig {
614
+ /** Base directory for key storage */
615
+ baseDir: string;
616
+ /** Password for key encryption (should come from secure source) */
617
+ encryptionPassword?: string;
618
+ /** Whether to generate keys if they don't exist */
619
+ autoGenerate: boolean;
620
+ }
621
+ interface KeyInfo {
622
+ /** Public key (hex) */
623
+ publicKey: HexString;
624
+ /** Whether the key is encrypted */
625
+ encrypted: boolean;
626
+ /** Key file path */
627
+ path: string;
628
+ /** Key creation timestamp */
629
+ createdAt?: number;
630
+ }
631
+ interface AgentSession {
632
+ /** Unique session ID */
633
+ sessionId: string;
634
+ /** Agent identifier */
635
+ agentId: string;
636
+ /** Session start time */
637
+ startedAt: number;
638
+ /** Session expiry time */
639
+ expiresAt?: number;
640
+ /** Session-specific policy overrides */
641
+ policyOverrides?: Partial<SecurityPolicy>;
642
+ /** Session metadata */
643
+ metadata?: Record<string, unknown>;
644
+ }
645
+ declare const DEFAULT_SECURITY_POLICY: SecurityPolicy;
646
+
647
+ /**
648
+ * Utility Functions
649
+ * Common utilities for hex conversion, CKB amount calculation, and random generation
650
+ */
651
+
652
+ /**
653
+ * Convert number to hex string
654
+ */
655
+ declare function toHex(value: number | bigint): HexString;
656
+ /**
657
+ * Convert hex string to bigint
658
+ */
659
+ declare function fromHex(hex: HexString): bigint;
660
+ /**
661
+ * Convert CKB amount (in CKB units) to shannons (hex)
662
+ */
663
+ declare function ckbToShannons(ckb: number | string): HexString;
664
+ /**
665
+ * Convert shannons (hex) to CKB amount
666
+ */
667
+ declare function shannonsToCkb(shannons: HexString): number;
668
+ /**
669
+ * Generate a random 32-byte hex string (for payment preimage)
670
+ */
671
+ declare function randomBytes32(): HexString;
672
+ /**
673
+ * Convert a Fiber node id (hex-encoded compressed secp256k1 pubkey, 33 bytes)
674
+ * to a libp2p peer id (base58btc encoded sha2-256 multihash).
675
+ */
676
+ declare function nodeIdToPeerId(nodeId: string): Promise<string>;
677
+ /**
678
+ * Build a canonical multiaddr by appending/replacing /p2p/<peerId>.
679
+ */
680
+ declare function buildMultiaddr(address: string, peerId: string): string;
681
+ /**
682
+ * Build a canonical multiaddr from a node id and base address.
683
+ */
684
+ declare function buildMultiaddrFromNodeId(address: string, nodeId: string): Promise<string>;
685
+ /**
686
+ * Build a best-effort local multiaddr from an RPC URL and peer id.
687
+ * Uses rpcPort + 1 as inferred P2P port when advertised addresses are unavailable.
688
+ */
689
+ declare function buildMultiaddrFromRpcUrl(rpcUrl: string, peerId: string): string;
690
+
691
+ /**
692
+ * Fiber RPC Client
693
+ * Type-safe JSON-RPC client for Fiber Network Node
694
+ */
695
+
696
+ interface RpcClientConfig {
697
+ /** RPC endpoint URL */
698
+ url: string;
699
+ /** Request timeout in milliseconds */
700
+ timeout?: number;
701
+ /** Custom headers */
702
+ headers?: Record<string, string>;
703
+ /**
704
+ * Biscuit token for authentication.
705
+ *
706
+ * Prefer server-side usage. In browser apps, avoid embedding long-lived
707
+ * privileged tokens and use a trusted backend/proxy where possible.
708
+ */
709
+ biscuitToken?: string;
710
+ }
711
+ declare class FiberRpcError extends Error {
712
+ code: number;
713
+ data?: unknown | undefined;
714
+ constructor(code: number, message: string, data?: unknown | undefined);
715
+ static fromJsonRpcError(error: JsonRpcError): FiberRpcError;
716
+ }
717
+ declare class FiberRpcClient {
718
+ private requestId;
719
+ private config;
720
+ private readonly channelStateAliases;
721
+ constructor(config: RpcClientConfig);
722
+ /**
723
+ * Make a raw JSON-RPC call
724
+ *
725
+ * Useful for advanced/experimental RPCs not wrapped by convenience methods.
726
+ *
727
+ * @example
728
+ * ```ts
729
+ * const result = await client.call<MyResult>('some_method', [{ foo: 'bar' }]);
730
+ * ```
731
+ */
732
+ call<TResult>(method: string, params?: unknown[]): Promise<TResult>;
733
+ /**
734
+ * Connect to a peer
735
+ */
736
+ connectPeer(params: ConnectPeerParams): Promise<ConnectPeerResult>;
737
+ /**
738
+ * Disconnect from a peer
739
+ */
740
+ disconnectPeer(params: DisconnectPeerParams): Promise<null>;
741
+ /**
742
+ * List all connected peers
743
+ */
744
+ listPeers(): Promise<ListPeersResult>;
745
+ /**
746
+ * Open a new channel with a peer
747
+ */
748
+ openChannel(params: OpenChannelParams): Promise<OpenChannelResult>;
749
+ /**
750
+ * Accept a channel opening request
751
+ */
752
+ acceptChannel(params: AcceptChannelParams): Promise<AcceptChannelResult>;
753
+ /**
754
+ * List all channels
755
+ */
756
+ listChannels(params?: ListChannelsParams): Promise<ListChannelsResult>;
757
+ private normalizeChannelStateName;
758
+ private normalizeChannel;
759
+ /**
760
+ * Shutdown (close) a channel
761
+ */
762
+ shutdownChannel(params: ShutdownChannelParams): Promise<null>;
763
+ /**
764
+ * Abandon a pending channel
765
+ */
766
+ abandonChannel(params: AbandonChannelParams): Promise<null>;
767
+ /**
768
+ * Update channel parameters
769
+ */
770
+ updateChannel(params: UpdateChannelParams): Promise<null>;
771
+ /**
772
+ * Send a payment
773
+ */
774
+ sendPayment(params: SendPaymentParams): Promise<SendPaymentResult>;
775
+ /**
776
+ * Get payment status
777
+ */
778
+ getPayment(params: GetPaymentParams): Promise<GetPaymentResult>;
779
+ /**
780
+ * Create a new invoice
781
+ */
782
+ newInvoice(params: NewInvoiceParams): Promise<NewInvoiceResult>;
783
+ /**
784
+ * Parse an invoice string
785
+ */
786
+ parseInvoice(params: ParseInvoiceParams): Promise<ParseInvoiceResult>;
787
+ /**
788
+ * Get invoice by payment hash
789
+ */
790
+ getInvoice(params: GetInvoiceParams): Promise<GetInvoiceResult>;
791
+ /**
792
+ * Cancel an open invoice
793
+ */
794
+ cancelInvoice(params: CancelInvoiceParams): Promise<CancelInvoiceResult>;
795
+ /**
796
+ * Settle a hold invoice with the preimage
797
+ * Used for conditional/escrow payments where the invoice was created
798
+ * with a payment_hash (no preimage provided upfront)
799
+ */
800
+ settleInvoice(params: SettleInvoiceParams): Promise<null>;
801
+ /**
802
+ * Build a custom route for payment
803
+ * Useful for channel rebalancing (circular payments) and advanced routing
804
+ */
805
+ buildRouter(params: BuildRouterParams): Promise<BuildRouterResult>;
806
+ /**
807
+ * Send a payment using a pre-built route from buildRouter()
808
+ * Use with allow_self_payment for channel rebalancing
809
+ */
810
+ sendPaymentWithRouter(params: SendPaymentWithRouterParams): Promise<SendPaymentResult>;
811
+ /**
812
+ * List nodes in the network graph
813
+ */
814
+ graphNodes(params?: GraphNodesParams): Promise<GraphNodesResult>;
815
+ /**
816
+ * List channels in the network graph
817
+ */
818
+ graphChannels(params?: GraphChannelsParams): Promise<GraphChannelsResult>;
819
+ /**
820
+ * Get local node information
821
+ */
822
+ nodeInfo(): Promise<NodeInfoResult>;
823
+ /**
824
+ * Check if the node is reachable
825
+ */
826
+ ping(): Promise<boolean>;
827
+ /**
828
+ * Wait for the node to be ready
829
+ */
830
+ waitForReady(options?: {
831
+ timeout?: number;
832
+ interval?: number;
833
+ }): Promise<void>;
834
+ /**
835
+ * Wait for a payment to reach a terminal state (Success or Failed)
836
+ * Polls get_payment at the specified interval.
837
+ *
838
+ * @returns The final payment result
839
+ * @throws FiberRpcError on timeout
840
+ */
841
+ waitForPayment(paymentHash: PaymentHash, options?: {
842
+ timeout?: number;
843
+ interval?: number;
844
+ }): Promise<GetPaymentResult>;
845
+ /**
846
+ * Wait for a channel to reach ChannelReady state.
847
+ * Polls list_channels at the specified interval.
848
+ *
849
+ * @returns The channel info once ready
850
+ * @throws FiberRpcError on timeout or if channel disappears
851
+ */
852
+ waitForChannelReady(channelId: ChannelId, options?: {
853
+ timeout?: number;
854
+ interval?: number;
855
+ }): Promise<Channel>;
856
+ /**
857
+ * Wait for an invoice to reach a specific status.
858
+ * Useful for hold invoice workflows: wait for 'Received' before settling.
859
+ *
860
+ * @returns The invoice info once the target status is reached
861
+ * @throws FiberRpcError on timeout
862
+ */
863
+ waitForInvoiceStatus(paymentHash: PaymentHash, targetStatus: CkbInvoiceStatus | CkbInvoiceStatus[], options?: {
864
+ timeout?: number;
865
+ interval?: number;
866
+ }): Promise<GetInvoiceResult>;
867
+ /**
868
+ * Watch for incoming payments on specified invoices.
869
+ * Polls invoice statuses and calls the callback when a status changes.
870
+ * Use an AbortSignal to stop watching.
871
+ *
872
+ * @example
873
+ * ```typescript
874
+ * const controller = new AbortController();
875
+ * client.watchIncomingPayments({
876
+ * paymentHashes: [hash1, hash2],
877
+ * onPayment: (invoice) => console.log('Payment received!', invoice),
878
+ * signal: controller.signal,
879
+ * });
880
+ * // Later: controller.abort(); to stop watching
881
+ * ```
882
+ */
883
+ watchIncomingPayments(options: {
884
+ /** Payment hashes of invoices to watch */
885
+ paymentHashes: PaymentHash[];
886
+ /** Callback when an invoice status changes to Received or Paid */
887
+ onPayment: (invoice: GetInvoiceResult) => void;
888
+ /** Polling interval in ms (default: 3000) */
889
+ interval?: number;
890
+ /** AbortSignal to stop watching */
891
+ signal?: AbortSignal;
892
+ }): Promise<void>;
893
+ }
894
+
895
+ export { type AbandonChannelParams, type AcceptChannelParams, type AcceptChannelResult, type AgentSession, type Attribute, type AuditAction, type AuditLogEntry, type BuildRouterParams, type BuildRouterResult, type CancelInvoiceParams, type CancelInvoiceResult, type CchInvoice, type CchOrderStatus, type CellOutput, type Channel, type ChannelId, type ChannelPolicy, ChannelPolicySchema, ChannelState, type ChannelStateFlags, type ChannelUpdateInfo, type CkbInvoice, type CkbInvoiceStatus, type ConnectPeerParams, type ConnectPeerResult, type Currency, DEFAULT_SECURITY_POLICY, type DisconnectPeerParams, FiberRpcClient, FiberRpcError, type GetInvoiceParams, type GetInvoiceResult, type GetPaymentParams, type GetPaymentResult, type GraphChannelInfo, type GraphChannelsParams, type GraphChannelsResult, type GraphNodeInfo, type GraphNodesParams, type GraphNodesResult, type Hash256, type HashAlgorithm, type HexString, type HopHint, type HopRequire, type Htlc, type InvoiceData, type InvoiceSignature, type JsonRpcError, type JsonRpcRequest, type JsonRpcResponse, type KeyConfig, type KeyInfo, type ListChannelsParams, type ListChannelsResult, type ListPeersResult, type Multiaddr, type NewInvoiceParams, type NewInvoiceResult, type NodeInfo, type NodeInfoResult, type OpenChannelParams, type OpenChannelResult, type OutPoint, type ParseInvoiceParams, type ParseInvoiceResult, type PaymentCustomRecords, type PaymentHash, type PaymentInfo, type PaymentStatus, type PeerId, type PeerInfo, type PolicyCheckResult, type PolicyViolation, type Privkey, type Pubkey, type RateLimit, RateLimitSchema, type RecipientPolicy, RecipientPolicySchema, type RemoveTlcReason, type RevocationData, type RouterHop, type Script$1 as Script, type SecurityPolicy, SecurityPolicySchema, type SendPaymentParams, type SendPaymentResult, type SendPaymentWithRouterParams, type SessionRoute, type SessionRouteNode, type SettleInvoiceParams, type SettlementData, type SettlementTlc, type ShutdownChannelParams, type SpendingLimit, SpendingLimitSchema, type TLCId, type TlcStatus, type UdtArgInfo, type UdtCellDep, type UdtCfgInfos, type UdtDep, type UdtScript, type UpdateChannelParams, type ViolationType, buildMultiaddr, buildMultiaddrFromNodeId, buildMultiaddrFromRpcUrl, ckbToShannons, fromHex, nodeIdToPeerId, randomBytes32, scriptToAddress, shannonsToCkb, toHex };