@dcentralab/d402-client 0.2.6 → 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.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
  /**
@@ -444,6 +437,25 @@ declare function signD402Payment(params: {
444
437
  * ```
445
438
  */
446
439
  declare function parsePaymentRequirement(response: Response): Promise<PaymentRequirement>;
440
+ /**
441
+ * Parse all payment requirements from 402 response.
442
+ *
443
+ * Similar to parsePaymentRequirement but returns all options instead of just first.
444
+ * Useful when client needs to choose from multiple payment options.
445
+ *
446
+ * @param response - HTTP Response object with status 402
447
+ * @returns Array of all payment requirements
448
+ * @throws {Invalid402ResponseError} If response is invalid
449
+ *
450
+ * @example
451
+ * ```ts
452
+ * const response = await fetch('http://api.example.com')
453
+ * const allOptions = await parseAllPaymentRequirements(response)
454
+ * // Choose based on network, token, etc.
455
+ * const preferred = allOptions.find(r => r.network === 'sepolia')
456
+ * ```
457
+ */
458
+ declare function parseAllPaymentRequirements(response: Response): Promise<PaymentRequirement[]>;
447
459
 
448
460
  /**
449
461
  * Base64 encoding/decoding for payment payloads
@@ -485,243 +497,7 @@ declare function encodePayment(payment: SignedPayment): string;
485
497
  declare function decodePayment(encodedPayment: string): SignedPayment;
486
498
 
487
499
  /**
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
- /**
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.
532
- *
533
- * @param network - Network name or chain ID as string
534
- * @returns Chain ID as number
535
- *
536
- * @throws {UnsupportedNetworkError} If network is not supported
537
- *
538
- * @example
539
- * ```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
599
- *
600
- * @example
601
- * const response = decodePaymentResponse(responseHeader)
602
- * console.log(response.success, response.transaction)
603
- */
604
- declare function decodePaymentResponse(header: string): {
605
- success: boolean;
606
- transaction?: string;
607
- network?: string;
608
- payer?: string;
609
- message?: string;
610
- };
611
-
612
- /**
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
- *
500
+ * Type definitions for wallet module
725
501
  */
726
502
 
727
503
  /**
@@ -741,6 +517,11 @@ interface WalletCreationResult {
741
517
  /** Chain ID */
742
518
  chainId: number;
743
519
  }
520
+
521
+ /**
522
+ * IATPWallet creation functions
523
+ */
524
+
744
525
  /**
745
526
  * Create a new IATPWallet using IATPWalletFactory.
746
527
  *
@@ -758,7 +539,6 @@ interface WalletCreationResult {
758
539
  * @param params.ownerAccount - Owner's account (will own the wallet)
759
540
  * @param params.network - Network to deploy on (default: "sepolia")
760
541
  * @param params.rpcUrl - Custom RPC URL (optional)
761
- * @param params.operatorPrivateKey - Use specific operator key instead of generating (optional)
762
542
  * @returns Wallet creation result with addresses and keys
763
543
  *
764
544
  * @example
@@ -774,7 +554,6 @@ interface WalletCreationResult {
774
554
  * })
775
555
  *
776
556
  * console.log('Wallet created:', result.walletAddress)
777
- * console.log('Operator key:', result.operatorPrivateKey) // Store securely!
778
557
  * ```
779
558
  */
