@dcentralab/d402-client 0.2.7 → 0.3.2

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
@@ -4,35 +4,6 @@ import { PublicClient, WalletClient, Hash, Address } from 'viem';
4
4
  /**
5
5
  * Type definitions for D402 payment protocol
6
6
  */
7
-
8
- /**
9
- * Supported blockchain networks (where IATP contracts are deployed)
10
- */
11
- type SupportedNetwork = 'sepolia';
12
- /**
13
- * D402 Client configuration
14
- */
15
- interface D402Config {
16
- /** Viem account for signing payments */
17
- account: Account;
18
- /** Blockchain network */
19
- network: SupportedNetwork;
20
- /** Maximum payment amount in wei (smallest token unit) */
21
- maxPaymentAmount: bigint;
22
- /** Token contract address (defaults to USDC if not provided) */
23
- tokenAddress?: `0x${string}`;
24
- /** Payment validity window in seconds (default: 300) */
25
- validityWindowSeconds?: number;
26
- }
27
- /**
28
- * EIP-712 domain for signature verification
29
- */
30
- interface EIP712Domain {
31
- name: string;
32
- version: string;
33
- chainId: number;
34
- verifyingContract: `0x${string}`;
35
- }
36
7
  /**
37
8
  * Payment requirement from 402 response.
38
9
  *
@@ -105,6 +76,24 @@ interface SignedPayment {
105
76
  authorization: PaymentAuthorization;
106
77
  };
107
78
  }
79
+ /**
80
+ * Raw 402 response structure
81
+ */
82
+ interface D402Response {
83
+ d402Version: number;
84
+ accepts?: PaymentRequirement[];
85
+ scheme?: string;
86
+ network?: string;
87
+ maxAmountRequired?: string;
88
+ payTo?: `0x${string}`;
89
+ asset?: `0x${string}`;
90
+ resource?: string;
91
+ extra?: {
92
+ name: string;
93
+ version: string;
94
+ chainId: number;
95
+ };
96
+ }
108
97
 
109
98
  /**
110
99
  * Payment requirements selection logic
@@ -126,9 +115,11 @@ interface PaymentSelectorOptions {
126
115
  preferredToken?: string;
127
116
  }
128
117
  /**
129
- * Select payment requirement from a list based on filters and preferences
118
+ * Select payment requirement from a list based on filters and preferences.
130
119
  *
131
- * This function implements the same logic as
120
+ * Applies filters (network, scheme, maxAmount) and preferences to choose
121
+ * the most appropriate payment option from the list. Prefers matching
122
+ * preferred network/token if specified, otherwise uses filters.
132
123
  *
133
124
  * @param requirements - List of accepted payment requirements from 402 response
134
125
  * @param options - Selection options and filters
@@ -138,11 +129,13 @@ interface PaymentSelectorOptions {
138
129
  * @throws {PaymentAmountExceededError} If payment exceeds max amount
139
130
  *
140
131
  * @example
132
+ * ```ts
141
133
  * const selected = selectPaymentRequirement(requirements, {
142
134
  * scheme: 'exact',
143
135
  * network: 'base-mainnet',
144
136
  * maxAmount: 1000000n
145
137
  * })
138
+ * ```
146
139
  */
147
140
  declare function selectPaymentRequirement(requirements: PaymentRequirement[], options?: PaymentSelectorOptions): PaymentRequirement;
148
141
  /**
@@ -173,6 +166,26 @@ declare function createPaymentSelector(defaultOptions: PaymentSelectorOptions):
173
166
  * @returns Sorted list (preferred first)
174
167
  */
175
168
  declare function sortPaymentRequirements(requirements: PaymentRequirement[], preferredNetwork?: string): PaymentRequirement[];
169
+ /**
170
+ * Find matching payment requirement from a list.
171
+ *
172
+ * Simple helper to find a requirement matching scheme and network.
173
+ * For more complex selection logic, use selectPaymentRequirement() instead.
174
+ *
175
+ * @param requirements - List of payment requirements
176
+ * @param scheme - Desired payment scheme (default: "exact")
177
+ * @param network - Desired network (optional)
178
+ * @returns Matching payment requirement or undefined
179
+ *
180
+ * @example
181
+ * ```ts
182
+ * const match = findMatchingPaymentRequirement(requirements, 'exact', 'sepolia')
183
+ * if (match) {
184
+ * console.log('Found exact payment on Sepolia')
185
+ * }
186
+ * ```
187
+ */
188
+ declare function findMatchingPaymentRequirement(requirements: PaymentRequirement[], scheme?: string, network?: string): PaymentRequirement | undefined;
176
189
 
