@zendfi/sdk 0.7.4 → 0.8.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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { C as CreateAgentApiKeyRequest, A as AgentApiKey, b as CreateAgentSessionRequest, c as AgentSession, d as AgentPaymentRequest, e as AgentPaymentResponse, f as AgentAnalytics, g as CreatePaymentIntentRequest, P as PaymentIntent, h as ConfirmPaymentIntentRequest, i as PaymentIntentEvent, j as PPPFactor, k as PricingSuggestionRequest, l as PricingSuggestion, E as EnableAutonomyRequest, m as EnableAutonomyResponse, n as AutonomyStatus, S as SmartPaymentRequest, o as SmartPaymentResponse, p as CreateSessionKeyRequest, q as CreateSessionKeyResponse, r as CreateDeviceBoundSessionKeyRequest$1, s as CreateDeviceBoundSessionKeyResponse$1, t as SubmitSignedTransactionRequest, u as SubmitTransactionResponse, v as SessionKeyStatus, w as SessionKeyListResponse, T as TopUpSessionKeyRequest, x as TopUpSessionKeyResponse, Z as ZendFiConfig, y as CreatePaymentRequest, z as Payment, L as ListPaymentsRequest, B as PaginatedResponse, D as CreateSubscriptionPlanRequest, F as SubscriptionPlan, G as CreateSubscriptionRequest, H as Subscription, I as CreatePaymentLinkRequest, J as PaymentLink, K as CreateInstallmentPlanRequest, M as InstallmentPlan, N as CreateEscrowRequest, O as Escrow, Q as ApproveEscrowRequest, R as RefundEscrowRequest, U as DisputeEscrowRequest, V as CreateInvoiceRequest, X as Invoice, Y as VerifyWebhookRequest, _ as WebhookPayload, $ as ApiKeyMode } from './webhook-handler-D5INiR-l.js';
2
- export { a6 as AgentKeyId, aD as ApiKeyScope, aJ as AutonomousDelegate, a3 as Brand, aG as CaptureMethod, aA as CreateInstallmentPlanResponse, ap as Currency, ao as Environment, aa as EscrowId, au as EscrowStatus, ab as InstallmentPlanId, at as InstallmentPlanStatus, az as InstallmentScheduleItem, ad as IntentId, a8 as InvoiceId, aC as InvoiceLineItem, av as InvoiceStatus, aO as LinkedSessionInfo, a7 as MerchantId, aI as PPPConfig, a4 as PaymentId, aF as PaymentIntentStatus, ac as PaymentLinkCode, ar as PaymentStatus, aq as PaymentToken, aB as ReleaseCondition, aK as RevokeAutonomyRequest, aP as SecurityStatus, a5 as SessionId, aM as SessionKeyInstructions, aN as SessionKeySecurityInfo, aQ as SessionKeyStats, aE as SessionLimits, aL as SmartPaymentStatus, ay as SplitRecipient, aw as SplitStatus, a9 as SubscriptionId, as as SubscriptionStatus, aH as UserProfile, ax as WebhookEvent, a2 as WebhookEventHandler, W as WebhookHandlerConfig, a as WebhookHandlers, a1 as WebhookResult, ag as asAgentKeyId, ak as asEscrowId, al as asInstallmentPlanId, an as asIntentId, ai as asInvoiceId, ah as asMerchantId, ae as asPaymentId, am as asPaymentLinkCode, af as asSessionId, aj as asSubscriptionId, a0 as processWebhook } from './webhook-handler-D5INiR-l.js';
3
- import { Transaction, Keypair } from '@solana/web3.js';
1
+ import { C as CreateAgentApiKeyRequest, A as AgentApiKey, b as CreateAgentSessionRequest, c as AgentSession, d as AgentPaymentRequest, e as AgentPaymentResponse, f as AgentAnalytics, g as CreatePaymentIntentRequest, P as PaymentIntent, h as ConfirmPaymentIntentRequest, i as PaymentIntentEvent, j as PPPFactor, k as PricingSuggestionRequest, l as PricingSuggestion, E as EnableAutonomyRequest, m as EnableAutonomyResponse, n as AutonomyStatus, S as SmartPaymentRequest, o as SmartPaymentResponse, Z as ZendFiConfig, p as CreatePaymentRequest, q as Payment, L as ListPaymentsRequest, r as PaginatedResponse, s as CreateSubscriptionPlanRequest, t as SubscriptionPlan, u as CreateSubscriptionRequest, v as Subscription, w as CreatePaymentLinkRequest, x as PaymentLink, y as CreateInstallmentPlanRequest, I as InstallmentPlan, z as CreateEscrowRequest, B as Escrow, D as ApproveEscrowRequest, R as RefundEscrowRequest, F as DisputeEscrowRequest, G as CreateInvoiceRequest, H as Invoice, V as VerifyWebhookRequest, J as WebhookPayload, K as ApiKeyMode } from './webhook-handler-CgaLeGO4.js';
2
+ export { X as AgentKeyId, at as ApiKeyScope, az as AutonomousDelegate, Q as Brand, aw as CaptureMethod, aF as CreateDeviceBoundSessionKeyRequest, aG as CreateDeviceBoundSessionKeyResponse, aq as CreateInstallmentPlanResponse, aC as CreateSessionKeyRequest, aD as CreateSessionKeyResponse, af as Currency, ae as Environment, a0 as EscrowId, ak as EscrowStatus, a1 as InstallmentPlanId, aj as InstallmentPlanStatus, ap as InstallmentScheduleItem, a3 as IntentId, _ as InvoiceId, as as InvoiceLineItem, al as InvoiceStatus, aJ as LinkedSessionInfo, Y as MerchantId, ay as PPPConfig, T as PaymentId, av as PaymentIntentStatus, a2 as PaymentLinkCode, ah as PaymentStatus, ag as PaymentToken, ar as ReleaseCondition, aA as RevokeAutonomyRequest, aK as SecurityStatus, U as SessionId, aE as SessionKeyInstructions, aP as SessionKeyListResponse, aH as SessionKeySecurityInfo, aQ as SessionKeyStats, aI as SessionKeyStatus, au as SessionLimits, aB as SmartPaymentStatus, ao as SplitRecipient, am as SplitStatus, aN as SubmitSignedTransactionRequest, aO as SubmitTransactionResponse, $ as SubscriptionId, ai as SubscriptionStatus, aL as TopUpSessionKeyRequest, aM as TopUpSessionKeyResponse, ax as UserProfile, an as WebhookEvent, O as WebhookEventHandler, W as WebhookHandlerConfig, a as WebhookHandlers, N as WebhookResult, a6 as asAgentKeyId, aa as asEscrowId, ab as asInstallmentPlanId, ad as asIntentId, a8 as asInvoiceId, a7 as asMerchantId, a4 as asPaymentId, ac as asPaymentLinkCode, a5 as asSessionId, a9 as asSubscriptionId, M as processWebhook } from './webhook-handler-CgaLeGO4.js';
3
+ import { Keypair, Transaction } from '@solana/web3.js';
4
4
 
