@payai/x402-evm 2.4.0 → 2.4.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.
Files changed (150) hide show
  1. package/dist/cjs/batch-settlement/client/file-storage.d.ts +47 -0
  2. package/dist/cjs/batch-settlement/client/file-storage.js +116 -0
  3. package/dist/cjs/batch-settlement/client/file-storage.js.map +1 -0
  4. package/dist/cjs/batch-settlement/client/index.d.ts +111 -0
  5. package/dist/cjs/batch-settlement/client/index.js +1565 -0
  6. package/dist/cjs/batch-settlement/client/index.js.map +1 -0
  7. package/dist/cjs/batch-settlement/facilitator/index.d.ts +71 -0
  8. package/dist/cjs/batch-settlement/facilitator/index.js +2032 -0
  9. package/dist/cjs/batch-settlement/facilitator/index.js.map +1 -0
  10. package/dist/cjs/batch-settlement/server/file-storage.d.ts +53 -0
  11. package/dist/cjs/batch-settlement/server/file-storage.js +181 -0
  12. package/dist/cjs/batch-settlement/server/file-storage.js.map +1 -0
  13. package/dist/cjs/batch-settlement/server/index.d.ts +491 -0
  14. package/dist/cjs/batch-settlement/server/index.js +1960 -0
  15. package/dist/cjs/batch-settlement/server/index.js.map +1 -0
  16. package/dist/cjs/batch-settlement/server/redis-storage.d.ts +87 -0
  17. package/dist/cjs/batch-settlement/server/redis-storage.js +181 -0
  18. package/dist/cjs/batch-settlement/server/redis-storage.js.map +1 -0
  19. package/dist/cjs/exact/client/index.d.ts +6 -4
  20. package/dist/cjs/exact/client/index.js +7 -5
  21. package/dist/cjs/exact/client/index.js.map +1 -1
  22. package/dist/cjs/exact/facilitator/index.d.ts +16 -9
  23. package/dist/cjs/exact/facilitator/index.js +56 -9
  24. package/dist/cjs/exact/facilitator/index.js.map +1 -1
  25. package/dist/cjs/exact/server/index.d.ts +0 -8
  26. package/dist/cjs/exact/server/index.js +53 -19
  27. package/dist/cjs/exact/server/index.js.map +1 -1
  28. package/dist/cjs/exact/v1/client/index.d.ts +2 -1
  29. package/dist/cjs/exact/v1/client/index.js.map +1 -1
  30. package/dist/cjs/exact/v1/facilitator/index.d.ts +11 -5
  31. package/dist/cjs/exact/v1/facilitator/index.js +16 -2
  32. package/dist/cjs/exact/v1/facilitator/index.js.map +1 -1
  33. package/dist/cjs/index.d.ts +113 -7
  34. package/dist/cjs/index.js +1353 -5
  35. package/dist/cjs/index.js.map +1 -1
  36. package/dist/{esm/permit2-CyZxwngN.d.mts → cjs/permit2-DhJRUcgY.d.ts} +1 -13
  37. package/dist/cjs/rpc-DULZzRne.d.ts +13 -0
  38. package/dist/cjs/scheme-CvkPJXBD.d.ts +307 -0
  39. package/dist/{esm/scheme-DCR7hsa3.d.mts → cjs/scheme-DTQFE9xp.d.ts} +2 -2
  40. package/dist/{esm/signer-D912R4mq.d.mts → cjs/signer-tYS6Y46X.d.ts} +3 -0
  41. package/dist/cjs/storage-6W5MO46W.d.ts +50 -0
  42. package/dist/cjs/storage-Bl6aD0Xg.d.ts +81 -0
  43. package/dist/cjs/types-CF8P2-NM.d.ts +180 -0
  44. package/dist/cjs/upto/client/index.d.ts +5 -3
  45. package/dist/cjs/upto/client/index.js +7 -5
  46. package/dist/cjs/upto/client/index.js.map +1 -1
  47. package/dist/cjs/upto/facilitator/index.d.ts +2 -1
  48. package/dist/cjs/upto/facilitator/index.js +2 -1
  49. package/dist/cjs/upto/facilitator/index.js.map +1 -1
  50. package/dist/cjs/upto/server/index.d.ts +0 -8
  51. package/dist/cjs/upto/server/index.js +51 -19
  52. package/dist/cjs/upto/server/index.js.map +1 -1
  53. package/dist/cjs/v1/index.d.ts +2 -1
  54. package/dist/cjs/v1/index.js.map +1 -1
  55. package/dist/esm/batch-settlement/client/file-storage.d.mts +47 -0
  56. package/dist/esm/batch-settlement/client/file-storage.mjs +63 -0
  57. package/dist/esm/batch-settlement/client/file-storage.mjs.map +1 -0
  58. package/dist/esm/batch-settlement/client/index.d.mts +111 -0
  59. package/dist/esm/batch-settlement/client/index.mjs +59 -0
  60. package/dist/esm/batch-settlement/client/index.mjs.map +1 -0
  61. package/dist/esm/batch-settlement/facilitator/index.d.mts +71 -0
  62. package/dist/esm/batch-settlement/facilitator/index.mjs +1235 -0
  63. package/dist/esm/batch-settlement/facilitator/index.mjs.map +1 -0
  64. package/dist/esm/batch-settlement/server/file-storage.d.mts +53 -0
  65. package/dist/esm/batch-settlement/server/file-storage.mjs +128 -0
  66. package/dist/esm/batch-settlement/server/file-storage.mjs.map +1 -0
  67. package/dist/esm/batch-settlement/server/index.d.mts +491 -0
  68. package/dist/esm/batch-settlement/server/index.mjs +1645 -0
  69. package/dist/esm/batch-settlement/server/index.mjs.map +1 -0
  70. package/dist/esm/batch-settlement/server/redis-storage.d.mts +87 -0
  71. package/dist/esm/batch-settlement/server/redis-storage.mjs +156 -0
  72. package/dist/esm/batch-settlement/server/redis-storage.mjs.map +1 -0
  73. package/dist/esm/chunk-2EUQTNJO.mjs +38 -0
  74. package/dist/esm/chunk-2EUQTNJO.mjs.map +1 -0
  75. package/dist/esm/chunk-53USC5VE.mjs +47 -0
  76. package/dist/esm/chunk-53USC5VE.mjs.map +1 -0
  77. package/dist/esm/{chunk-GJ57SZGI.mjs → chunk-6WQOGWBE.mjs} +7 -5
  78. package/dist/esm/{chunk-GJ57SZGI.mjs.map → chunk-6WQOGWBE.mjs.map} +1 -1
  79. package/dist/esm/{chunk-NSFLAANF.mjs → chunk-BTYNCDNS.mjs} +51 -2
  80. package/dist/esm/chunk-BTYNCDNS.mjs.map +1 -0
  81. package/dist/esm/{chunk-RYT6M3PA.mjs → chunk-CSQS7ZON.mjs} +47 -7
  82. package/dist/esm/chunk-CSQS7ZON.mjs.map +1 -0
  83. package/dist/esm/chunk-GD4MKCN7.mjs +57 -0
  84. package/dist/esm/chunk-GD4MKCN7.mjs.map +1 -0
  85. package/dist/esm/chunk-HYABYUBD.mjs +432 -0
  86. package/dist/esm/chunk-HYABYUBD.mjs.map +1 -0
  87. package/dist/esm/chunk-IN5YIT5C.mjs +159 -0
  88. package/dist/esm/chunk-IN5YIT5C.mjs.map +1 -0
  89. package/dist/esm/{chunk-JII456TS.mjs → chunk-JK7SLLF7.mjs} +1 -1
  90. package/dist/esm/chunk-JK7SLLF7.mjs.map +1 -0
  91. package/dist/esm/{chunk-C4ZQMS77.mjs → chunk-MACPBXCT.mjs} +2 -216
  92. package/dist/esm/chunk-MACPBXCT.mjs.map +1 -0
  93. package/dist/esm/chunk-NKYVYGRA.mjs +911 -0
  94. package/dist/esm/chunk-NKYVYGRA.mjs.map +1 -0
  95. package/dist/esm/{chunk-D6RXZXOS.mjs → chunk-R7I3RZFF.mjs} +10 -6
  96. package/dist/esm/{chunk-D6RXZXOS.mjs.map → chunk-R7I3RZFF.mjs.map} +1 -1
  97. package/dist/esm/{chunk-CRT6YNY5.mjs → chunk-RWLVVO3B.mjs} +21 -61
  98. package/dist/esm/chunk-RWLVVO3B.mjs.map +1 -0
  99. package/dist/esm/chunk-TGFAVNUD.mjs +111 -0
  100. package/dist/esm/chunk-TGFAVNUD.mjs.map +1 -0
  101. package/dist/esm/chunk-TW7Z65AO.mjs +34 -0
  102. package/dist/esm/chunk-TW7Z65AO.mjs.map +1 -0
  103. package/dist/esm/chunk-U4HCGTLU.mjs +35 -0
  104. package/dist/esm/chunk-U4HCGTLU.mjs.map +1 -0
  105. package/dist/esm/chunk-VS3RYAYE.mjs +80 -0
  106. package/dist/esm/chunk-VS3RYAYE.mjs.map +1 -0
  107. package/dist/esm/chunk-W6ON4LG2.mjs +39 -0
  108. package/dist/esm/chunk-W6ON4LG2.mjs.map +1 -0
  109. package/dist/esm/{chunk-WKBC5YMI.mjs → chunk-YMQCTKDU.mjs} +23 -55
  110. package/dist/esm/chunk-YMQCTKDU.mjs.map +1 -0
  111. package/dist/esm/exact/client/index.d.mts +6 -4
  112. package/dist/esm/exact/client/index.mjs +10 -5
  113. package/dist/esm/exact/facilitator/index.d.mts +16 -9
  114. package/dist/esm/exact/facilitator/index.mjs +39 -16
  115. package/dist/esm/exact/facilitator/index.mjs.map +1 -1
  116. package/dist/esm/exact/server/index.d.mts +0 -8
  117. package/dist/esm/exact/server/index.mjs +3 -19
  118. package/dist/esm/exact/server/index.mjs.map +1 -1
  119. package/dist/esm/exact/v1/client/index.d.mts +2 -1
  120. package/dist/esm/exact/v1/client/index.mjs +5 -2
  121. package/dist/esm/exact/v1/facilitator/index.d.mts +11 -5
  122. package/dist/esm/exact/v1/facilitator/index.mjs +5 -2
  123. package/dist/esm/index.d.mts +113 -7
  124. package/dist/esm/index.mjs +53 -7
  125. package/dist/esm/index.mjs.map +1 -1
  126. package/dist/esm/permit2-DhJRUcgY.d.mts +729 -0
  127. package/dist/esm/rpc-DULZzRne.d.mts +13 -0
  128. package/dist/esm/scheme-DtbSS4Fk.d.mts +307 -0
  129. package/dist/esm/scheme-gtqAIYPJ.d.mts +47 -0
  130. package/dist/esm/signer-tYS6Y46X.d.mts +170 -0
  131. package/dist/esm/storage-6W5MO46W.d.mts +50 -0
  132. package/dist/esm/storage-sZ1CDS4P.d.mts +81 -0
  133. package/dist/esm/types-CF8P2-NM.d.mts +180 -0
  134. package/dist/esm/upto/client/index.d.mts +5 -3
  135. package/dist/esm/upto/client/index.mjs +9 -4
  136. package/dist/esm/upto/facilitator/index.d.mts +2 -1
  137. package/dist/esm/upto/facilitator/index.mjs +17 -9
  138. package/dist/esm/upto/facilitator/index.mjs.map +1 -1
  139. package/dist/esm/upto/server/index.d.mts +0 -8
  140. package/dist/esm/upto/server/index.mjs +3 -19
  141. package/dist/esm/upto/server/index.mjs.map +1 -1
  142. package/dist/esm/v1/index.d.mts +2 -1
  143. package/dist/esm/v1/index.mjs +5 -2
  144. package/package.json +5 -5
  145. package/dist/esm/chunk-C4ZQMS77.mjs.map +0 -1
  146. package/dist/esm/chunk-CRT6YNY5.mjs.map +0 -1
  147. package/dist/esm/chunk-JII456TS.mjs.map +0 -1
  148. package/dist/esm/chunk-NSFLAANF.mjs.map +0 -1
  149. package/dist/esm/chunk-RYT6M3PA.mjs.map +0 -1
  150. package/dist/esm/chunk-WKBC5YMI.mjs.map +0 -1
