@mixrpay/agent-sdk 0.2.0 → 0.3.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.cts CHANGED
@@ -1,5 +1,3 @@
1
- import { Hex } from 'viem';
2
-
3
1
  /**
4
2
  * MixrPay Agent SDK - Type definitions
5
3
  *
@@ -124,29 +122,6 @@ interface PaymentEvent {
124
122
  /** URL that triggered the payment */
125
123
  url?: string;
126
124
  }
127
- /**
128
- * Payment requirements parsed from a 402 response.
129
- *
130
- * This represents what the server is asking for in exchange for the resource.
131
- */
132
- interface PaymentRequirements {
133
- /** Address to send payment to */
134
- recipient: string;
135
- /** Amount in USDC minor units (6 decimals). 1000000 = $1.00 */
136
- amount: bigint;
137
- /** Currency code (currently only "USDC" is supported) */
138
- currency: string;
139
- /** Chain ID (8453 for Base mainnet, 84532 for Base Sepolia) */
140
- chainId: number;
141
- /** URL where the payment should be submitted */
142
- facilitatorUrl: string;
143
- /** Unique nonce for this payment request */
144
- nonce: string;
145
- /** Unix timestamp when this payment request expires */
146
- expiresAt: number;
147
- /** Human-readable description of the payment */
148
- description?: string;
149
- }
150
125
  /**
151
126
  * Information about a session key.
152
127
  */
@@ -221,97 +196,6 @@ interface DiagnosticsResult {
221
196
  /** Wallet address */
222
197
  walletAddress: string;
223
198
  }
224
- /**
225
- * The X-PAYMENT header payload structure.
226
- *
227
- * This is what gets base64-encoded and sent in the X-PAYMENT header.
228
- */
229
- interface X402PaymentPayload {
230
- /** Protocol version (currently 1) */
231
- x402Version: number;
232
- /** Payment scheme ('exact' for USDC transfers) */
233
- scheme: 'exact';
234
- /** Network identifier */
235
- network: 'base' | 'base-sepolia';
236
- /** Payment payload containing signature and authorization */
237
- payload: {
238
- /** EIP-712 signature of the transferWithAuthorization */
239
- signature: string;
240
- /** TransferWithAuthorization parameters */
241
- authorization: {
242
- /** Sender address (smart wallet) */
243
- from: string;
244
- /** Recipient address */
245
- to: string;
246
- /** Amount in USDC minor units as string */
247
- value: string;
248
- /** Unix timestamp after which the authorization is valid */
249
- validAfter: string;
250
- /** Unix timestamp before which the authorization is valid */
251
- validBefore: string;
252
- /** Unique nonce (32 bytes hex) */
253
- nonce: string;
254
- };
255
- };
256
- }
257
- /**
258
- * EIP-712 domain for USDC transferWithAuthorization.
259
- */
260
- interface EIP712Domain {
261
- /** Contract name ('USD Coin' for USDC) */
262
- name: string;
263
- /** Contract version ('2' for USDC) */
264
- version: string;
265
- /** Chain ID */
266
- chainId: number;
267
- /** USDC contract address */
268
- verifyingContract: `0x${string}`;
269
- }
270
- /**
271
- * EIP-3009 TransferWithAuthorization message structure.
272
- */
273
- interface TransferWithAuthorizationMessage {
274
- /** Sender address */
275
- from: `0x${string}`;
276
- /** Recipient address */
277
- to: `0x${string}`;
278
- /** Amount in minor units */
279
- value: bigint;
280
- /** Unix timestamp after which the authorization is valid */
281
- validAfter: bigint;
282
- /** Unix timestamp before which the authorization is valid */
283
- validBefore: bigint;
284
- /** Unique nonce (32 bytes) */
285
- nonce: `0x${string}`;
286
- }
287
- /**
288
- * Response from the wallet balance endpoint.
289
- */
290
- interface WalletBalanceResponse {
291
- /** Balance in USD */
292
- balanceUsd: number;
293
- /** Balance in USDC minor units as string */
294
- balanceMinor: string;
295
- /** Currency code */
296
- currency: string;
297
- /** Wallet address */
298
- walletAddress: string;
299
- }
300
- /**
301
- * Response from the session key stats endpoint.
302
- */
303
- interface SessionKeyStatsResponse {
304
- /** Total spent in USD */
305
- totalSpentUsd: number;
306
- /** Number of transactions */
307
- txCount: number;
308
- /** Remaining daily limit in USD (null if no limit) */
309
- remainingDailyUsd: number | null;
310
- /** Remaining total limit in USD (null if no limit) */
311
- remainingTotalUsd: number | null;
312
- /** Expiration timestamp ISO string (null if never) */
313
- expiresAt: string | null;
314
- }
315
199
  /**
316
200
  * Options for creating a session authorization with a MixrPay merchant.
317
201
  */
