@zendfi/sdk 0.3.1 → 0.5.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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,780 @@
1
- import { Z as ZendFiConfig, C as CreatePaymentRequest, P as Payment, L as ListPaymentsRequest, b as PaginatedResponse, c as CreateSubscriptionPlanRequest, S as SubscriptionPlan, d as CreateSubscriptionRequest, e as Subscription, f as CreatePaymentLinkRequest, g as PaymentLink, h as CreateInstallmentPlanRequest, I as InstallmentPlan, i as CreateEscrowRequest, E as Escrow, A as ApproveEscrowRequest, R as RefundEscrowRequest, D as DisputeEscrowRequest, j as CreateInvoiceRequest, k as Invoice, V as VerifyWebhookRequest, l as WebhookPayload } from './webhook-handler-DG-zic8m.mjs';
2
- export { q as ApiKeyMode, G as AuthenticationError, M as CreateInstallmentPlanResponse, r as Currency, o as Environment, w as EscrowStatus, v as InstallmentPlanStatus, K as InstallmentScheduleItem, Q as InvoiceLineItem, x as InvoiceStatus, N as NetworkError, t as PaymentStatus, s as PaymentToken, J as RateLimitError, O as ReleaseCondition, B as SplitRecipient, y as SplitStatus, u as SubscriptionStatus, H as ValidationError, z as WebhookEvent, n as WebhookEventHandler, W as WebhookHandlerConfig, a as WebhookHandlers, m as WebhookResult, F as ZendFiError, p as processWebhook } from './webhook-handler-DG-zic8m.mjs';
1
+ import { C as CreateAgentApiKeyRequest, A as AgentApiKey, b as CreateAgentSessionRequest, c as AgentSession, d as AgentAnalytics, e as CreatePaymentIntentRequest, P as PaymentIntent, f as ConfirmPaymentIntentRequest, g as PaymentIntentEvent, h as PPPFactor, i as PricingSuggestionRequest, j as PricingSuggestion, E as EnableAutonomyRequest, k as EnableAutonomyResponse, l as AutonomyStatus, S as SmartPaymentRequest, m as SmartPaymentResponse, Z as ZendFiConfig, n as CreatePaymentRequest, o as Payment, L as ListPaymentsRequest, p as PaginatedResponse, q as CreateSubscriptionPlanRequest, r as SubscriptionPlan, s as CreateSubscriptionRequest, t as Subscription, u as CreatePaymentLinkRequest, v as PaymentLink, w as CreateInstallmentPlanRequest, I as InstallmentPlan, x as CreateEscrowRequest, y as Escrow, z as ApproveEscrowRequest, R as RefundEscrowRequest, D as DisputeEscrowRequest, B as CreateInvoiceRequest, F as Invoice, V as VerifyWebhookRequest, G as WebhookPayload } from './webhook-handler-D8wEoYd7.mjs';
2
+ export { Q as AgentKeyId, ac as ApiKeyMode, ar as ApiKeyScope, ax as AutonomousDelegate, M as Brand, au as CaptureMethod, ao as CreateInstallmentPlanResponse, ad as Currency, ab as Environment, Y as EscrowId, ai as EscrowStatus, _ as InstallmentPlanId, ah as InstallmentPlanStatus, an as InstallmentScheduleItem, a0 as IntentId, U as InvoiceId, aq as InvoiceLineItem, aj as InvoiceStatus, T as MerchantId, aw as PPPConfig, N as PaymentId, at as PaymentIntentStatus, $ as PaymentLinkCode, af as PaymentStatus, ae as PaymentToken, ap as ReleaseCondition, ay as RevokeAutonomyRequest, O as SessionId, as as SessionLimits, az as SmartPaymentStatus, am as SplitRecipient, ak as SplitStatus, X as SubscriptionId, ag as SubscriptionStatus, av as UserProfile, al as WebhookEvent, K as WebhookEventHandler, W as WebhookHandlerConfig, a as WebhookHandlers, J as WebhookResult, a3 as asAgentKeyId, a7 as asEscrowId, a8 as asInstallmentPlanId, aa as asIntentId, a5 as asInvoiceId, a4 as asMerchantId, a1 as asPaymentId, a9 as asPaymentLinkCode, a2 as asSessionId, a6 as asSubscriptionId, H as processWebhook } from './webhook-handler-D8wEoYd7.mjs';
3
+ import { Transaction, Keypair } from '@solana/web3.js';
4
+
5
+ /**
6
+ * Request/Response Interceptor System
7
+ *
8
+ * Allows modifying requests before they're sent and responses after they're received
9
+ */
10
+ interface RequestConfig {
11
+ method: string;
12
+ url: string;
13
+ headers: Record<string, string>;
14
+ body?: any;
15
+ }
16
+ interface ResponseData {
17
+ status: number;
18
+ statusText: string;
19
+ headers: Record<string, string>;
20
+ data: any;
21
+ config: RequestConfig;
22
+ }
23
+ type RequestInterceptor = (config: RequestConfig) => RequestConfig | Promise<RequestConfig>;
24
+ type ResponseInterceptor = (response: ResponseData) => ResponseData | Promise<ResponseData>;
25
+ type ErrorInterceptor = (error: Error) => Error | Promise<Error>;
26
+ /**
27
+ * Interceptor Manager
28
+ */
29
+ declare class InterceptorManager<T extends (...args: any[]) => any> {
30
+ private handlers;
31
+ /**
32
+ * Add an interceptor
33
+ */
34
+ use(handler: T): number;
35
+ /**
36
+ * Remove an interceptor
37
+ */
38
+ eject(id: number): void;
39
+ /**
40
+ * Execute all interceptors in sequence
41
+ */
42
+ execute(initialValue: Parameters<T>[0]): Promise<ReturnType<T>>;
43
+ /**
44
+ * Check if any interceptors are registered
45
+ */
46
+ has(): boolean;
47
+ /**
48
+ * Clear all interceptors
49
+ */
50
+ clear(): void;
51
+ }
52
+ /**
53
+ * Interceptors collection
54
+ */
55
+ interface Interceptors {
56
+ request: InterceptorManager<RequestInterceptor>;
57
+ response: InterceptorManager<ResponseInterceptor>;
58
+ error: InterceptorManager<ErrorInterceptor>;
59
+ }
60
+
61
+ /**
62
+ * Agent API - Manage agent API keys and sessions
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * // Create an agent API key
67
+ * const agentKey = await zendfi.agent.createKey({
68
+ * name: 'Shopping Assistant',
69
+ * agent_id: 'shopping-assistant-v1',
70
+ * scopes: ['create_payments', 'read_analytics'],
71
+ * rate_limit_per_hour: 1000,
72
+ * });
73
+ *
74
+ * // Create an agent session with spending limits
75
+ * const session = await zendfi.agent.createSession({
76
+ * agent_id: 'shopping-assistant-v1',
77
+ * user_wallet: 'Hx7B...abc',
78
+ * limits: {
79
+ * max_per_transaction: 100,
80
+ * max_per_day: 500,
81
+ * },
82
+ * duration_hours: 24,
83
+ * });
84
+ * ```
85
+ */
86
+
87
+ type RequestFn$4 = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
88
+ declare class AgentAPI {
89
+ private request;
90
+ constructor(request: RequestFn$4);
91
+ /**
92
+ * Create a new agent API key with scoped permissions
93
+ *
94
+ * Agent keys (prefixed with `zai_`) have limited permissions compared to
95
+ * merchant keys. This enables safe delegation to AI agents.
96
+ *
97
+ * @param request - Agent key configuration
98
+ * @returns The created agent key (full_key only returned on creation!)
99
+ *
100
+ * @example
101
+ * ```typescript
102
+ * const agentKey = await zendfi.agent.createKey({
103
+ * name: 'Shopping Assistant',
104
+ * agent_id: 'shopping-assistant-v1',
105
+ * scopes: ['create_payments'],
106
+ * rate_limit_per_hour: 500,
107
+ * });
108
+ *
109
+ * // IMPORTANT: Save the full_key now - it won't be shown again!
110
+ * console.log(agentKey.full_key); // => "zai_test_abc123..."
111
+ * ```
112
+ */
113
+ createKey(request: CreateAgentApiKeyRequest): Promise<AgentApiKey>;
114
+ /**
115
+ * List all agent API keys for the merchant
116
+ *
117
+ * @returns Array of agent API keys (without full_key for security)
118
+ *
119
+ * @example
120
+ * ```typescript
121
+ * const keys = await zendfi.agent.listKeys();
122
+ * keys.forEach(key => {
123
+ * console.log(`${key.name}: ${key.key_prefix}*** (${key.scopes.join(', ')})`);
124
+ * });
125
+ * ```
126
+ */
127
+ listKeys(): Promise<AgentApiKey[]>;
128
+ /**
129
+ * Revoke an agent API key
130
+ *
131
+ * Once revoked, the key cannot be used for any API calls.
132
+ * This action is irreversible.
133
+ *
134
+ * @param keyId - UUID of the agent key to revoke
135
+ *
136
+ * @example
137
+ * ```typescript
138
+ * await zendfi.agent.revokeKey('ak_123...');
139
+ * console.log('Agent key revoked');
140
+ * ```
141
+ */
142
+ revokeKey(keyId: string): Promise<void>;
143
+ /**
144
+ * Create an agent session with spending limits
145
+ *
146
+ * Sessions provide time-bounded authorization for agents to make payments
147
+ * on behalf of users, with configurable spending limits.
148
+ *
149
+ * @param request - Session configuration
150
+ * @returns The created session with token
151
+ *
152
+ * @example
153
+ * ```typescript
154
+ * const session = await zendfi.agent.createSession({
155
+ * agent_id: 'shopping-assistant-v1',
156
+ * agent_name: 'Shopping Assistant',
157
+ * user_wallet: 'Hx7B...abc',
158
+ * limits: {
159
+ * max_per_transaction: 100,
160
+ * max_per_day: 500,
161
+ * require_approval_above: 50,
162
+ * },
163
+ * duration_hours: 24,
164
+ * });
165
+ *
166
+ * // Use session_token for subsequent API calls
167
+ * console.log(session.session_token); // => "zai_session_..."
168
+ * ```
169
+ */
170
+ createSession(request: CreateAgentSessionRequest): Promise<AgentSession>;
171
+ /**
172
+ * List all agent sessions
173
+ *
174
+ * @returns Array of agent sessions (both active and expired)
175
+ *
176
+ * @example
177
+ * ```typescript
178
+ * const sessions = await zendfi.agent.listSessions();
179
+ * const activeSessions = sessions.filter(s => s.is_active);
180
+ * console.log(`${activeSessions.length} active sessions`);
181
+ * ```
182
+ */
183
+ listSessions(): Promise<AgentSession[]>;
184
+ /**
185
+ * Get a specific agent session by ID
186
+ *
187
+ * @param sessionId - UUID of the session
188
+ * @returns The session details with remaining limits
189
+ *
190
+ * @example
191
+ * ```typescript
192
+ * const session = await zendfi.agent.getSession('sess_123...');
193
+ * console.log(`Remaining today: $${session.remaining_today}`);
194
+ * console.log(`Expires: ${session.expires_at}`);
195
+ * ```
196
+ */
197
+ getSession(sessionId: string): Promise<AgentSession>;
198
+ /**
199
+ * Revoke an agent session
200
+ *
201
+ * Immediately invalidates the session, preventing any further payments.
202
+ * This action is irreversible.
203
+ *
204
+ * @param sessionId - UUID of the session to revoke
205
+ *
206
+ * @example
207
+ * ```typescript
208
+ * await zendfi.agent.revokeSession('sess_123...');
209
+ * console.log('Session revoked - agent can no longer make payments');
210
+ * ```
211
+ */
212
+ revokeSession(sessionId: string): Promise<void>;
213
+ /**
214
+ * Get analytics for all agent activity
215
+ *
216
+ * @returns Comprehensive analytics including payments, success rate, and PPP savings
217
+ *
218
+ * @example
219
+ * ```typescript
220
+ * const analytics = await zendfi.agent.getAnalytics();
221
+ * console.log(`Total volume: $${analytics.total_volume_usd}`);
222
+ * console.log(`Success rate: ${(analytics.success_rate * 100).toFixed(1)}%`);
223
+ * console.log(`PPP savings: $${analytics.ppp_savings_usd}`);
224
+ * ```
225
+ */
226
+ getAnalytics(): Promise<AgentAnalytics>;
227
+ }
228
+
229
+ /**
230
+ * Payment Intents API - Two-phase payment flow
231
+ *
232
+ * Payment Intents provide a modern checkout experience with:
233
+ * - Create intent first (reserves amount)
234
+ * - Confirm when ready (completes payment)
235
+ * - Cancel if needed (releases hold)
236
+ *
237
+ * @example
238
+ * ```typescript
239
+ * // Step 1: Create intent when user starts checkout
240
+ * const intent = await zendfi.intents.create({
241
+ * amount: 99.99,
242
+ * description: 'Premium subscription',
243
+ * });
244
+ *
245
+ * // Step 2: Show payment form, collect wallet
246
+ * // ...
247
+ *
248
+ * // Step 3: Confirm when user clicks "Pay"
249
+ * const confirmed = await zendfi.intents.confirm(intent.id, {
250
+ * client_secret: intent.client_secret,
251
+ * customer_wallet: userWallet,
252
+ * });
253
+ * ```
254
+ */
255
+
256
+ type RequestFn$3 = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
257
+ interface ListIntentsOptions {
258
+ /** Filter by status */
259
+ status?: string;
260
+ /** Maximum results to return */
261
+ limit?: number;
262
+ /** Pagination offset */
263
+ offset?: number;
264
+ }
265
+ declare class PaymentIntentsAPI {
266
+ private request;
267
+ constructor(request: RequestFn$3);
268
+ /**
269
+ * Create a payment intent
270
+ *
271
+ * This is step 1 of the two-phase payment flow. The intent reserves
272
+ * the payment amount and provides a client_secret for confirmation.
273
+ *
274
+ * @param request - Payment intent configuration
275
+ * @returns The created payment intent with client_secret
276
+ *
277
+ * @example
278
+ * ```typescript
279
+ * const intent = await zendfi.intents.create({
280
+ * amount: 49.99,
281
+ * description: 'Pro Plan - Monthly',
282
+ * capture_method: 'automatic', // or 'manual' for auth-only
283
+ * expires_in_seconds: 3600, // 1 hour
284
+ * });
285
+ *
286
+ * // Store intent.id and pass intent.client_secret to frontend
287
+ * console.log(`Intent created: ${intent.id}`);
288
+ * console.log(`Status: ${intent.status}`); // "requires_payment"
289
+ * ```
290
+ */
291
+ create(request: CreatePaymentIntentRequest): Promise<PaymentIntent>;
292
+ /**
293
+ * Get a payment intent by ID
294
+ *
295
+ * @param intentId - UUID of the payment intent
296
+ * @returns The payment intent details
297
+ *
298
+ * @example
299
+ * ```typescript
300
+ * const intent = await zendfi.intents.get('pi_123...');
301
+ * console.log(`Status: ${intent.status}`);
302
+ * if (intent.payment_id) {
303
+ * console.log(`Payment: ${intent.payment_id}`);
304
+ * }
305
+ * ```
306
+ */
307
+ get(intentId: string): Promise<PaymentIntent>;
308
+ /**
309
+ * List payment intents
310
+ *
311
+ * @param options - Filter and pagination options
312
+ * @returns Array of payment intents
313
+ *
314
+ * @example
315
+ * ```typescript
316
+ * // Get recent pending intents
317
+ * const intents = await zendfi.intents.list({
318
+ * status: 'requires_payment',
319
+ * limit: 20,
320
+ * });
321
+ * ```
322
+ */
323
+ list(options?: ListIntentsOptions): Promise<PaymentIntent[]>;
324
+ /**
325
+ * Confirm a payment intent
326
+ *
327
+ * This is step 2 of the two-phase payment flow. Confirmation triggers
328
+ * the actual payment using the customer's wallet.
329
+ *
330
+ * @param intentId - UUID of the payment intent
331
+ * @param request - Confirmation details including customer wallet
332
+ * @returns The confirmed payment intent with payment_id
333
+ *
334
+ * @example
335
+ * ```typescript
336
+ * const confirmed = await zendfi.intents.confirm('pi_123...', {
337
+ * client_secret: 'pi_secret_abc...',
338
+ * customer_wallet: 'Hx7B...abc',
339
+ * auto_gasless: true,
340
+ * });
341
+ *
342
+ * if (confirmed.status === 'succeeded') {
343
+ * console.log(`Payment complete: ${confirmed.payment_id}`);
344
+ * }
345
+ * ```
346
+ */
347
+ confirm(intentId: string, request: ConfirmPaymentIntentRequest): Promise<PaymentIntent>;
348
+ /**
349
+ * Cancel a payment intent
350
+ *
351
+ * Canceling releases any hold on the payment amount. Cannot cancel
352
+ * intents that are already processing or succeeded.
353
+ *
354
+ * @param intentId - UUID of the payment intent
355
+ * @returns The canceled payment intent
356
+ *
357
+ * @example
358
+ * ```typescript
359
+ * const canceled = await zendfi.intents.cancel('pi_123...');
360
+ * console.log(`Status: ${canceled.status}`); // "canceled"
361
+ * ```
362
+ */
363
+ cancel(intentId: string): Promise<PaymentIntent>;
364
+ /**
365
+ * Get events for a payment intent
366
+ *
367
+ * Events track the full lifecycle of the intent, including creation,
368
+ * confirmation attempts, and status changes.
369
+ *
370
+ * @param intentId - UUID of the payment intent
371
+ * @returns Array of events in chronological order
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * const events = await zendfi.intents.getEvents('pi_123...');
376
+ * events.forEach(event => {
377
+ * console.log(`${event.created_at}: ${event.event_type}`);
378
+ * });
379
+ * ```
380
+ */
381
+ getEvents(intentId: string): Promise<PaymentIntentEvent[]>;
382
+ }
383
+
384
+ /**
385
+ * Pricing API - Purchasing Power Parity (PPP) and AI-powered pricing
386
+ *
387
+ * Enable global reach with geo-aware pricing that automatically adjusts
388
+ * prices based on the customer's location and purchasing power.
389
+ *
390
+ * @example
391
+ * ```typescript
392
+ * // Get PPP factor for Brazil
393
+ * const factor = await zendfi.pricing.getPPPFactor('BR');
394
+ * console.log(`Brazil: ${factor.adjustment_percentage}% discount suggested`);
395
+ *
396
+ * // Apply PPP to a product price
397
+ * const basePrice = 100;
398
+ * const localPrice = basePrice * factor.ppp_factor;
399
+ * console.log(`$${basePrice} → $${localPrice.toFixed(2)} for Brazilian customers`);
400
+ * ```
401
+ */
402
+
403
+ type RequestFn$2 = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
404
+ declare class PricingAPI {
405
+ private request;
406
+ constructor(request: RequestFn$2);
407
+ /**
408
+ * Get PPP factor for a specific country
409
+ *
410
+ * Returns the purchasing power parity adjustment factor for the given
411
+ * country code. Use this to calculate localized pricing.
412
+ *
413
+ * @param countryCode - ISO 3166-1 alpha-2 country code (e.g., "BR", "IN", "NG")
414
+ * @returns PPP factor and suggested adjustment
415
+ *
416
+ * @example
417
+ * ```typescript
418
+ * const factor = await zendfi.pricing.getPPPFactor('BR');
419
+ * // {
420
+ * // country_code: 'BR',
421
+ * // country_name: 'Brazil',
422
+ * // ppp_factor: 0.35,
423
+ * // currency_code: 'BRL',
424
+ * // adjustment_percentage: 35.0
425
+ * // }
426
+ *
427
+ * // Calculate localized price
428
+ * const usdPrice = 100;
429
+ * const localPrice = usdPrice * (1 - factor.adjustment_percentage / 100);
430
+ * console.log(`$${localPrice} for Brazilian customers`);
431
+ * ```
432
+ */
433
+ getPPPFactor(countryCode: string): Promise<PPPFactor>;
434
+ /**
435
+ * List all available PPP factors
436
+ *
437
+ * Returns PPP factors for all supported countries. Useful for building
438
+ * pricing tables or pre-computing regional prices.
439
+ *
440
+ * @returns Array of PPP factors for all supported countries
441
+ *
442
+ * @example
443
+ * ```typescript
444
+ * const factors = await zendfi.pricing.listFactors();
445
+ *
446
+ * // Create pricing tiers
447
+ * const tiers = factors.map(f => ({
448
+ * country: f.country_name,
449
+ * price: (100 * f.ppp_factor).toFixed(2),
450
+ * }));
451
+ *
452
+ * console.table(tiers);
453
+ * ```
454
+ */
455
+ listFactors(): Promise<PPPFactor[]>;
456
+ /**
457
+ * Get AI-powered pricing suggestion
458
+ *
459
+ * Returns an intelligent pricing recommendation based on the user's
460
+ * location, wallet history, and your pricing configuration.
461
+ *
462
+ * @param request - Pricing suggestion request with user context
463
+ * @returns AI-generated pricing suggestion with reasoning
464
+ *
465
+ * @example
466
+ * ```typescript
467
+ * const suggestion = await zendfi.pricing.getSuggestion({
468
+ * agent_id: 'shopping-assistant',
469
+ * base_price: 99.99,
470
+ * user_profile: {
471
+ * location_country: 'BR',
472
+ * context: 'first-time',
473
+ * },
474
+ * ppp_config: {
475
+ * enabled: true,
476
+ * max_discount_percent: 50,
477
+ * floor_price: 29.99,
478
+ * },
479
+ * });
480
+ *
481
+ * console.log(`Suggested: $${suggestion.suggested_amount}`);
482
+ * console.log(`Reason: ${suggestion.reasoning}`);
483
+ * // => "Price adjusted for Brazilian purchasing power (35% PPP discount)
484
+ * // plus 10% first-time customer discount"
485
+ * ```
486
+ */
487
+ getSuggestion(request: PricingSuggestionRequest): Promise<PricingSuggestion>;
488
+ /**
489
+ * Calculate localized price for a given base price and country
490
+ *
491
+ * Convenience method that combines getPPPFactor with price calculation.
492
+ *
493
+ * @param basePrice - Original price in USD
494
+ * @param countryCode - ISO 3166-1 alpha-2 country code
495
+ * @returns Object with original and adjusted prices
496
+ *
497
+ * @example
498
+ * ```typescript
499
+ * const result = await zendfi.pricing.calculateLocalPrice(100, 'IN');
500
+ * console.log(`Original: $${result.original}`);
501
+ * console.log(`Local: $${result.adjusted}`);
502
+ * console.log(`Savings: $${result.savings} (${result.discount_percentage}%)`);
503
+ * ```
504
+ */
505
+ calculateLocalPrice(basePrice: number, countryCode: string): Promise<{
506
+ original: number;
507
+ adjusted: number;
508
+ savings: number;
509
+ discount_percentage: number;
510
+ country: string;
511
+ ppp_factor: number;
512
+ }>;
513
+ }
514
+
515
+ /**
516
+ * Autonomy API - Enable autonomous agent signing
517
+ *
518
+ * The Autonomy API enables AI agents to make payments without user interaction
519
+ * for each transaction, while maintaining cryptographic security through:
520
+ *
521
+ * 1. **Delegation Signatures** - User signs a message authorizing the agent
522
+ * 2. **Spending Limits** - Hard caps on total spending
523
+ * 3. **Time Bounds** - Automatic expiration
524
+ * 4. **Lit Protocol** (optional) - Threshold cryptography for key management
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * // Enable autonomous mode for a session key
529
+ * const delegate = await zendfi.autonomy.enable({
530
+ * session_key_id: 'sk_123...',
531
+ * max_amount_usd: 100,
532
+ * duration_hours: 24,
533
+ * delegation_signature: signature, // Ed25519 sig from user
534
+ * });
535
+ *
536
+ * // Agent can now make payments automatically
537
+ * console.log(`Delegate active: $${delegate.max_amount_usd} limit`);
538
+ * ```
539
+ */
540
+
541
+ type RequestFn$1 = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
542
+ declare class AutonomyAPI {
543
+ private request;
544
+ constructor(request: RequestFn$1);
545
+ /**
546
+ * Enable autonomous signing for a session key
547
+ *
548
+ * This grants an AI agent the ability to sign transactions on behalf of
549
+ * the user, up to the specified spending limit and duration.
550
+ *
551
+ * **Prerequisites:**
552
+ * 1. Create a device-bound session key first
553
+ * 2. Generate a delegation signature (see `createDelegationMessage`)
554
+ * 3. Optionally encrypt keypair with Lit Protocol for true autonomy
555
+ *
556
+ * @param sessionKeyId - UUID of the session key
557
+ * @param request - Autonomy configuration including delegation signature
558
+ * @returns The created autonomous delegate
559
+ *
560
+ * @example
561
+ * ```typescript
562
+ * // The user must sign this exact message format
563
+ * const message = zendfi.autonomy.createDelegationMessage(
564
+ * sessionKeyId, 100, '2024-12-10T00:00:00Z'
565
+ * );
566
+ *
567
+ * // Have user sign with their session key
568
+ * const signature = await signWithSessionKey(message, pin);
569
+ *
570
+ * // Enable autonomous mode
571
+ * const delegate = await zendfi.autonomy.enable(sessionKeyId, {
572
+ * max_amount_usd: 100,
573
+ * duration_hours: 24,
574
+ * delegation_signature: signature,
575
+ * });
576
+ *
577
+ * console.log(`Delegate ID: ${delegate.delegate_id}`);
578
+ * console.log(`Expires: ${delegate.expires_at}`);
579
+ * ```
580
+ */
581
+ enable(sessionKeyId: string, request: EnableAutonomyRequest): Promise<EnableAutonomyResponse>;
582
+ /**
583
+ * Revoke autonomous mode for a session key
584
+ *
585
+ * Immediately invalidates the autonomous delegate, preventing any further
586
+ * automatic payments. The session key itself remains valid for manual use.
587
+ *
588
+ * @param sessionKeyId - UUID of the session key
589
+ * @param reason - Optional reason for revocation (logged for audit)
590
+ *
591
+ * @example
592
+ * ```typescript
593
+ * await zendfi.autonomy.revoke('sk_123...', 'User requested revocation');
594
+ * console.log('Autonomous mode disabled');
595
+ * ```
596
+ */
597
+ revoke(sessionKeyId: string, reason?: string): Promise<void>;
598
+ /**
599
+ * Get autonomy status for a session key
600
+ *
601
+ * Returns whether autonomous mode is enabled and details about the
602
+ * active delegate including remaining spending allowance.
603
+ *
604
+ * @param sessionKeyId - UUID of the session key
605
+ * @returns Autonomy status with delegate details
606
+ *
607
+ * @example
608
+ * ```typescript
609
+ * const status = await zendfi.autonomy.getStatus('sk_123...');
610
+ *
611
+ * if (status.autonomous_mode_enabled && status.delegate) {
612
+ * console.log(`Remaining: $${status.delegate.remaining_usd}`);
613
+ * console.log(`Expires: ${status.delegate.expires_at}`);
614
+ * } else {
615
+ * console.log('Autonomous mode not enabled');
616
+ * }
617
+ * ```
618
+ */
619
+ getStatus(sessionKeyId: string): Promise<AutonomyStatus>;
620
+ /**
621
+ * Create the delegation message that needs to be signed
622
+ *
623
+ * This generates the exact message format required for the delegation
624
+ * signature. The user must sign this message with their session key.
625
+ *
626
+ * **Message format:**
627
+ * ```
628
+ * I authorize autonomous delegate for session {id} to spend up to ${amount} until {expiry}
629
+ * ```
630
+ *
631
+ * @param sessionKeyId - UUID of the session key
632
+ * @param maxAmountUsd - Maximum spending amount in USD
633
+ * @param expiresAt - ISO 8601 expiration timestamp
634
+ * @returns The message to be signed
635
+ *
636
+ * @example
637
+ * ```typescript
638
+ * const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
639
+ * const message = zendfi.autonomy.createDelegationMessage(
640
+ * 'sk_123...',
641
+ * 100,
642
+ * expiresAt
643
+ * );
644
+ * // => "I authorize autonomous delegate for session sk_123... to spend up to $100 until 2024-12-06T..."
645
+ *
646
+ * // Sign with nacl.sign.detached() or similar
647
+ * const signature = signMessage(message, keypair);
648
+ * ```
649
+ */
650
+ createDelegationMessage(sessionKeyId: string, maxAmountUsd: number, expiresAt: string): string;
651
+ /**
652
+ * Validate delegation signature parameters
653
+ *
654
+ * Helper method to check if autonomy parameters are valid before
655
+ * making the API call.
656
+ *
657
+ * @param request - The enable autonomy request to validate
658
+ * @throws Error if validation fails
659
+ *
660
+ * @example
661
+ * ```typescript
662
+ * try {
663
+ * zendfi.autonomy.validateRequest(request);
664
+ * const delegate = await zendfi.autonomy.enable(sessionKeyId, request);
665
+ * } catch (error) {
666
+ * console.error('Invalid request:', error.message);
667
+ * }
668
+ * ```
669
+ */
670
+ validateRequest(request: EnableAutonomyRequest): void;
671
+ }
672
+
673
+ /**
674
+ * Smart Payments API - AI-powered payment routing
675
+ *
676
+ * Smart payments combine multiple features into a single intelligent API:
677
+ * - Automatic PPP pricing adjustments
678
+ * - Gasless transaction detection
679
+ * - Instant settlement options
680
+ * - Escrow integration
681
+ * - Receipt generation
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * const result = await zendfi.payments.smart({
686
+ * agent_id: 'shopping-assistant',
687
+ * user_wallet: 'Hx7B...abc',
688
+ * amount_usd: 50,
689
+ * auto_detect_gasless: true,
690
+ * description: 'Premium subscription',
691
+ * });
692
+ *
693
+ * console.log(`Payment: ${result.payment_id}`);
694
+ * console.log(`Receipt: ${result.receipt_url}`);
695
+ * ```
696
+ */
697
+
698
+ type RequestFn = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
699
+ declare class SmartPaymentsAPI {
700
+ private request;
701
+ constructor(request: RequestFn);
702
+ /**
703
+ * Execute an AI-powered smart payment
704
+ *
705
+ * Smart payments analyze the context and automatically apply optimizations:
706
+ * - **PPP Pricing**: Auto-adjusts based on customer location
707
+ * - **Gasless**: Detects when user needs gas subsidization
708
+ * - **Instant Settlement**: Optional immediate merchant payout
709
+ * - **Escrow**: Optional fund holding for service delivery
710
+ *
711
+ * @param request - Smart payment request configuration
712
+ * @returns Payment result with status and receipt
713
+ *
714
+ * @example
715
+ * ```typescript
716
+ * // Basic smart payment
717
+ * const result = await zendfi.payments.smart({
718
+ * agent_id: 'my-agent',
719
+ * user_wallet: 'Hx7B...abc',
720
+ * amount_usd: 99.99,
721
+ * description: 'Annual Pro Plan',
722
+ * });
723
+ *
724
+ * // With all options
725
+ * const result = await zendfi.payments.smart({
726
+ * agent_id: 'my-agent',
727
+ * session_token: 'zai_session_...', // For limit enforcement
728
+ * user_wallet: 'Hx7B...abc',
729
+ * amount_usd: 99.99,
730
+ * token: 'USDC',
731
+ * auto_detect_gasless: true,
732
+ * instant_settlement: true,
733
+ * enable_escrow: false,
734
+ * description: 'Annual Pro Plan',
735
+ * product_details: {
736
+ * name: 'Pro Plan',
737
+ * sku: 'PRO-ANNUAL',
738
+ * },
739
+ * metadata: {
740
+ * user_id: 'usr_123',
741
+ * },
742
+ * });
743
+ *
744
+ * if (result.requires_signature) {
745
+ * // Device-bound flow: need user to sign
746
+ * console.log('Please sign:', result.unsigned_transaction);
747
+ * console.log('Submit to:', result.submit_url);
748
+ * } else {
749
+ * // Auto-signed (custodial or autonomous delegate)
750
+ * console.log('Payment complete:', result.transaction_signature);
751
+ * }
752
+ * ```
753
+ */
754
+ execute(request: SmartPaymentRequest): Promise<SmartPaymentResponse>;
755
+ /**
756
+ * Submit a signed transaction from device-bound flow
757
+ *
758
+ * When a smart payment returns `requires_signature: true`, the client
759
+ * must sign the transaction and submit it here.
760
+ *
761
+ * @param paymentId - UUID of the payment
762
+ * @param signedTransaction - Base64 encoded signed transaction
763
+ * @returns Updated payment response
764
+ *
765
+ * @example
766
+ * ```typescript
767
+ * // After user signs the transaction
768
+ * const result = await zendfi.payments.submitSigned(
769
+ * payment.payment_id,
770
+ * signedTransaction
771
+ * );
772
+ *
773
+ * console.log(`Confirmed in ${result.confirmed_in_ms}ms`);
774
+ * ```
775
+ */
776
+ submitSigned(paymentId: string, signedTransaction: string): Promise<SmartPaymentResponse>;
777
+ }
3
778
 