177
190
  /**
178
191
  * D402 Client - Main client class for handling HTTP 402 payments
@@ -444,6 +457,25 @@ declare function signD402Payment(params: {
444
457
  * ```
445
458
  */
446
459
  declare function parsePaymentRequirement(response: Response): Promise<PaymentRequirement>;
460
+ /**
461
+ * Parse all payment requirements from 402 response.
462
+ *
463
+ * Similar to parsePaymentRequirement but returns all options instead of just first.
464
+ * Useful when client needs to choose from multiple payment options.
465
+ *
466
+ * @param response - HTTP Response object with status 402
467
+ * @returns Array of all payment requirements
468
+ * @throws {Invalid402ResponseError} If response is invalid
469
+ *
470
+ * @example
471
+ * ```ts
472
+ * const response = await fetch('http://api.example.com')
473
+ * const allOptions = await parseAllPaymentRequirements(response)
474
+ * // Choose based on network, token, etc.
475
+ * const preferred = allOptions.find(r => r.network === 'sepolia')
476
+ * ```
477
+ */
478
+ declare function parseAllPaymentRequirements(response: Response): Promise<PaymentRequirement[]>;
447
479
 
448
480
  /**
449
481
  * Base64 encoding/decoding for payment payloads
@@ -483,123 +515,26 @@ declare function encodePayment(payment: SignedPayment): string;
483
515
  * ```
484
516
  */
485
517
  declare function decodePayment(encodedPayment: string): SignedPayment;
486
-
487
- /**
488
- * Utility functions for D402 payment processing
489
- */
490
-
491
- /**
492
- * Parse a money string or number into atomic units (wei)
493
- *
494
- * @param amount - Amount as string (e.g., "$1.00", "1.5") or number
495
- * @param decimals - Token decimals (e.g., 6 for USDC, 18 for ETH)
496
- * @returns Amount in atomic units (wei)
497
- *
498
- * @example
499
- * parseMoney("$1.00", 6) // Returns 1000000n (1 USDC in wei)
500
- * parseMoney("0.5", 18) // Returns 500000000000000000n (0.5 ETH in wei)
501
- */
502
- declare function parseMoney(amount: string | number | bigint, decimals: number): bigint;
503
- /**
504
- * Format atomic units back to human-readable format
505
- *
506
- * @param amount - Amount in atomic units (wei)
507
- * @param decimals - Token decimals
508
- * @returns Formatted string
509
- *
510
- * @example
511
- * formatMoney(1000000n, 6) // Returns "1.000000"
512
- */
513
- declare function formatMoney(amount: bigint, decimals: number): string;
514
- /**
515
- * Get USDC token address for a given network
516
- *
517
- * @param network - Network name
518
- * @returns USDC token address
519
- *
520
- * @throws {UnsupportedNetworkError} If network is not supported
521
- */
522
- declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
523
518
  /**
524
- * Get chain ID for a given network.
525
- *
526
- * This function maps network names to chain IDs for parsing 402 payment requirements
527
- * from external APIs. It supports many networks that may appear in 402 responses,
528
- * even if IATP contracts are not deployed on those networks.
529
- *
530
- * Note: IATP contracts are currently only deployed on Sepolia. This function exists
531
- * to handle 402 responses from any API that might support other networks.
519
+ * Decode X-PAYMENT-RESPONSE header from server.
532
520
  *
533
- * @param network - Network name or chain ID as string
534
- * @returns Chain ID as number
521
+ * After a successful payment, servers may return payment confirmation
522
+ * in the X-PAYMENT-RESPONSE header. This function decodes it.
535
523
  *
536
- * @throws {UnsupportedNetworkError} If network is not supported
524
+ * @param header - Base64 encoded payment response header
525
+ * @returns Decoded payment response object
537
526
  *
538
527
  * @example
539
528
  * ```ts
540
- * getChainId('sepolia') // Returns 11155111
541
- * getChainId('11155111') // Returns 11155111 (passthrough)
542
- * getChainId('base') // Returns 8453 (for parsing 402 responses)
543
- * ```
544
- */
545
- declare function getChainId(network: string): number;
546
- /**
547
- * Find matching payment requirement from a list
548
- *
549
- * @param requirements - List of payment requirements
550
- * @param scheme - Desired payment scheme (default: "exact")
551
- * @param network - Desired network (optional)
552
- * @returns Matching payment requirement or undefined
553
- */
554
- declare function findMatchingPaymentRequirement(requirements: PaymentRequirement[], scheme?: string, network?: string): PaymentRequirement | undefined;
555
- /**
556
- * Convert USD amount to USDC atomic units
557
- *
558
- * @param usdAmount - Amount in USD (e.g., "1.00" or 1.5)
559
- * @param decimals - USDC decimals (default: 6)
560
- * @returns Amount in USDC atomic units
561
- *
562
- * @example
563
- * usdToUsdc("1.00") // Returns 1000000n
564
- * usdToUsdc(1.5) // Returns 1500000n
565
- */
566
- declare function usdToUsdc(usdAmount: string | number, decimals?: number): bigint;
567
- /**
568
- * Generate a random nonce for payment authorization
569
- *
570
- * @returns Random 32-byte nonce as hex string
571
- */
572
- declare function generateNonce(): `0x${string}`;
573
- /**
574
- * Get current timestamp in seconds
575
- *
576
- * @returns Unix timestamp in seconds
577
- */
578
- declare function getCurrentTimestamp(): number;
579
- /**
580
- * Validate Ethereum address format
581
- *
582
- * @param address - Address to validate
583
- * @returns True if valid Ethereum address
584
- */
585
- declare function isValidAddress(address: string): boolean;
586
- /**
587
- * Normalize Ethereum address to checksummed format
588
- * Note: This is a simple lowercase normalization. For full checksum validation, use viem's getAddress()
589
- *
590
- * @param address - Address to normalize
591
- * @returns Normalized address
592
- */
593
- declare function normalizeAddress(address: string): `0x${string}`;
594
- /**
595
- * Decode X-PAYMENT-RESPONSE header from server
596
- *
597
- * @param header - Base64 encoded payment response
598
- * @returns Decoded payment response
529
+ * const response = await fetch(url, { headers: { 'X-Payment': payment } })
530
+ * const responseHeader = response.headers.get('X-Payment-Response')
599
531
  *
600
- * @example
601
- * const response = decodePaymentResponse(responseHeader)
602
- * console.log(response.success, response.transaction)
532
+ * if (responseHeader) {
533
+ * const paymentResponse = decodePaymentResponse(responseHeader)
534
+ * console.log('Success:', paymentResponse.success)
535
+ * console.log('Transaction:', paymentResponse.transaction)
536
+ * }
537
+ * ```
603
538
  */
