@dcentralab/d402-client 0.3.0 → 0.3.3

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.mts CHANGED
@@ -166,6 +166,26 @@ declare function createPaymentSelector(defaultOptions: PaymentSelectorOptions):
166
166
  * @returns Sorted list (preferred first)
167
167
  */
168
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;
169
189
 
170
190
  /**
171
191
  * D402 Client - Main client class for handling HTTP 402 payments
@@ -495,6 +515,34 @@ declare function encodePayment(payment: SignedPayment): string;
495
515
  * ```
496
516
  */
497
517
  declare function decodePayment(encodedPayment: string): SignedPayment;
518
+ /**
519
+ * Decode X-PAYMENT-RESPONSE header from server.
520
+ *
521
+ * After a successful payment, servers may return payment confirmation
522
+ * in the X-PAYMENT-RESPONSE header. This function decodes it.
523
+ *
524
+ * @param header - Base64 encoded payment response header
525
+ * @returns Decoded payment response object
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * const response = await fetch(url, { headers: { 'X-Payment': payment } })
530
+ * const responseHeader = response.headers.get('X-Payment-Response')
531
+ *
532
+ * if (responseHeader) {
533
+ * const paymentResponse = decodePaymentResponse(responseHeader)
534
+ * console.log('Success:', paymentResponse.success)
535
+ * console.log('Transaction:', paymentResponse.transaction)
536
+ * }
537
+ * ```
538
+ */
539
+ declare function decodePaymentResponse(header: string): {
540
+ success: boolean;
541
+ transaction?: string;
542
+ network?: string;
543
+ payer?: string;
544
+ message?: string;
545
+ };
498
546
 
499
547
  /**
500
548
  * Type definitions for wallet module
@@ -561,45 +609,6 @@ declare function createIATPWallet(params: {
561
609
  network?: 'sepolia';
562
610
  rpcUrl?: string;
563
611
  }): Promise<WalletCreationResult>;
564
- /**
565
- * Get all IATPWallet addresses owned by a user.
566
- *
567
- * Queries the IATPWalletFactory contract to retrieve all wallets
568
- * where the specified address is the owner.
569
- *
570
- * Use this to check if a user already has a wallet before calling createIATPWallet().
571
- *
572
- * @param params - Query parameters
573
- * @param params.ownerAddress - User's wallet address (from MetaMask)
574
- * @param params.network - Network to query (default: "sepolia")
575
- * @param params.rpcUrl - Custom RPC URL (optional)
576
- * @returns Array of IATPWallet contract addresses (empty if user has no wallets)
577
- *
578
- * @example
579
- * ```ts
580
- * import { getWalletsByOwner } from '@dcentralab/d402-client'
581
- * import { useAccount } from 'wagmi'
582
- *
583
- * const { address } = useAccount()
584
- *
585
- * // Check if user has any wallets
586
- * const wallets = await getWalletsByOwner({
587
- * ownerAddress: address,
588
- * network: 'sepolia'
589
- * })
590
- *
591
- * if (wallets.length === 0) {
592
- * // Show "Create Wallet" button
593
- * } else {
594
- * // Use existing wallet: wallets[0]
595
- * }
596
- * ```
597
- */
598
- declare function getWalletsByOwner(params: {
599
- ownerAddress: Address;
600
- network?: 'sepolia';
601
- rpcUrl?: string;
602
- }): Promise<Address[]>;
603
612
 
604
613
  /**
605
614
  * IATPWallet query functions
@@ -640,6 +649,45 @@ declare function getAvailableBalance(params: {
640
649
  tokenAddress: Address;
641
650
  network?: 'sepolia';
642
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'
669
+ * import { useAccount } from 'wagmi'
670
+ *
671
+ * const { address } = useAccount()
672
+ *
673
+ * // Check if user has any wallets
674
+ * const wallets = await getWalletsByOwner({
675
+ * ownerAddress: address,
676
+ * network: 'sepolia'
677
+ * })
678
+ *
679
+ * if (wallets.length === 0) {
680
+ * // Show "Create Wallet" button
681
+ * } else {
682
+ * // Use existing wallet: wallets[0]
683
+ * }
684
+ * ```
685
+ */
686
+ declare function getWalletsByOwner(params: {
687
+ ownerAddress: Address;
688
+ network?: 'sepolia';
689
+ rpcUrl?: string;
690
+ }): Promise<Address[]>;
643
691
 
644
692
  /**
645
693
  * IATPWallet withdrawal functions
@@ -1011,15 +1059,6 @@ declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
1011
1059
  * ```
1012
1060
  */
1013
1061
  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
1062
  /**
1024
1063
  * Convert USD amount to USDC atomic units
1025
1064
  *
@@ -1059,23 +1098,6 @@ declare function isValidAddress(address: string): boolean;
1059
1098
  * @returns Normalized address
1060
1099
  */
1061
1100
  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
1101
 
1080
1102
  /**
1081
1103
  * Error classes for D402 payment protocol
package/dist/index.d.ts CHANGED
@@ -166,6 +166,26 @@ declare function createPaymentSelector(defaultOptions: PaymentSelectorOptions):
166
166
  * @returns Sorted list (preferred first)
167
167
  */