5
5
  /**
6
6
  * Request/Response Interceptor System
@@ -886,340 +886,296 @@ declare class SmartPaymentsAPI {
886
886
  }
887
887
 
888
888
  /**
889
- * Session Keys API - On-chain funded session wallets
889
+ * Session Keys API - Device-Bound Non-Custodial Session Keys
890
890
  *
891
- * Session keys are dedicated wallets funded by users for AI agents to use.
892
- * Two modes are supported:
891
+ * TRUE non-custodial session keys where:
892
+ * - Client generates keypair (backend NEVER sees private key)
893
+ * - Client encrypts with PIN + device fingerprint (Argon2id + AES-256-GCM)
894
+ * - Backend stores encrypted blob (cannot decrypt!)
895
+ * - Client decrypts and signs for each payment
893
896
  *
894
- * 1. **Custodial Mode**: Backend generates and stores the keypair (simpler)
895
- * 2. **Device-Bound Mode**: Client generates keypair and encrypts with PIN (more secure)
897
+ * This is the ONLY supported mode. Custodial session keys are deprecated.
896
898
  *
897
899
  * @example
898
900
  * ```typescript
899
- * // Create a custodial session key
901
+ * // Create a session key with PIN encryption
900
902
  * const result = await zendfi.sessionKeys.create({
901
- * user_wallet: 'Hx7B...abc',
902
- * limit_usdc: 100,
903
- * duration_days: 7,
904
- * device_fingerprint: await getDeviceFingerprint(),
903
+ * userWallet: '7xKNH...',
904
+ * agentId: 'shopping-assistant-v1',
905
+ * agentName: 'AI Shopping Assistant',
906
+ * limitUSDC: 100,
907
+ * durationDays: 7,
908
+ * pin: '123456',
909
+ * generateRecoveryQR: true,
905
910
  * });
906
911
  *
907
- * // User signs the approval transaction in their wallet
908
- * const signedTx = await wallet.signTransaction(result.approval_transaction);
912
+ * console.log(`Session key: ${result.sessionKeyId}`);
913
+ * console.log(`Works across all apps with agent: ${result.agentId}`);
909
914
  *
910
- * // Submit the signed transaction
911
- * await zendfi.sessionKeys.submitApproval({
912
- * session_key_id: result.session_key_id,
913
- * signed_transaction: signedTx,
914
- * });
915
+ * // Unlock for auto-signing (one-time PIN entry)
916
+ * await zendfi.sessionKeys.unlock(result.sessionKeyId, '123456');
915
917
  *
916
- * // Check status
917
- * const status = await zendfi.sessionKeys.getStatus(result.session_key_id);
918
- * console.log(`Remaining: $${status.remaining_usdc}`);
918
+ * // Make payments without PIN (instant!)
919
+ * const payment = await zendfi.sessionKeys.makePayment({
920
+ * sessionKeyId: result.sessionKeyId,
921
+ * amount: 5.0,
922
+ * recipient: '8xYZA...',
923
+ * description: 'Coffee purchase',
924
+ * });
919
925
  * ```
926
+ *
927
+ * @module aip/session-keys
920
928
  */
921
-
922
929
  type RequestFn = <T>(method: string, endpoint: string, data?: any) => Promise<T>;