@@ -422,6 +306,34 @@ interface ChargeResult {
422
306
  /** Remaining session balance in USD */
423
307
  remainingSessionBalanceUsd: number;
424
308
  }
309
+ /**
310
+ * Statistics about session authorizations.
311
+ *
312
+ * This provides an overview of all sessions managed by the wallet.
313
+ */
314
+ interface SessionStats {
315
+ /** Number of active sessions */
316
+ activeCount: number;
317
+ /** Number of expired sessions */
318
+ expiredCount: number;
319
+ /** Number of revoked sessions */
320
+ revokedCount: number;
321
+ /** Total amount authorized across all active sessions in USD */
322
+ totalAuthorizedUsd: number;
323
+ /** Total amount spent across all sessions in USD */
324
+ totalSpentUsd: number;
325
+ /** Total remaining across all active sessions in USD */
326
+ totalRemainingUsd: number;
327
+ /** List of active sessions (summary) */
328
+ activeSessions: Array<{
329
+ id: string;
330
+ merchantName: string;
331
+ merchantPublicKey: string;
332
+ spendingLimitUsd: number;
333
+ remainingUsd: number;
334
+ expiresAt: Date;
335
+ }>;
336
+ }
425
337
 
426
338
  /**
427
339
  * MixrPay Agent SDK - AgentWallet
@@ -447,13 +359,7 @@ interface ChargeResult {
447
359
  */
448
360
 
449
361
  /** Current SDK version */
450
- declare const SDK_VERSION = "0.1.0";
451
- /** Default API base URL - override with baseUrl option or MIXRPAY_BASE_URL env var */
452
- declare const DEFAULT_BASE_URL: string;
453
- /** Default x402 facilitator URL */
454
- declare const DEFAULT_FACILITATOR_URL = "https://x402.org/facilitator";
455
- /** Default request timeout in milliseconds */
456
- declare const DEFAULT_TIMEOUT = 30000;
362
+ declare const SDK_VERSION = "0.3.0";
457
363
  /** Supported networks */