604
539
  declare function decodePaymentResponse(header: string): {
605
540
  success: boolean;
@@ -610,118 +545,7 @@ declare function decodePaymentResponse(header: string): {
610
545
  };
611
546
 
612
547
  /**
613
- * Error classes for D402 payment protocol
614
- */
615
- /**
616
- * Base error class for all payment-related errors
617
- */
618
- declare class PaymentError extends Error {
619
- constructor(message: string);
620
- }
621
- /**
622
- * Thrown when payment amount exceeds the configured maximum allowed value
623
- */
624
- declare class PaymentAmountExceededError extends PaymentError {
625
- amount: bigint;
626
- maxAmount: bigint;
627
- tokenAddress?: string | undefined;
628
- constructor(amount: bigint, maxAmount: bigint, tokenAddress?: string | undefined);
629
- }
630
- /**
631
- * Thrown when request configuration is missing required fields
632
- */
633
- declare class MissingRequestConfigError extends PaymentError {
634
- constructor(message: string);
635
- }
636
- /**
637
- * Thrown when payment has already been attempted for a request
638
- */
639
- declare class PaymentAlreadyAttemptedError extends PaymentError {
640
- constructor(message?: string);
641
- }
642
- /**
643
- * Thrown when no supported payment scheme is found in payment requirements
644
- */
645
- declare class UnsupportedSchemeError extends PaymentError {
646
- availableSchemes: string[];
647
- constructor(availableSchemes: string[], message?: string);
648
- }
649
- /**
650
- * Thrown when payment verification fails
651
- */
652
- declare class PaymentVerificationError extends PaymentError {
653
- constructor(message: string);
654
- }
655
- /**
656
- * Thrown when HTTP 402 response is malformed
657
- */
658
- declare class Invalid402ResponseError extends PaymentError {
659
- constructor(message: string);
660
- }
661
- /**
662
- * Thrown when network is not supported
663
- */
664
- declare class UnsupportedNetworkError extends PaymentError {
665
- network: string;
666
- constructor(network: string);
667
- }
668
-
669
- /**
670
- * Network and token constants
671
- */
672
-
673
- /**
674
- * Chain IDs for supported networks
675
- */
676
- declare const CHAIN_IDS: Record<SupportedNetwork, number>;
677
- /**
678
- * Network configuration
679
- */
680
- declare const NETWORKS: Record<SupportedNetwork, {
681
- chainId: number;
682
- name: string;
683
- nativeCurrency: {
684
- name: string;
685
- symbol: string;
686
- decimals: number;
687
- };
688
- }>;
689
- /**
690
- * Default USDC token addresses per network
691
- */
692
- declare const TOKEN_ADDRESSES: Record<SupportedNetwork, `0x${string}`>;
693
- /**
694
- * Default payment validity window (5 minutes)
695
- */
696
- declare const DEFAULT_VALIDITY_WINDOW_SECONDS = 300;
697
- /**
698
- * EIP-712 type definitions for PullFundsForSettlement
699
- */
700
- declare const EIP712_TYPES: {
701
- readonly PullFundsForSettlement: readonly [{
702
- readonly name: "wallet";
703
- readonly type: "address";
704
- }, {
705
- readonly name: "provider";
706
- readonly type: "address";
707
- }, {
708
- readonly name: "token";
709
- readonly type: "address";
710
- }, {
711
- readonly name: "amount";
712
- readonly type: "uint256";
713
- }, {
714
- readonly name: "deadline";
715
- readonly type: "uint256";
716
- }, {
717
- readonly name: "requestPath";
718
- readonly type: "string";
719
- }];
720
- };
721
-
722
- /**
723
- * IATPWallet creation and management
724
- *
548
+ * Type definitions for wallet module
725
549
  */
726
550
 
727
551
  /**
@@ -741,6 +565,11 @@ interface WalletCreationResult {
741
565
  /** Chain ID */
742
566
  chainId: number;
743
567
  }