930
+ interface CreateSessionKeyOptions {
931
+ /** User's main wallet address */
932
+ userWallet: string;
933
+ /** Agent identifier for cross-app compatibility (e.g., "shopping-assistant-v1") */
934
+ agentId: string;
935
+ /** Human-readable agent name (e.g., "AI Shopping Assistant") */
936
+ agentName?: string;
937
+ /** Spending limit in USDC */
938
+ limitUSDC: number;
939
+ /** Duration in days (1-30) */
940
+ durationDays: number;
941
+ /** 6-digit numeric PIN for encryption */
942
+ pin: string;
943
+ /** Generate recovery QR code (recommended) */
944
+ generateRecoveryQR?: boolean;
945
+ /** Enable Lit Protocol for true autonomous signing (default: true) */
946
+ enableLitProtocol?: boolean;
947
+ /** Lit Protocol network (default: 'datil-dev') */
948
+ litNetwork?: 'datil' | 'datil-dev' | 'datil-test';
949
+ }
950
+ interface SessionKeyResult {
951
+ /** UUID of the created session key */
952
+ sessionKeyId: string;
953
+ /** Agent identifier */
954
+ agentId: string;
955
+ /** Agent name (if provided) */
956
+ agentName?: string;
957
+ /** Session wallet public key */
958
+ sessionWallet: string;
959
+ /** Spending limit in USDC */
960
+ limitUsdc: number;
961
+ /** Expiration timestamp */
962
+ expiresAt: string;
963
+ /** Recovery QR code data (if generated) */
964
+ recoveryQR?: string;
965
+ /** True if this session key works across multiple apps with same agent_id */
966
+ crossAppCompatible: boolean;
967
+ }
968
+ interface MakePaymentOptions {
969
+ /** Session key ID to pay from */
970
+ sessionKeyId: string;
971
+ /** Payment amount in USD */
972
+ amount: number;
973
+ /** Recipient wallet address */
974
+ recipient: string;
975
+ /** Token to pay with (default: USDC) */
976
+ token?: string;
977
+ /** Payment description */
978
+ description?: string;
979
+ /** PIN (only required if session key not unlocked) */
980
+ pin?: string;
981
+ /** Whether to cache keypair for future payments (default: true) */
982
+ enableAutoSign?: boolean;
983
+ }
984
+ interface PaymentResult$1 {
985
+ paymentId: string;
986
+ signature: string;
987
+ status: string;
988
+ }
989
+ interface SessionKeyInfo {
990
+ sessionKeyId: string;
991
+ isActive: boolean;
992
+ isApproved: boolean;
993
+ limitUsdc: number;
994
+ usedAmountUsdc: number;
995
+ remainingUsdc: number;
996
+ expiresAt: string;
997
+ daysUntilExpiry: number;
998
+ }
923
999
  declare class SessionKeysAPI {
924
- private request;
1000
+ private sessionKeys;
1001
+ private sessionMetadata;
1002
+ private requestFn;
1003
+ private debugMode;
925
1004
  constructor(request: RequestFn);
926
1005
  /**
927
- * Create a custodial session key
928
- *
929
- * The backend generates and securely stores the keypair.
930
- * Returns an approval transaction that the user must sign to fund the session wallet.
931
- *
932
- * @param request - Session key configuration
933
- * @returns Creation response with approval transaction
934
- *
935
- * @example
936
- * ```typescript
937
- * // Basic creation
938
- * const result = await zendfi.sessionKeys.create({
939
- * user_wallet: 'Hx7B...abc',
940
- * limit_usdc: 100,
941
- * duration_days: 7,
942
- * device_fingerprint: deviceFingerprint,
943
- * });
944
- *
945
- * // Create with linked session for policy enforcement
946
- * const result = await zendfi.sessionKeys.create({
947
- * user_wallet: 'Hx7B...abc',
948
- * limit_usdc: 500,
949
- * duration_days: 7,
950
- * device_fingerprint: deviceFingerprint,
951
- * link_session_id: session.id, // Links to existing session
952
- * });
953
- *
954
- * console.log(`Session key: ${result.session_key_id}`);
955
- * console.log('Please sign the approval transaction');
956
- * ```
1006
+ * Enable debug logging
957
1007
  */
958
- create(request: CreateSessionKeyRequest): Promise<CreateSessionKeyResponse>;
1008
+ private debug;
959
1009
  /**
960
- * Create a device-bound session key (non-custodial)
1010
+ * Create a new device-bound session key
961
1011
  *
962
- * The client generates the keypair and encrypts it with a PIN before sending.
963
- * The backend cannot decrypt the keypair - only the user's device can.
1012
+ * The keypair is generated client-side and encrypted with your PIN.
1013
+ * The backend NEVER sees your private key.
964
1014
  *
965
- * @param request - Device-bound session key configuration
966
- * @returns Creation response with session wallet address
1015
+ * @param options - Session key configuration
1016
+ * @returns Created session key info with optional recovery QR
967
1017
  *
968
1018
  * @example
969
1019
  * ```typescript
970
- * // Generate keypair client-side
971
- * const keypair = Keypair.generate();
972
- *
973
- * // Encrypt with PIN
974
- * const encrypted = await encryptWithPin(keypair.secretKey, pin);
975
- *
976
- * const result = await zendfi.sessionKeys.createDeviceBound({
977
- * user_wallet: 'Hx7B...abc',
978
- * limit_usdc: 100,
979
- * duration_days: 7,
980
- * encrypted_session_key: encrypted.ciphertext,
981
- * nonce: encrypted.nonce,
982
- * session_public_key: keypair.publicKey.toBase58(),
983
- * device_fingerprint: deviceFingerprint,
1020
+ * const result = await zendfi.sessionKeys.create({
1021
+ * userWallet: '7xKNH...',
1022
+ * agentId: 'shopping-assistant-v1',
1023
+ * agentName: 'AI Shopping Assistant',
1024
+ * limitUSDC: 100,
1025
+ * durationDays: 7,
1026
+ * pin: '123456',
1027
+ * generateRecoveryQR: true,
984
1028
  * });
985
1029
  *
986
- * console.log(`Session wallet: ${result.session_wallet}`);
1030
+ * console.log(`Session key: ${result.sessionKeyId}`);
1031
+ * console.log(`Recovery QR: ${result.recoveryQR}`);
987
1032
  * ```
988
1033
  */
989
- createDeviceBound(request: CreateDeviceBoundSessionKeyRequest$1): Promise<CreateDeviceBoundSessionKeyResponse$1>;
1034
+ create(options: CreateSessionKeyOptions): Promise<SessionKeyResult>;
990
1035
  /**
991
- * Get encrypted session key for device-bound mode
1036
+ * Load an existing session key from backend
992
1037
  *
993
- * Retrieves the encrypted keypair so the client can decrypt it with their PIN.
994
- * The device fingerprint must match the one used during creation.
1038
+ * Fetches the encrypted session key and decrypts it with your PIN.
1039
+ * Use this when resuming a session on the same device.
995
1040
  *
996
1041
  * @param sessionKeyId - UUID of the session key
997
- * @param deviceFingerprint - Current device fingerprint
998
- * @returns Encrypted key data
999
- */
1000
- getEncrypted(sessionKeyId: string, deviceFingerprint: string): Promise<{
1001
- encrypted_session_key: string;
1002
- nonce: string;
1003
- device_fingerprint_valid: boolean;
1004
- }>;
1005
- /**
1006
- * Submit a signed approval transaction
1007
- *
1008
- * After the user signs the approval transaction from `create()`,
1009
- * submit it here to activate the session key.
1010
- *
1011
- * @param request - Signed transaction data
1012
- * @returns Submission result with signature
1042
+ * @param pin - PIN to decrypt the session key
1013
1043
  *
1014
1044
  * @example
1015
1045
  * ```typescript
1016
- * const result = await zendfi.sessionKeys.submitApproval({
1017
- * session_key_id: sessionKeyId,
1018
- * signed_transaction: signedTxBase64,
1019
- * });
1046
+ * // Resume session on same device
1047
+ * await zendfi.sessionKeys.load('uuid-of-session-key', '123456');
1020
1048
  *
1021
- * console.log(`Approved! Signature: ${result.signature}`);
1049
+ * // Now you can make payments
1050
+ * await zendfi.sessionKeys.makePayment({...});
1022
1051
  * ```
1023
1052
  */
1024
- submitApproval(request: SubmitSignedTransactionRequest & {
1025
- session_key_id: string;
1026
- }): Promise<SubmitTransactionResponse>;
1053
+ load(sessionKeyId: string, pin: string): Promise<void>;
1027
1054
  /**
1028
- * Submit a signed top-up transaction
1029
- *
1030
- * After the user signs the top-up transaction from `topUp()`,
1031
- * submit it here to add funds.
1055
+ * Unlock a session key for auto-signing
1032
1056
  *
1033
- * @param sessionKeyId - UUID of the session key
1034
- * @param signedTransaction - Base64 encoded signed transaction
1035
- * @returns Submission result with new limit
1036
- */
1037
- submitTopUp(sessionKeyId: string, signedTransaction: string): Promise<SubmitTransactionResponse>;
1038
- /**
1039
- * Get session key status
1057
+ * After unlocking, payments can be made without entering PIN.
1058
+ * The decrypted keypair is cached in memory with a TTL.
1040
1059
  *
1041
1060
  * @param sessionKeyId - UUID of the session key
1042
- * @returns Current status with remaining balance
1061
+ * @param pin - PIN to decrypt the session key
1062
+ * @param cacheTTL - How long to cache (default: 30 minutes)
1043
1063
  *
1044
1064
  * @example
1045
1065
  * ```typescript
1046
- * const status = await zendfi.sessionKeys.getStatus(sessionKeyId);
1066
+ * // Unlock once
1067
+ * await zendfi.sessionKeys.unlock('uuid', '123456');
1047
1068
  *
1048
- * console.log(`Active: ${status.is_active}`);
1049
- * console.log(`Limit: $${status.limit_usdc}`);
1050
- * console.log(`Used: $${status.used_amount_usdc}`);
1051
- * console.log(`Remaining: $${status.remaining_usdc}`);
1052
- * console.log(`Expires in ${status.days_until_expiry} days`);
1069
+ * // Make payments instantly (no PIN!)
1070
+ * await zendfi.sessionKeys.makePayment({...}); // Instant!
1071
+ * await zendfi.sessionKeys.makePayment({...}); // Instant!
1053
1072
  * ```
1054
1073
  */
1055
- getStatus(sessionKeyId: string): Promise<SessionKeyStatus>;
1074
+ unlock(sessionKeyId: string, pin: string, cacheTTL?: number): Promise<void>;
1056
1075
  /**
1057
- * List all session keys for the merchant
1076
+ * Make a payment using a session key
1077
+ *
1078
+ * If the session key is unlocked (cached), no PIN is needed.
1079
+ * Otherwise, you must provide the PIN.
1058
1080
  *
1059
- * @returns List of session keys with stats
1081
+ * @param options - Payment configuration
1082
+ * @returns Payment result with signature
1060
1083
  *
1061
1084
  * @example
1062
1085
  * ```typescript
1063
- * const { session_keys, stats } = await zendfi.sessionKeys.list();
1064
- *
1065
- * console.log(`Total keys: ${stats.total_keys}`);
1066
- * console.log(`Active: ${stats.active_keys}`);
1086
+ * // With unlocked session key (no PIN)
1087
+ * const result = await zendfi.sessionKeys.makePayment({
1088
+ * sessionKeyId: 'uuid',
1089
+ * amount: 5.0,
1090
+ * recipient: '8xYZA...',
1091
+ * description: 'Coffee purchase',
1092
+ * });
1067
1093
  *
1068
- * session_keys.forEach(key => {
1069
- * console.log(`${key.session_key_id}: $${key.remaining_usdc} remaining`);
1094
+ * // Or with PIN (one-time)
1095
+ * const result = await zendfi.sessionKeys.makePayment({
1096
+ * sessionKeyId: 'uuid',
1097
+ * amount: 5.0,
1098
+ * recipient: '8xYZA...',
1099
+ * pin: '123456',
1070
1100
  * });
1071
1101
  * ```
1072
1102
  */
1073
- list(): Promise<SessionKeyListResponse>;
1103
+ makePayment(options: MakePaymentOptions): Promise<PaymentResult$1>;
1074
1104
  /**
1075
- * Top up a session key with additional funds
1076
- *
1077
- * Returns a transaction that the user must sign to add funds.
1105
+ * Get session key status
1078
1106
  *
1079
1107
  * @param sessionKeyId - UUID of the session key
1080
- * @param request - Top-up configuration
1081
- * @returns Top-up transaction to sign
1082
- *
1083
- * @example
1084
- * ```typescript
1085
- * const topUp = await zendfi.sessionKeys.topUp(sessionKeyId, {
1086
- * user_wallet: 'Hx7B...abc',
1087
- * amount_usdc: 50,
1088
- * device_fingerprint: deviceFingerprint,
1089
- * });
1090
- *
1091
- * console.log(`Adding $${topUp.added_amount}`);
1092
- * console.log(`New limit will be: $${topUp.new_limit}`);
1093
- *
1094
- * // User signs the transaction
1095
- * const signedTx = await wallet.signTransaction(topUp.top_up_transaction);
1096
- *
1097
- * // Submit it
1098
- * await zendfi.sessionKeys.submitTopUp(sessionKeyId, signedTx);
1099
- * ```
1108
+ * @returns Current status including balance and expiry
1100
1109
  */
1101
- topUp(sessionKeyId: string, request: TopUpSessionKeyRequest): Promise<TopUpSessionKeyResponse>;
1110
+ getStatus(sessionKeyId: string): Promise<SessionKeyInfo>;
1102
1111
  /**
1103
1112
  * Revoke a session key
1104
1113
  *
1105
- * Immediately deactivates the session key. Any remaining funds
1106
- * are refunded to the user's wallet.
1114
+ * Permanently deactivates the session key. Cannot be undone.
1107
1115
  *
1108
- * @param sessionKeyId - UUID of the session key
1109
- * @returns Revocation result with optional refund details
1110
- *
1111
- * @example
1112
- * ```typescript
1113
- * const result = await zendfi.sessionKeys.revoke(sessionKeyId);
1114
- *
1115
- * console.log('Session key revoked');
1116
- * if (result.refund?.refunded) {
1117
- * console.log(`Refunded: ${result.refund.transaction_signature}`);
1118
- * }
1119
- * ```
1116
+ * @param sessionKeyId - UUID of the session key to revoke
1120
1117
  */
1121
- revoke(sessionKeyId: string): Promise<{
1122
- message: string;
1123
- session_key_id: string;
1124
- note: string;
1125
- refund?: {
1126
- refunded: boolean;
1127
- transaction_signature: string;
1128
- message: string;
1129
- };
1130
- }>;
1118
+ revoke(sessionKeyId: string): Promise<void>;
1131
1119
  /**
1132
- * Link a session key to an AI session for policy enforcement
1120
+ * Recover session key on new device
1133
1121
  *
1134
- * When linked, payments through this session key will check both:
1135
- * 1. Session key balance (hard cap)
1136
- * 2. AI session limits (per-tx, daily, weekly, monthly)
1122
+ * Use this when moving to a new device with a recovery QR code.
1137
1123
  *
1138
- * This provides defense-in-depth: the session key provides signing
1139
- * capability while the session enforces granular spending policies.
1140
- *
1141
- * @param sessionKeyId - UUID of the session key
1142
- * @param sessionId - UUID of the AI session to link
1143
- * @returns Updated session key status
1124
+ * @param options - Recovery configuration
1144
1125
  *
1145
1126
  * @example
1146
1127
  * ```typescript
1147
- * // Create a session with limits
1148
- * const session = await zendfi.agent.createSession({
1149
- * agent_id: 'shopping-bot',
1150
- * user_wallet: userWallet,
1151
- * limits: {
1152
- * max_per_transaction: 25,
1153
- * max_per_day: 100,
1154
- * },
1155
- * duration_hours: 24,
1156
- * });
1157
- *
1158
- * // Create and fund a session key
1159
- * const key = await zendfi.sessionKeys.create({
1160
- * user_wallet: userWallet,
1161
- * limit_usdc: 500, // Fund with $500
1162
- * duration_days: 7,
1163
- * device_fingerprint: fp,
1128
+ * await zendfi.sessionKeys.recover({
1129
+ * sessionKeyId: 'uuid',
1130
+ * recoveryQR: '{"encryptedSessionKey":"..."}',
1131
+ * oldPin: '123456',
1132
+ * newPin: '654321',
1164
1133
  * });
1134
+ * ```
1135
+ */
1136
+ recover(options: {
1137
+ sessionKeyId: string;
1138
+ recoveryQR: string;
1139
+ oldPin: string;
1140
+ newPin: string;
1141
+ }): Promise<void>;
1142
+ /**
1143
+ * Clear cached keypair for a session key
1165
1144
  *
1166
- * // Link them together
1167
- * await zendfi.sessionKeys.linkSession(key.session_key_id, session.id);
1145
+ * Use this on logout or when session ends.
1168
1146
  *
1169
- * // Now payments will:
1170
- * // - Be limited to $25 per transaction (session policy)
1171
- * // - Be limited to $100 per day (session policy)
1172
- * // - Never exceed $500 total (session key balance)
1173
- * ```
1147
+ * @param sessionKeyId - UUID of the session key (or all if not specified)
1174
1148
  */
1175
- linkSession(sessionKeyId: string, sessionId: string): Promise<{
1176
- success: boolean;
1177
- session_key_id: string;
1178
- linked_session_id: string;
1179
- message: string;
1180
- }>;
1149
+ clearCache(sessionKeyId?: string): void;
1181
1150
  /**
1182
- * Unlink a session key from its AI session
1151
+ * Check if a session key is cached (unlocked)
1183
1152
  *
1184
- * After unlinking, the session key will only be limited by its funded balance.
1153
+ * @param sessionKeyId - UUID of the session key
1154
+ * @returns True if keypair is cached and auto-signing is enabled
1155
+ */
1156
+ isCached(sessionKeyId: string): boolean;
1157
+ /**
1158
+ * Get time remaining until cache expires
1185
1159
  *
1186
1160
  * @param sessionKeyId - UUID of the session key
1187
- * @returns Result of the unlink operation
1161
+ * @returns Milliseconds until cache expires
1188
1162
  */
1189
- unlinkSession(sessionKeyId: string): Promise<{
1190
- success: boolean;
1191
- session_key_id: string;
1192
- message: string;
1193
- }>;
1163
+ getCacheTimeRemaining(sessionKeyId: string): number;
1194
1164
  /**
1195
- * Check if a payment amount is allowed
1165
+ * Extend cache expiry time
1196
1166
  *
1197
- * Checks both session key balance and linked session limits (if any).
1198
- * Useful for pre-validating payments before attempting them.
1167
+ * Useful to keep session active during user activity.
1199
1168
  *
1200
1169
  * @param sessionKeyId - UUID of the session key
1201
- * @param amount - Amount in USD to check
1202
- * @returns Whether the payment is allowed and the effective limit
1203
- *
1204
- * @example
1205
- * ```typescript
1206
- * const check = await zendfi.sessionKeys.canAfford(keyId, 50);
1170
+ * @param additionalTTL - Additional time in milliseconds
1171
+ */
1172
+ extendCache(sessionKeyId: string, additionalTTL: number): void;
1173
+ /**
1174
+ * Get all loaded session key IDs
1207
1175
  *
1208
- * if (check.allowed) {
1209
- * await zendfi.smart.execute({ ... });
1210
- * } else {
1211
- * console.log(`Cannot afford: ${check.reason}`);
1212
- * console.log(`Effective limit: $${check.effective_limit}`);
1213
- * }
1214
- * ```
1176
+ * @returns Array of session key UUIDs currently loaded
1215
1177
  */
1216
- canAfford(sessionKeyId: string, amount: number): Promise<{
1217
- allowed: boolean;
1218
- reason?: string;
1219
- effective_limit: number;
1220
- session_key_remaining: number;
1221
- session_remaining_today?: number;
1222
- }>;
1178
+ getLoadedSessionKeys(): string[];
1223
1179
  }
