@mixrpay/agent-sdk 0.1.0 → 0.2.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
@@ -312,6 +312,116 @@ interface SessionKeyStatsResponse {
312
312
  /** Expiration timestamp ISO string (null if never) */
313
313
  expiresAt: string | null;
314
314
  }
315
+ /**
316
+ * Options for creating a session authorization with a MixrPay merchant.
317
+ */
318
+ interface CreateSessionOptions {
319
+ /**
320
+ * The merchant's MixrPay public key.
321
+ * Format: `pk_live_...` or `pk_test_...`
322
+ */
323
+ merchantPublicKey: string;
324
+ /**
325
+ * Maximum spending limit for this session in USD.
326
+ * @default 25.00
327
+ */
328
+ spendingLimitUsd?: number;
329
+ /**
330
+ * Number of days this session should be valid.
331
+ * @default 7
332
+ */
333
+ durationDays?: number;
334
+ }
335
+ /**
336
+ * Status of a session authorization.
337
+ */
338
+ type SessionAuthStatus = 'pending' | 'active' | 'expired' | 'revoked';
339
+ /**
340
+ * A session authorization with a MixrPay merchant.
341
+ *
342
+ * This represents a user-approved spending permission for a specific merchant.
343
+ */
344
+ interface SessionAuthorization {
345
+ /** Unique session ID */
346
+ id: string;
347
+ /** Merchant ID */
348
+ merchantId: string;
349
+ /** Merchant name */
350
+ merchantName: string;
351
+ /** Current session status */
352
+ status: SessionAuthStatus;
353
+ /** Maximum spending limit in USD */
354
+ spendingLimitUsd: number;
355
+ /** Amount already spent in USD */
356
+ amountUsedUsd: number;
357
+ /** Remaining spending limit in USD */
358
+ remainingLimitUsd: number;
359
+ /** When the session expires */
360
+ expiresAt: Date;
361
+ /** When the session was created */
362
+ createdAt: Date;
363
+ }
364
+ /**
365
+ * Options for calling a MixrPay merchant's API.
366
+ */
367
+ interface CallMerchantApiOptions {
368
+ /**
369
+ * The merchant API URL to call.
370
+ */
371
+ url: string;
372
+ /**
373
+ * HTTP method (default: 'POST').
374
+ */
375
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
376
+ /**
377
+ * Request body (will be JSON-serialized if object).
378
+ */
379
+ body?: unknown;
380
+ /**
381
+ * Additional headers to include.
382
+ */
383
+ headers?: Record<string, string>;
384
+ /**
385
+ * The merchant's MixrPay public key.
386
+ * Required to identify which session to use.
387
+ */
388
+ merchantPublicKey: string;
389
+ /**
390
+ * Expected price in USD for this request.
391
+ * Used for client-side validation.
392
+ */
393
+ priceUsd?: number;
394
+ /**
395
+ * Feature slug for tracking/analytics.
396
+ */
397
+ feature?: string;
398
+ }
399
+ /**
400
+ * Options for charging against a session.
401
+ */
402
+ interface ChargeSessionOptions {
403
+ /** Feature slug for tracking */
404
+ feature?: string;
405
+ /** Idempotency key to prevent double-charges */
406
+ idempotencyKey?: string;
407
+ /** Additional metadata */
408
+ metadata?: Record<string, unknown>;
409
+ }
410
+ /**
411
+ * Result of a session charge.
412
+ */
413
+ interface ChargeResult {
414
+ /** Whether the charge succeeded */
415
+ success: boolean;
416
+ /** Charge ID */
417
+ chargeId: string;
418
+ /** Amount charged in USD */
419
+ amountUsd: number;
420
+ /** Transaction hash (if on-chain) */
421
+ txHash?: string;
422
+ /** Remaining session balance in USD */
423
+ remainingSessionBalanceUsd: number;
424
+ }
315
425
 
316
426
  /**
317
427
  * MixrPay Agent SDK - AgentWallet
@@ -587,6 +697,127 @@ declare class AgentWallet {
587
697
  * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
588
698
  */
589
699
  setLogLevel(level: LogLevel): void;