4
779
  /**
5
780
  * ZendFi SDK Client.
@@ -7,6 +782,104 @@ export { q as ApiKeyMode, G as AuthenticationError, M as CreateInstallmentPlanRe
7
782
  */
8
783
  declare class ZendFiClient {
9
784
  private config;
785
+ readonly interceptors: Interceptors;
786
+ /**
787
+ * Agent API - Manage agent API keys and sessions
788
+ *
789
+ * @example
790
+ * ```typescript
791
+ * // Create an agent API key
792
+ * const agentKey = await zendfi.agent.createKey({
793
+ * name: 'Shopping Assistant',
794
+ * agent_id: 'shopping-assistant-v1',
795
+ * scopes: ['create_payments'],
796
+ * });
797
+ *
798
+ * // Create an agent session
799
+ * const session = await zendfi.agent.createSession({
800
+ * agent_id: 'shopping-assistant-v1',
801
+ * user_wallet: 'Hx7B...abc',
802
+ * limits: { max_per_day: 500 },
803
+ * });
804
+ * ```
805
+ */
806
+ readonly agent: AgentAPI;
807
+ /**
808
+ * Payment Intents API - Two-phase payment flow
809
+ *
810
+ * @example
811
+ * ```typescript
812
+ * // Create intent
813
+ * const intent = await zendfi.intents.create({ amount: 99.99 });
814
+ *
815
+ * // Confirm when ready
816
+ * await zendfi.intents.confirm(intent.id, {
817
+ * client_secret: intent.client_secret,
818
+ * customer_wallet: 'Hx7B...abc',
819
+ * });
820
+ * ```
821
+ */
822
+ readonly intents: PaymentIntentsAPI;
823
+ /**
824
+ * Pricing API - PPP and AI-powered pricing
825
+ *
826
+ * @example
827
+ * ```typescript
828
+ * // Get PPP factor for Brazil
829
+ * const factor = await zendfi.pricing.getPPPFactor('BR');
830
+ * const localPrice = 100 * factor.ppp_factor; // $35 for Brazil
831
+ *
832
+ * // Get AI pricing suggestion
833
+ * const suggestion = await zendfi.pricing.getSuggestion({
834
+ * agent_id: 'my-agent',
835
+ * base_price: 100,
836
+ * user_profile: { location_country: 'BR' },
837
+ * });
838
+ * ```
839
+ */
840
+ readonly pricing: PricingAPI;
841
+ /**
842
+ * Autonomy API - Enable autonomous agent signing
843
+ *
844
+ * @example
845
+ * ```typescript
846
+ * // Enable autonomous mode for a session key
847
+ * const delegate = await zendfi.autonomy.enable(sessionKeyId, {
848
+ * max_amount_usd: 100,
849
+ * duration_hours: 24,
850
+ * delegation_signature: signature,
851
+ * });
852
+ *
853
+ * // Check status
854
+ * const status = await zendfi.autonomy.getStatus(sessionKeyId);
855
+ * ```
856
+ */
857
+ readonly autonomy: AutonomyAPI;
858
+ /**
859
+ * Smart Payments API - AI-powered payment routing
860
+ *
861
+ * Create intelligent payments that automatically:
862
+ * - Apply PPP discounts based on user location
863
+ * - Use agent sessions when available
864
+ * - Route to optimal payment paths
865
+ *
866
+ * @example
867
+ * ```typescript
868
+ * const payment = await zendfi.smart.create({
869
+ * amount_usd: 99.99,
870
+ * wallet_address: 'Hx7B...abc',
871
+ * merchant_id: 'merch_123',
872
+ * country_code: 'BR', // Apply PPP
873
+ * enable_ppp: true,
874
+ * });
875
+ *
876
+ * console.log(`Original: $${payment.original_amount_usd}`);
877
+ * console.log(`Final: $${payment.final_amount_usd}`);
878
+ * // Original: $99.99
879
+ * // Final: $64.99 (35% PPP discount applied)
880
+ * ```
881
+ */
882
+ readonly smart: SmartPaymentsAPI;
10
883
  constructor(options?: Partial<ZendFiConfig>);
11
884
  /**
12
885
  * Create a new payment
@@ -144,6 +1017,47 @@ declare class ZendFiClient {
144
1017
  payment_url: string;
145
1018
  status: string;
146
1019
  }>;
1020
+ /**
1021
+ * Execute an AI-powered smart payment
1022
+ *
1023
+ * Smart payments combine multiple features:
1024
+ * - Automatic PPP pricing adjustments
1025
+ * - Gasless transaction detection
1026
+ * - Instant settlement options
1027
+ * - Escrow integration
1028
+ * - Receipt generation
1029
+ *
1030
+ * @param request - Smart payment configuration
1031
+ * @returns Payment result with status and receipt
1032
+ *
1033
+ * @example
1034
+ * ```typescript
1035
+ * const result = await zendfi.smartPayment({
1036
+ * agent_id: 'shopping-assistant',
1037
+ * user_wallet: 'Hx7B...abc',
1038
+ * amount_usd: 50,
1039
+ * auto_detect_gasless: true,
1040
+ * description: 'Premium subscription',
1041
+ * });
1042
+ *
1043
+ * if (result.requires_signature) {
1044
+ * // Device-bound flow: user needs to sign
1045
+ * console.log('Sign and submit:', result.submit_url);
1046
+ * } else {
1047
+ * // Auto-signed
1048
+ * console.log('Payment complete:', result.transaction_signature);
1049
+ * }
1050
+ * ```
1051
+ */
1052
+ smartPayment(request: SmartPaymentRequest): Promise<SmartPaymentResponse>;
1053
+ /**
1054
+ * Submit a signed transaction for device-bound smart payment
1055
+ *
1056
+ * @param paymentId - UUID of the payment
1057
+ * @param signedTransaction - Base64 encoded signed transaction
1058
+ * @returns Updated payment response
1059
+ */
1060
+ submitSignedPayment(paymentId: string, signedTransaction: string): Promise<SmartPaymentResponse>;
147
1061
  /**
148
1062
  * Verify webhook signature using HMAC-SHA256
149
1063
  *
@@ -174,7 +1088,7 @@ declare class ZendFiClient {
174
1088
  */
175
1089
  private timingSafeEqual;
176
1090
  /**
177
- * Make an HTTP request with retry logic
1091
+ * Make an HTTP request with retry logic, interceptors, and debug logging
178
1092
  */
179
1093
  private request;
180
1094
  }