168
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;
169
189
 
170
190
  /**
171
191
  * D402 Client - Main client class for handling HTTP 402 payments
@@ -495,6 +515,34 @@ declare function encodePayment(payment: SignedPayment): string;
495
515
  * ```
496
516
  */
497
517
  declare function decodePayment(encodedPayment: string): SignedPayment;
518
+ /**
519
+ * Decode X-PAYMENT-RESPONSE header from server.
520
+ *
521
+ * After a successful payment, servers may return payment confirmation
522
+ * in the X-PAYMENT-RESPONSE header. This function decodes it.
523
+ *
524
+ * @param header - Base64 encoded payment response header
525
+ * @returns Decoded payment response object
526
+ *
527
+ * @example
528
+ * ```ts
529
+ * const response = await fetch(url, { headers: { 'X-Payment': payment } })
530
+ * const responseHeader = response.headers.get('X-Payment-Response')
531
+ *
532
+ * if (responseHeader) {
533
+ * const paymentResponse = decodePaymentResponse(responseHeader)
534
+ * console.log('Success:', paymentResponse.success)
535
+ * console.log('Transaction:', paymentResponse.transaction)
536
+ * }
537
+ * ```
538
+ */
539
+ declare function decodePaymentResponse(header: string): {
540
+ success: boolean;
541
+ transaction?: string;
542
+ network?: string;
543
+ payer?: string;
544
+ message?: string;
545
+ };
498
546
 
499
547
  /**
500
548
  * Type definitions for wallet module
@@ -561,45 +609,6 @@ declare function createIATPWallet(params: {
561
609
  network?: 'sepolia';
562
610
  rpcUrl?: string;
563
611
  }): Promise<WalletCreationResult>;
564
- /**
565
- * Get all IATPWallet addresses owned by a user.
566
- *
567
- * Queries the IATPWalletFactory contract to retrieve all wallets
568
- * where the specified address is the owner.
569
- *
570
- * Use this to check if a user already has a wallet before calling createIATPWallet().
571
- *
572
- * @param params - Query parameters
573
- * @param params.ownerAddress - User's wallet address (from MetaMask)
574
- * @param params.network - Network to query (default: "sepolia")
575
- * @param params.rpcUrl - Custom RPC URL (optional)
576
- * @returns Array of IATPWallet contract addresses (empty if user has no wallets)
577
- *
578
- * @example
579
- * ```ts
580
- * import { getWalletsByOwner } from '@dcentralab/d402-client'
581
- * import { useAccount } from 'wagmi'
582
- *
583
- * const { address } = useAccount()
584
- *
585
- * // Check if user has any wallets
586
- * const wallets = await getWalletsByOwner({
587
- * ownerAddress: address,
588
- * network: 'sepolia'
589
- * })
590
- *
591
- * if (wallets.length === 0) {
592
- * // Show "Create Wallet" button
593
- * } else {
594
- * // Use existing wallet: wallets[0]
595
- * }
596
- * ```
597
- */
598
- declare function getWalletsByOwner(params: {
599
- ownerAddress: Address;
600
- network?: 'sepolia';
601
- rpcUrl?: string;
602
- }): Promise<Address[]>;
603
612
 
604
613
  /**
605
614
  * IATPWallet query functions
@@ -640,6 +649,45 @@ declare function getAvailableBalance(params: {
640
649
  tokenAddress: Address;
641
650
  network?: 'sepolia';
642
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'
669
+ * import { useAccount } from 'wagmi'
670
+ *
671
+ * const { address } = useAccount()
672
+ *
673
+ * // Check if user has any wallets
674
+ * const wallets = await getWalletsByOwner({
675
+ * ownerAddress: address,
676
+ * network: 'sepolia'
677
+ * })
678
+ *
679
+ * if (wallets.length === 0) {
680
+ * // Show "Create Wallet" button
681
+ * } else {
682
+ * // Use existing wallet: wallets[0]
683
+ * }
684
+ * ```
685
+ */
686
+ declare function getWalletsByOwner(params: {
687
+ ownerAddress: Address;
688
+ network?: 'sepolia';
689
+ rpcUrl?: string;
690
+ }): Promise<Address[]>;
643
691
 
644
692
  /**
645
693
  * IATPWallet withdrawal functions
@@ -1011,15 +1059,6 @@ declare function getUsdcAddress(network: SupportedNetwork): `0x${string}`;
1011
1059
  * ```
1012
1060
  */
1013
1061
  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
1062
  /**
1024
1063
  * Convert USD amount to USDC atomic units
1025
1064
  *
@@ -1059,23 +1098,6 @@ declare function isValidAddress(address: string): boolean;
1059
1098
  * @returns Normalized address
1060
1099
  */
1061
1100
  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
1101
 