package/dist/cjs/index.js CHANGED
@@ -20,21 +20,37 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/index.ts
21
21
  var src_exports = {};
22
22
  __export(src_exports, {
23
+ BATCH_SETTLEMENT_ADDRESS: () => BATCH_SETTLEMENT_ADDRESS,
24
+ BATCH_SETTLEMENT_DOMAIN: () => BATCH_SETTLEMENT_DOMAIN,
25
+ BATCH_SETTLEMENT_SCHEME: () => BATCH_SETTLEMENT_SCHEME,
26
+ BatchSettlementEvmScheme: () => BatchSettlementEvmScheme,
27
+ DEFAULT_STABLECOINS: () => DEFAULT_STABLECOINS,
28
+ ERC3009_DEPOSIT_COLLECTOR_ADDRESS: () => ERC3009_DEPOSIT_COLLECTOR_ADDRESS,
23
29
  ExactEvmScheme: () => ExactEvmScheme,
24
30
  PERMIT2_ADDRESS: () => PERMIT2_ADDRESS,
25
31
  UptoEvmScheme: () => UptoEvmScheme,
26
32
  authorizationTypes: () => authorizationTypes,
33
+ claimBatchTypes: () => claimBatchTypes,
27
34
  createPermit2ApprovalTx: () => createPermit2ApprovalTx,
28
35
  eip3009ABI: () => eip3009ABI,
29
36
  erc20AllowanceAbi: () => erc20AllowanceAbi,
37
+ getDefaultAsset: () => getDefaultAsset,
30
38
  getPermit2AllowanceReadParams: () => getPermit2AllowanceReadParams,
39
+ isBatchSettlementClaimPayload: () => isBatchSettlementClaimPayload,
40
+ isBatchSettlementDepositPayload: () => isBatchSettlementDepositPayload,
41
+ isBatchSettlementEnrichedRefundPayload: () => isBatchSettlementEnrichedRefundPayload,
42
+ isBatchSettlementRefundPayload: () => isBatchSettlementRefundPayload,
43
+ isBatchSettlementSettlePayload: () => isBatchSettlementSettlePayload,
44
+ isBatchSettlementVoucherPayload: () => isBatchSettlementVoucherPayload,
31
45
  isEIP3009Payload: () => isEIP3009Payload,
32
46
  isPermit2Payload: () => isPermit2Payload,
33
47
  isUptoPermit2Payload: () => isUptoPermit2Payload,
34
48
  permit2WitnessTypes: () => permit2WitnessTypes,
49
+ refundTypes: () => refundTypes,
35
50
  toClientEvmSigner: () => toClientEvmSigner,
36
51
  toFacilitatorEvmSigner: () => toFacilitatorEvmSigner,
37
52
  uptoPermit2WitnessTypes: () => uptoPermit2WitnessTypes,
53
+ voucherTypes: () => voucherTypes,
38
54
  x402ExactPermit2ProxyABI: () => x402ExactPermit2ProxyABI,
39
55
  x402ExactPermit2ProxyAddress: () => x402ExactPermit2ProxyAddress,
40
56
  x402UptoPermit2ProxyABI: () => x402UptoPermit2ProxyABI,
@@ -767,7 +783,7 @@ function resolveExtensionRpcCapabilities(network, signer, options) {
767
783
  }
768
784
 
769
785
  // src/shared/extensions.ts
770
- async function trySignEip2612PermitExtension(signer, options, requirements, result, context) {
786
+ async function trySignEip2612PermitExtension(signer, options, requirements, result, context, approvalAmount) {
771
787
  const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
772
788
  if (!capabilities.readContract) {
773
789
  return void 0;
@@ -782,6 +798,7 @@ async function trySignEip2612PermitExtension(signer, options, requirements, resu
782
798
  }
783
799
  const chainId = getEvmChainId(requirements.network);
784
800
  const tokenAddress = (0, import_viem10.getAddress)(requirements.asset);
801
+ const requiredAllowance = approvalAmount ?? requirements.amount;
785
802
  try {
786
803
  const allowance = await capabilities.readContract({
787
804
  address: tokenAddress,
@@ -789,7 +806,7 @@ async function trySignEip2612PermitExtension(signer, options, requirements, resu
789
806
  functionName: "allowance",
790
807
  args: [signer.address, PERMIT2_ADDRESS]
791
808
  });
792
- if (allowance >= BigInt(requirements.amount)) {
809
+ if (allowance >= BigInt(requiredAllowance)) {
793
810
  return void 0;
794
811
  }
795
812
  } catch {
@@ -807,13 +824,13 @@ async function trySignEip2612PermitExtension(signer, options, requirements, resu
807
824
  tokenVersion,
808
825
  chainId,
809
826
  deadline,
810
- requirements.amount
827
+ requiredAllowance
811
828
  );
812
829
  return {
813
830
  [EIP2612_GAS_SPONSORING_KEY]: { info }
814
831
  };
815
832
  }
816
- async function trySignErc20ApprovalExtension(signer, options, requirements, context) {
833
+ async function trySignErc20ApprovalExtension(signer, options, requirements, context, approvalAmount) {
817
834
  const capabilities = resolveExtensionRpcCapabilities(requirements.network, signer, options);
818
835
  if (!capabilities.readContract) {
819
836
  return void 0;
@@ -826,6 +843,7 @@ async function trySignErc20ApprovalExtension(signer, options, requirements, cont
826
843
  }
827
844
  const chainId = getEvmChainId(requirements.network);
828
845
  const tokenAddress = (0, import_viem10.getAddress)(requirements.asset);
846
+ const requiredAllowance = approvalAmount ?? requirements.amount;
829
847
  try {
830
848
  const allowance = await capabilities.readContract({
831
849
  address: tokenAddress,
@@ -833,7 +851,7 @@ async function trySignErc20ApprovalExtension(signer, options, requirements, cont
833
851
  functionName: "allowance",
834
852
  args: [signer.address, PERMIT2_ADDRESS]
835
853
  });
836
- if (allowance >= BigInt(requirements.amount)) {
854
+ if (allowance >= BigInt(requiredAllowance)) {
837
855
  return void 0;
838
856
  }
839
857
  } catch {
@@ -985,6 +1003,32 @@ function toFacilitatorEvmSigner(client) {
985
1003
  };
986
1004
  }
987
1005
 
1006
+ // src/batch-settlement/types.ts
1007
+ function isObject(payload) {
1008
+ return typeof payload === "object" && payload !== null;
1009
+ }
1010
+ function isVoucherFields(payload) {
1011
+ return isObject(payload) && "channelId" in payload && "maxClaimableAmount" in payload && "signature" in payload;
1012
+ }
1013
+ function isBatchSettlementDepositPayload(payload) {
1014
+ return isObject(payload) && payload.type === "deposit" && "channelConfig" in payload && isVoucherFields(payload.voucher) && isObject(payload.deposit) && typeof payload.deposit.amount === "string" && isObject(payload.deposit.authorization);
1015
+ }
1016
+ function isBatchSettlementVoucherPayload(payload) {
1017
+ return isObject(payload) && payload.type === "voucher" && "channelConfig" in payload && isVoucherFields(payload.voucher);
1018
+ }
1019
+ function isBatchSettlementRefundPayload(payload) {
1020
+ return isObject(payload) && payload.type === "refund" && "channelConfig" in payload && isVoucherFields(payload.voucher);
1021
+ }
1022
+ function isBatchSettlementClaimPayload(payload) {
1023
+ return isObject(payload) && payload.type === "claim" && "claims" in payload;
1024
+ }
1025
+ function isBatchSettlementSettlePayload(payload) {
1026
+ return isObject(payload) && payload.type === "settle" && "receiver" in payload && "token" in payload;
1027
+ }
1028
+ function isBatchSettlementEnrichedRefundPayload(payload) {
1029
+ return isBatchSettlementRefundPayload(payload) && "amount" in payload && "refundNonce" in payload && "claims" in payload;
1030
+ }
1031
+
988
1032
  // src/types.ts
989
1033
  function isPermit2Payload(payload) {
990
1034
  return "permit2Authorization" in payload;
@@ -1117,23 +1161,1327 @@ var UptoEvmScheme = class {
1117
1161
  return result;
1118
1162
  }
1119
1163
  };
1164
+
1165
+ // src/batch-settlement/client/scheme.ts
1166
+ var import_viem22 = require("viem");
1167
+
1168
+ // src/batch-settlement/constants.ts
1169
+ var import_viem15 = require("viem");
1170
+ var BATCH_SETTLEMENT_SCHEME = "batch-settlement";
1171
+ var BATCH_SETTLEMENT_ADDRESS = "0x4020074e9dF2ce1deE5A9C1b5c3f541D02a10003";
1172
+ var ERC3009_DEPOSIT_COLLECTOR_ADDRESS = "0x4020806089470a89826cB9fB1f4059150b550004";
1173
+ var PERMIT2_DEPOSIT_COLLECTOR_ADDRESS = "0x4020425FAf3B746C082C2f942b4E5159887B0005";
1174
+ var MIN_WITHDRAW_DELAY = 900;
1175
+ var BATCH_SETTLEMENT_DOMAIN = {
1176
+ name: "x402 Batch Settlement",
1177
+ version: "1"
1178
+ };
1179
+ var CHANNEL_CONFIG_TYPEHASH = (0, import_viem15.keccak256)(
1180
+ (0, import_viem15.toBytes)(
1181
+ "ChannelConfig(address payer,address payerAuthorizer,address receiver,address receiverAuthorizer,address token,uint40 withdrawDelay,bytes32 salt)"
1182
+ )
1183
+ );
1184
+ var channelConfigTypes = {
1185
+ ChannelConfig: [
1186
+ { name: "payer", type: "address" },
1187
+ { name: "payerAuthorizer", type: "address" },
1188
+ { name: "receiver", type: "address" },
1189
+ { name: "receiverAuthorizer", type: "address" },
1190
+ { name: "token", type: "address" },
1191
+ { name: "withdrawDelay", type: "uint40" },
1192
+ { name: "salt", type: "bytes32" }
1193
+ ]
1194
+ };
1195
+ var voucherTypes = {
1196
+ Voucher: [
1197
+ { name: "channelId", type: "bytes32" },
1198
+ { name: "maxClaimableAmount", type: "uint128" }
1199
+ ]
1200
+ };
1201
+ var refundTypes = {
1202
+ Refund: [
1203
+ { name: "channelId", type: "bytes32" },
1204
+ { name: "nonce", type: "uint256" },
1205
+ { name: "amount", type: "uint128" }
1206
+ ]
1207
+ };
1208
+ var claimBatchTypes = {
1209
+ ClaimBatch: [{ name: "claims", type: "ClaimEntry[]" }],
1210
+ ClaimEntry: [
1211
+ { name: "channelId", type: "bytes32" },
1212
+ { name: "maxClaimableAmount", type: "uint128" },
1213
+ { name: "totalClaimed", type: "uint128" }
1214
+ ]
1215
+ };
1216
+ var receiveAuthorizationTypes = {
1217
+ ReceiveWithAuthorization: [
1218
+ { name: "from", type: "address" },
1219
+ { name: "to", type: "address" },
1220
+ { name: "value", type: "uint256" },
1221
+ { name: "validAfter", type: "uint256" },
1222
+ { name: "validBefore", type: "uint256" },
1223
+ { name: "nonce", type: "bytes32" }
1224
+ ]
1225
+ };
1226
+ var batchPermit2WitnessTypes = {
1227
+ PermitWitnessTransferFrom: [
1228
+ { name: "permitted", type: "TokenPermissions" },
1229
+ { name: "spender", type: "address" },
1230
+ { name: "nonce", type: "uint256" },
1231
+ { name: "deadline", type: "uint256" },
1232
+ { name: "witness", type: "DepositWitness" }
1233
+ ],
1234
+ TokenPermissions: [
1235
+ { name: "token", type: "address" },
1236
+ { name: "amount", type: "uint256" }
1237
+ ],
1238
+ DepositWitness: [{ name: "channelId", type: "bytes32" }]
1239
+ };
1240
+
1241
+ // src/batch-settlement/utils.ts
1242
+ var import_viem16 = require("viem");
1243
+ function computeChannelId(config, networkOrChainId) {
1244
+ const chainId = typeof networkOrChainId === "number" ? networkOrChainId : getEvmChainId(networkOrChainId);
1245
+ return (0, import_viem16.hashTypedData)({
1246
+ domain: getBatchSettlementEip712Domain(chainId),
1247
+ types: channelConfigTypes,
1248
+ primaryType: "ChannelConfig",
1249
+ message: {
1250
+ payer: config.payer,
1251
+ payerAuthorizer: config.payerAuthorizer,
1252
+ receiver: config.receiver,
1253
+ receiverAuthorizer: config.receiverAuthorizer,
1254
+ token: config.token,
1255
+ withdrawDelay: config.withdrawDelay,
1256
+ salt: config.salt
1257
+ }
1258
+ });
1259
+ }
1260
+ function getBatchSettlementEip712Domain(chainId) {
1261
+ return {
1262
+ ...BATCH_SETTLEMENT_DOMAIN,
1263
+ chainId,
1264
+ verifyingContract: (0, import_viem16.getAddress)(BATCH_SETTLEMENT_ADDRESS)
1265
+ };
1266
+ }
1267
+
1268
+ // src/batch-settlement/client/eip3009.ts
1269
+ var import_viem18 = require("viem");
1270
+
1271
+ // src/batch-settlement/client/voucher.ts
1272
+ async function signVoucher(signer, channelId, maxClaimableAmount, network) {
1273
+ const chainId = getEvmChainId(network);
1274
+ const signature = await signer.signTypedData({
1275
+ domain: getBatchSettlementEip712Domain(chainId),
1276
+ types: voucherTypes,
1277
+ primaryType: "Voucher",
1278
+ message: {
1279
+ channelId,
1280
+ maxClaimableAmount: BigInt(maxClaimableAmount)
1281
+ }
1282
+ });
1283
+ return {
1284
+ channelId,
1285
+ maxClaimableAmount,
1286
+ signature
1287
+ };
1288
+ }
1289
+
1290
+ // src/batch-settlement/encoding.ts
1291
+ var import_viem17 = require("viem");
1292
+ function buildErc3009DepositNonce(channelId, salt) {
1293
+ return (0, import_viem17.keccak256)(
1294
+ (0, import_viem17.encodeAbiParameters)([{ type: "bytes32" }, { type: "uint256" }], [channelId, BigInt(salt)])
1295
+ );
1296
+ }
1297
+
1298
+ // src/batch-settlement/client/eip3009.ts
1299
+ async function createBatchSettlementEIP3009DepositPayload(signer, x402Version, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
1300
+ const salt = createNonce();
1301
+ const now = Math.floor(Date.now() / 1e3);
1302
+ const chainId = getEvmChainId(paymentRequirements.network);
1303
+ if (!paymentRequirements.extra?.name || !paymentRequirements.extra?.version) {
1304
+ throw new Error(
1305
+ `EIP-712 domain parameters (name, version) are required in payment requirements for asset ${paymentRequirements.asset}`
1306
+ );
1307
+ }
1308
+ const { name, version } = paymentRequirements.extra;
1309
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
1310
+ const erc3009Nonce = buildErc3009DepositNonce(channelId, salt);
1311
+ const signature = await signer.signTypedData({
1312
+ domain: {
1313
+ name,
1314
+ version,
1315
+ chainId,
1316
+ verifyingContract: (0, import_viem18.getAddress)(paymentRequirements.asset)
1317
+ },
1318
+ types: receiveAuthorizationTypes,
1319
+ primaryType: "ReceiveWithAuthorization",
1320
+ message: {
1321
+ from: (0, import_viem18.getAddress)(signer.address),
1322
+ to: (0, import_viem18.getAddress)(ERC3009_DEPOSIT_COLLECTOR_ADDRESS),
1323
+ value: BigInt(depositAmount),
1324
+ validAfter: BigInt(now - 600),
1325
+ validBefore: BigInt(now + paymentRequirements.maxTimeoutSeconds),
1326
+ nonce: erc3009Nonce
1327
+ }
1328
+ });
1329
+ const vSigner = voucherSigner ?? signer;
1330
+ const voucher = await signVoucher(
1331
+ vSigner,
1332
+ channelId,
1333
+ maxClaimableAmount,
1334
+ paymentRequirements.network
1335
+ );
1336
+ const payload = {
1337
+ type: "deposit",
1338
+ channelConfig,
1339
+ voucher,
1340
+ deposit: {
1341
+ amount: depositAmount,
1342
+ authorization: {
1343
+ erc3009Authorization: {
1344
+ validAfter: (now - 600).toString(),
1345
+ validBefore: (now + paymentRequirements.maxTimeoutSeconds).toString(),
1346
+ salt,
1347
+ signature
1348
+ }
1349
+ }
1350
+ }
1351
+ };
1352
+ return {
1353
+ x402Version,
1354
+ payload
1355
+ };
1356
+ }
1357
+
1358
+ // src/batch-settlement/client/permit2.ts
1359
+ var import_viem19 = require("viem");
1360
+ async function createBatchSettlementPermit2DepositPayload(signer, x402Version, paymentRequirements, channelConfig, depositAmount, maxClaimableAmount, voucherSigner) {
1361
+ const chainId = getEvmChainId(paymentRequirements.network);
1362
+ const nonce = createPermit2Nonce();
1363
+ const deadline = Math.floor(Date.now() / 1e3 + paymentRequirements.maxTimeoutSeconds).toString();
1364
+ const channelId = computeChannelId(channelConfig, paymentRequirements.network);
1365
+ const permit2Authorization = {
1366
+ from: signer.address,
1367
+ permitted: {
1368
+ token: (0, import_viem19.getAddress)(paymentRequirements.asset),
1369
+ amount: depositAmount
1370
+ },
1371
+ spender: (0, import_viem19.getAddress)(PERMIT2_DEPOSIT_COLLECTOR_ADDRESS),
1372
+ nonce,
1373
+ deadline,
1374
+ witness: {
1375
+ channelId
1376
+ }
1377
+ };
1378
+ const signature = await signer.signTypedData({
1379
+ domain: { name: "Permit2", chainId, verifyingContract: PERMIT2_ADDRESS },
1380
+ types: batchPermit2WitnessTypes,
1381
+ primaryType: "PermitWitnessTransferFrom",
1382
+ message: {
1383
+ permitted: {
1384
+ token: permit2Authorization.permitted.token,
1385
+ amount: BigInt(permit2Authorization.permitted.amount)
1386
+ },
1387
+ spender: permit2Authorization.spender,
1388
+ nonce: BigInt(permit2Authorization.nonce),
1389
+ deadline: BigInt(permit2Authorization.deadline),
1390
+ witness: {
1391
+ channelId
1392
+ }
1393
+ }
1394
+ });
1395
+ const voucher = await signVoucher(
1396
+ voucherSigner ?? signer,
1397
+ channelId,
1398
+ maxClaimableAmount,
1399
+ paymentRequirements.network
1400
+ );
1401
+ const payload = {
1402
+ type: "deposit",
1403
+ channelConfig,
1404
+ voucher,
1405
+ deposit: {
1406
+ amount: depositAmount,
1407
+ authorization: {
1408
+ permit2Authorization: {
1409
+ ...permit2Authorization,
1410
+ signature
1411
+ }
1412
+ }
1413
+ }
1414
+ };
1415
+ return { x402Version, payload };
1416
+ }
1417
+
1418
+ // src/batch-settlement/client/storage.ts
1419
+ var InMemoryClientChannelStorage = class {
1420
+ constructor() {
1421
+ this.channels = /* @__PURE__ */ new Map();
1422
+ }
1423
+ /**
1424
+ * Returns the channel record for `key` if present.
1425
+ *
1426
+ * @param key - Channel storage key (channelId).
1427
+ * @returns Persisted context or undefined.
1428
+ */
1429
+ async get(key) {
1430
+ return this.channels.get(key);
1431
+ }
1432
+ /**
1433
+ * Stores or replaces the channel record for `key`.
1434
+ *
1435
+ * @param key - Channel storage key.
1436
+ * @param context - Channel fields to persist.
1437
+ * @returns Resolves when stored.
1438
+ */
1439
+ async set(key, context) {
1440
+ this.channels.set(key, context);
1441
+ }
1442
+ /**
1443
+ * Removes the channel record for `key` if it exists.
1444
+ *
1445
+ * @param key - Channel storage key.
1446
+ * @returns Resolves when removed.
1447
+ */
1448
+ async delete(key) {
1449
+ this.channels.delete(key);
1450
+ }
1451
+ };
1452
+
1453
+ // src/batch-settlement/client/config.ts
1454
+ var DEFAULT_SALT = "0x0000000000000000000000000000000000000000000000000000000000000000";
1455
+ function isBatchSettlementEvmSchemeOptions(o) {
1456
+ return o !== void 0 && typeof o === "object" && ("storage" in o || "depositPolicy" in o || "depositStrategy" in o || "salt" in o || "payerAuthorizer" in o || "rpcUrl" in o || "voucherSigner" in o);
1457
+ }
1458
+ function resolveClientOptions(second) {
1459
+ if (second === void 0) {
1460
+ return { storage: new InMemoryClientChannelStorage(), salt: DEFAULT_SALT };
1461
+ }
1462
+ if (isBatchSettlementEvmSchemeOptions(second)) {
1463
+ return {
1464
+ storage: second.storage ?? new InMemoryClientChannelStorage(),
1465
+ depositPolicy: second.depositPolicy,
1466
+ depositStrategy: second.depositStrategy,
1467
+ salt: second.salt ?? DEFAULT_SALT,
1468
+ payerAuthorizer: second.payerAuthorizer,
1469
+ voucherSigner: second.voucherSigner,
1470
+ extensionRpcOptions: second.rpcUrl ? { rpcUrl: second.rpcUrl } : void 0
1471
+ };
1472
+ }
1473
+ return {
1474
+ storage: new InMemoryClientChannelStorage(),
1475
+ depositPolicy: second,
1476
+ salt: DEFAULT_SALT
1477
+ };
1478
+ }
1479
+ function validateDepositPolicy(policy) {
1480
+ if (!policy) return;
1481
+ const m = policy.depositMultiplier;
1482
+ if (m !== void 0 && (!Number.isInteger(m) || m < 3)) {
1483
+ throw new Error("depositMultiplier must be an integer >= 3");
1484
+ }
1485
+ }
1486
+ function depositAmountForRequest(policy, requestAmount) {
1487
+ const mult = BigInt(policy?.depositMultiplier ?? 5);
1488
+ return (mult * requestAmount).toString();
1489
+ }
1490
+
1491
+ // src/batch-settlement/client/refund.ts
1492
+ var import_http2 = require("@payai/x402/http");
1493
+ var import_client = require("@payai/x402/client");
1494
+
1495
+ // src/batch-settlement/errors.ts
1496
+ var ErrCumulativeAmountBelowClaimed = "invalid_batch_settlement_evm_cumulative_below_claimed";
1497
+ var ErrCumulativeAmountMismatch = "invalid_batch_settlement_evm_cumulative_amount_mismatch";
1498
+ var ErrRefundNoBalance = "invalid_batch_settlement_evm_refund_no_balance";
1499
+ var ErrRefundAmountInvalid = "invalid_batch_settlement_evm_refund_amount_invalid";
1500
+
1501
+ // src/batch-settlement/client/channel.ts
1502
+ var import_http = require("@payai/x402/http");
1503
+ var import_viem20 = require("viem");
1504
+
1505
+ // src/batch-settlement/abi.ts
1506
+ var channelConfigComponents = [
1507
+ { name: "payer", type: "address" },
1508
+ { name: "payerAuthorizer", type: "address" },
1509
+ { name: "receiver", type: "address" },
1510
+ { name: "receiverAuthorizer", type: "address" },
1511
+ { name: "token", type: "address" },
1512
+ { name: "withdrawDelay", type: "uint40" },
1513
+ { name: "salt", type: "bytes32" }
1514
+ ];
1515
+ var voucherClaimComponents = [
1516
+ {
1517
+ name: "voucher",
1518
+ type: "tuple",
1519
+ components: [
1520
+ {
1521
+ name: "channel",
1522
+ type: "tuple",
1523
+ components: channelConfigComponents
1524
+ },
1525
+ { name: "maxClaimableAmount", type: "uint128" }
1526
+ ]
1527
+ },
1528
+ { name: "signature", type: "bytes" },
1529
+ { name: "totalClaimed", type: "uint128" }
1530
+ ];
1531
+ var batchSettlementABI = [
1532
+ {
1533
+ type: "function",
1534
+ name: "multicall",
1535
+ inputs: [{ name: "data", type: "bytes[]" }],
1536
+ outputs: [{ name: "results", type: "bytes[]" }],
1537
+ stateMutability: "nonpayable"
1538
+ },
1539
+ {
1540
+ type: "function",
1541
+ name: "deposit",
1542
+ inputs: [
1543
+ { name: "config", type: "tuple", components: channelConfigComponents },
1544
+ { name: "amount", type: "uint128" },
1545
+ { name: "collector", type: "address" },
1546
+ { name: "collectorData", type: "bytes" }
1547
+ ],
1548
+ outputs: [],
1549
+ stateMutability: "nonpayable"
1550
+ },
1551
+ {
1552
+ type: "function",
1553
+ name: "claim",
1554
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
1555
+ outputs: [],
1556
+ stateMutability: "nonpayable"
1557
+ },
1558
+ {
1559
+ type: "function",
1560
+ name: "claimWithSignature",
1561
+ inputs: [
1562
+ { name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents },
1563
+ { name: "authorizerSignature", type: "bytes" }
1564
+ ],
1565
+ outputs: [],
1566
+ stateMutability: "nonpayable"
1567
+ },
1568
+ {
1569
+ type: "function",
1570
+ name: "settle",
1571
+ inputs: [
1572
+ { name: "receiver", type: "address" },
1573
+ { name: "token", type: "address" }
1574
+ ],
1575
+ outputs: [],
1576
+ stateMutability: "nonpayable"
1577
+ },
1578
+ {
1579
+ type: "function",
1580
+ name: "initiateWithdraw",
1581
+ inputs: [
1582
+ { name: "config", type: "tuple", components: channelConfigComponents },
1583
+ { name: "amount", type: "uint128" }
1584
+ ],
1585
+ outputs: [],
1586
+ stateMutability: "nonpayable"
1587
+ },
1588
+ {
1589
+ type: "function",
1590
+ name: "finalizeWithdraw",
1591
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
1592
+ outputs: [],
1593
+ stateMutability: "nonpayable"
1594
+ },
1595
+ {
1596
+ type: "function",
1597
+ name: "refund",
1598
+ inputs: [
1599
+ { name: "config", type: "tuple", components: channelConfigComponents },
1600
+ { name: "amount", type: "uint128" }
1601
+ ],
1602
+ outputs: [],
1603
+ stateMutability: "nonpayable"
1604
+ },
1605
+ {
1606
+ type: "function",
1607
+ name: "refundWithSignature",
1608
+ inputs: [
1609
+ { name: "config", type: "tuple", components: channelConfigComponents },
1610
+ { name: "amount", type: "uint128" },
1611
+ { name: "nonce", type: "uint256" },
1612
+ { name: "receiverAuthorizerSignature", type: "bytes" }
1613
+ ],
1614
+ outputs: [],
1615
+ stateMutability: "nonpayable"
1616
+ },
1617
+ {
1618
+ type: "function",
1619
+ name: "getChannelId",
1620
+ inputs: [{ name: "config", type: "tuple", components: channelConfigComponents }],
1621
+ outputs: [{ name: "", type: "bytes32" }],
1622
+ stateMutability: "view"
1623
+ },
1624
+ {
1625
+ type: "function",
1626
+ name: "CHANNEL_CONFIG_TYPEHASH",
1627
+ inputs: [],
1628
+ outputs: [{ name: "", type: "bytes32" }],
1629
+ stateMutability: "view"
1630
+ },
1631
+ {
1632
+ type: "function",
1633
+ name: "channels",
1634
+ inputs: [{ name: "channelId", type: "bytes32" }],
1635
+ outputs: [
1636
+ { name: "balance", type: "uint128" },
1637
+ { name: "totalClaimed", type: "uint128" }
1638
+ ],
1639
+ stateMutability: "view"
1640
+ },
1641
+ {
1642
+ type: "function",
1643
+ name: "pendingWithdrawals",
1644
+ inputs: [{ name: "channelId", type: "bytes32" }],
1645
+ outputs: [
1646
+ { name: "amount", type: "uint128" },
1647
+ { name: "initiatedAt", type: "uint40" }
1648
+ ],
1649
+ stateMutability: "view"
1650
+ },
1651
+ {
1652
+ type: "function",
1653
+ name: "receivers",
1654
+ inputs: [
1655
+ { name: "receiver", type: "address" },
1656
+ { name: "token", type: "address" }
1657
+ ],
1658
+ outputs: [
1659
+ { name: "totalClaimed", type: "uint128" },
1660
+ { name: "totalSettled", type: "uint128" }
1661
+ ],
1662
+ stateMutability: "view"
1663
+ },
1664
+ {
1665
+ type: "function",
1666
+ name: "getVoucherDigest",
1667
+ inputs: [
1668
+ { name: "channelId", type: "bytes32" },
1669
+ { name: "maxClaimableAmount", type: "uint128" }
1670
+ ],
1671
+ outputs: [{ name: "", type: "bytes32" }],
1672
+ stateMutability: "view"
1673
+ },
1674
+ {
1675
+ type: "function",
1676
+ name: "getRefundDigest",
1677
+ inputs: [
1678
+ { name: "channelId", type: "bytes32" },
1679
+ { name: "nonce", type: "uint256" },
1680
+ { name: "amount", type: "uint128" }
1681
+ ],
1682
+ outputs: [{ name: "", type: "bytes32" }],
1683
+ stateMutability: "view"
1684
+ },
1685
+ {
1686
+ type: "function",
1687
+ name: "refundNonce",
1688
+ inputs: [{ name: "channelId", type: "bytes32" }],
1689
+ outputs: [{ name: "", type: "uint256" }],
1690
+ stateMutability: "view"
1691
+ },
1692
+ {
1693
+ type: "function",
1694
+ name: "getClaimBatchDigest",
1695
+ inputs: [{ name: "voucherClaims", type: "tuple[]", components: voucherClaimComponents }],
1696
+ outputs: [{ name: "", type: "bytes32" }],
1697
+ stateMutability: "view"
1698
+ },
1699
+ {
1700
+ type: "event",
1701
+ name: "Settled",
1702
+ inputs: [
1703
+ { name: "receiver", type: "address", indexed: true },
1704
+ { name: "token", type: "address", indexed: true },
1705
+ { name: "sender", type: "address", indexed: true },
1706
+ { name: "amount", type: "uint128", indexed: false }
1707
+ ],
1708
+ anonymous: false
1709
+ }
1710
+ ];
1711
+
1712
+ // src/batch-settlement/client/channel.ts
1713
+ function readResponseChannelState(extra) {
1714
+ const channelState = extra.channelState;
1715
+ if (typeof channelState !== "object" || channelState === null) {
1716
+ return void 0;
1717
+ }
1718
+ return channelState;
1719
+ }
1720
+ function buildChannelConfig(deps, paymentRequirements) {
1721
+ const extra = paymentRequirements.extra;
1722
+ const receiverAuthorizer = extra?.receiverAuthorizer;
1723
+ if (!receiverAuthorizer || (0, import_viem20.getAddress)(receiverAuthorizer) === "0x0000000000000000000000000000000000000000") {
1724
+ throw new Error("Payment requirements must include a non-zero extra.receiverAuthorizer");
1725
+ }
1726
+ return {
1727
+ payer: deps.signer.address,
1728
+ payerAuthorizer: (0, import_viem20.getAddress)(
1729
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
1730
+ ),
1731
+ receiver: paymentRequirements.payTo,
1732
+ receiverAuthorizer: (0, import_viem20.getAddress)(receiverAuthorizer),
1733
+ token: paymentRequirements.asset,
1734
+ withdrawDelay: typeof extra?.withdrawDelay === "number" ? extra.withdrawDelay : MIN_WITHDRAW_DELAY,
1735
+ salt: deps.salt
1736
+ };
1737
+ }
1738
+ async function processSettleResponse(storage, settle) {
1739
+ const extra = settle.extra ?? {};
1740
+ const channelState = readResponseChannelState(extra);
1741
+ if (!channelState) return;
1742
+ const channelId = channelState.channelId;
1743
+ const key = channelId.toLowerCase();
1744
+ const prev = await storage.get(key);
1745
+ const next = { ...prev ?? {} };
1746
+ if (channelState.chargedCumulativeAmount !== void 0) {
1747
+ next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
1748
+ }
1749
+ if (channelState.balance !== void 0) {
1750
+ next.balance = String(channelState.balance);
1751
+ }
1752
+ if (channelState.totalClaimed !== void 0) {
1753
+ next.totalClaimed = String(channelState.totalClaimed);
1754
+ }
1755
+ await storage.set(key, next);
1756
+ }
1757
+ async function updateChannelAfterRefund(storage, channelKey, settleExtra) {
1758
+ const channelState = readResponseChannelState(settleExtra);
1759
+ if (!channelState) {
1760
+ await storage.delete(channelKey);
1761
+ return;
1762
+ }
1763
+ const balanceAfter = channelState.balance !== void 0 ? BigInt(String(channelState.balance)) : void 0;
1764
+ if (balanceAfter === void 0 || balanceAfter <= 0n) {
1765
+ await storage.delete(channelKey);
1766
+ return;
1767
+ }
1768
+ const prev = await storage.get(channelKey);
1769
+ const next = { ...prev ?? {} };
1770
+ next.balance = balanceAfter.toString();
1771
+ if (channelState.chargedCumulativeAmount !== void 0) {
1772
+ next.chargedCumulativeAmount = String(channelState.chargedCumulativeAmount);
1773
+ }
1774
+ if (channelState.totalClaimed !== void 0) {
1775
+ next.totalClaimed = String(channelState.totalClaimed);
1776
+ }
1777
+ await storage.set(channelKey, next);
1778
+ }
1779
+ async function recoverChannel(deps, paymentRequirements) {
1780
+ if (!deps.signer.readContract) {
1781
+ throw new Error("recoverChannel requires ClientEvmSigner.readContract");
1782
+ }
1783
+ const config = buildChannelConfig(deps, paymentRequirements);
1784
+ const channelId = computeChannelId(config, paymentRequirements.network);
1785
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1786
+ deps.signer,
1787
+ channelId
1788
+ );
1789
+ const ctx = {
1790
+ chargedCumulativeAmount: chTotalClaimed.toString(),
1791
+ balance: chBalance.toString(),
1792
+ totalClaimed: chTotalClaimed.toString()
1793
+ };
1794
+ await deps.storage.set(channelId.toLowerCase(), ctx);
1795
+ return ctx;
1796
+ }
1797
+ async function readChannelBalanceAndTotalClaimed(signer, channelId) {
1798
+ if (!signer.readContract) {
1799
+ throw new Error("readChannelBalanceAndTotalClaimed requires ClientEvmSigner.readContract");
1800
+ }
1801
+ return await signer.readContract({
1802
+ address: BATCH_SETTLEMENT_ADDRESS,
1803
+ abi: batchSettlementABI,
1804
+ functionName: "channels",
1805
+ args: [channelId]
1806
+ });
1807
+ }
1808
+
1809
+ // src/batch-settlement/client/recovery.ts
1810
+ var import_viem21 = require("viem");
1811
+ async function processCorrectivePaymentRequired(deps, paymentRequired) {
1812
+ if (paymentRequired.error !== ErrCumulativeAmountMismatch && paymentRequired.error !== ErrCumulativeAmountBelowClaimed) {
1813
+ return false;
1814
+ }
1815
+ const accept = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1816
+ if (!accept) {
1817
+ return false;
1818
+ }
1819
+ const channelState = accept.extra.channelState;
1820
+ const voucherState = accept.extra.voucherState;
1821
+ const hasSig = channelState?.chargedCumulativeAmount !== void 0 && voucherState?.signedMaxClaimable !== void 0 && voucherState.signature !== void 0;
1822
+ if (!hasSig) {
1823
+ return recoverFromOnChainState(deps, accept);
1824
+ }
1825
+ return recoverFromSignature(deps, accept, channelState, voucherState);
1826
+ }
1827
+ async function recoverFromSignature(deps, accept, channelState, voucherState) {
1828
+ const chargedRaw = channelState.chargedCumulativeAmount;
1829
+ const signedRaw = voucherState.signedMaxClaimable;
1830
+ const sig = voucherState.signature;
1831
+ const charged = BigInt(String(chargedRaw));
1832
+ const signed = BigInt(String(signedRaw));
1833
+ if (charged > signed) {
1834
+ return false;
1835
+ }
1836
+ const config = buildChannelConfig(deps, accept);
1837
+ const channelId = computeChannelId(config, accept.network);
1838
+ if (!deps.signer.readContract) {
1839
+ return false;
1840
+ }
1841
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1842
+ deps.signer,
1843
+ channelId
1844
+ );
1845
+ if (charged < chTotalClaimed) {
1846
+ return false;
1847
+ }
1848
+ const chainId = getEvmChainId(accept.network);
1849
+ const recovered = await (0, import_viem21.recoverTypedDataAddress)({
1850
+ domain: getBatchSettlementEip712Domain(chainId),
1851
+ types: voucherTypes,
1852
+ primaryType: "Voucher",
1853
+ message: {
1854
+ channelId,
1855
+ maxClaimableAmount: signed
1856
+ },
1857
+ signature: sig
1858
+ });
1859
+ const expectedSigner = (0, import_viem21.getAddress)(
1860
+ deps.payerAuthorizer ?? deps.voucherSigner?.address ?? deps.signer.address
1861
+ );
1862
+ if (recovered.toLowerCase() !== expectedSigner.toLowerCase()) {
1863
+ return false;
1864
+ }
1865
+ const ctx = {
1866
+ chargedCumulativeAmount: charged.toString(),
1867
+ signedMaxClaimable: signed.toString(),
1868
+ signature: sig,
1869
+ balance: chBalance.toString(),
1870
+ totalClaimed: chTotalClaimed.toString()
1871
+ };
1872
+ await deps.storage.set(channelId.toLowerCase(), ctx);
1873
+ return true;
1874
+ }
1875
+ async function recoverFromOnChainState(deps, accept) {
1876
+ if (!deps.signer.readContract) {
1877
+ return false;
1878
+ }
1879
+ const config = buildChannelConfig(deps, accept);
1880
+ const channelId = computeChannelId(config, accept.network);
1881
+ const [chBalance, chTotalClaimed] = await readChannelBalanceAndTotalClaimed(
1882
+ deps.signer,
1883
+ channelId
1884
+ );
1885
+ const ctx = {
1886
+ chargedCumulativeAmount: chTotalClaimed.toString(),
1887
+ balance: chBalance.toString(),
1888
+ totalClaimed: chTotalClaimed.toString()
1889
+ };
1890
+ await deps.storage.set(channelId.toLowerCase(), ctx);
1891
+ return true;
1892
+ }
1893
+
1894
+ // src/batch-settlement/client/hooks.ts
1895
+ function createBatchSettlementClientHooks(deps) {
1896
+ return {
1897
+ onPaymentResponse: (ctx) => handleBatchSettlementPaymentResponse(deps, ctx)
1898
+ };
1899
+ }
1900
+ async function handleBatchSettlementPaymentResponse(deps, ctx) {
1901
+ if (ctx.settleResponse) {
1902
+ if (isBatchSettlementRefundPayload(ctx.paymentPayload.payload)) {
1903
+ const extra = ctx.settleResponse.extra ?? {};
1904
+ const channelState = extra.channelState;
1905
+ const channelId = typeof channelState === "object" && channelState !== null && "channelId" in channelState ? channelState.channelId : void 0;
1906
+ if (typeof channelId === "string" && channelId) {
1907
+ await updateChannelAfterRefund(deps.storage, channelId.toLowerCase(), extra);
1908
+ }
1909
+ return;
1910
+ }
1911
+ await processSettleResponse(deps.storage, ctx.settleResponse);
1912
+ return;
1913
+ }
1914
+ if (ctx.paymentRequired) {
1915
+ const recovered = await processCorrectivePaymentRequired(deps, ctx.paymentRequired);
1916
+ return recovered ? { recovered: true } : void 0;
1917
+ }
1918
+ }
1919
+
1920
+ // src/batch-settlement/client/refund.ts
1921
+ var NON_RECOVERABLE_REFUND_ERRORS = /* @__PURE__ */ new Set([
1922
+ ErrRefundNoBalance,
1923
+ ErrRefundAmountInvalid
1924
+ ]);
1925
+ async function refundChannel(ctx, url, options) {
1926
+ const fetchImpl = options?.fetch ?? globalThis.fetch;
1927
+ if (!fetchImpl) {
1928
+ throw new Error("refund requires a fetch implementation (globalThis.fetch unavailable)");
1929
+ }
1930
+ const refundAmount = normalizeRefundAmount(options?.amount);
1931
+ const probe = await probeRefundRequirements(url, fetchImpl);
1932
+ return executeRefund(ctx, url, probe, refundAmount, fetchImpl);
1933
+ }
1934
+ async function probeRefundRequirements(url, fetchImpl) {
1935
+ const probe = await fetchImpl(url, { method: "GET" });
1936
+ if (probe.status !== 402) {
1937
+ throw new Error(`Refund probe expected 402, got ${probe.status}`);
1938
+ }
1939
+ const header = probe.headers.get("PAYMENT-REQUIRED");
1940
+ if (!header) {
1941
+ throw new Error("Refund probe response missing PAYMENT-REQUIRED header");
1942
+ }
1943
+ const paymentRequired = (0, import_http2.decodePaymentRequiredHeader)(header);
1944
+ const requirements = paymentRequired.accepts.find((a) => a.scheme === BATCH_SETTLEMENT_SCHEME);
1945
+ if (!requirements) {
1946
+ throw new Error(`No ${BATCH_SETTLEMENT_SCHEME} payment option at ${url}`);
1947
+ }
1948
+ const extra = requirements.extra;
1949
+ if (!extra?.receiverAuthorizer) {
1950
+ throw new Error("Refund requires a configured receiverAuthorizer on the receiver");
1951
+ }
1952
+ return { paymentRequired, requirements };
1953
+ }
1954
+ async function executeRefund(ctx, url, probe, refundAmount, fetchImpl) {
1955
+ const maxAttempts = 2;
1956
+ const { paymentRequired, requirements } = probe;
1957
+ const httpClient = createRefundHttpClient(ctx, requirements);
1958
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
1959
+ const paymentPayload = await buildRefundPaymentPayload(
1960
+ ctx,
1961
+ paymentRequired,
1962
+ requirements,
1963
+ refundAmount
1964
+ );
1965
+ const headers = httpClient.encodePaymentSignatureHeader(paymentPayload);
1966
+ const response = await fetchImpl(url, { method: "GET", headers });
1967
+ if (response.status === 402) {
1968
+ const nonRecoverable = getNonRecoverableRefundFailure(response);
1969
+ if (nonRecoverable) {
1970
+ throw new Error(nonRecoverable);
1971
+ }
1972
+ }
1973
+ const result = await httpClient.processPaymentResult(
1974
+ paymentPayload,
1975
+ (name) => response.headers.get(name),
1976
+ response.status
1977
+ );
1978
+ if (response.status === 402) {
1979
+ if (result.recovered && attempt < maxAttempts) {
1980
+ continue;
1981
+ }
1982
+ if (result.recovered) {
1983
+ throw new Error(`Refund failed: server returned 402 after ${attempt} attempt(s)`);
1984
+ }
1985
+ const corrective = getRefundPaymentRequired(response);
1986
+ throw new Error(`Refund failed: ${corrective.error ?? "unknown"}`);
1987
+ }
1988
+ if (!result.settleResponse) {
1989
+ throw new Error(
1990
+ `Refund response missing PAYMENT-RESPONSE header (status ${response.status})`
1991
+ );
1992
+ }
1993
+ return result.settleResponse;
1994
+ }
1995
+ throw new Error("Refund failed: retry budget exhausted");
1996
+ }
1997
+ async function buildRefundPaymentPayload(ctx, paymentRequired, requirements, refundAmount) {
1998
+ const config = buildChannelConfig(ctx, requirements);
1999
+ const channelId = computeChannelId(config, requirements.network);
2000
+ const key = channelId.toLowerCase();
2001
+ let channel = await ctx.storage.get(key);
2002
+ if (channel === void 0 && ctx.signer.readContract) {
2003
+ channel = await recoverChannel(ctx, requirements);
2004
+ }
2005
+ if (channel === void 0) {
2006
+ throw new Error(
2007
+ "Refund requires an existing channel record; deposit first or call from a context with an EVM RPC"
2008
+ );
2009
+ }
2010
+ const charged = channel.chargedCumulativeAmount ?? "0";
2011
+ if (channel.balance !== void 0 && BigInt(channel.balance) <= BigInt(charged)) {
2012
+ throw new Error(
2013
+ `Refund failed: channel has no remaining balance (balance=${channel.balance}, chargedCumulativeAmount=${charged})`
2014
+ );
2015
+ }
2016
+ const voucherSigner = ctx.voucherSigner ?? ctx.signer;
2017
+ const voucher = await signVoucher(voucherSigner, channelId, charged, requirements.network);
2018
+ const payload = {
2019
+ type: "refund",
2020
+ channelConfig: config,
2021
+ voucher,
2022
+ ...refundAmount !== void 0 ? { amount: refundAmount } : {}
2023
+ };
2024
+ return {
2025
+ x402Version: 2,
2026
+ accepted: requirements,
2027
+ payload,
2028
+ ...paymentRequired.resource ? { resource: paymentRequired.resource } : {},
2029
+ ...paymentRequired.extensions ? { extensions: paymentRequired.extensions } : {}
2030
+ };
2031
+ }
2032
+ function createRefundHttpClient(ctx, requirements) {
2033
+ const client = new import_client.x402Client().register(requirements.network, {
2034
+ scheme: BATCH_SETTLEMENT_SCHEME,
2035
+ schemeHooks: createBatchSettlementClientHooks(ctx),
2036
+ createPaymentPayload: async () => {
2037
+ throw new Error("Refund payloads are built by refundChannel");
2038
+ }
2039
+ });
2040
+ return new import_client.x402HTTPClient(client);
2041
+ }
2042
+ function getNonRecoverableRefundFailure(response) {
2043
+ const settleHeader = response.headers.get("PAYMENT-RESPONSE");
2044
+ if (settleHeader) {
2045
+ return formatRefundFailure((0, import_http2.decodePaymentResponseHeader)(settleHeader));
2046
+ }
2047
+ const paymentRequired = getRefundPaymentRequired(response);
2048
+ const errorCode = paymentRequired.error;
2049
+ if (errorCode && NON_RECOVERABLE_REFUND_ERRORS.has(errorCode)) {
2050
+ return `Refund failed: ${errorCode}`;
2051
+ }
2052
+ }
2053
+ function getRefundPaymentRequired(response) {
2054
+ const requiredHeader = response.headers.get("PAYMENT-REQUIRED");
2055
+ if (!requiredHeader) {
2056
+ throw new Error("Refund 402 missing PAYMENT-REQUIRED header");
2057
+ }
2058
+ return (0, import_http2.decodePaymentRequiredHeader)(requiredHeader);
2059
+ }
2060
+ function formatRefundFailure(settle) {
2061
+ const reason = settle.errorReason ?? "unknown_settlement_error";
2062
+ const message = settle.errorMessage;
2063
+ if (message && message !== reason) {
2064
+ return `Refund failed: ${reason}: ${message}`;
2065
+ }
2066
+ return `Refund failed: ${reason}`;
2067
+ }
2068
+ function normalizeRefundAmount(amount) {
2069
+ if (amount === void 0) return void 0;
2070
+ if (!/^\d+$/.test(amount) || amount === "0") {
2071
+ throw new Error(`Invalid refund amount "${amount}": must be a positive integer string`);
2072
+ }
2073
+ return amount;
2074
+ }
2075
+
2076
+ // src/batch-settlement/client/scheme.ts
2077
+ var BatchSettlementEvmScheme = class {
2078
+ /**
2079
+ * Constructs a batched client scheme.
2080
+ *
2081
+ * @param signer - Client EVM wallet used for signing vouchers and ERC-3009 authorizations.
2082
+ * @param optionsOrPolicy - Either a full options object or a bare deposit-policy.
2083
+ */
2084
+ constructor(signer, optionsOrPolicy) {
2085
+ this.signer = signer;
2086
+ this.scheme = BATCH_SETTLEMENT_SCHEME;
2087
+ const {
2088
+ storage,
2089
+ depositPolicy,
2090
+ depositStrategy,
2091
+ salt,
2092
+ payerAuthorizer,
2093
+ voucherSigner,
2094
+ extensionRpcOptions
2095
+ } = resolveClientOptions(optionsOrPolicy);
2096
+ this.storage = storage;
2097
+ this.depositPolicy = depositPolicy;
2098
+ this.depositStrategy = depositStrategy;
2099
+ this.salt = salt;
2100
+ this.payerAuthorizer = payerAuthorizer;
2101
+ this.voucherSigner = voucherSigner;
2102
+ this.extensionRpcOptions = extensionRpcOptions;
2103
+ if (payerAuthorizer !== void 0 && voucherSigner !== void 0 && (0, import_viem22.getAddress)(payerAuthorizer) !== (0, import_viem22.getAddress)(voucherSigner.address)) {
2104
+ throw new Error("payerAuthorizer address must match voucherSigner.address");
2105
+ }
2106
+ validateDepositPolicy(depositPolicy);
2107
+ this.schemeHooks = createBatchSettlementClientHooks(this.deps());
2108
+ }
2109
+ /**
2110
+ * Creates the payment payload for a batched request.
2111
+ *
2112
+ * If the channel has no onchain deposit (or needs a top-up), builds an
2113
+ * ERC-3009 deposit payload bundled with a voucher. Otherwise, signs and
2114
+ * returns a voucher-only payload.
2115
+ *
2116
+ * @param x402Version - Protocol version for the payload envelope.
2117
+ * @param paymentRequirements - Server payment requirements (scheme, network, asset, amount).
2118
+ * @param context - Optional payment payload context with extension hints.
2119
+ * @returns A {@link PaymentPayloadResult} ready to be sent as the `X-PAYMENT` header.
2120
+ */
2121
+ async createPaymentPayload(x402Version, paymentRequirements, context) {
2122
+ const deps = this.deps();
2123
+ const config = buildChannelConfig(deps, paymentRequirements);
2124
+ const channelId = computeChannelId(config, paymentRequirements.network);
2125
+ const key = channelId.toLowerCase();
2126
+ let batchedCtx = await this.storage.get(key);
2127
+ if (batchedCtx === void 0 && this.signer.readContract) {
2128
+ batchedCtx = await recoverChannel(deps, paymentRequirements);
2129
+ }
2130
+ batchedCtx = batchedCtx ?? {};
2131
+ const needsInitialDeposit = !batchedCtx.balance || batchedCtx.balance === "0";
2132
+ const baseCumulative = BigInt(batchedCtx.chargedCumulativeAmount ?? "0");
2133
+ const requestAmount = BigInt(paymentRequirements.amount);
2134
+ const maxClaimableAmount = (baseCumulative + requestAmount).toString();
2135
+ const currentBalance = BigInt(batchedCtx.balance ?? "0");
2136
+ const needsTopUp = !needsInitialDeposit && BigInt(maxClaimableAmount) > currentBalance;
2137
+ if (needsInitialDeposit || needsTopUp) {
2138
+ const computedDeposit = depositAmountForRequest(this.depositPolicy, requestAmount);
2139
+ const minimumDepositAmount = BigInt(maxClaimableAmount) - currentBalance;
2140
+ const depositAmount = await this.resolveDepositAmount({
2141
+ paymentRequirements,
2142
+ channelConfig: config,
2143
+ channelId,
2144
+ clientContext: batchedCtx,
2145
+ requestAmount: requestAmount.toString(),
2146
+ maxClaimableAmount,
2147
+ currentBalance: currentBalance.toString(),
2148
+ minimumDepositAmount: minimumDepositAmount.toString(),
2149
+ depositAmount: computedDeposit
2150
+ });
2151
+ if (depositAmount === false) {
2152
+ return this.createVoucherPayload(
2153
+ x402Version,
2154
+ channelId,
2155
+ maxClaimableAmount,
2156
+ paymentRequirements.network,
2157
+ config
2158
+ );
2159
+ }
2160
+ const assetTransferMethod = paymentRequirements.extra?.assetTransferMethod ?? "eip3009";
2161
+ if (assetTransferMethod === "eip3009") {
2162
+ return createBatchSettlementEIP3009DepositPayload(
2163
+ this.signer,
2164
+ x402Version,
2165
+ paymentRequirements,
2166
+ config,
2167
+ depositAmount,
2168
+ maxClaimableAmount,
2169
+ this.voucherSigner
2170
+ );
2171
+ }
2172
+ if (assetTransferMethod !== "permit2") {
2173
+ throw new Error(`unsupported batch-settlement assetTransferMethod: ${assetTransferMethod}`);
2174
+ }
2175
+ const result = await createBatchSettlementPermit2DepositPayload(
2176
+ this.signer,
2177
+ x402Version,
2178
+ paymentRequirements,
2179
+ config,
2180
+ depositAmount,
2181
+ maxClaimableAmount,
2182
+ this.voucherSigner
2183
+ );
2184
+ const eip2612Extensions = await trySignEip2612PermitExtension(
2185
+ this.signer,
2186
+ this.extensionRpcOptions,
2187
+ paymentRequirements,
2188
+ result,
2189
+ context,
2190
+ depositAmount
2191
+ );
2192
+ if (eip2612Extensions) {
2193
+ return { ...result, extensions: eip2612Extensions };
2194
+ }
2195
+ const erc20Extensions = await trySignErc20ApprovalExtension(
2196
+ this.signer,
2197
+ this.extensionRpcOptions,
2198
+ paymentRequirements,
2199
+ context,
2200
+ depositAmount
2201
+ );
2202
+ if (erc20Extensions) {
2203
+ return { ...result, extensions: erc20Extensions };
2204
+ }
2205
+ return result;
2206
+ }
2207
+ return this.createVoucherPayload(
2208
+ x402Version,
2209
+ channelId,
2210
+ maxClaimableAmount,
2211
+ paymentRequirements.network,
2212
+ config
2213
+ );
2214
+ }
2215
+ /**
2216
+ * Sends a cooperative refund request.
2217
+ *
2218
+ * @param url - The route URL backing the channel to refund.
2219
+ * @param options - Optional `amount` (partial refund) and `fetch` override.
2220
+ * @returns The settle response describing the refund outcome.
2221
+ */
2222
+ async refund(url, options) {
2223
+ return refundChannel(this.deps(), url, options);
2224
+ }
2225
+ /**
2226
+ * Updates local channel state from a settle response.
2227
+ *
2228
+ * @param settle - The parsed settle response from the server.
2229
+ * @returns Resolves when local channel state has been updated.
2230
+ */
2231
+ async processSettleResponse(settle) {
2232
+ return processSettleResponse(this.storage, settle);
2233
+ }
2234
+ /**
2235
+ * Resyncs local channel state from a corrective 402 response.
2236
+ *
2237
+ * @param paymentRequired - The decoded 402 response body.
2238
+ * @returns `true` if local state was successfully resynced and a retry is warranted.
2239
+ */
2240
+ async processCorrectivePaymentRequired(paymentRequired) {
2241
+ return processCorrectivePaymentRequired(this.deps(), paymentRequired);
2242
+ }
2243
+ /**
2244
+ * Builds the immutable {@link ChannelConfig} for a given set of payment
2245
+ * requirements, using the scheme's own signer and salt.
2246
+ *
2247
+ * @param paymentRequirements - Server payment requirements for the channel.
2248
+ * @returns The channel config that uniquely identifies the payment channel.
2249
+ */
2250
+ buildChannelConfig(paymentRequirements) {
2251
+ return buildChannelConfig(this.deps(), paymentRequirements);
2252
+ }
2253
+ /**
2254
+ * Resolves the deposit amount after applying the optional custom strategy.
2255
+ *
2256
+ * @param context - Deposit attempt context exposed to the strategy.
2257
+ * @returns The deposit amount to sign, or `false` to skip this deposit attempt.
2258
+ */
2259
+ async resolveDepositAmount(context) {
2260
+ const strategyResult = await this.depositStrategy?.(context);
2261
+ if (strategyResult === false) return false;
2262
+ if (strategyResult === void 0) return context.depositAmount;
2263
+ const depositAmount = this.normalizeStrategyDepositAmount(strategyResult);
2264
+ if (BigInt(depositAmount) < BigInt(context.minimumDepositAmount)) {
2265
+ throw new Error(
2266
+ `depositStrategy returned ${depositAmount}, below required top-up ${context.minimumDepositAmount}`
2267
+ );
2268
+ }
2269
+ return depositAmount;
2270
+ }
2271
+ /**
2272
+ * Normalizes and validates a strategy-provided base-unit deposit amount.
2273
+ *
2274
+ * @param value - Strategy-provided string or bigint amount.
2275
+ * @returns Normalized decimal string.
2276
+ */
2277
+ normalizeStrategyDepositAmount(value) {
2278
+ if (typeof value === "bigint") {
2279
+ if (value <= 0n) {
2280
+ throw new Error("depositStrategy must return a positive integer deposit amount");
2281
+ }
2282
+ return value.toString();
2283
+ }
2284
+ if (/^\d+$/.test(value) && BigInt(value) > 0n) {
2285
+ return BigInt(value).toString();
2286
+ }
2287
+ throw new Error("depositStrategy must return a positive integer deposit amount");
2288
+ }
2289
+ /**
2290
+ * Signs a voucher-only payment payload for the current channel.
2291
+ *
2292
+ * @param x402Version - Protocol version for the payload envelope.
2293
+ * @param channelId - Channel identifier for the voucher.
2294
+ * @param maxClaimableAmount - Cumulative ceiling for the voucher.
2295
+ * @param network - CAIP-2 network identifier.
2296
+ * @param config - Immutable channel configuration.
2297
+ * @returns Voucher-only payment payload.
2298
+ */
2299
+ async createVoucherPayload(x402Version, channelId, maxClaimableAmount, network, config) {
2300
+ const voucherSigner = this.voucherSigner ?? this.signer;
2301
+ const voucher = await signVoucher(voucherSigner, channelId, maxClaimableAmount, network);
2302
+ const payload = {
2303
+ type: "voucher",
2304
+ channelConfig: config,
2305
+ voucher
2306
+ };
2307
+ return {
2308
+ x402Version,
2309
+ payload
2310
+ };
2311
+ }
2312
+ /**
2313
+ * Bundles the class state into the {@link BatchSettlementClientDeps} shape
2314
+ * consumed by the `channel`, `recovery`, and `refund` modules.
2315
+ *
2316
+ * @returns Client deps wrapping the scheme's own signer and storage.
2317
+ */
2318
+ deps() {
2319
+ return {
2320
+ signer: this.signer,
2321
+ storage: this.storage,
2322
+ salt: this.salt,
2323
+ payerAuthorizer: this.payerAuthorizer,
2324
+ voucherSigner: this.voucherSigner
2325
+ };
2326
+ }
2327
+ };
2328
+
2329
+ // src/shared/defaultAssets.ts
2330
+ var DEFAULT_STABLECOINS = {
2331
+ "eip155:8453": {
2332
+ address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
2333
+ name: "USD Coin",
2334
+ version: "2",
2335
+ decimals: 6
2336
+ },
2337
+ // Base mainnet USDC
2338
+ "eip155:84532": {
2339
+ address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
2340
+ name: "USDC",
2341
+ version: "2",
2342
+ decimals: 6
2343
+ },
2344
+ // Base Sepolia USDC
2345
+ "eip155:4326": {
2346
+ address: "0xFAfDdbb3FC7688494971a79cc65DCa3EF82079E7",
2347
+ name: "MegaUSD",
2348
+ version: "1",
2349
+ decimals: 18,
2350
+ assetTransferMethod: "permit2",
2351
+ supportsEip2612: true
2352
+ },
2353
+ // MegaETH mainnet MegaUSD (no EIP-3009, supports EIP-2612)
2354
+ "eip155:143": {
2355
+ address: "0x754704Bc059F8C67012fEd69BC8A327a5aafb603",
2356
+ name: "USD Coin",
2357
+ version: "2",
2358
+ decimals: 6
2359
+ },
2360
+ // Monad mainnet USDC
2361
+ "eip155:988": {
2362
+ address: "0x779Ded0c9e1022225f8E0630b35a9b54bE713736",
2363
+ name: "USDT0",
2364
+ version: "1",
2365
+ decimals: 6
2366
+ },
2367
+ // Stable mainnet USDT0
2368
+ "eip155:2201": {
2369
+ address: "0x78Cf24370174180738C5B8E352B6D14c83a6c9A9",
2370
+ name: "USDT0",
2371
+ version: "1",
2372
+ decimals: 6
2373
+ },
2374
+ // Stable testnet USDT0
2375
+ "eip155:137": {
2376
+ address: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
2377
+ name: "USD Coin",
2378
+ version: "2",
2379
+ decimals: 6
2380
+ },
2381
+ // Polygon mainnet USDC
2382
+ "eip155:42161": {
2383
+ address: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
2384
+ name: "USD Coin",
2385
+ version: "2",
2386
+ decimals: 6
2387
+ },
2388
+ // Arbitrum One USDC
2389
+ "eip155:421614": {
2390
+ address: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d",
2391
+ name: "USD Coin",
2392
+ version: "2",
2393
+ decimals: 6
2394
+ },
2395
+ // Arbitrum Sepolia USDC
2396
+ "eip155:31611": {
2397
+ address: "0x118917a40FAF1CD7a13dB0Ef56C86De7973Ac503",
2398
+ name: "Mezo USD",
2399
+ version: "1",
2400
+ decimals: 18,
2401
+ assetTransferMethod: "permit2",
2402
+ supportsEip2612: true
2403
+ },
2404
+ // Mezo Testnet mUSD (no EIP-3009, supports EIP-2612)
2405
+ "eip155:723487": {
2406
+ address: "0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",
2407
+ name: "Stable Coin",
2408
+ version: "1",
2409
+ decimals: 6,
2410
+ assetTransferMethod: "permit2",
2411
+ supportsEip2612: true
2412
+ },
2413
+ // Radius Network SBC (no EIP-3009, supports EIP-2612)
2414
+ "eip155:72344": {
2415
+ address: "0x33ad9e4BD16B69B5BFdED37D8B5D9fF9aba014Fb",
2416
+ name: "Stable Coin",
2417
+ version: "1",
2418
+ decimals: 6,
2419
+ assetTransferMethod: "permit2",
2420
+ supportsEip2612: true
2421
+ },
2422
+ // Radius Testnet SBC (no EIP-3009, supports EIP-2612)
2423
+ "eip155:36900": {
2424
+ address: "0x9cb8142aEBBcdc60AF7c97Af897A67A8f3CA71C2",
2425
+ name: "USDC.e",
2426
+ version: "2",
2427
+ decimals: 6
2428
+ },
2429
+ // ADI Chain USDC.e (EIP-3009 supported)
2430
+ "eip155:190415": {
2431
+ address: "0x401eCb1D350407f13ba348573E5630B83638E30D",
2432
+ name: "Bridged USDC",
2433
+ version: "2",
2434
+ decimals: 6
2435
+ },
2436
+ // HPP mainnet USDC.e
2437
+ "eip155:181228": {
2438
+ address: "0x401eCb1D350407f13ba348573E5630B83638E30D",
2439
+ name: "Bridged USDC",
2440
+ version: "2",
2441
+ decimals: 6
2442
+ }
2443
+ // HPP Sepolia USDC.e
2444
+ };
2445
+ function getDefaultAsset(network) {
2446
+ const info = DEFAULT_STABLECOINS[network];
2447
+ if (!info) {
2448
+ throw new Error(`No default asset configured for network ${network}`);
2449
+ }
2450
+ return info;
2451
+ }
1120
2452
  // Annotate the CommonJS export names for ESM import in node:
1121
2453
  0 && (module.exports = {
2454
+ BATCH_SETTLEMENT_ADDRESS,
2455
+ BATCH_SETTLEMENT_DOMAIN,
2456
+ BATCH_SETTLEMENT_SCHEME,
2457
+ BatchSettlementEvmScheme,
2458
+ DEFAULT_STABLECOINS,
2459
+ ERC3009_DEPOSIT_COLLECTOR_ADDRESS,
1122
2460
  ExactEvmScheme,
1123
2461
  PERMIT2_ADDRESS,
1124
2462
  UptoEvmScheme,
1125
2463
  authorizationTypes,
2464
+ claimBatchTypes,
1126
2465
  createPermit2ApprovalTx,
1127
2466
  eip3009ABI,
1128
2467
  erc20AllowanceAbi,
2468
+ getDefaultAsset,
1129
2469
  getPermit2AllowanceReadParams,
2470
+ isBatchSettlementClaimPayload,
2471
+ isBatchSettlementDepositPayload,
2472
+ isBatchSettlementEnrichedRefundPayload,
2473
+ isBatchSettlementRefundPayload,
2474
+ isBatchSettlementSettlePayload,
2475
+ isBatchSettlementVoucherPayload,
1130
2476
  isEIP3009Payload,
1131
2477
  isPermit2Payload,
1132
2478
  isUptoPermit2Payload,
1133
2479
  permit2WitnessTypes,
2480
+ refundTypes,
1134
2481
  toClientEvmSigner,
1135
2482
  toFacilitatorEvmSigner,
1136
2483
  uptoPermit2WitnessTypes,
2484
+ voucherTypes,
1137
2485
  x402ExactPermit2ProxyABI,
1138
2486
  x402ExactPermit2ProxyAddress,
1139
2487
  x402UptoPermit2ProxyABI,