@@ -223,6 +1137,72 @@ declare class ConfigLoader {
223
1137
  */
224
1138
  static validateApiKey(apiKey: string): void;
225
1139
  }
1140
+ /**
1141
+ * Generate idempotency key
1142
+ */
1143
+ declare function generateIdempotencyKey(): string;
1144
+ /**
1145
+ * Sleep utility for retry backoff
1146
+ */
1147
+ declare function sleep(ms: number): Promise<void>;
1148
+ /**
1149
+ * Client-side rate limiter to prevent hitting API rate limits
1150
+ *
1151
+ * @example
1152
+ * ```typescript
1153
+ * const limiter = new RateLimiter({
1154
+ * maxRequests: 100,
1155
+ * windowMs: 60000, // 100 requests per minute
1156
+ * });
1157
+ *
1158
+ * if (limiter.canMakeRequest()) {
1159
+ * limiter.recordRequest();
1160
+ * await zendfi.createPayment({ amount: 50 });
1161
+ * } else {
1162
+ * const waitTime = limiter.getTimeUntilReset();
1163
+ * console.log(`Rate limited. Try again in ${waitTime}ms`);
1164
+ * }
1165
+ * ```
1166
+ */
1167
+ declare class RateLimiter {
1168
+ private requests;
1169
+ private maxRequests;
1170
+ private windowMs;
1171
+ constructor(options?: {
1172
+ maxRequests?: number;
1173
+ windowMs?: number;
1174
+ });
1175
+ /**
1176
+ * Check if a request can be made without exceeding rate limit
1177
+ */
1178
+ canMakeRequest(): boolean;
1179
+ /**
1180
+ * Record a request timestamp
1181
+ */
1182
+ recordRequest(): void;
1183
+ /**
1184
+ * Get remaining requests in current window
1185
+ */
1186
+ getRemainingRequests(): number;
1187
+ /**
1188
+ * Get time in ms until the rate limit window resets
1189
+ */
1190
+ getTimeUntilReset(): number;
1191
+ /**
1192
+ * Get current rate limit status
1193
+ */
1194
+ getStatus(): {
1195
+ remaining: number;
1196
+ limit: number;
1197
+ resetInMs: number;
1198
+ isLimited: boolean;
1199
+ };
1200
+ /**
1201
+ * Reset the rate limiter (useful for testing)
1202
+ */
1203
+ reset(): void;
1204
+ private pruneOldRequests;
1205
+ }
226
1206
 