700
+ /**
701
+ * Create the X-Session-Auth header for secure API authentication.
702
+ * Uses signature-based authentication - private key is NEVER transmitted.
703
+ *
704
+ * @returns Headers object with X-Session-Auth
705
+ */
706
+ private getSessionAuthHeaders;
707
+ /**
708
+ * Get an existing session or create a new one with a MixrPay merchant.
709
+ *
710
+ * This is the recommended way to interact with MixrPay-enabled APIs.
711
+ * If an active session exists, it will be returned. Otherwise, a new
712
+ * session authorization request will be created and confirmed.
713
+ *
714
+ * @param options - Session creation options
715
+ * @returns Active session authorization
716
+ *
717
+ * @throws {MixrPayError} If merchant is not found or session creation fails
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * const session = await wallet.getOrCreateSession({
722
+ * merchantPublicKey: 'pk_live_abc123...',
723
+ * spendingLimitUsd: 25.00,
724
+ * durationDays: 7,
725
+ * });
726
+ *
727
+ * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
728
+ * ```
729
+ */
730
+ getOrCreateSession(options: CreateSessionOptions): Promise<SessionAuthorization>;
731
+ /**
732
+ * Get session status for a specific merchant.
733
+ *
734
+ * @param merchantPublicKey - The merchant's public key
735
+ * @returns Session authorization or null if not found
736
+ */
737
+ getSessionByMerchant(merchantPublicKey: string): Promise<SessionAuthorization | null>;
738
+ /**
739
+ * List all session authorizations for this wallet.
740
+ *
741
+ * @returns Array of session authorizations
742
+ *
743
+ * @example
744
+ * ```typescript
745
+ * const sessions = await wallet.listSessions();
746
+ * for (const session of sessions) {
747
+ * console.log(`${session.merchantName}: $${session.remainingLimitUsd} remaining`);
748
+ * }
749
+ * ```
750
+ */
751
+ listSessions(): Promise<SessionAuthorization[]>;
752
+ /**
753
+ * Revoke a session authorization.
754
+ *
755
+ * After revocation, no further charges can be made against this session.
756
+ *
757
+ * @param sessionId - The session ID to revoke
758
+ * @returns true if revoked successfully
759
+ *
760
+ * @example
761
+ * ```typescript
762
+ * const revoked = await wallet.revokeSession('sess_abc123');
763
+ * if (revoked) {
764
+ * console.log('Session revoked successfully');
765
+ * }
766
+ * ```
767
+ */
768
+ revokeSession(sessionId: string): Promise<boolean>;
769
+ /**
770
+ * Charge against an active session authorization.
771
+ *
772
+ * This is useful when you need to manually charge a session outside of
773
+ * the `callMerchantApi()` flow.
774
+ *
775
+ * @param sessionId - The session ID to charge
776
+ * @param amountUsd - Amount to charge in USD
777
+ * @param options - Additional charge options
778
+ * @returns Charge result
779
+ *
780
+ * @example
781
+ * ```typescript
782
+ * const result = await wallet.chargeSession('sess_abc123', 0.05, {
783
+ * feature: 'ai-generation',
784
+ * idempotencyKey: 'unique-key-123',
785
+ * });
786
+ *
787
+ * console.log(`Charged $${result.amountUsd}, remaining: $${result.remainingSessionBalanceUsd}`);
788
+ * ```
789
+ */
790
+ chargeSession(sessionId: string, amountUsd: number, options?: ChargeSessionOptions): Promise<ChargeResult>;
791
+ /**
792
+ * Call a MixrPay merchant's API with automatic session management.
793
+ *
794
+ * This is the recommended way to interact with MixrPay-enabled APIs.
795
+ * It automatically:
796
+ * 1. Gets or creates a session authorization
797
+ * 2. Adds the `X-Mixr-Session` header to the request
798
+ * 3. Handles payment errors and session expiration
799
+ *
800
+ * @param options - API call options
801
+ * @returns Response from the merchant API
802
+ *
803
+ * @example
804
+ * ```typescript
805
+ * const response = await wallet.callMerchantApi({
806
+ * url: 'https://api.merchant.com/generate',
807
+ * merchantPublicKey: 'pk_live_abc123...',
808
+ * method: 'POST',
809
+ * body: { prompt: 'Hello world' },
810
+ * priceUsd: 0.05,
811
+ * });
812
+ *
813
+ * const data = await response.json();
814
+ * ```
815
+ */
816
+ callMerchantApi(options: CallMerchantApiOptions): Promise<Response>;
817
+ /**
818
+ * Parse session response data into SessionAuthorization object.
819
+ */
820
+ private parseSessionResponse;
590
821
  }