780
559
  declare function createIATPWallet(params: {
@@ -821,6 +600,11 @@ declare function getWalletsByOwner(params: {
821
600
  network?: 'sepolia';
822
601
  rpcUrl?: string;
823
602
  }): Promise<Address[]>;
603
+
604
+ /**
605
+ * IATPWallet query functions
606
+ */
607
+
824
608
  /**
825
609
  * Get available balance for a specific token in an IATPWallet.
826
610
  *
@@ -858,28 +642,141 @@ declare function getAvailableBalance(params: {
858
642
  }): Promise<bigint>;
859
643
 
860
644
  /**
861
- * IATPSettlementLayer contract operations
862
- *
863
- * Functions for providers (utility agents) to query settlement balances,
864
- * epochs, and manage withdrawals from the settlement layer.
645
+ * IATPWallet withdrawal functions
865
646
  */
866
647
 
867
648
  /**
868
- * Get locked balance for a provider across unreleased epochs.
649
+ * Get withdrawal request for a token in an IATPWallet.
869
650
  *
870
- * This is the balance that's locked in the settlement layer and cannot
871
- * be withdrawn yet (still within the release delay period).
651
+ * Queries the IATPWallet contract to get the current withdrawal request
652
+ * (amount and unlock timestamp) for a specific token.
872
653
  *
873
654
  * @param params - Query parameters
874
- * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
875
- * @param params.providerAddress - Provider (utility agent) IATPWallet address
655
+ * @param params.publicClient - Viem PublicClient
656
+ * @param params.walletAddress - IATPWallet contract address
876
657
  * @param params.tokenAddress - Token contract address
877
- * @param params.network - Network (default: "sepolia")
878
- * @returns Locked balance in base units (wei)
658
+ * @param params.network - Network to query (default: "sepolia")
659
+ * @returns Withdrawal request: [amount, unlockTimestamp] or null if no request exists
879
660
  *
880
661
  * @example
881
662
  * ```ts
882
- * import { getLockedBalanceForProvider } from '@dcentralab/d402-client'
663
+ * import { getWithdrawalRequest } from '@dcentralab/d402-client'
664
+ *
665
+ * const request = await getWithdrawalRequest({
666
+ * publicClient,
667
+ * walletAddress: '0xUserIATPWallet...',
668
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
669
+ * })
670
+ *
671
+ * if (request) {
672
+ * const [amount, unlockTimestamp] = request
673
+ * const isUnlocked = Date.now() >= Number(unlockTimestamp) * 1000
674
+ * }
675
+ * ```
676
+ */
677
+ declare function getWithdrawalRequest(params: {
678
+ publicClient: PublicClient;
679
+ walletAddress: Address;
680
+ tokenAddress: Address;
681
+ network?: 'sepolia';
682
+ }): Promise<[bigint, bigint] | null>;
683
+ /**
684
+ * Request a withdrawal from an IATPWallet.
685
+ *
686
+ * Initiates a withdrawal request for a token. The withdrawal will be locked
687
+ * for a period (typically 5 minutes) before it can be executed.
688
+ *
689
+ * @param params - Transaction parameters
690
+ * @param params.walletClient - Viem WalletClient (from wagmi useWalletClient)
691
+ * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
692
+ * @param params.walletAddress - IATPWallet contract address
693
+ * @param params.tokenAddress - Token contract address
694
+ * @param params.amount - Amount in token's base units (wei)
695
+ * @param params.account - Account to sign transaction (operator)
696
+ * @param params.network - Network (default: "sepolia")
697
+ * @returns Transaction hash
698
+ *
699
+ * @example
700
+ * ```ts
701
+ * import { requestWithdrawal } from '@dcentralab/d402-client'
702
+ * import { parseUnits } from 'viem'
703
+ *
704
+ * const hash = await requestWithdrawal({
705
+ * walletClient,
706
+ * publicClient,
707
+ * walletAddress: '0xUserIATPWallet...',
708
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
709
+ * amount: parseUnits('100', 6), // 100 USDC (6 decimals)
710
+ * account: walletClient.account,
711
+ * })
712
+ * ```
713
+ */
714
+ declare function requestWithdrawal(params: {
715
+ walletClient: WalletClient;
716
+ publicClient: PublicClient;
717
+ walletAddress: Address;
718
+ tokenAddress: Address;
719
+ amount: bigint;
720
+ account: Account;
721
+ network?: 'sepolia';
722
+ }): Promise<Hash>;
723
+ /**
724
+ * Execute a withdrawal from an IATPWallet (after unlock period).
725
+ *
726
+ * Completes a withdrawal that has passed its unlock period. This transfers
727
+ * the tokens from the IATPWallet back to the user's wallet.
728
+ *
729
+ * @param params - Transaction parameters
730
+ * @param params.walletClient - Viem WalletClient
731
+ * @param params.publicClient - Viem PublicClient
732
+ * @param params.walletAddress - IATPWallet contract address
733
+ * @param params.tokenAddress - Token contract address
734
+ * @param params.account - Account to sign transaction (operator)
735
+ * @param params.network - Network (default: "sepolia")
736
+ * @returns Transaction hash
737
+ *
738
+ * @example
739
+ * ```ts
740
+ * import { executeWithdrawal } from '@dcentralab/d402-client'
741
+ *
742
+ * const hash = await executeWithdrawal({
743
+ * walletClient,
744
+ * publicClient,
745
+ * walletAddress: '0xUserIATPWallet...',
746
+ * tokenAddress: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238',
747
+ * account: walletClient.account,
748
+ * })
749
+ * ```
750
+ */
751
+ declare function executeWithdrawal(params: {
752
+ walletClient: WalletClient;
753
+ publicClient: PublicClient;
754
+ walletAddress: Address;
755
+ tokenAddress: Address;
756
+ account: Account;
757
+ network?: 'sepolia';
758
+ }): Promise<Hash>;
759
+
760
+ /**
761
+ * IATPSettlementLayer query functions
762
+ */
763
+
764
+ /**
765
+ * Get locked balance for a provider across unreleased epochs.
766
+ *
767
+ * This is the balance that's locked in the settlement layer and cannot
768
+ * be withdrawn yet (still within the release delay period).
769
+ *
770
+ * @param params - Query parameters
771
+ * @param params.publicClient - Viem PublicClient (from wagmi usePublicClient)
772
+ * @param params.providerAddress - Provider (utility agent) IATPWallet address
773
+ * @param params.tokenAddress - Token contract address
774
+ * @param params.network - Network (default: "sepolia")
775
+ * @returns Locked balance in base units (wei)
776
+ *
777
+ * @example
778
+ * ```ts
779
+ * import { getLockedBalanceForProvider } from '@dcentralab/d402-client'
883
780
  *
884
781
  * const locked = await getLockedBalanceForProvider({
885
782
  * publicClient,
@@ -930,6 +827,13 @@ declare function getUnlockedBalanceForProvider(params: {
930
827
  tokenAddress: Address;
931
828
  network?: 'sepolia';
932
829
  }): Promise<bigint>;
830
+
831
+ /**
832
+ * IATPSettlementLayer operations
833
+ *
834
+ * Functions for managing withdrawals from the settlement layer.
835
+ */
836
+
933
837
  /**
934
838
  * Withdraw all available epochs for a provider (utility agent).
935
839
  *
@@ -965,4 +869,269 @@ declare function withdrawAllAvailableEpochs(params: {
965
869
  network?: 'sepolia';
966
870
  }): Promise<Hash>;
967
871
 
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 };
872
+ /**
873
+ * Core type definitions shared across the package
874
+ */
875
+ /**
876
+ * Supported blockchain networks (where IATP contracts are deployed)
877
+ */
878
+ type SupportedNetwork = 'sepolia';
879
+ /**
880
+ * EIP-712 domain for signature verification
881
+ */
882
+ interface EIP712Domain {
883
+ name: string;
884
+ version: string;
885
+ chainId: number;
886
+ verifyingContract: `0x${string}`;
887
+ }
888
+
889
+ /**
890
+ * Contract configuration and utilities.
891
+ *
892
+ * Provides access to IATPWallet contract ABIs and deployed addresses.
893
+ * Contract data is bundled directly in the package for reliability.
894
+ */
895
+
896
+ /**
897
+ * Supported contract names.
898
+ */
899
+ declare enum ContractName {
900
+ IATP_WALLET = "IATPWallet",
901
+ IATP_WALLET_FACTORY = "IATPWalletFactory",
902
+ IATP_SETTLEMENT_LAYER = "IATPSettlementLayer",
903
+ ROLE_MANAGER = "RoleManager"
904
+ }
905
+ /**
906
+ * Get contract address for a given network.
907
+ *
908
+ * @param contractName - Name of the contract (use ContractName enum)
909
+ * @param network - Network name (default: "sepolia")
910
+ * @param useProxy - Use proxy address if true, implementation if false (default: true)
911
+ * @returns Contract address as hex string, or null if not found
912
+ *
913
+ * @example
914
+ * ```ts
915
+ * const factoryAddr = getContractAddress(ContractName.IATP_WALLET_FACTORY, 'sepolia')
916
+ * console.log(factoryAddr) // "0x15D83638E339a0f29283f6B93dC1bb90b8339078"
917
+ * ```
918
+ */
919
+ declare function getContractAddress(contractName: string | ContractName, network?: SupportedNetwork, useProxy?: boolean): string | null;
920
+ /**
921
+ * Get contract ABI for a given network.
922
+ *
923
+ * @param contractName - Name of the contract (use ContractName enum)
924
+ * @param network - Network name (default: "sepolia")
925
+ * @returns Contract ABI as array of objects, or null if not found
926
+ *
927
+ * @example
928
+ * ```ts
929
+ * const factoryAbi = getContractAbi(ContractName.IATP_WALLET_FACTORY, 'sepolia')
930
+ * console.log(factoryAbi.length) // Number of ABI entries
931
+ * ```
932
+ */
933
+ declare function getContractAbi(contractName: string | ContractName, network?: SupportedNetwork): any[] | null;
934
+ /**
935
+ * Get contract configuration (address and ABI) for a network.
936
+ *
937
+ * @param contractName - Name of the contract
938
+ * @param network - Network name (default: "sepolia")
939
+ * @returns Object with address and abi, or null if not found
940
+ *
941
+ * @example
942
+ * ```ts
943
+ * const config = getContractConfig(ContractName.IATP_WALLET_FACTORY, 'sepolia')
944
+ * if (config) {
945
+ * console.log(config.address)
946
+ * console.log(config.abi.length)
947
+ * }
948
+ * ```
949
+ */
950
+ declare function getContractConfig(contractName: string | ContractName, network?: SupportedNetwork): {
951
+ address: string;
952
+ abi: any[];
953
+ } | null;
954
+
955
+ /**
956
+ * Utility functions for D402 payment processing
957
+ */
958
+
959
+ /**
960
+ * Parse a money string or number into atomic units (wei)
961
+ *
962
+ * @param amount - Amount as string (e.g., "$1.00", "1.5") or number
963
+ * @param decimals - Token decimals (e.g., 6 for USDC, 18 for ETH)
964
+ * @returns Amount in atomic units (wei)
965
+ *
966
+ * @example
967
+ * parseMoney("$1.00", 6) // Returns 1000000n (1 USDC in wei)
968
+ * parseMoney("0.5", 18) // Returns 500000000000000000n (0.5 ETH in wei)
969
+ */
970
+ declare function parseMoney(amount: string | number | bigint, decimals: number): bigint;
971
+ /**
972
+ * Format atomic units back to human-readable format
973
+ *
974
+ * @param amount - Amount in atomic units (wei)
975
+ * @param decimals - Token decimals
976
+ * @returns Formatted string
977
+ *
978
+ * @example
979
+ * formatMoney(1000000n, 6) // Returns "1.000000"
980
+ */
981
+ declare function formatMoney(amount: bigint, decimals: number): string;
982
+ /**
983
+ * Get USDC token address for a given network
984
+ *
985
+ * @param network - Network name
986
+ * @returns USDC token address
987
+ *
988
+ * @throws {UnsupportedNetworkError} If network is not supported
989
+ */
990
+ declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
991
+ /**
992
+ * Get chain ID for a given network.
993
+ *
994
+ * This function maps network names to chain IDs for parsing 402 payment requirements
995
+ * from external APIs. It supports many networks that may appear in 402 responses,
996
+ * even if IATP contracts are not deployed on those networks.
997
+ *
998
+ * Note: IATP contracts are currently only deployed on Sepolia. This function exists
999
+ * to handle 402 responses from any API that might support other networks.
1000
+ *
1001
+ * @param network - Network name or chain ID as string
1002
+ * @returns Chain ID as number
1003
+ *
1004
+ * @throws {UnsupportedNetworkError} If network is not supported
1005
+ *
1006
+ * @example
1007
+ * ```ts
1008
+ * getChainId('sepolia') // Returns 11155111
1009
+ * getChainId('11155111') // Returns 11155111 (passthrough)
1010
+ * getChainId('base') // Returns 8453 (for parsing 402 responses)
1011
+ * ```
1012
+ */
1013
+ declare function getChainId(network: string): number;
1014
+ /**
1015
+ * Find matching payment requirement from a list
1016
+ *
1017
+ * @param requirements - List of payment requirements
1018
+ * @param scheme - Desired payment scheme (default: "exact")
1019
+ * @param network - Desired network (optional)
1020
+ * @returns Matching payment requirement or undefined
1021
+ */
1022
+ declare function findMatchingPaymentRequirement(requirements: PaymentRequirement[], scheme?: string, network?: string): PaymentRequirement | undefined;
1023
+ /**
1024
+ * Convert USD amount to USDC atomic units
1025
+ *
1026
+ * @param usdAmount - Amount in USD (e.g., "1.00" or 1.5)
1027
+ * @param decimals - USDC decimals (default: 6)
1028
+ * @returns Amount in USDC atomic units
1029
+ *
1030
+ * @example
1031
+ * usdToUsdc("1.00") // Returns 1000000n
1032
+ * usdToUsdc(1.5) // Returns 1500000n
1033
+ */
1034
+ declare function usdToUsdc(usdAmount: string | number, decimals?: number): bigint;
1035
+ /**
1036
+ * Generate a random nonce for payment authorization
1037
+ *
1038
+ * @returns Random 32-byte nonce as hex string
1039
+ */
1040
+ declare function generateNonce(): `0x${string}`;
1041
+ /**
1042
+ * Get current timestamp in seconds
1043
+ *
1044
+ * @returns Unix timestamp in seconds
1045
+ */
1046
+ declare function getCurrentTimestamp(): number;
1047
+ /**
1048
+ * Validate Ethereum address format
1049
+ *
1050
+ * @param address - Address to validate
1051
+ * @returns True if valid Ethereum address
1052
+ */
1053
+ declare function isValidAddress(address: string): boolean;
1054
+ /**
1055
+ * Normalize Ethereum address to checksummed format
1056
+ * Note: This is a simple lowercase normalization. For full checksum validation, use viem's getAddress()
1057
+ *
1058
+ * @param address - Address to normalize
1059
+ * @returns Normalized address
1060
+ */
1061
+ declare function normalizeAddress(address: string): `0x${string}`;
1062
+ /**
1063
+ * Decode X-PAYMENT-RESPONSE header from server
1064
+ *
1065
+ * @param header - Base64 encoded payment response
1066
+ * @returns Decoded payment response
1067
+ *
1068
+ * @example
1069
+ * const response = decodePaymentResponse(responseHeader)
1070
+ * console.log(response.success, response.transaction)
1071
+ */
1072
+ declare function decodePaymentResponse(header: string): {
1073
+ success: boolean;
1074
+ transaction?: string;
1075
+ network?: string;
1076
+ payer?: string;
1077
+ message?: string;
1078
+ };
1079
+
1080
+ /**
1081
+ * Error classes for D402 payment protocol
1082
+ */
1083
+ /**
1084
+ * Base error class for all payment-related errors
1085
+ */
1086
+ declare class PaymentError extends Error {
1087
+ constructor(message: string);
1088
+ }
1089
+ /**
1090
+ * Thrown when payment amount exceeds the configured maximum allowed value
1091
+ */
1092
+ declare class PaymentAmountExceededError extends PaymentError {
1093
+ amount: bigint;
1094
+ maxAmount: bigint;
1095
+ tokenAddress?: string | undefined;
1096
+ constructor(amount: bigint, maxAmount: bigint, tokenAddress?: string | undefined);
1097
+ }
1098
+ /**
1099
+ * Thrown when request configuration is missing required fields
1100
+ */
1101
+ declare class MissingRequestConfigError extends PaymentError {
1102
+ constructor(message: string);
1103
+ }
1104
+ /**
1105
+ * Thrown when payment has already been attempted for a request
1106
+ */
1107
+ declare class PaymentAlreadyAttemptedError extends PaymentError {
1108
+ constructor(message?: string);
1109
+ }
1110
+ /**
1111
+ * Thrown when no supported payment scheme is found in payment requirements
1112
+ */
1113
+ declare class UnsupportedSchemeError extends PaymentError {
1114
+ availableSchemes: string[];
1115
+ constructor(availableSchemes: string[], message?: string);
1116
+ }
1117
+ /**
1118
+ * Thrown when payment verification fails
1119
+ */
1120
+ declare class PaymentVerificationError extends PaymentError {
1121
+ constructor(message: string);
1122
+ }
1123
+ /**
1124
+ * Thrown when HTTP 402 response is malformed
1125
+ */
1126
+ declare class Invalid402ResponseError extends PaymentError {
1127
+ constructor(message: string);
1128
+ }
1129
+ /**
1130
+ * Thrown when network is not supported
1131
+ */
1132
+ declare class UnsupportedNetworkError extends PaymentError {
1133
+ network: string;
1134
+ constructor(network: string);
1135
+ }
1136
+
1137
+ 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 };