227
1207
  /**
228
1208
  * Webhook Verification Helpers
@@ -295,4 +1275,673 @@ declare function verifyExpressWebhook(request: any, secret?: string): Promise<We
295
1275
  */
296
1276
  declare function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean;
297
1277
 
298
- export { ApproveEscrowRequest, ConfigLoader, CreateEscrowRequest, CreateInstallmentPlanRequest, CreateInvoiceRequest, CreatePaymentLinkRequest, CreatePaymentRequest, CreateSubscriptionPlanRequest, CreateSubscriptionRequest, DisputeEscrowRequest, Escrow, InstallmentPlan, Invoice, ListPaymentsRequest, PaginatedResponse, Payment, PaymentLink, RefundEscrowRequest, Subscription, SubscriptionPlan, VerifyWebhookRequest, WebhookPayload, ZendFiClient, ZendFiConfig, verifyExpressWebhook, verifyNextWebhook, verifyWebhookSignature, zendfi };
1278
+ /**
1279
+ * ZendFi SDK Error Classes
1280
+ *
1281
+ * Custom error types with helpful messages, error codes, and documentation links
1282
+ */
1283
+ type ZendFiErrorType = 'authentication_error' | 'payment_error' | 'validation_error' | 'network_error' | 'rate_limit_error' | 'api_error' | 'webhook_error' | 'unknown_error';
1284
+ interface ZendFiErrorData {
1285
+ code: string;
1286
+ message: string;
1287
+ type: ZendFiErrorType;
1288
+ suggestion?: string;
1289
+ statusCode?: number;
1290
+ response?: unknown;
1291
+ }
1292
+ /**
1293
+ * Base ZendFi Error class with enhanced developer experience
1294
+ */
1295
+ declare class ZendFiError extends Error {
1296
+ readonly code: string;
1297
+ readonly type: ZendFiErrorType;
1298
+ readonly suggestion?: string;
1299
+ readonly docs_url: string;
1300
+ readonly statusCode?: number;
1301
+ readonly response?: unknown;
1302
+ constructor(data: ZendFiErrorData);
1303
+ /**
1304
+ * Format error for display
1305
+ */
1306
+ toString(): string;
1307
+ /**
1308
+ * Convert error to JSON
1309
+ */
1310
+ toJSON(): Record<string, unknown>;
1311
+ }
1312
+ /**
1313
+ * Authentication errors
1314
+ */
1315
+ declare class AuthenticationError extends ZendFiError {
1316
+ constructor(message: string, code?: string, suggestion?: string);
1317
+ }
1318
+ /**
1319
+ * Payment processing errors
1320
+ */
1321
+ declare class PaymentError extends ZendFiError {
1322
+ constructor(message: string, code?: string, suggestion?: string);
1323
+ }
1324
+ /**
1325
+ * Validation errors
1326
+ */
1327
+ declare class ValidationError extends ZendFiError {
1328
+ constructor(message: string, code?: string, suggestion?: string);
1329
+ }
1330
+ /**
1331
+ * Network/connection errors
1332
+ */
1333
+ declare class NetworkError extends ZendFiError {
1334
+ constructor(message: string, code?: string, suggestion?: string);
1335
+ }
1336
+ /**
1337
+ * Rate limit errors
1338
+ */
1339
+ declare class RateLimitError extends ZendFiError {
1340
+ constructor(message: string, retryAfter?: number);
1341
+ }
1342
+ /**
1343
+ * Generic API errors
1344
+ */
1345
+ declare class ApiError extends ZendFiError {
1346
+ constructor(message: string, code: string, statusCode: number, response?: unknown);
1347
+ }
1348
+ /**
1349
+ * Webhook verification errors
1350
+ */
1351
+ declare class WebhookError extends ZendFiError {
1352
+ constructor(message: string, code?: string, suggestion?: string);
1353
+ }
1354
+ /**
1355
+ * Error factory - creates appropriate error based on response
1356
+ */
1357
+ declare function createZendFiError(statusCode: number, responseBody: any, message?: string): ZendFiError;
1358
+ /**
1359
+ * Common error codes and their messages
1360
+ */
1361
+ declare const ERROR_CODES: {
1362
+ readonly INVALID_API_KEY: "invalid_api_key";
1363
+ readonly API_KEY_EXPIRED: "api_key_expired";
1364
+ readonly API_KEY_REVOKED: "api_key_revoked";
1365
+ readonly INSUFFICIENT_BALANCE: "insufficient_balance";
1366
+ readonly PAYMENT_DECLINED: "payment_declined";
1367
+ readonly PAYMENT_EXPIRED: "payment_expired";
1368
+ readonly INVALID_AMOUNT: "invalid_amount";
1369
+ readonly INVALID_CURRENCY: "invalid_currency";
1370
+ readonly MISSING_REQUIRED_FIELD: "missing_required_field";
1371
+ readonly INVALID_PARAMETER: "invalid_parameter";
1372
+ readonly NETWORK_ERROR: "network_error";
1373
+ readonly TIMEOUT: "timeout";
1374
+ readonly RATE_LIMIT_EXCEEDED: "rate_limit_exceeded";
1375
+ readonly WEBHOOK_SIGNATURE_INVALID: "webhook_signature_invalid";
1376
+ readonly WEBHOOK_TIMESTAMP_TOO_OLD: "webhook_timestamp_too_old";
1377
+ };
1378
+ /**
1379
+ * Helper to check if error is a ZendFi error
1380
+ */
1381
+ declare function isZendFiError(error: unknown): error is ZendFiError;
1382
+
1383
+ /**
1384
+ * Device-Bound Session Keys - Client-Side Cryptography
1385
+ *
1386
+ * This module provides TRUE non-custodial session keys where:
1387
+ * - Client generates keypair (backend NEVER sees private key)
1388
+ * - Client encrypts with PIN + device fingerprint
1389
+ * - Backend stores encrypted blob (cannot decrypt!)
1390
+ * - Client decrypts for each payment
1391
+ *
1392
+ * Security: Argon2id key derivation + AES-256-GCM encryption
1393
+ *
1394
+ * @module device-bound-crypto
1395
+ */
1396
+
1397
+ interface DeviceFingerprint {
1398
+ /** SHA-256 hash of device attributes */
1399
+ fingerprint: string;
1400
+ /** Timestamp when fingerprint was generated */
1401
+ generatedAt: number;
1402
+ /** Raw components (for debugging) */
1403
+ components: {
1404
+ canvas?: string;
1405
+ webgl?: string;
1406
+ audio?: string;
1407
+ screen?: string;
1408
+ timezone?: string;
1409
+ languages?: string;
1410
+ platform?: string;
1411
+ hardwareConcurrency?: string;
1412
+ };
1413
+ }
1414
+ interface EncryptedSessionKey {
1415
+ /** Base64 encoded encrypted private key */
1416
+ encryptedData: string;
1417
+ /** Base64 encoded nonce (12 bytes) */
1418
+ nonce: string;
1419
+ /** Solana public key (base58) */
1420
+ publicKey: string;
1421
+ /** Device fingerprint hash */
1422
+ deviceFingerprint: string;
1423
+ /** Encryption algorithm version */
1424
+ version: 'argon2id-aes256gcm-v1';
1425
+ }
1426
+ interface RecoveryQR {
1427
+ /** Base64 encoded encrypted session key */
1428
+ encryptedSessionKey: string;
1429
+ /** Base64 encoded nonce */
1430
+ nonce: string;
1431
+ /** Public key */
1432
+ publicKey: string;
1433
+ /** Recovery QR version */
1434
+ version: string;
1435
+ /** Timestamp */
1436
+ createdAt: number;
1437
+ }
1438
+ interface DeviceBoundSessionKeyOptions {
1439
+ /** 6-digit numeric PIN */
1440
+ pin: string;
1441
+ /** Spending limit in USD */
1442
+ limitUSDC: number;
1443
+ /** Duration in days */
1444
+ durationDays: number;
1445
+ /** User's wallet address */
1446
+ userWallet: string;
1447
+ /** Generate recovery QR (recommended) */
1448
+ generateRecoveryQR?: boolean;
1449
+ }
1450
+ declare class DeviceFingerprintGenerator {
1451
+ /**
1452
+ * Generate a unique device fingerprint
1453
+ * Combines multiple browser attributes for uniqueness
1454
+ */
1455
+ static generate(): Promise<DeviceFingerprint>;
1456
+ /**
1457
+ * Graceful fallback fingerprint generation
1458
+ * Works in headless browsers, SSR, and restricted environments
1459
+ */
1460
+ private static generateFallbackFingerprint;
1461
+ private static getCanvasFingerprint;
1462
+ private static getWebGLFingerprint;
1463
+ private static getAudioFingerprint;
1464
+ private static sha256;
1465
+ }
1466
+ declare class SessionKeyCrypto {
1467
+ /**
1468
+ * Encrypt a Solana keypair with PIN + device fingerprint
1469
+ * Uses Argon2id for key derivation and AES-256-GCM for encryption
1470
+ */
1471
+ static encrypt(keypair: Keypair, pin: string, deviceFingerprint: string): Promise<EncryptedSessionKey>;
1472
+ /**
1473
+ * Decrypt an encrypted session key with PIN + device fingerprint
1474
+ */
1475
+ static decrypt(encrypted: EncryptedSessionKey, pin: string, deviceFingerprint: string): Promise<Keypair>;
1476
+ /**
1477
+ * Derive encryption key from PIN + device fingerprint using Argon2id
1478
+ *
1479
+ * Argon2id parameters (OWASP recommended):
1480
+ * - Memory: 64MB (65536 KB)
1481
+ * - Iterations: 3
1482
+ * - Parallelism: 4
1483
+ * - Salt: device fingerprint
1484
+ */
1485
+ private static deriveKey;
1486
+ /**
1487
+ * Generate random nonce for AES-GCM (12 bytes)
1488
+ */
1489
+ private static generateNonce;
1490
+ /**
1491
+ * Encrypt with AES-256-GCM
1492
+ */
1493
+ private static aesEncrypt;
1494
+ /**
1495
+ * Decrypt with AES-256-GCM
1496
+ */
1497
+ private static aesDecrypt;
1498
+ }
1499
+ declare class RecoveryQRGenerator {
1500
+ /**
1501
+ * Generate recovery QR data
1502
+ * This allows users to recover their session key on a new device
1503
+ */
1504
+ static generate(encrypted: EncryptedSessionKey): RecoveryQR;
1505
+ /**
1506
+ * Encode recovery QR as JSON string
1507
+ */
1508
+ static encode(recoveryQR: RecoveryQR): string;
1509
+ /**
1510
+ * Decode recovery QR from JSON string
1511
+ */
1512
+ static decode(qrData: string): RecoveryQR;
1513
+ /**
1514
+ * Re-encrypt session key for new device
1515
+ */
1516
+ static reEncryptForNewDevice(recoveryQR: RecoveryQR, oldPin: string, oldDeviceFingerprint: string, newPin: string, newDeviceFingerprint: string): Promise<EncryptedSessionKey>;
1517
+ }
1518
+ declare class DeviceBoundSessionKey {
1519
+ private encrypted;
1520
+ private deviceFingerprint;
1521
+ private sessionKeyId;
1522
+ private recoveryQR;
1523
+ private cachedKeypair;
1524
+ private cacheExpiry;
1525
+ private readonly DEFAULT_CACHE_TTL_MS;
1526
+ /**
1527
+ * Create a new device-bound session key
1528
+ */
1529
+ static create(options: DeviceBoundSessionKeyOptions): Promise<DeviceBoundSessionKey>;
1530
+ /**
1531
+ * Get encrypted data for backend storage
1532
+ */
1533
+ getEncryptedData(): EncryptedSessionKey;
1534
+ /**
1535
+ * Get device fingerprint
1536
+ */
1537
+ getDeviceFingerprint(): string;
1538
+ /**
1539
+ * Get public key
1540
+ */
1541
+ getPublicKey(): string;
1542
+ /**
1543
+ * Get recovery QR data (if generated)
1544
+ */
1545
+ getRecoveryQR(): RecoveryQR | null;
1546
+ /**
1547
+ * Decrypt and sign a transaction
1548
+ *
1549
+ * @param transaction - The transaction to sign
1550
+ * @param pin - User's PIN (required only if keypair not cached)
1551
+ * @param cacheKeypair - Whether to cache the decrypted keypair for future use (default: true)
1552
+ * @param cacheTTL - Cache time-to-live in milliseconds (default: 30 minutes)
1553
+ *
1554
+ * @example
1555
+ * ```typescript
1556
+ * // First payment: requires PIN, caches keypair
1557
+ * await sessionKey.signTransaction(tx1, '123456', true);
1558
+ *
1559
+ * // Subsequent payments: uses cached keypair, no PIN needed!
1560
+ * await sessionKey.signTransaction(tx2, '', false); // PIN ignored if cached
1561
+ *
1562
+ * // Clear cache when done
1563
+ * sessionKey.clearCache();
1564
+ * ```
1565
+ */
1566
+ signTransaction(transaction: Transaction, pin?: string, cacheKeypair?: boolean, cacheTTL?: number): Promise<Transaction>;
1567
+ /**
1568
+ * Check if keypair is cached and valid
1569
+ */
1570
+ isCached(): boolean;
1571
+ /**
1572
+ * Manually cache a keypair
1573
+ * Called internally after PIN decryption
1574
+ */
1575
+ private cacheKeypair;
1576
+ /**
1577
+ * Clear cached keypair
1578
+ * Should be called when user logs out or session ends
1579
+ *
1580
+ * @example
1581
+ * ```typescript
1582
+ * // Clear cache on logout
1583
+ * sessionKey.clearCache();
1584
+ *
1585
+ * // Or clear automatically on tab close
1586
+ * window.addEventListener('beforeunload', () => {
1587
+ * sessionKey.clearCache();
1588
+ * });
1589
+ * ```
1590
+ */
1591
+ clearCache(): void;
1592
+ /**
1593
+ * Decrypt and cache keypair without signing a transaction
1594
+ * Useful for pre-warming the cache before user makes payments
1595
+ *
1596
+ * @example
1597
+ * ```typescript
1598
+ * // After session key creation, decrypt and cache
1599
+ * await sessionKey.unlockWithPin('123456');
1600
+ *
1601
+ * // Now all subsequent payments are instant (no PIN)
1602
+ * await sessionKey.signTransaction(tx1, '', false); // Instant!
1603
+ * await sessionKey.signTransaction(tx2, '', false); // Instant!
1604
+ * ```
1605
+ */
1606
+ unlockWithPin(pin: string, cacheTTL?: number): Promise<void>;
1607
+ /**
1608
+ * Get time remaining until cache expires (in milliseconds)
1609
+ * Returns 0 if not cached
1610
+ */
1611
+ getCacheTimeRemaining(): number;
1612
+ /**
1613
+ * Extend cache expiry time
1614
+ * Useful to keep session active during user activity
1615
+ *
1616
+ * @example
1617
+ * ```typescript
1618
+ * // Extend cache by 15 minutes on each payment
1619
+ * await sessionKey.signTransaction(tx, '');
1620
+ * sessionKey.extendCache(15 * 60 * 1000);
1621
+ * ```
1622
+ */
1623
+ extendCache(additionalTTL: number): void;
1624
+ /**
1625
+ * Set session key ID after backend creation
1626
+ */
1627
+ setSessionKeyId(id: string): void;
1628
+ /**
1629
+ * Get session key ID
1630
+ */
1631
+ getSessionKeyId(): string;
1632
+ }
1633
+
1634
+ /**
1635
+ * Device-Bound Session Keys - SDK Integration
1636
+ *
1637
+ * High-level API for managing non-custodial session keys
1638
+ * Integrates with ZendFi backend API
1639
+ *
1640
+ * @module device-bound-session-keys
1641
+ */
1642
+
1643
+ interface CreateDeviceBoundSessionKeyRequest {
1644
+ userWallet: string;
1645
+ limitUsdc: number;
1646
+ durationDays: number;
1647
+ encryptedSessionKey: string;
1648
+ nonce: string;
1649
+ sessionPublicKey: string;
1650
+ deviceFingerprint: string;
1651
+ recoveryQrData?: string;
1652
+ }
1653
+ interface CreateDeviceBoundSessionKeyResponse {
1654
+ sessionKeyId: string;
1655
+ mode: 'device_bound';
1656
+ isCustodial: false;
1657
+ userWallet: string;
1658
+ sessionWallet: string;
1659
+ limitUsdc: number;
1660
+ expiresAt: string;
1661
+ requiresClientSigning: true;
1662
+ securityInfo: {
1663
+ encryptionType: string;
1664
+ deviceBound: boolean;
1665
+ backendCanDecrypt: boolean;
1666
+ recoveryQrSaved: boolean;
1667
+ };
1668
+ }
1669
+ interface SessionKeyPaymentRequest {
1670
+ amount: number;
1671
+ recipient: string;
1672
+ token?: string;
1673
+ description?: string;
1674
+ pin?: string;
1675
+ enableAutoSign?: boolean;
1676
+ }
1677
+ declare class ZendFiSessionKeyManager {
1678
+ private baseURL;
1679
+ private apiKey;
1680
+ private sessionKey;
1681
+ private sessionKeyId;
1682
+ constructor(apiKey: string, baseURL?: string);
1683
+ /**
1684
+ * Create a new device-bound session key
1685
+ *
1686
+ * @example
1687
+ * ```typescript
1688
+ * const manager = new ZendFiSessionKeyManager('your-api-key');
1689
+ *
1690
+ * const sessionKey = await manager.createSessionKey({
1691
+ * userWallet: '7xKNH....',
1692
+ * limitUSDC: 100,
1693
+ * durationDays: 7,
1694
+ * pin: '123456',
1695
+ * generateRecoveryQR: true,
1696
+ * });
1697
+ *
1698
+ * console.log('Session key created:', sessionKey.sessionKeyId);
1699
+ * console.log('Recovery QR:', sessionKey.recoveryQR);
1700
+ * ```
1701
+ */
1702
+ createSessionKey(options: {
1703
+ userWallet: string;
1704
+ limitUSDC: number;
1705
+ durationDays: number;
1706
+ pin: string;
1707
+ generateRecoveryQR?: boolean;
1708
+ }): Promise<{
1709
+ sessionKeyId: string;
1710
+ sessionWallet: string;
1711
+ expiresAt: string;
1712
+ recoveryQR?: string;
1713
+ limitUsdc: number;
1714
+ }>;
1715
+ /**
1716
+ * Load an existing session key from backend
1717
+ * Requires PIN to decrypt
1718
+ */
1719
+ loadSessionKey(sessionKeyId: string, pin: string): Promise<void>;
1720
+ /**
1721
+ * Make a payment using the session key
1722
+ *
1723
+ * First payment: Requires PIN to decrypt session key
1724
+ * Subsequent payments: Uses cached keypair (no PIN needed!) ✨
1725
+ *
1726
+ * @example
1727
+ * ```typescript
1728
+ * // First payment: requires PIN
1729
+ * const result1 = await manager.makePayment({
1730
+ * amount: 5.0,
1731
+ * recipient: '7xKNH....',
1732
+ * pin: '123456',
1733
+ * description: 'Coffee purchase',
1734
+ * });
1735
+ *
1736
+ * // Second payment: NO PIN NEEDED! Instant signing!
1737
+ * const result2 = await manager.makePayment({
1738
+ * amount: 3.0,
1739
+ * recipient: '7xKNH....',
1740
+ * description: 'Donut purchase',
1741
+ * }); // <- No PIN! Uses cached keypair
1742
+ *
1743
+ * console.log('Payment signature:', result2.signature);
1744
+ *
1745
+ * // Disable auto-signing for single payment
1746
+ * const result3 = await manager.makePayment({
1747
+ * amount: 100.0,
1748
+ * recipient: '7xKNH....',
1749
+ * pin: '123456',
1750
+ * enableAutoSign: false, // Will require PIN every time
1751
+ * });
1752
+ * ```
1753
+ */
1754
+ makePayment(options: SessionKeyPaymentRequest): Promise<{
1755
+ paymentId: string;
1756
+ signature: string;
1757
+ status: string;
1758
+ }>;
1759
+ /**
1760
+ * Recover session key on new device
1761
+ * Requires recovery QR and PIN from original device
1762
+ *
1763
+ * @example
1764
+ * ```typescript
1765
+ * const recovered = await manager.recoverSessionKey({
1766
+ * sessionKeyId: 'uuid...',
1767
+ * recoveryQR: '{"encryptedSessionKey":"..."}',
1768
+ * oldPin: '123456',
1769
+ * newPin: '654321',
1770
+ * });
1771
+ * ```
1772
+ */
1773
+ recoverSessionKey(options: {
1774
+ sessionKeyId: string;
1775
+ recoveryQR: string;
1776
+ oldPin: string;
1777
+ newPin: string;
1778
+ }): Promise<void>;
1779
+ /**
1780
+ * Revoke session key
1781
+ */
1782
+ revokeSessionKey(sessionKeyId?: string): Promise<void>;
1783
+ /**
1784
+ * Unlock session key with PIN and cache for auto-signing
1785
+ * Call this after creating/loading session key to enable instant payments
1786
+ *
1787
+ * @example
1788
+ * ```typescript
1789
+ * // Create session key
1790
+ * await manager.createSessionKey({...});
1791
+ *
1792
+ * // Unlock with PIN (one-time)
1793
+ * await manager.unlockSessionKey('123456');
1794
+ *
1795
+ * // Now all payments are instant (no PIN!)
1796
+ * await manager.makePayment({amount: 5, ...}); // Instant!
1797
+ * await manager.makePayment({amount: 3, ...}); // Instant!
1798
+ * ```
1799
+ */
1800
+ unlockSessionKey(pin: string, cacheTTL?: number): Promise<void>;
1801
+ /**
1802
+ * Clear cached keypair
1803
+ * Should be called on logout or when session ends
1804
+ *
1805
+ * @example
1806
+ * ```typescript
1807
+ * // Clear on logout
1808
+ * manager.clearCache();
1809
+ *
1810
+ * // Or auto-clear on tab close
1811
+ * window.addEventListener('beforeunload', () => {
1812
+ * manager.clearCache();
1813
+ * });
1814
+ * ```
1815
+ */
1816
+ clearCache(): void;
1817
+ /**
1818
+ * Check if keypair is cached (auto-signing enabled)
1819
+ */
1820
+ isCached(): boolean;
1821
+ /**
1822
+ * Get time remaining until cache expires (in milliseconds)
1823
+ */
1824
+ getCacheTimeRemaining(): number;
1825
+ /**
1826
+ * Extend cache expiry time
1827
+ * Useful to keep session active during user activity
1828
+ */
1829
+ extendCache(additionalTTL: number): void;
1830
+ /**
1831
+ * Get session key status
1832
+ */
1833
+ getStatus(sessionKeyId?: string): Promise<{
1834
+ isActive: boolean;
1835
+ isApproved: boolean;
1836
+ limitUsdc: number;
1837
+ usedAmountUsdc: number;
1838
+ remainingUsdc: number;
1839
+ expiresAt: string;
1840
+ daysUntilExpiry: number;
1841
+ }>;
1842
+ private request;
1843
+ }
1844
+
1845
+ /**
1846
+ * Lit Protocol PKP Session Identity Module
1847
+ *
1848
+ * ⚠️ STATUS: EXPERIMENTAL / AUDIT TRAIL ONLY
1849
+ *
1850
+ * This module provides client-side integration with Lit Protocol for
1851
+ * on-chain session identity. When a session has `mint_pkp: true`,
1852
+ * a PKP (Programmable Key Pair) is minted to create a blockchain-verified
1853
+ * session identity for audit and compliance purposes.
1854
+ *
1855
+ * ## Current Limitations
1856
+ *
1857
+ * **PKP Cannot Sign Solana Transactions**: Due to ECDSA vs Ed25519
1858
+ * incompatibility, PKPs cannot directly sign Solana transactions.
1859
+ * The PKP serves as an IDENTITY ANCHOR and AUDIT TRAIL only.
1860
+ *
1861
+ * **Spending Limits Are Server-Side**: All spending limit enforcement
1862
+ * happens in the backend via `validate_session_and_check_limits()`.
1863
+ * The PKP does NOT enforce spending limits cryptographically.
1864
+ *
1865
+ * ## What PKP Provides
1866
+ *
1867
+ * 1. **On-chain Identity**: Verifiable session identity on Lit Protocol
1868
+ * 2. **Audit Trail**: Immutable record of session creation
1869
+ * 3. **Future Extensibility**: Foundation for cross-chain identity
1870
+ *
1871
+ * ## Future Roadmap
1872
+ *
1873
+ * - Cross-chain identity verification
1874
+ * - Solana Ed25519 support in Lit Actions (pending Lit Protocol update)
1875
+ * - Decentralized spending limit enforcement
1876
+ *
1877
+ * @example
1878
+ * ```typescript
1879
+ * import { LitCryptoSigner, requiresLitSigning } from '@zendfi/sdk';
1880
+ *
1881
+ * // Check if session has PKP identity
1882
+ * if (session.mint_pkp) {
1883
+ * console.log('Session has on-chain identity:', session.pkp_address);
1884
+ * // Note: This is for audit purposes only, not for signing
1885
+ * }
1886
+ *
1887
+ * // Spending limits are enforced server-side automatically
1888
+ * // No client-side PKP interaction needed for payments
1889
+ * ```
1890
+ *
1891
+ * @module lit-crypto-signer
1892
+ * @experimental
1893
+ */
1894
+ declare const SPENDING_LIMIT_ACTION_CID = "QmXXunoMeNhXhnr4onzBuvnMzDqH8rf1qdM94RKXayypX3";
1895
+ type LitNetwork = 'datil' | 'datil-test' | 'datil-dev';
1896
+ interface LitCryptoSignerConfig {
1897
+ network?: LitNetwork;
1898
+ apiEndpoint?: string;
1899
+ apiKey?: string;
1900
+ debug?: boolean;
1901
+ }
1902
+ interface SignPaymentParams {
1903
+ sessionId: string;
1904
+ amountUsd: number;
1905
+ transactionToSign: string;
1906
+ pkpPublicKey: string;
1907
+ merchantId?: string;
1908
+ sessionSigs?: any;
1909
+ }
1910
+ interface SignPaymentResult {
1911
+ success: boolean;
1912
+ signature?: string;
1913
+ publicKey?: string;
1914
+ recid?: number;
1915
+ sessionId?: string;
1916
+ amountUsd?: number;
1917
+ remainingBudget?: number;
1918
+ cryptoEnforced: boolean;
1919
+ error?: string;
1920
+ code?: string;
1921
+ currentSpent?: number;
1922
+ limit?: number;
1923
+ remaining?: number;
1924
+ }
1925
+ declare class LitCryptoSigner {
1926
+ private config;
1927
+ private litNodeClient;
1928
+ private connected;
1929
+ constructor(config?: LitCryptoSignerConfig);
1930
+ connect(): Promise<void>;
1931
+ disconnect(): Promise<void>;
1932
+ signPayment(params: SignPaymentParams): Promise<SignPaymentResult>;
1933
+ private getSessionSigs;
1934
+ private log;
1935
+ }
1936
+ /**
1937
+ * Helper function to check if a session has PKP identity
1938
+ * @deprecated Spending limits are enforced server-side. This checks for audit trail only.
1939
+ */
1940
+ declare function requiresLitSigning(session: {
1941
+ crypto_enforced?: boolean;
1942
+ mint_pkp?: boolean;
1943
+ }): boolean;
1944
+ declare function encodeTransactionForLit(transaction: Uint8Array | Buffer): string;
1945
+ declare function decodeSignatureFromLit(result: SignPaymentResult): Uint8Array | null;
1946
+
1947
+ export { AgentAPI, AgentAnalytics, AgentApiKey, AgentSession, ApiError, ApproveEscrowRequest, AuthenticationError, AutonomyAPI, AutonomyStatus, ConfigLoader, ConfirmPaymentIntentRequest, CreateAgentApiKeyRequest, CreateAgentSessionRequest, type CreateDeviceBoundSessionKeyRequest, type CreateDeviceBoundSessionKeyResponse, CreateEscrowRequest, CreateInstallmentPlanRequest, CreateInvoiceRequest, CreatePaymentIntentRequest, CreatePaymentLinkRequest, CreatePaymentRequest, CreateSubscriptionPlanRequest, CreateSubscriptionRequest, DeviceBoundSessionKey, type DeviceBoundSessionKeyOptions, DeviceFingerprintGenerator, DisputeEscrowRequest, ERROR_CODES, EnableAutonomyRequest, EnableAutonomyResponse, type EncryptedSessionKey, type ErrorInterceptor, Escrow, InstallmentPlan, InterceptorManager, type Interceptors, Invoice, ListPaymentsRequest, LitCryptoSigner, type LitCryptoSignerConfig, type LitNetwork, NetworkError, PPPFactor, PaginatedResponse, Payment, PaymentError, PaymentIntent, PaymentIntentEvent, PaymentIntentsAPI, PaymentLink, PricingAPI, PricingSuggestion, PricingSuggestionRequest, RateLimitError, RateLimiter, type RecoveryQR, RecoveryQRGenerator, RefundEscrowRequest, type RequestConfig, type RequestInterceptor, type ResponseData, type ResponseInterceptor, SPENDING_LIMIT_ACTION_CID, SessionKeyCrypto, type SessionKeyPaymentRequest, type SignPaymentParams, type SignPaymentResult, SmartPaymentRequest, SmartPaymentResponse, SmartPaymentsAPI, Subscription, SubscriptionPlan, ValidationError, VerifyWebhookRequest, WebhookError, WebhookPayload, ZendFiClient, ZendFiConfig, ZendFiError, type ZendFiErrorData, type ZendFiErrorType, ZendFiSessionKeyManager, createZendFiError, decodeSignatureFromLit, encodeTransactionForLit, generateIdempotencyKey, isZendFiError, requiresLitSigning, sleep, verifyExpressWebhook, verifyNextWebhook, verifyWebhookSignature, zendfi };