591
822
 
592
823
  /**
@@ -865,6 +1096,11 @@ declare class SessionKey {
865
1096
  readonly address: `0x${string}`;
866
1097
  readonly isTest: boolean;
867
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;
868
1104
  /**
869
1105
  * Parse a session key string into a SessionKey object.
870
1106
  *
@@ -881,6 +1117,13 @@ declare class SessionKey {
881
1117
  * @returns Hex-encoded signature
882
1118
  */
883
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>;
884
1127
  /**
885
1128
  * Get the chain ID based on whether this is a test key.
886
1129
  */
@@ -958,4 +1201,4 @@ declare function getAmountUsd(requirements: PaymentRequirements): number;
958
1201
  */
959
1202
  declare function validatePaymentAmount(amountUsd: number, maxPaymentUsd?: number): void;
960
1203
 
961
- export { AgentWallet, type AgentWalletConfig, DEFAULT_BASE_URL, DEFAULT_FACILITATOR_URL, DEFAULT_TIMEOUT, type DiagnosticsResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, NETWORKS, type PaymentEvent, PaymentFailedError, type PaymentRequirements, SDK_VERSION, SessionKey, SessionKeyExpiredError, type SessionKeyInfo, type SessionKeyStatsResponse, SpendingLimitExceededError, type SpendingStats, type WalletBalanceResponse, type X402PaymentPayload, X402ProtocolError, buildTransferAuthorizationData, buildXPaymentHeader, generateNonce, getAmountUsd, getErrorMessage, isMixrPayError, isPaymentExpired, parse402Response, validatePaymentAmount };
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 };
package/dist/index.d.ts CHANGED
@@ -312,6 +312,116 @@ interface SessionKeyStatsResponse {
312
312
  /** Expiration timestamp ISO string (null if never) */
313
313
  expiresAt: string | null;
314
314
  }
315
+ /**
316
+ * Options for creating a session authorization with a MixrPay merchant.
317
+ */
318
+ interface CreateSessionOptions {
319
+ /**
320
+ * The merchant's MixrPay public key.
321
+ * Format: `pk_live_...` or `pk_test_...`
322
+ */
323
+ merchantPublicKey: string;
324
+ /**
325
+ * Maximum spending limit for this session in USD.
326
+ * @default 25.00
327
+ */
328
+ spendingLimitUsd?: number;
329
+ /**
330
+ * Number of days this session should be valid.
331
+ * @default 7
332
+ */
333
+ durationDays?: number;
334
+ }
335
+ /**
336
+ * Status of a session authorization.
337
+ */
338
+ type SessionAuthStatus = 'pending' | 'active' | 'expired' | 'revoked';
339
+ /**
340
+ * A session authorization with a MixrPay merchant.
341
+ *
342
+ * This represents a user-approved spending permission for a specific merchant.
343
+ */
344
+ interface SessionAuthorization {
345
+ /** Unique session ID */
346
+ id: string;
347
+ /** Merchant ID */
348
+ merchantId: string;
349
+ /** Merchant name */
350
+ merchantName: string;
351
+ /** Current session status */
352
+ status: SessionAuthStatus;
353
+ /** Maximum spending limit in USD */
354
+ spendingLimitUsd: number;
355
+ /** Amount already spent in USD */
356
+ amountUsedUsd: number;
357
+ /** Remaining spending limit in USD */
358
+ remainingLimitUsd: number;
359
+ /** When the session expires */
360
+ expiresAt: Date;
361
+ /** When the session was created */
362
+ createdAt: Date;
363
+ }
364
+ /**
365
+ * Options for calling a MixrPay merchant's API.
366
+ */
367
+ interface CallMerchantApiOptions {
368
+ /**
369
+ * The merchant API URL to call.
370
+ */
371
+ url: string;
372
+ /**
373
+ * HTTP method (default: 'POST').
374
+ */
375
+ method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
376
+ /**
377
+ * Request body (will be JSON-serialized if object).
378
+ */
379
+ body?: unknown;
380
+ /**
381
+ * Additional headers to include.
382
+ */
383
+ headers?: Record<string, string>;
384
+ /**
385
+ * The merchant's MixrPay public key.
386
+ * Required to identify which session to use.
387
+ */
388
+ merchantPublicKey: string;
389
+ /**
390
+ * Expected price in USD for this request.
391
+ * Used for client-side validation.
392
+ */
393
+ priceUsd?: number;
394
+ /**
395
+ * Feature slug for tracking/analytics.
396
+ */
397
+ feature?: string;
398
+ }
399
+ /**
400
+ * Options for charging against a session.
401
+ */
402
+ interface ChargeSessionOptions {
403
+ /** Feature slug for tracking */
404
+ feature?: string;
405
+ /** Idempotency key to prevent double-charges */
406
+ idempotencyKey?: string;
407
+ /** Additional metadata */
408
+ metadata?: Record<string, unknown>;
409
+ }
410
+ /**
411
+ * Result of a session charge.
412
+ */
413
+ interface ChargeResult {
414
+ /** Whether the charge succeeded */
415
+ success: boolean;
416
+ /** Charge ID */
417
+ chargeId: string;
418
+ /** Amount charged in USD */
419
+ amountUsd: number;
420
+ /** Transaction hash (if on-chain) */
421
+ txHash?: string;
422
+ /** Remaining session balance in USD */
423
+ remainingSessionBalanceUsd: number;
424
+ }
315
425
 