458
364
  declare const NETWORKS: {
459
365
  readonly BASE_MAINNET: {
@@ -766,6 +672,27 @@ declare class AgentWallet {
766
672
  * ```
767
673
  */
768
674
  revokeSession(sessionId: string): Promise<boolean>;
675
+ /**
676
+ * Get statistics about all session authorizations.
677
+ *
678
+ * This provides an overview of active, expired, and revoked sessions,
679
+ * along with aggregate spending information.
680
+ *
681
+ * @returns Session statistics
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * const stats = await wallet.getSessionStats();
686
+ * console.log(`Active sessions: ${stats.activeCount}`);
687
+ * console.log(`Total authorized: $${stats.totalAuthorizedUsd.toFixed(2)}`);
688
+ * console.log(`Total remaining: $${stats.totalRemainingUsd.toFixed(2)}`);
689
+ *
690
+ * for (const session of stats.activeSessions) {
691
+ * console.log(`${session.merchantName}: $${session.remainingUsd} remaining`);
692
+ * }
693
+ * ```
694
+ */
695
+ getSessionStats(): Promise<SessionStats>;
769
696
  /**
770
697
  * Charge against an active session authorization.
771
698
  *
@@ -1016,189 +943,136 @@ declare class InvalidSessionKeyError extends MixrPayError {
1016
943
  constructor(reason?: string);
1017
944
  }
1018
945
  /**
1019
- * Thrown when there's an error in x402 protocol handling.
946
+ * Thrown when a session authorization has expired.
1020
947
  *
1021
- * This indicates a problem with the payment protocol, usually due to:
1022
- * - Malformed 402 response from server
1023
- * - Missing required payment fields
1024
- * - Invalid payment parameters
1025
- * - Protocol version mismatch
948
+ * Session authorizations have an expiration date set when created. Once expired,
949
+ * the session can no longer be used for payments.
1026
950
  *
1027
951
  * ## Resolution
1028
- * This is usually a server-side issue. Contact the API provider if the error persists.
952
+ * Create a new session with the merchant using `wallet.getOrCreateSession()`.
953
+ * The SDK will automatically create a new session on the next `callMerchantApi()` call.
1029
954
  *
1030
955
  * @example
1031
956
  * ```typescript
1032
957
  * catch (error) {
1033
- * if (error instanceof X402ProtocolError) {
1034
- * console.log(`Protocol error: ${error.reason}`);
1035
- * // Contact API provider or check server configuration
958
+ * if (error instanceof SessionExpiredError) {
959
+ * console.log(`Session ${error.sessionId} expired at ${error.expiredAt}`);
960
+ * // SDK will auto-create new session on next callMerchantApi()
1036
961
  * }
1037
962
  * }
1038
963
  * ```
1039
964
  */
1040
- declare class X402ProtocolError extends MixrPayError {
1041
- /** Detailed reason for the protocol error */
1042
- readonly reason: string;
1043
- constructor(reason: string);
965
+ declare class SessionExpiredError extends MixrPayError {
966
+ /** ID of the expired session */
967
+ readonly sessionId: string;
968
+ /** When the session expired (ISO string or Date) */
969
+ readonly expiredAt?: string;
970
+ constructor(sessionId: string, expiredAt?: string);
1044
971
  }
1045
972
  /**
1046
- * Check if an error is a MixrPay SDK error.
973
+ * Thrown when a payment would exceed the session's spending limit.
1047
974
  *
1048
- * @param error - The error to check
1049
- * @returns true if the error is a MixrPayError or subclass
975
+ * Each session authorization has a spending limit set by the user. Once the limit
976
+ * is reached, no more payments can be made until a new session is created.
977
+ *
978
+ * ## Resolution
979
+ * - Create a new session with a higher limit
980
+ * - Wait for the current session to be renewed (if auto-renewal is enabled)
1050
981
  *
1051
982
  * @example
1052
983
  * ```typescript
1053
- * try {
1054
- * await wallet.fetch(...);
1055
- * } catch (error) {
1056
- * if (isMixrPayError(error)) {
1057
- * console.log('MixrPay error:', error.code, error.message);
1058
- * } else {
1059
- * console.log('Other error:', error);
984
+ * catch (error) {
985
+ * if (error instanceof SessionLimitExceededError) {
986
+ * console.log(`Session limit: $${error.limit}, requested: $${error.requested}`);
987
+ * console.log(`Remaining: $${error.remaining}`);
1060
988
  * }
1061
989
  * }
1062
990
  * ```
1063
991
  */
1064
- declare function isMixrPayError(error: unknown): error is MixrPayError;
992
+ declare class SessionLimitExceededError extends MixrPayError {
993
+ /** ID of the session */
994
+ readonly sessionId?: string;
995
+ /** The session's spending limit in USD */
996
+ readonly limit: number;
997
+ /** The amount requested in USD */
998
+ readonly requested: number;
999
+ /** Remaining balance in the session (limit - used) */
1000
+ readonly remaining: number;
1001
+ constructor(limit: number, requested: number, remaining: number, sessionId?: string);
1002
+ }
1065
1003
  /**
1066
- * Get a user-friendly error message from any error.
1004
+ * Thrown when a session ID is invalid or not found.
1005
+ *
1006
+ * This can happen if:
1007
+ * - The session ID was incorrectly formatted
1008
+ * - The session was deleted
1009
+ * - The session belongs to a different user/merchant
1067
1010
  *
1068
- * @param error - The error to get a message from
1069
- * @returns A user-friendly error message
1011
+ * ## Resolution
1012
+ * Create a new session using `wallet.getOrCreateSession()`.
1070
1013
  *
1071
1014
  * @example
1072
1015
  * ```typescript
1073
1016
  * catch (error) {
1074
- * const message = getErrorMessage(error);
1075
- * showToast(message);
1017
+ * if (error instanceof SessionNotFoundError) {
1018
+ * console.log(`Session ${error.sessionId} not found`);
1019
+ * const newSession = await wallet.getOrCreateSession({ ... });
1020
+ * }
1076
1021
  * }
1077
1022
  * ```
1078
1023
  */
1079
- declare function getErrorMessage(error: unknown): string;
1080
-
1081
- /**
1082
- * MixrPay Agent SDK - Session Key Handling
1083
- *
1084
- * Session keys are derived private keys with on-chain spending limits that enable
1085
- * AI agents to sign USDC transferWithAuthorization transactions autonomously.
1086
- */
1087
-
1088
- /**
1089
- * Represents a session key for signing x402 payments.
1090
- *
1091
- * The session key format is: sk_live_{64_hex_chars} or sk_test_{64_hex_chars}
1092
- */
1093
- declare class SessionKey {
1094
- private readonly privateKey;
1095
- private readonly account;
1096
- readonly address: `0x${string}`;
1097
- readonly isTest: boolean;
1098
- private constructor();
1099
- /**
1100
- * Get the private key as hex string (without 0x prefix).
1101
- * Used for API authentication headers.
1102
- */
1103
- get privateKeyHex(): string;
1104
- /**
1105
- * Parse a session key string into a SessionKey object.
1106
- *
1107
- * @param sessionKey - Session key in format sk_live_... or sk_test_...
1108
- * @returns SessionKey object
1109
- * @throws InvalidSessionKeyError if the format is invalid
1110
- */
1111
- static fromString(sessionKey: string): SessionKey;
1112
- /**
1113
- * Sign EIP-712 typed data for TransferWithAuthorization.
1114
- *
1115
- * @param domain - EIP-712 domain
1116
- * @param message - Transfer authorization message
1117
- * @returns Hex-encoded signature
1118
- */
1119
- signTransferAuthorization(domain: EIP712Domain, message: TransferWithAuthorizationMessage): Promise<Hex>;
1120
- /**
1121
- * Sign a plain message (EIP-191 personal sign).
1122
- *
1123
- * @param message - Message to sign
1124
- * @returns Hex-encoded signature
1125
- */
1126
- signMessage(message: string): Promise<Hex>;
1127
- /**
1128
- * Get the chain ID based on whether this is a test key.
1129
- */
1130
- getDefaultChainId(): number;
1024
+ declare class SessionNotFoundError extends MixrPayError {
1025
+ /** The session ID that was not found */
1026
+ readonly sessionId: string;
1027
+ constructor(sessionId: string);
1131
1028
  }
1132
1029
  /**
1133
- * Build EIP-712 typed data for USDC transferWithAuthorization (EIP-3009).
1134
- *
1135
- * @param params - Parameters for the transfer authorization
1136
- * @returns Domain and message for EIP-712 signing
1137
- */
1138
- declare function buildTransferAuthorizationData(params: {
1139
- fromAddress: `0x${string}`;
1140
- toAddress: `0x${string}`;
1141
- value: bigint;
1142
- validAfter: bigint;
1143
- validBefore: bigint;
1144
- nonce: Hex;
1145
- chainId: number;
1146
- }): {
1147
- domain: EIP712Domain;
1148
- message: TransferWithAuthorizationMessage;
1149
- };
1150
- /**
1151
- * Generate a random 32-byte nonce as hex.
1152
- */
1153
- declare function generateNonce(): Hex;
1154
-
1155
- /**
1156
- * MixrPay Agent SDK - x402 Protocol Handling
1030
+ * Thrown when attempting to use a session that has been revoked.
1157
1031
  *
1158
- * The x402 protocol enables HTTP-native payments. When a server returns a 402 Payment
1159
- * Required response, the client can automatically fulfill the payment and retry.
1160
- */
1161
-
1162
- /**
1163
- * Parse payment requirements from a 402 response.
1032
+ * Sessions can be revoked by:
1033
+ * - The user (wallet owner)
1034
+ * - The merchant
1035
+ * - Automatically by the system (e.g., suspicious activity)
1164
1036
  *
1165
- * The 402 response can include payment requirements in:
1166
- * 1. X-Payment-Required header (JSON)
1167
- * 2. WWW-Authenticate header (per x402 spec)
1168
- * 3. Response body (JSON)
1037
+ * ## Resolution
1038
+ * Create a new session using `wallet.getOrCreateSession()`.
1169
1039
  *
1170
- * @param response - The HTTP response with status 402
1171
- * @returns Parsed payment requirements
1172
- * @throws X402ProtocolError if requirements cannot be parsed
1040
+ * @example
1041
+ * ```typescript
1042
+ * catch (error) {
1043
+ * if (error instanceof SessionRevokedError) {
1044
+ * console.log(`Session ${error.sessionId} was revoked`);
1045
+ * if (error.reason) console.log(`Reason: ${error.reason}`);
1046
+ * }
1047
+ * }
1048
+ * ```
1173
1049
  */
1174
- declare function parse402Response(response: Response): Promise<PaymentRequirements>;
1050
+ declare class SessionRevokedError extends MixrPayError {
1051
+ /** The session ID that was revoked */
1052
+ readonly sessionId: string;
1053
+ /** Optional reason for revocation */
1054
+ readonly reason?: string;
1055
+ constructor(sessionId: string, reason?: string);
1056
+ }
1175
1057
  /**
1176
- * Build the X-PAYMENT header value for a payment request.
1177
- *
1178
- * This creates an EIP-3009 transferWithAuthorization, signs it with the session key,
1179
- * and encodes it for the X-PAYMENT header.
1058
+ * Check if an error is a MixrPay SDK error.
1180
1059
  *
1181
- * @param requirements - Payment requirements from the 402 response
1182
- * @param sessionKey - Session key to sign the payment
1183
- * @param walletAddress - The smart wallet address that holds USDC
1184
- * @returns Base64-encoded JSON string for the X-PAYMENT header
1185
- */
1186
- declare function buildXPaymentHeader(requirements: PaymentRequirements, sessionKey: SessionKey, walletAddress: `0x${string}`): Promise<string>;
1187
- /**
1188
- * Check if payment requirements have expired.
1189
- */
1190
- declare function isPaymentExpired(requirements: PaymentRequirements): boolean;
1191
- /**
1192
- * Get payment amount in USD (USDC has 6 decimals).
1193
- */
1194
- declare function getAmountUsd(requirements: PaymentRequirements): number;
1195
- /**
1196
- * Validate that a payment amount is within acceptable limits.
1060
+ * @param error - The error to check
1061
+ * @returns true if the error is a MixrPayError or subclass
1197
1062
  *
1198
- * @param amountUsd - Payment amount in USD
1199
- * @param maxPaymentUsd - Optional client-side maximum per payment
1200
- * @throws X402ProtocolError if the amount exceeds limits
1063
+ * @example
1064
+ * ```typescript
1065
+ * try {
1066
+ * await wallet.fetch(...);
1067
+ * } catch (error) {
1068
+ * if (isMixrPayError(error)) {
1069
+ * console.log('MixrPay error:', error.code, error.message);
1070
+ * } else {
1071
+ * console.log('Other error:', error);
1072
+ * }
1073
+ * }
1074
+ * ```
1201
1075
  */
1202
- declare function validatePaymentAmount(amountUsd: number, maxPaymentUsd?: number): void;
1076
+ declare function isMixrPayError(error: unknown): error is MixrPayError;
1203
1077
 
1204
- export { AgentWallet, type AgentWalletConfig, type CallMerchantApiOptions, type ChargeResult, type ChargeSessionOptions, type CreateSessionOptions, DEFAULT_BASE_URL, DEFAULT_FACILITATOR_URL, DEFAULT_TIMEOUT, type DiagnosticsResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, NETWORKS, type PaymentEvent, PaymentFailedError, type PaymentRequirements, SDK_VERSION, type SessionAuthStatus, type SessionAuthorization, SessionKey, SessionKeyExpiredError, type SessionKeyInfo, type SessionKeyStatsResponse, SpendingLimitExceededError, type SpendingStats, type WalletBalanceResponse, type X402PaymentPayload, X402ProtocolError, buildTransferAuthorizationData, buildXPaymentHeader, generateNonce, getAmountUsd, getErrorMessage, isMixrPayError, isPaymentExpired, parse402Response, validatePaymentAmount };
1078
+ export { AgentWallet, type AgentWalletConfig, type CallMerchantApiOptions, type ChargeResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, type PaymentEvent, PaymentFailedError, SDK_VERSION, type SessionAuthorization, SessionExpiredError, SessionKeyExpiredError, SessionLimitExceededError, SessionNotFoundError, SessionRevokedError, type SessionStats, SpendingLimitExceededError, type SpendingStats, isMixrPayError };