568
+
569
+ /**
570
+ * IATPWallet creation functions
571
+ */
572
+
744
573
  /**
745
574
  * Create a new IATPWallet using IATPWalletFactory.
746
575
  *
@@ -758,7 +587,6 @@ interface WalletCreationResult {
758
587
  * @param params.ownerAccount - Owner's account (will own the wallet)
759
588
  * @param params.network - Network to deploy on (default: "sepolia")
760
589
  * @param params.rpcUrl - Custom RPC URL (optional)
761
- * @param params.operatorPrivateKey - Use specific operator key instead of generating (optional)
762
590
  * @returns Wallet creation result with addresses and keys
763
591
  *
764
592
  * @example
@@ -774,7 +602,6 @@ interface WalletCreationResult {
774
602
  * })
775
603
  *
776
604
  * console.log('Wallet created:', result.walletAddress)
777
- * console.log('Operator key:', result.operatorPrivateKey) // Store securely!
778
605
  * ```
779
606
  */
780
607
  declare function createIATPWallet(params: {
@@ -782,23 +609,63 @@ declare function createIATPWallet(params: {
782
609
  network?: 'sepolia';
783
610
  rpcUrl?: string;
784
611
  }): Promise<WalletCreationResult>;
612
+
785
613
  /**
786
- * Get all IATPWallet addresses owned by a user.
787
- *
788
- * Queries the IATPWalletFactory contract to retrieve all wallets
789
- * where the specified address is the owner.
614
+ * IATPWallet query functions
615
+ */
616
+
617
+ /**
618
+ * Get available balance for a specific token in an IATPWallet.
790
619
  *
791
- * Use this to check if a user already has a wallet before calling createIATPWallet().
620
+ * Queries the IATPWallet contract's getAvailableBalance function to retrieve
621
+ * the available balance for a given token.
792
622
  *
793
623
  * @param params - Query parameters
794
- * @param params.ownerAddress - User's wallet address (from MetaMask)
624
+ * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
625
+ * @param params.walletAddress - IATPWallet contract address
626
+ * @param params.tokenAddress - Token contract address (e.g., USDC)
795
627
  * @param params.network - Network to query (default: "sepolia")
796
- * @param params.rpcUrl - Custom RPC URL (optional)
797
- * @returns Array of IATPWallet contract addresses (empty if user has no wallets)
628
+ * @returns Available balance in token's base units (wei)
798
629
  *
799
630
  * @example
800
631
  * ```ts
801
- * import { getWalletsByOwner } from '@dcentralab/d402-client'
632
+ * import { getAvailableBalance } from '@dcentralab/d402-client'
633
+ * import { usePublicClient } from 'wagmi'
634
+ *
635
+ * const publicClient = usePublicClient()
636
+ *
637
+ * const balance = await getAvailableBalance({
638
+ * publicClient,
639
+ * walletAddress: '0xUserIATPWallet...',
640
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // USDC on Sepolia
641
+ * })
642
+ *
643
+ * console.log('Available balance:', balance) // 1000000n (1 USDC)
644
+ * ```
645
+ */
646
+ declare function getAvailableBalance(params: {
647
+ publicClient: PublicClient;
648
+ walletAddress: Address;
649
+ tokenAddress: Address;
650
+ network?: 'sepolia';
651
+ }): Promise<bigint>;
652
+ /**
653
+ * Get all IATPWallet addresses owned by a user.
654
+ *
655
+ * Queries the IATPWalletFactory contract to retrieve all wallets
656
+ * where the specified address is the owner.
657
+ *
658
+ * Use this to check if a user already has a wallet before calling createIATPWallet().
659
+ *
660
+ * @param params - Query parameters
661
+ * @param params.ownerAddress - User's wallet address (from MetaMask)
662
+ * @param params.network - Network to query (default: "sepolia")
663
+ * @param params.rpcUrl - Custom RPC URL (optional)
664
+ * @returns Array of IATPWallet contract addresses (empty if user has no wallets)
665
+ *
666
+ * @example
667
+ * ```ts
668
+ * import { getWalletsByOwner } from '@dcentralab/d402-client'
802
669
  * import { useAccount } from 'wagmi'
803
670
  *
804
671
  * const { address } = useAccount()
@@ -821,47 +688,125 @@ declare function getWalletsByOwner(params: {
821
688
  network?: 'sepolia';
822
689
  rpcUrl?: string;
823
690
  }): Promise<Address[]>;
691
+
824
692
  /**
825
- * Get available balance for a specific token in an IATPWallet.
693
+ * IATPWallet withdrawal functions
694
+ */
695
+
696
+ /**
697
+ * Get withdrawal request for a token in an IATPWallet.
826
698
  *
827
- * Queries the IATPWallet contract's getAvailableBalance function to retrieve
828
- * the available balance for a given token.
699
+ * Queries the IATPWallet contract to get the current withdrawal request
700
+ * (amount and unlock timestamp) for a specific token.
829
701
  *
830
702
  * @param params - Query parameters
831
- * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
703
+ * @param params.publicClient - Viem PublicClient
832
704
  * @param params.walletAddress - IATPWallet contract address
833
- * @param params.tokenAddress - Token contract address (e.g., USDC)
705
+ * @param params.tokenAddress - Token contract address
834
706
  * @param params.network - Network to query (default: "sepolia")
835
- * @returns Available balance in token's base units (wei)
707
+ * @returns Withdrawal request: [amount, unlockTimestamp] or null if no request exists
836
708
  *
837
709
  * @example
838
710
  * ```ts
839
- * import { getAvailableBalance } from '@dcentralab/d402-client'
840
- * import { usePublicClient } from 'wagmi'
711
+ * import { getWithdrawalRequest } from '@dcentralab/d402-client'
841
712
  *
842
- * const publicClient = usePublicClient()
713
+ * const request = await getWithdrawalRequest({
714
+ * publicClient,
715
+ * walletAddress: '0xUserIATPWallet...',
716
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
717
+ * })
843
718
  *
844
- * const balance = await getAvailableBalance({
719
+ * if (request) {
720
+ * const [amount, unlockTimestamp] = request
721
+ * const isUnlocked = Date.now() >= Number(unlockTimestamp) * 1000
722
+ * }
723
+ * ```
724
+ */
725
+ declare function getWithdrawalRequest(params: {
726
+ publicClient: PublicClient;
727
+ walletAddress: Address;
728
+ tokenAddress: Address;
729
+ network?: 'sepolia';
730
+ }): Promise<[bigint, bigint] | null>;
731
+ /**
732
+ * Request a withdrawal from an IATPWallet.
733
+ *
734
+ * Initiates a withdrawal request for a token. The withdrawal will be locked
735
+ * for a period (typically 5 minutes) before it can be executed.
736
+ *
737
+ * @param params - Transaction parameters
738
+ * @param params.walletClient - Viem WalletClient (from wagmi useWalletClient)
739
+ * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
740
+ * @param params.walletAddress - IATPWallet contract address
741
+ * @param params.tokenAddress - Token contract address
742
+ * @param params.amount - Amount in token's base units (wei)
743
+ * @param params.account - Account to sign transaction (operator)
744
+ * @param params.network - Network (default: "sepolia")
745
+ * @returns Transaction hash
746
+ *
747
+ * @example
748
+ * ```ts
749
+ * import { requestWithdrawal } from '@dcentralab/d402-client'
750
+ * import { parseUnits } from 'viem'
751
+ *
752
+ * const hash = await requestWithdrawal({
753
+ * walletClient,
845
754
  * publicClient,
846
755
  * walletAddress: '0xUserIATPWallet...',
847
- * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // USDC on Sepolia
756
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
757
+ * amount: parseUnits('100', 6), // 100 USDC (6 decimals)
758
+ * account: walletClient.account,
848
759
  * })
760
+ * ```
761
+ */
762
+ declare function requestWithdrawal(params: {
763
+ walletClient: WalletClient;
764
+ publicClient: PublicClient;
765
+ walletAddress: Address;
766
+ tokenAddress: Address;
767
+ amount: bigint;
768
+ account: Account;
769
+ network?: 'sepolia';
770
+ }): Promise<Hash>;
771
+ /**
772
+ * Execute a withdrawal from an IATPWallet (after unlock period).
849
773
  *
850
- * console.log('Available balance:', balance) // 1000000n (1 USDC)
774
+ * Completes a withdrawal that has passed its unlock period. This transfers
775
+ * the tokens from the IATPWallet back to the user's wallet.
776
+ *
777
+ * @param params - Transaction parameters
778
+ * @param params.walletClient - Viem WalletClient
779
+ * @param params.publicClient - Viem PublicClient
780
+ * @param params.walletAddress - IATPWallet contract address
781
+ * @param params.tokenAddress - Token contract address
782
+ * @param params.account - Account to sign transaction (operator)
783
+ * @param params.network - Network (default: "sepolia")
784
+ * @returns Transaction hash
785
+ *
786
+ * @example
787
+ * ```ts
788
+ * import { executeWithdrawal } from '@dcentralab/d402-client'
789
+ *
790
+ * const hash = await executeWithdrawal({
791
+ * walletClient,
792
+ * publicClient,
793
+ * walletAddress: '0xUserIATPWallet...',
794
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
795
+ * account: walletClient.account,
796
+ * })
851
797
  * ```
852
798
  */
853
- declare function getAvailableBalance(params: {
799
+ declare function executeWithdrawal(params: {
800
+ walletClient: WalletClient;
854
801
  publicClient: PublicClient;
855
802
  walletAddress: Address;
856
803
  tokenAddress: Address;
804
+ account: Account;
857
805
  network?: 'sepolia';
858
- }): Promise<bigint>;
806
+ }): Promise<Hash>;
859
807
 
860
808
  /**
861
- * IATPSettlementLayer contract operations
862
- *
863
- * Functions for providers (utility agents) to query settlement balances,
864
- * epochs, and manage withdrawals from the settlement layer.
809
+ * IATPSettlementLayer query functions
865
810
  */
866
811
 
867
812
  /**
@@ -930,6 +875,13 @@ declare function getUnlockedBalanceForProvider(params: {
930
875
  tokenAddress: Address;
931
876
  network?: 'sepolia';
932
877
  }): Promise<bigint>;
878
+
879
+ /**
880
+ * IATPSettlementLayer operations
881
+ *
882
+ * Functions for managing withdrawals from the settlement layer.
883
+ */
884
+
933
885
  /**
934
886
  * Withdraw all available epochs for a provider (utility agent).
935
887
  *
@@ -965,4 +917,243 @@ declare function withdrawAllAvailableEpochs(params: {
965
917
  network?: 'sepolia';
966
918
  }): Promise<Hash>;
967
919
 
968
- export { CHAIN_IDS, D402Client, type D402ClientConfig, type D402Config, DEFAULT_VALIDITY_WINDOW_SECONDS, type EIP712Domain, EIP712_TYPES, Invalid402ResponseError, MissingRequestConfigError, NETWORKS, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, TOKEN_ADDRESSES, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, isValidAddress, normalizeAddress, parseMoney, parsePaymentRequirement, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };
920
+ /**
921
+ * Core type definitions shared across the package
922
+ */
923
+ /**
924
+ * Supported blockchain networks (where IATP contracts are deployed)
925
+ */
926
+ type SupportedNetwork = 'sepolia';
927
+ /**
928
+ * EIP-712 domain for signature verification
929
+ */
930
+ interface EIP712Domain {
931
+ name: string;
932
+ version: string;
933
+ chainId: number;
934
+ verifyingContract: `0x${string}`;
935
+ }
936
+
937
+ /**
938
+ * Contract configuration and utilities.
939
+ *
940
+ * Provides access to IATPWallet contract ABIs and deployed addresses.
941
+ * Contract data is bundled directly in the package for reliability.
942
+ */
943
+
944
+ /**
945
+ * Supported contract names.
946
+ */
947
+ declare enum ContractName {
948
+ IATP_WALLET = "IATPWallet",
949
+ IATP_WALLET_FACTORY = "IATPWalletFactory",
950
+ IATP_SETTLEMENT_LAYER = "IATPSettlementLayer",
951
+ ROLE_MANAGER = "RoleManager"
952
+ }
953
+ /**
954
+ * Get contract address for a given network.
955
+ *
956
+ * @param contractName - Name of the contract (use ContractName enum)
957
+ * @param network - Network name (default: "sepolia")
958
+ * @param useProxy - Use proxy address if true, implementation if false (default: true)
959
+ * @returns Contract address as hex string, or null if not found
960
+ *
961
+ * @example
962
+ * ```ts
963
+ * const factoryAddr = getContractAddress(ContractName.IATP_WALLET_FACTORY, 'sepolia')
964
+ * console.log(factoryAddr) // "0x15D83638E339a0f29283f6B93dC1bb90b8339078"
965
+ * ```
966
+ */
967
+ declare function getContractAddress(contractName: string | ContractName, network?: SupportedNetwork, useProxy?: boolean): string | null;
968
+ /**
969
+ * Get contract ABI for a given network.
970
+ *
971
+ * @param contractName - Name of the contract (use ContractName enum)
972
+ * @param network - Network name (default: "sepolia")
973
+ * @returns Contract ABI as array of objects, or null if not found
974
+ *
975
+ * @example
976
+ * ```ts
977
+ * const factoryAbi = getContractAbi(ContractName.IATP_WALLET_FACTORY, 'sepolia')
978
+ * console.log(factoryAbi.length) // Number of ABI entries
979
+ * ```
980
+ */
981
+ declare function getContractAbi(contractName: string | ContractName, network?: SupportedNetwork): any[] | null;
982
+ /**
983
+ * Get contract configuration (address and ABI) for a network.
984
+ *
985
+ * @param contractName - Name of the contract
986
+ * @param network - Network name (default: "sepolia")
987
+ * @returns Object with address and abi, or null if not found
988
+ *
989
+ * @example
990
+ * ```ts
991
+ * const config = getContractConfig(ContractName.IATP_WALLET_FACTORY, 'sepolia')
992
+ * if (config) {
993
+ * console.log(config.address)
994
+ * console.log(config.abi.length)
995
+ * }
996
+ * ```
997
+ */
998
+ declare function getContractConfig(contractName: string | ContractName, network?: SupportedNetwork): {
999
+ address: string;
1000
+ abi: any[];
1001
+ } | null;
1002
+
1003
+ /**
1004
+ * Utility functions for D402 payment processing
1005
+ */
1006
+
1007
+ /**
1008
+ * Parse a money string or number into atomic units (wei)
1009
+ *
1010
+ * @param amount - Amount as string (e.g., "$1.00", "1.5") or number
1011
+ * @param decimals - Token decimals (e.g., 6 for USDC, 18 for ETH)
1012
+ * @returns Amount in atomic units (wei)
1013
+ *
1014
+ * @example
1015
+ * parseMoney("$1.00", 6) // Returns 1000000n (1 USDC in wei)
1016
+ * parseMoney("0.5", 18) // Returns 500000000000000000n (0.5 ETH in wei)
1017
+ */
1018
+ declare function parseMoney(amount: string | number | bigint, decimals: number): bigint;
1019
+ /**
1020
+ * Format atomic units back to human-readable format
1021
+ *
1022
+ * @param amount - Amount in atomic units (wei)
1023
+ * @param decimals - Token decimals
1024
+ * @returns Formatted string
1025
+ *
1026
+ * @example
1027
+ * formatMoney(1000000n, 6) // Returns "1.000000"
1028
+ */
1029
+ declare function formatMoney(amount: bigint, decimals: number): string;
1030
+ /**
1031
+ * Get USDC token address for a given network
1032
+ *
1033
+ * @param network - Network name
1034
+ * @returns USDC token address
1035
+ *
1036
+ * @throws {UnsupportedNetworkError} If network is not supported
1037
+ */
1038
+ declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
1039
+ /**
1040
+ * Get chain ID for a given network.
1041
+ *
1042
+ * This function maps network names to chain IDs for parsing 402 payment requirements
1043
+ * from external APIs. It supports many networks that may appear in 402 responses,
1044
+ * even if IATP contracts are not deployed on those networks.
1045
+ *
1046
+ * Note: IATP contracts are currently only deployed on Sepolia. This function exists
1047
+ * to handle 402 responses from any API that might support other networks.
1048
+ *
1049
+ * @param network - Network name or chain ID as string
1050
+ * @returns Chain ID as number
1051
+ *
1052
+ * @throws {UnsupportedNetworkError} If network is not supported
1053
+ *
1054
+ * @example
1055
+ * ```ts
1056
+ * getChainId('sepolia') // Returns 11155111
1057
+ * getChainId('11155111') // Returns 11155111 (passthrough)
1058
+ * getChainId('base') // Returns 8453 (for parsing 402 responses)
1059
+ * ```
1060
+ */
1061
+ declare function getChainId(network: string): number;
1062
+ /**
1063
+ * Convert USD amount to USDC atomic units
1064
+ *
1065
+ * @param usdAmount - Amount in USD (e.g., "1.00" or 1.5)
1066
+ * @param decimals - USDC decimals (default: 6)
1067
+ * @returns Amount in USDC atomic units
1068
+ *
1069
+ * @example
1070
+ * usdToUsdc("1.00") // Returns 1000000n
1071
+ * usdToUsdc(1.5) // Returns 1500000n
1072
+ */
1073
+ declare function usdToUsdc(usdAmount: string | number, decimals?: number): bigint;
1074
+ /**
1075
+ * Generate a random nonce for payment authorization
1076
+ *
1077
+ * @returns Random 32-byte nonce as hex string
1078
+ */
1079
+ declare function generateNonce(): `0x${string}`;
1080
+ /**
1081
+ * Get current timestamp in seconds
1082
+ *
1083
+ * @returns Unix timestamp in seconds
1084
+ */
1085
+ declare function getCurrentTimestamp(): number;
1086
+ /**
1087
+ * Validate Ethereum address format
1088
+ *
1089
+ * @param address - Address to validate
1090
+ * @returns True if valid Ethereum address
1091
+ */
1092
+ declare function isValidAddress(address: string): boolean;
1093
+ /**
1094
+ * Normalize Ethereum address to checksummed format
1095
+ * Note: This is a simple lowercase normalization. For full checksum validation, use viem's getAddress()
1096
+ *
1097
+ * @param address - Address to normalize
1098
+ * @returns Normalized address
1099
+ */
1100
+ declare function normalizeAddress(address: string): `0x${string}`;
1101
+
1102
+ /**
1103
+ * Error classes for D402 payment protocol
1104
+ */
1105
+ /**
1106
+ * Base error class for all payment-related errors
1107
+ */
1108
+ declare class PaymentError extends Error {
1109
+ constructor(message: string);
1110
+ }
1111
+ /**
1112
+ * Thrown when payment amount exceeds the configured maximum allowed value
1113
+ */
1114
+ declare class PaymentAmountExceededError extends PaymentError {
1115
+ amount: bigint;
1116
+ maxAmount: bigint;
1117
+ tokenAddress?: string | undefined;
1118
+ constructor(amount: bigint, maxAmount: bigint, tokenAddress?: string | undefined);
1119
+ }
1120
+ /**
1121
+ * Thrown when request configuration is missing required fields
1122
+ */
1123
+ declare class MissingRequestConfigError extends PaymentError {
1124
+ constructor(message: string);
1125
+ }
1126
+ /**
1127
+ * Thrown when payment has already been attempted for a request
1128
+ */
1129
+ declare class PaymentAlreadyAttemptedError extends PaymentError {
1130
+ constructor(message?: string);
1131
+ }
1132
+ /**
1133
+ * Thrown when no supported payment scheme is found in payment requirements
1134
+ */
1135
+ declare class UnsupportedSchemeError extends PaymentError {
1136
+ availableSchemes: string[];
1137
+ constructor(availableSchemes: string[], message?: string);
1138
+ }
1139
+ /**
1140
+ * Thrown when payment verification fails
1141
+ */
1142
+ declare class PaymentVerificationError extends PaymentError {
1143
+ constructor(message: string);
1144
+ }
1145
+ /**
1146
+ * Thrown when HTTP 402 response is malformed
1147
+ */
1148
+ declare class Invalid402ResponseError extends PaymentError {
1149
+ constructor(message: string);
1150
+ }
1151
+ /**
1152
+ * Thrown when network is not supported
1153
+ */
1154
+ declare class UnsupportedNetworkError extends PaymentError {
1155
+ network: string;
1156
+ constructor(network: string);
1157
+ }
1158
+
1159
+ export { ContractName, D402Client, type D402ClientConfig, type D402Response, type EIP712Domain, Invalid402ResponseError, MissingRequestConfigError, PaymentAlreadyAttemptedError, PaymentAmountExceededError, type PaymentAuthorization, PaymentError, type PaymentRequirement, type PaymentSelector, type PaymentSelectorOptions, PaymentVerificationError, type SignedPayment, type SupportedNetwork, UnsupportedNetworkError, UnsupportedSchemeError, type WalletCreationResult, createIATPWallet, createPaymentSelector, decodePayment, decodePaymentResponse, encodePayment, executeWithdrawal, findMatchingPaymentRequirement, formatMoney, generateNonce, getAvailableBalance, getChainId, getContractAbi, getContractAddress, getContractConfig, getCurrentTimestamp, getLockedBalanceForProvider, getUnlockedBalanceForProvider, getUsdcAddress, getWalletsByOwner, getWithdrawalRequest, isValidAddress, normalizeAddress, parseAllPaymentRequirements, parseMoney, parsePaymentRequirement, requestWithdrawal, selectPaymentRequirement, signD402Payment, sortPaymentRequirements, usdToUsdc, withdrawAllAvailableEpochs };