316
426
  /**
317
427
  * MixrPay Agent SDK - AgentWallet
@@ -587,6 +697,127 @@ declare class AgentWallet {
587
697
  * @param level - 'debug' | 'info' | 'warn' | 'error' | 'none'
588
698
  */
589
699
  setLogLevel(level: LogLevel): void;
700
+ /**
701
+ * Create the X-Session-Auth header for secure API authentication.
702
+ * Uses signature-based authentication - private key is NEVER transmitted.
703
+ *
704
+ * @returns Headers object with X-Session-Auth
705
+ */
706
+ private getSessionAuthHeaders;
707
+ /**
708
+ * Get an existing session or create a new one with a MixrPay merchant.
709
+ *
710
+ * This is the recommended way to interact with MixrPay-enabled APIs.
711
+ * If an active session exists, it will be returned. Otherwise, a new
712
+ * session authorization request will be created and confirmed.
713
+ *
714
+ * @param options - Session creation options
715
+ * @returns Active session authorization
716
+ *
717
+ * @throws {MixrPayError} If merchant is not found or session creation fails
718
+ *
719
+ * @example
720
+ * ```typescript
721
+ * const session = await wallet.getOrCreateSession({
722
+ * merchantPublicKey: 'pk_live_abc123...',
723
+ * spendingLimitUsd: 25.00,
724
+ * durationDays: 7,
725
+ * });
726
+ *
727
+ * console.log(`Session active: $${session.remainingLimitUsd} remaining`);
728
+ * ```
729
+ */
730
+ getOrCreateSession(options: CreateSessionOptions): Promise<SessionAuthorization>;
731
+ /**
732
+ * Get session status for a specific merchant.
733
+ *
734
+ * @param merchantPublicKey - The merchant's public key
735
+ * @returns Session authorization or null if not found
736
+ */
737
+ getSessionByMerchant(merchantPublicKey: string): Promise<SessionAuthorization | null>;
738
+ /**
739
+ * List all session authorizations for this wallet.
740
+ *
741
+ * @returns Array of session authorizations
742
+ *
743
+ * @example
744
+ * ```typescript
745
+ * const sessions = await wallet.listSessions();
746
+ * for (const session of sessions) {
747
+ * console.log(`${session.merchantName}: $${session.remainingLimitUsd} remaining`);
748
+ * }
749
+ * ```
750
+ */
751
+ listSessions(): Promise<SessionAuthorization[]>;
752
+ /**
753
+ * Revoke a session authorization.
754
+ *
755
+ * After revocation, no further charges can be made against this session.
756
+ *
757
+ * @param sessionId - The session ID to revoke
758
+ * @returns true if revoked successfully
759
+ *
760
+ * @example
761
+ * ```typescript
762
+ * const revoked = await wallet.revokeSession('sess_abc123');
763
+ * if (revoked) {
764
+ * console.log('Session revoked successfully');
765
+ * }
766
+ * ```
767
+ */
768
+ revokeSession(sessionId: string): Promise<boolean>;
769
+ /**
770
+ * Charge against an active session authorization.
771
+ *
772
+ * This is useful when you need to manually charge a session outside of
773
+ * the `callMerchantApi()` flow.
774
+ *
775
+ * @param sessionId - The session ID to charge
776
+ * @param amountUsd - Amount to charge in USD
777
+ * @param options - Additional charge options
778
+ * @returns Charge result
779
+ *
780
+ * @example
781
+ * ```typescript
782
+ * const result = await wallet.chargeSession('sess_abc123', 0.05, {
783
+ * feature: 'ai-generation',
784
+ * idempotencyKey: 'unique-key-123',
785
+ * });
786
+ *
787
+ * console.log(`Charged $${result.amountUsd}, remaining: $${result.remainingSessionBalanceUsd}`);
788
+ * ```
789
+ */
790
+ chargeSession(sessionId: string, amountUsd: number, options?: ChargeSessionOptions): Promise<ChargeResult>;
791
+ /**
792
+ * Call a MixrPay merchant's API with automatic session management.
793
+ *
794
+ * This is the recommended way to interact with MixrPay-enabled APIs.
795
+ * It automatically:
796
+ * 1. Gets or creates a session authorization
797
+ * 2. Adds the `X-Mixr-Session` header to the request
798
+ * 3. Handles payment errors and session expiration
799
+ *
800
+ * @param options - API call options
801
+ * @returns Response from the merchant API
802
+ *
803
+ * @example
804
+ * ```typescript
805
+ * const response = await wallet.callMerchantApi({
806
+ * url: 'https://api.merchant.com/generate',
807
+ * merchantPublicKey: 'pk_live_abc123...',
808
+ * method: 'POST',
809
+ * body: { prompt: 'Hello world' },
810
+ * priceUsd: 0.05,
811
+ * });
812
+ *
813
+ * const data = await response.json();
814
+ * ```
815
+ */
816
+ callMerchantApi(options: CallMerchantApiOptions): Promise<Response>;
817
+ /**
818
+ * Parse session response data into SessionAuthorization object.
819
+ */
820
+ private parseSessionResponse;
590
821
  }