1080
1102
  /**
1081
1103
  * Error classes for D402 payment protocol
package/dist/index.js CHANGED
@@ -267,13 +267,6 @@ function getChainId(network) {
267
267
  }
268
268
  return chainId;
269
269
  }
270
- function findMatchingPaymentRequirement(requirements, scheme = "exact", network) {
271
- return requirements.find((req) => {
272
- const schemeMatches = req.scheme === scheme;
273
- const networkMatches = !network || req.network === network;
274
- return schemeMatches && networkMatches;
275
- });
276
- }
277
270
  function usdToUsdc(usdAmount, decimals = 6) {
278
271
  return parseMoney(usdAmount, decimals);
279
272
  }
@@ -291,16 +284,6 @@ function isValidAddress(address) {
291
284
  function normalizeAddress(address) {
292
285
  return address.toLowerCase();
293
286
  }
294
- function decodePaymentResponse(header) {
295
- try {
296
- const binString = atob(header);
297
- const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
298
- const decoded = new TextDecoder().decode(bytes);
299
- return JSON.parse(decoded);
300
- } catch (error) {
301
- throw new Error(`Failed to decode payment response: ${error}`);
302
- }
303
- }
304
287
  var init_utils = __esm({
305
288
  "src/core/utils.ts"() {
306
289
  init_constants();
@@ -389,6 +372,7 @@ var init_signer = __esm({
389
372
  var encoder_exports = {};
390
373
  __export(encoder_exports, {
391
374
  decodePayment: () => decodePayment,
375
+ decodePaymentResponse: () => decodePaymentResponse,
392
376
  encodePayment: () => encodePayment,
393
377
  safeBase64Decode: () => safeBase64Decode,
394
378
  safeBase64Encode: () => safeBase64Encode
@@ -411,6 +395,14 @@ function decodePayment(encodedPayment) {
411
395
  const jsonString = safeBase64Decode(encodedPayment);
412
396
  return JSON.parse(jsonString);
413
397
  }
398
+ function decodePaymentResponse(header) {
399
+ try {
400
+ const jsonString = safeBase64Decode(header);
401
+ return JSON.parse(jsonString);
402
+ } catch (error) {
403
+ throw new Error(`Failed to decode payment response: ${error instanceof Error ? error.message : "Unknown error"}`);
404
+ }
405
+ }
414
406
  var init_encoder = __esm({
415
407
  "src/payment/encoder.ts"() {
416
408
  }
@@ -498,6 +490,13 @@ function sortPaymentRequirements(requirements, preferredNetwork) {
498
490
  return 0;
499
491
  });
500
492
  }
493
+ function findMatchingPaymentRequirement(requirements, scheme = "exact", network) {
494
+ return requirements.find((req) => {
495
+ const schemeMatches = req.scheme === scheme;
496
+ const networkMatches = !network || req.network === network;
497
+ return schemeMatches && networkMatches;
498
+ });
499
+ }
501
500
 
502
501
  // src/contracts/abis/sepolia.json
503
502
  var sepolia_default = {
@@ -5108,6 +5107,20 @@ async function createIATPWallet(params) {
5108
5107
  chainId: chain.id
5109
5108
  };
5110
5109
  }
5110
+ async function getAvailableBalance(params) {
5111
+ const { publicClient, walletAddress, tokenAddress, network = "sepolia" } = params;
5112
+ const walletConfig = getContractConfig("IATPWallet" /* IATP_WALLET */, network);
5113
+ if (!walletConfig) {
5114
+ throw new Error(`IATPWallet contract not found for network: ${network}`);
5115
+ }
5116
+ const balance = await publicClient.readContract({
5117
+ address: walletAddress,
5118
+ abi: walletConfig.abi,
5119
+ functionName: "getAvailableBalance",
5120
+ args: [tokenAddress]
5121
+ });
5122
+ return balance;
5123
+ }
5111
5124
  async function getWalletsByOwner(params) {
5112
5125
  const { ownerAddress, network = "sepolia", rpcUrl } = params;
5113
5126
  const factoryConfig = getContractConfig("IATPWalletFactory" /* IATP_WALLET_FACTORY */, network);
@@ -5129,22 +5142,6 @@ async function getWalletsByOwner(params) {
5129
5142
  return wallets;
5130
5143
  }
5131
5144
 
5132
- // src/wallet/queries.ts
5133
- async function getAvailableBalance(params) {
5134
- const { publicClient, walletAddress, tokenAddress, network = "sepolia" } = params;
5135
- const walletConfig = getContractConfig("IATPWallet" /* IATP_WALLET */, network);
5136
- if (!walletConfig) {
5137
- throw new Error(`IATPWallet contract not found for network: ${network}`);
5138
- }
5139
- const balance = await publicClient.readContract({
5140
- address: walletAddress,
5141
- abi: walletConfig.abi,
5142
- functionName: "getAvailableBalance",
5143
- args: [tokenAddress]
5144
- });
5145
- return balance;
5146
- }
5147
-
5148
5145
  // src/wallet/withdrawals.ts
5149
5146
  async function getWithdrawalRequest(params) {
5150
5147
  const { publicClient, walletAddress, tokenAddress, network = "sepolia" } = params;