1224
1180
 
1225
1181
  /**
@@ -2204,6 +2160,7 @@ declare class DeviceBoundSessionKey {
2204
2160
  private deviceFingerprint;
2205
2161
  private sessionKeyId;
2206
2162
  private recoveryQR;
2163
+ private originalKeypair;
2207
2164
  private cachedKeypair;
2208
2165
  private cacheExpiry;
2209
2166
  private readonly DEFAULT_CACHE_TTL_MS;
@@ -2211,6 +2168,12 @@ declare class DeviceBoundSessionKey {
2211
2168
  * Create a new device-bound session key
2212
2169
  */
2213
2170
  static create(options: DeviceBoundSessionKeyOptions): Promise<DeviceBoundSessionKey>;
2171
+ /**
2172
+ * Get the original keypair (only available immediately after creation)
2173
+ * Used for Lit Protocol encryption during session creation
2174
+ * @internal
2175
+ */
2176
+ getKeypair(): Keypair;
2214
2177
  /**
2215
2178
  * Get encrypted data for backend storage
2216
2179
  */
@@ -2315,230 +2278,6 @@ declare class DeviceBoundSessionKey {
2315
2278
  getSessionKeyId(): string;
2316
2279
  }
2317
2280
 
2318
- /**
2319
- * Device-Bound Session Keys - SDK Integration
2320
- *
2321
- * High-level API for managing non-custodial session keys
2322
- * Integrates with ZendFi backend API
2323
- *
2324
- * @module device-bound-session-keys
2325
- */
2326
-
2327
- interface CreateDeviceBoundSessionKeyRequest {
2328
- userWallet: string;
2329
- agentId: string;
2330
- agentName?: string;
2331
- limitUsdc: number;
2332
- durationDays: number;
2333
- encryptedSessionKey: string;
2334
- nonce: string;
2335
- sessionPublicKey: string;
2336
- deviceFingerprint: string;
2337
- recoveryQrData?: string;
2338
- }
2339
- interface CreateDeviceBoundSessionKeyResponse {
2340
- sessionKeyId: string;
2341
- mode: 'device_bound';
2342
- isCustodial: false;
2343
- userWallet: string;
2344
- agentId: string;
2345
- agentName?: string;
2346
- sessionWallet: string;
2347
- limitUsdc: number;
2348
- expiresAt: string;
2349
- requiresClientSigning: true;
2350
- crossAppCompatible: boolean;
2351
- securityInfo: {
2352
- encryptionType: string;
2353
- deviceBound: boolean;
2354
- backendCanDecrypt: boolean;
2355
- recoveryQrSaved: boolean;
2356
- };
2357
- }
2358
- interface SessionKeyPaymentRequest {
2359
- amount: number;
2360
- recipient: string;
2361
- token?: string;
2362
- description?: string;
2363
- pin?: string;
2364
- enableAutoSign?: boolean;
2365
- }
2366
- declare class ZendFiSessionKeyManager {
2367
- private baseURL;
2368
- private apiKey;
2369
- private sessionKey;
2370
- private sessionKeyId;
2371
- constructor(apiKey: string, baseURL?: string);
2372
- /**
2373
- * Create a new device-bound session key
2374
- *
2375
- * @example
2376
- * ```typescript
2377
- * const manager = new ZendFiSessionKeyManager('your-api-key');
2378
- *
2379
- * const sessionKey = await manager.createSessionKey({
2380
- * userWallet: '7xKNH....',
2381
- * agentId: 'shopping-assistant-v1',
2382
- * agentName: 'AI Shopping Assistant',
2383
- * limitUSDC: 100,
2384
- * durationDays: 7,
2385
- * pin: '123456',
2386
- * generateRecoveryQR: true,
2387
- * });
2388
- *
2389
- * console.log('Session key created:', sessionKey.sessionKeyId);
2390
- * console.log('Works across all apps with agent:', sessionKey.agentId);
2391
- * console.log('Recovery QR:', sessionKey.recoveryQR);
2392
- * ```
2393
- */
2394
- createSessionKey(options: {
2395
- userWallet: string;
2396
- agentId: string;
2397
- agentName?: string;
2398
- limitUSDC: number;
2399
- durationDays: number;
2400
- pin: string;
2401
- generateRecoveryQR?: boolean;
2402
- }): Promise<{
2403
- sessionKeyId: string;
2404
- agentId: string;
2405
- agentName?: string;
2406
- sessionWallet: string;
2407
- expiresAt: string;
2408
- recoveryQR?: string;
2409
- limitUsdc: number;
2410
- crossAppCompatible: boolean;
2411
- }>;
2412
- /**
2413
- * Load an existing session key from backend
2414
- * Requires PIN to decrypt
2415
- */
2416
- loadSessionKey(sessionKeyId: string, pin: string): Promise<void>;
2417
- /**
2418
- * Make a payment using the session key
2419
- *
2420
- * First payment: Requires PIN to decrypt session key
2421
- * Subsequent payments: Uses cached keypair (no PIN needed!) ✨
2422
- *
2423
- * @example
2424
- * ```typescript
2425
- * // First payment: requires PIN
2426
- * const result1 = await manager.makePayment({
2427
- * amount: 5.0,
2428
- * recipient: '7xKNH....',
2429
- * pin: '123456',
2430
- * description: 'Coffee purchase',
2431
- * });
2432
- *
2433
- * // Second payment: NO PIN NEEDED! Instant signing!
2434
- * const result2 = await manager.makePayment({
2435
- * amount: 3.0,
2436
- * recipient: '7xKNH....',
2437
- * description: 'Donut purchase',
2438
- * }); // <- No PIN! Uses cached keypair
2439
- *
2440
- * console.log('Payment signature:', result2.signature);
2441
- *
2442
- * // Disable auto-signing for single payment
2443
- * const result3 = await manager.makePayment({
2444
- * amount: 100.0,
2445
- * recipient: '7xKNH....',
2446
- * pin: '123456',
2447
- * enableAutoSign: false, // Will require PIN every time
2448
- * });
2449
- * ```
2450
- */
2451
- makePayment(options: SessionKeyPaymentRequest): Promise<{
2452
- paymentId: string;
2453
- signature: string;
2454
- status: string;
2455
- }>;
2456
- /**
2457
- * Recover session key on new device
2458
- * Requires recovery QR and PIN from original device
2459
- *
2460
- * @example
2461
- * ```typescript
2462
- * const recovered = await manager.recoverSessionKey({
2463
- * sessionKeyId: 'uuid...',
2464
- * recoveryQR: '{"encryptedSessionKey":"..."}',
2465
- * oldPin: '123456',
2466
- * newPin: '654321',
2467
- * });
2468
- * ```
2469
- */
2470
- recoverSessionKey(options: {
2471
- sessionKeyId: string;
2472
- recoveryQR: string;
2473
- oldPin: string;
2474
- newPin: string;
2475
- }): Promise<void>;
2476
- /**
2477
- * Revoke session key
2478
- */
2479
- revokeSessionKey(sessionKeyId?: string): Promise<void>;
2480
- /**
2481
- * Unlock session key with PIN and cache for auto-signing
2482
- * Call this after creating/loading session key to enable instant payments
2483
- *
2484
- * @example
2485
- * ```typescript
2486
- * // Create session key
2487
- * await manager.createSessionKey({...});
2488
- *
2489
- * // Unlock with PIN (one-time)
2490
- * await manager.unlockSessionKey('123456');
2491
- *
2492
- * // Now all payments are instant (no PIN!)
2493
- * await manager.makePayment({amount: 5, ...}); // Instant!
2494
- * await manager.makePayment({amount: 3, ...}); // Instant!
2495
- * ```
2496
- */
2497
- unlockSessionKey(pin: string, cacheTTL?: number): Promise<void>;
2498
- /**
2499
- * Clear cached keypair
2500
- * Should be called on logout or when session ends
2501
- *
2502
- * @example
2503
- * ```typescript
2504
- * // Clear on logout
2505
- * manager.clearCache();
2506
- *
2507
- * // Or auto-clear on tab close
2508
- * window.addEventListener('beforeunload', () => {
2509
- * manager.clearCache();
2510
- * });
2511
- * ```
2512
- */
2513
- clearCache(): void;
2514
- /**
2515
- * Check if keypair is cached (auto-signing enabled)
2516
- */
2517
- isCached(): boolean;
2518
- /**
2519
- * Get time remaining until cache expires (in milliseconds)
2520
- */
2521
- getCacheTimeRemaining(): number;
2522
- /**
2523
- * Extend cache expiry time
2524
- * Useful to keep session active during user activity
2525
- */
2526
- extendCache(additionalTTL: number): void;
2527
- /**
2528
- * Get session key status
2529
- */
2530
- getStatus(sessionKeyId?: string): Promise<{
2531
- isActive: boolean;
2532
- isApproved: boolean;
2533
- limitUsdc: number;
2534
- usedAmountUsdc: number;
2535
- remainingUsdc: number;
2536
- expiresAt: string;
2537
- daysUntilExpiry: number;
2538
- }>;
2539
- private request;
2540
- }
2541
-
2542
2281
  /**
2543
2282
  * Lit Protocol PKP Session Identity Module
2544
2283
  *
@@ -3392,12 +3131,11 @@ declare class SessionKeyLifecycle {
3392
3131
  private config;
3393
3132
  private sessionKeyId;
3394
3133
  private sessionWallet;
3395
- private encryptedKey;
3396
- private deviceFingerprint;
3397
3134
  constructor(client: ZendFiClient, config?: LifecycleConfig);
3398
3135
  /**
3399
3136
  * Create and fund session key in one call
3400
- * Handles: keypair generation → encryption → backend registration → funding
3137
+ * Handles: keypair generation → encryption → backend registration
3138
+ * Note: The SDK now handles all crypto internally
3401
3139
  */