591
822
 
592
823
  /**
@@ -865,6 +1096,11 @@ declare class SessionKey {
865
1096
  readonly address: `0x${string}`;
866
1097
  readonly isTest: boolean;
867
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;
868
1104
  /**
869
1105
  * Parse a session key string into a SessionKey object.
870
1106
  *
@@ -881,6 +1117,13 @@ declare class SessionKey {
881
1117
  * @returns Hex-encoded signature
882
1118
  */
883
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>;
884
1127
  /**
885
1128
  * Get the chain ID based on whether this is a test key.
886
1129
  */
@@ -958,4 +1201,4 @@ declare function getAmountUsd(requirements: PaymentRequirements): number;
958
1201
  */
959
1202
  declare function validatePaymentAmount(amountUsd: number, maxPaymentUsd?: number): void;
960
1203
 
961
- export { AgentWallet, type AgentWalletConfig, DEFAULT_BASE_URL, DEFAULT_FACILITATOR_URL, DEFAULT_TIMEOUT, type DiagnosticsResult, InsufficientBalanceError, InvalidSessionKeyError, MixrPayError, NETWORKS, type PaymentEvent, PaymentFailedError, type PaymentRequirements, SDK_VERSION, SessionKey, SessionKeyExpiredError, type SessionKeyInfo, type SessionKeyStatsResponse, SpendingLimitExceededError, type SpendingStats, type WalletBalanceResponse, type X402PaymentPayload, X402ProtocolError, buildTransferAuthorizationData, buildXPaymentHeader, generateNonce, getAmountUsd, getErrorMessage, isMixrPayError, isPaymentExpired, parse402Response, validatePaymentAmount };
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 };