3402
3140
  createAndFund(config: CreateAndFundConfig): Promise<{
3403
3141
  sessionKeyId: string;
@@ -3405,17 +3143,28 @@ declare class SessionKeyLifecycle {
3405
3143
  }>;
3406
3144
  /**
3407
3145
  * Make a payment using the session key
3408
- * Auto-handles caching, PIN prompts, and signing
3146
+ * Uses the new SDK's makePayment which handles caching internally
3409
3147
  */
3410
3148
  pay(amount: number, description: string): Promise<PaymentResult>;
3411
3149
  /**
3412
3150
  * Check session key status
3413
3151
  */
3414
- getStatus(): Promise<SessionKeyStatus>;
3152
+ getStatus(): Promise<{
3153
+ sessionKeyId: string;
3154
+ isActive: boolean;
3155
+ isApproved: boolean;
3156
+ limitUsdc: number;
3157
+ usedAmountUsdc: number;
3158
+ remainingUsdc: number;
3159
+ expiresAt: string;
3160
+ daysUntilExpiry: number;
3161
+ }>;
3415
3162
  /**
3416
3163
  * Top up session key
3164
+ * @deprecated Device-bound session keys are funded directly by the user.
3165
+ * Use the session wallet address to send funds directly.
3417
3166
  */
3418
- topUp(amount: number, userWallet: string, onApprovalNeeded?: (tx: string) => Promise<void>): Promise<void>;
3167
+ topUp(_amount: number, _userWallet: string, _onApprovalNeeded?: (tx: string) => Promise<void>): Promise<void>;
3419
3168
  /**
3420
3169
  * Revoke session key
3421
3170
  */
@@ -3432,10 +3181,7 @@ declare class SessionKeyLifecycle {
3432
3181
  * Check if session is active
3433
3182
  */
3434
3183
  isActive(): boolean;
3435
- private decryptKeypair;
3436
- private generateDeviceFingerprint;
3437
3184
  private promptForPIN;
3438
- private getSolanaWeb3;
3439
3185
  }
3440
3186
  /**
3441
3187
  * Quick setup function for common use case
@@ -3625,4 +3371,4 @@ declare class PerformanceMonitor {
3625
3371
  clear(): void;
3626
3372
  }
3627
3373
 
3628
- export { AgentAPI, AgentAnalytics, AgentApiKey, AgentPaymentRequest, AgentPaymentResponse, AgentSession, AnthropicAdapter, ApiError, ApiKeyMode, ApproveEscrowRequest, AuthenticationError, AutonomyAPI, AutonomyStatus, type CachedKeypair, type CheckoutError, type CheckoutTheme, ConfigLoader, ConfirmPaymentIntentRequest, type ConnectedWallet, CreateAgentApiKeyRequest, CreateAgentSessionRequest, type CreateAndFundConfig, type CreateDeviceBoundSessionKeyRequest, type CreateDeviceBoundSessionKeyResponse, CreateEscrowRequest, CreateInstallmentPlanRequest, CreateInvoiceRequest, CreatePaymentIntentRequest, CreatePaymentLinkRequest, CreatePaymentRequest, CreateSessionKeyRequest, CreateSessionKeyResponse, CreateSubscriptionPlanRequest, CreateSubscriptionRequest, type CustomStorageAdapter, DevTools, DeviceBoundSessionKey, type DeviceBoundSessionKeyOptions, DeviceFingerprintGenerator, DisputeEscrowRequest, ERROR_CODES, type EmbeddedCheckoutConfig, EnableAutonomyRequest, EnableAutonomyResponse, type EncryptedSessionKey, type ErrorInterceptor, ErrorRecovery, Escrow, GeminiAdapter, InstallmentPlan, InterceptorManager, type Interceptors, Invoice, type LifecycleConfig, ListPaymentsRequest, LitCryptoSigner, type LitCryptoSignerConfig, type LitNetwork, type MockWallet, NetworkError, OpenAIAdapter, PINRateLimiter, type PINValidationResult, PINValidator, PPPFactor, PaginatedResponse, type ParsedIntent, Payment, PaymentError, PaymentIntent, PaymentIntentEvent, PaymentIntentParser, PaymentIntentsAPI, PaymentLink, type PaymentResult, type PaymentSuccessData, PerformanceMonitor, type PollingOptions, PricingAPI, PricingSuggestion, PricingSuggestionRequest, QuickCaches, RateLimitError, RateLimiter, type RecoveryQR, RecoveryQRGenerator, RefundEscrowRequest, type RequestConfig, type RequestInterceptor, type ResponseData, type ResponseInterceptor, type RetryOptions, RetryStrategy, SPENDING_LIMIT_ACTION_CID, SecureStorage, SessionKeyCache, type SessionKeyCacheConfig, SessionKeyCrypto, SessionKeyLifecycle, SessionKeyListResponse, type SessionKeyPaymentRequest, SessionKeyStatus, SessionKeysAPI, type SignPaymentParams, type SignPaymentResult, SmartPaymentRequest, SmartPaymentResponse, SmartPaymentsAPI, SubmitSignedTransactionRequest, SubmitTransactionResponse, Subscription, SubscriptionPlan, type TestSessionKey, TopUpSessionKeyRequest, TopUpSessionKeyResponse, TransactionMonitor, TransactionPoller, type TransactionStatus, ValidationError, VerifyWebhookRequest, WalletConnector, WebhookError, WebhookPayload, ZendFiClient, ZendFiConfig, ZendFiEmbeddedCheckout, ZendFiError, type ZendFiErrorData, type ZendFiErrorType, ZendFiSessionKeyManager, createWalletHook, createZendFiError, decodeSignatureFromLit, encodeTransactionForLit, generateIdempotencyKey, isZendFiError, requiresLitSigning, setupQuickSessionKey, sleep, verifyExpressWebhook, verifyNextWebhook, verifyWebhookSignature, zendfi };
3374
+ export { AgentAPI, AgentAnalytics, AgentApiKey, AgentPaymentRequest, AgentPaymentResponse, AgentSession, AnthropicAdapter, ApiError, ApiKeyMode, ApproveEscrowRequest, AuthenticationError, AutonomyAPI, AutonomyStatus, type CachedKeypair, type CheckoutError, type CheckoutTheme, ConfigLoader, ConfirmPaymentIntentRequest, type ConnectedWallet, CreateAgentApiKeyRequest, CreateAgentSessionRequest, type CreateAndFundConfig, CreateEscrowRequest, CreateInstallmentPlanRequest, CreateInvoiceRequest, CreatePaymentIntentRequest, CreatePaymentLinkRequest, CreatePaymentRequest, CreateSubscriptionPlanRequest, CreateSubscriptionRequest, type CustomStorageAdapter, DevTools, DeviceBoundSessionKey, type DeviceBoundSessionKeyOptions, DeviceFingerprintGenerator, DisputeEscrowRequest, ERROR_CODES, type EmbeddedCheckoutConfig, EnableAutonomyRequest, EnableAutonomyResponse, type EncryptedSessionKey, type ErrorInterceptor, ErrorRecovery, Escrow, GeminiAdapter, InstallmentPlan, InterceptorManager, type Interceptors, Invoice, type LifecycleConfig, ListPaymentsRequest, LitCryptoSigner, type LitCryptoSignerConfig, type LitNetwork, type MockWallet, NetworkError, OpenAIAdapter, PINRateLimiter, type PINValidationResult, PINValidator, PPPFactor, PaginatedResponse, type ParsedIntent, Payment, PaymentError, PaymentIntent, PaymentIntentEvent, PaymentIntentParser, PaymentIntentsAPI, PaymentLink, type PaymentResult, type PaymentSuccessData, PerformanceMonitor, type PollingOptions, PricingAPI, PricingSuggestion, PricingSuggestionRequest, QuickCaches, RateLimitError, RateLimiter, type RecoveryQR, RecoveryQRGenerator, RefundEscrowRequest, type RequestConfig, type RequestInterceptor, type ResponseData, type ResponseInterceptor, type RetryOptions, RetryStrategy, SPENDING_LIMIT_ACTION_CID, SecureStorage, SessionKeyCache, type SessionKeyCacheConfig, SessionKeyCrypto, SessionKeyLifecycle, SessionKeysAPI, type SignPaymentParams, type SignPaymentResult, SmartPaymentRequest, SmartPaymentResponse, SmartPaymentsAPI, Subscription, SubscriptionPlan, type TestSessionKey, TransactionMonitor, TransactionPoller, type TransactionStatus, ValidationError, VerifyWebhookRequest, WalletConnector, WebhookError, WebhookPayload, ZendFiClient, ZendFiConfig, ZendFiEmbeddedCheckout, ZendFiError, type ZendFiErrorData, type ZendFiErrorType, createWalletHook, createZendFiError, decodeSignatureFromLit, encodeTransactionForLit, generateIdempotencyKey, isZendFiError, requiresLitSigning, setupQuickSessionKey, sleep, verifyExpressWebhook, verifyNextWebhook, verifyWebhookSignature, zendfi };