@wtflabs/x402 0.0.1-beta.14 → 0.0.1-beta.16

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 (51) hide show
  1. package/dist/cjs/client/index.d.ts +1 -1
  2. package/dist/cjs/client/index.js +1 -1
  3. package/dist/cjs/client/index.js.map +1 -1
  4. package/dist/cjs/facilitator/index.d.ts +1 -1
  5. package/dist/cjs/facilitator/index.js +1169 -1077
  6. package/dist/cjs/facilitator/index.js.map +1 -1
  7. package/dist/cjs/index.d.ts +1 -1
  8. package/dist/cjs/index.js +1636 -1544
  9. package/dist/cjs/index.js.map +1 -1
  10. package/dist/cjs/middleware-qavKyUnr.d.ts +93 -0
  11. package/dist/cjs/paywall/index.d.ts +1 -1
  12. package/dist/cjs/schemes/index.d.ts +1 -1
  13. package/dist/cjs/schemes/index.js +697 -605
  14. package/dist/cjs/schemes/index.js.map +1 -1
  15. package/dist/cjs/shared/index.d.ts +2 -2
  16. package/dist/cjs/types/index.d.ts +335 -4
  17. package/dist/cjs/types/index.js +426 -0
  18. package/dist/cjs/types/index.js.map +1 -1
  19. package/dist/cjs/verify/index.d.ts +2 -2
  20. package/dist/esm/{chunk-VTLJOZXM.mjs → chunk-27VV4F7H.mjs} +3 -3
  21. package/dist/esm/chunk-27VV4F7H.mjs.map +1 -0
  22. package/dist/esm/{chunk-NPWDNT2P.mjs → chunk-5UE5XTGG.mjs} +428 -1
  23. package/dist/esm/chunk-5UE5XTGG.mjs.map +1 -0
  24. package/dist/esm/{chunk-KABV25HJ.mjs → chunk-VHQZ4KRR.mjs} +3 -3
  25. package/dist/esm/{chunk-WCQCFJWV.mjs → chunk-YWZNW3IG.mjs} +74 -409
  26. package/dist/esm/chunk-YWZNW3IG.mjs.map +1 -0
  27. package/dist/esm/{chunk-A6TSFIQP.mjs → chunk-YZUMYCYA.mjs} +3 -3
  28. package/dist/esm/client/index.d.mts +1 -1
  29. package/dist/esm/client/index.mjs +3 -3
  30. package/dist/esm/facilitator/index.d.mts +1 -1
  31. package/dist/esm/facilitator/index.mjs +4 -4
  32. package/dist/esm/index.d.mts +1 -1
  33. package/dist/esm/index.mjs +5 -5
  34. package/dist/esm/{middleware-DSDucaQ5.d.mts → middleware-CFWW-MAF.d.mts} +1 -1
  35. package/dist/esm/paywall/index.d.mts +1 -1
  36. package/dist/esm/schemes/index.d.mts +1 -1
  37. package/dist/esm/schemes/index.mjs +3 -3
  38. package/dist/esm/shared/index.d.mts +2 -2
  39. package/dist/esm/shared/index.mjs +1 -1
  40. package/dist/esm/types/index.d.mts +335 -4
  41. package/dist/esm/types/index.mjs +1 -1
  42. package/dist/esm/verify/index.d.mts +2 -2
  43. package/dist/esm/verify/index.mjs +1 -1
  44. package/dist/esm/x402Specs-B9zS3LnZ.d.mts +1778 -0
  45. package/package.json +1 -1
  46. package/dist/esm/chunk-NPWDNT2P.mjs.map +0 -1
  47. package/dist/esm/chunk-VTLJOZXM.mjs.map +0 -1
  48. package/dist/esm/chunk-WCQCFJWV.mjs.map +0 -1
  49. package/dist/{esm/x402Specs-BtRXj67U.d.mts → cjs/x402Specs-B9zS3LnZ.d.ts} +6 -6
  50. /package/dist/esm/{chunk-KABV25HJ.mjs.map → chunk-VHQZ4KRR.mjs.map} +0 -0
  51. /package/dist/esm/{chunk-A6TSFIQP.mjs.map → chunk-YZUMYCYA.mjs.map} +0 -0
@@ -1190,968 +1190,1135 @@ var usdcABI = [
1190
1190
  }
1191
1191
  ];
1192
1192
 
1193
- // src/types/shared/svm/regex.ts
1194
- var SvmAddressRegex = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
1195
-
1196
- // src/shared/network.ts
1197
- function getNetworkId(network) {
1198
- if (EvmNetworkToChainId.has(network)) {
1199
- return EvmNetworkToChainId.get(network);
1200
- }
1201
- if (SvmNetworkToChainId.has(network)) {
1202
- return SvmNetworkToChainId.get(network);
1203
- }
1204
- throw new Error(`Unsupported network: ${network}`);
1205
- }
1206
-
1207
- // src/types/verify/x402Specs.ts
1208
- var import_zod3 = require("zod");
1209
- var EvmMaxAtomicUnits = 40;
1210
- var EvmAddressRegex = /^0x[0-9a-fA-F]{40}$/;
1211
- var MixedAddressRegex = /^0x[a-fA-F0-9]{40}|[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$/;
1212
- var HexEncoded64ByteRegex = /^0x[0-9a-fA-F]{64}$/;
1213
- var EvmSignatureRegex = /^0x[0-9a-fA-F]+$/;
1214
- var schemes = ["exact"];
1215
- var x402Versions = [1];
1216
- var ErrorReasons = [
1217
- "insufficient_funds",
1218
- "invalid_exact_evm_payload_authorization_valid_after",
1219
- "invalid_exact_evm_payload_authorization_valid_before",
1220
- "invalid_exact_evm_payload_authorization_value",
1221
- "invalid_exact_evm_payload_signature",
1222
- "invalid_exact_evm_payload_recipient_mismatch",
1223
- "invalid_exact_svm_payload_transaction",
1224
- "invalid_exact_svm_payload_transaction_amount_mismatch",
1225
- "invalid_exact_svm_payload_transaction_create_ata_instruction",
1226
- "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee",
1227
- "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset",
1228
- "invalid_exact_svm_payload_transaction_instructions",
1229
- "invalid_exact_svm_payload_transaction_instructions_length",
1230
- "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction",
1231
- "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction",
1232
- "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high",
1233
- "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked",
1234
- "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked",
1235
- "invalid_exact_svm_payload_transaction_not_a_transfer_instruction",
1236
- "invalid_exact_svm_payload_transaction_receiver_ata_not_found",
1237
- "invalid_exact_svm_payload_transaction_sender_ata_not_found",
1238
- "invalid_exact_svm_payload_transaction_simulation_failed",
1239
- "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata",
1240
- "invalid_network",
1241
- "invalid_payload",
1242
- "invalid_payment_requirements",
1243
- "invalid_scheme",
1244
- "invalid_payment",
1245
- "payment_expired",
1246
- "unsupported_scheme",
1247
- "invalid_x402_version",
1248
- "invalid_transaction_state",
1249
- "settle_exact_svm_block_height_exceeded",
1250
- "settle_exact_svm_transaction_confirmation_timed_out",
1251
- "unexpected_settle_error",
1252
- "unexpected_verify_error",
1253
- // New error reasons for Permit and Permit2
1254
- "unsupported_authorization_type",
1255
- "invalid_authorization_type",
1256
- "invalid_permit_signature",
1257
- "invalid_permit2_signature",
1258
- "invalid_permit2_witness_signature",
1259
- "witness_recipient_mismatch",
1260
- "permit_expired",
1261
- "permit2_expired",
1262
- "permit2_not_approved",
1263
- "invalid_token_address",
1264
- "invalid_spender_address",
1265
- "token_mismatch",
1266
- "insufficient_payment_amount",
1267
- "insufficient_token_balance",
1268
- "transaction_failed",
1269
- "settlement_failed"
1270
- ];
1271
- var isInteger = (value) => Number.isInteger(Number(value)) && Number(value) >= 0;
1272
- var hasMaxLength = (maxLength) => (value) => value.length <= maxLength;
1273
- var EvmOrSvmAddress = import_zod3.z.string().regex(EvmAddressRegex).or(import_zod3.z.string().regex(SvmAddressRegex));
1274
- var mixedAddressOrSvmAddress = import_zod3.z.string().regex(MixedAddressRegex).or(import_zod3.z.string().regex(SvmAddressRegex));
1275
- var PaymentRequirementsSchema = import_zod3.z.object({
1276
- scheme: import_zod3.z.enum(schemes),
1277
- network: NetworkSchema,
1278
- maxAmountRequired: import_zod3.z.string().refine(isInteger),
1279
- resource: import_zod3.z.string().url(),
1280
- description: import_zod3.z.string(),
1281
- mimeType: import_zod3.z.string(),
1282
- outputSchema: import_zod3.z.record(import_zod3.z.any()).optional(),
1283
- payTo: EvmOrSvmAddress,
1284
- maxTimeoutSeconds: import_zod3.z.number().int(),
1285
- asset: mixedAddressOrSvmAddress,
1286
- paymentType: import_zod3.z.enum(["eip3009", "permit", "permit2"]).optional(),
1287
- extra: import_zod3.z.record(import_zod3.z.any()).optional()
1288
- });
1289
- var ExactEvmPayloadAuthorizationSchema = import_zod3.z.object({
1290
- from: import_zod3.z.string().regex(EvmAddressRegex),
1291
- to: import_zod3.z.string().regex(EvmAddressRegex),
1292
- value: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1293
- validAfter: import_zod3.z.string().refine(isInteger),
1294
- validBefore: import_zod3.z.string().refine(isInteger),
1295
- nonce: import_zod3.z.string().regex(HexEncoded64ByteRegex)
1296
- });
1297
- var PermitEvmPayloadAuthorizationSchema = import_zod3.z.object({
1298
- owner: import_zod3.z.string().regex(EvmAddressRegex),
1299
- spender: import_zod3.z.string().regex(EvmAddressRegex),
1300
- value: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1301
- deadline: import_zod3.z.string().refine(isInteger),
1302
- nonce: import_zod3.z.string().refine(isInteger)
1303
- });
1304
- var Permit2EvmPayloadAuthorizationSchema = import_zod3.z.object({
1305
- owner: import_zod3.z.string().regex(EvmAddressRegex),
1306
- spender: import_zod3.z.string().regex(EvmAddressRegex),
1307
- token: import_zod3.z.string().regex(EvmAddressRegex),
1308
- amount: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1309
- deadline: import_zod3.z.string().refine(isInteger),
1310
- nonce: import_zod3.z.string().refine(isInteger),
1311
- to: import_zod3.z.string().regex(EvmAddressRegex).optional()
1312
- // Witness: binds recipient address to signature
1313
- });
1314
- var ExactEvmPayloadSchema = import_zod3.z.discriminatedUnion("authorizationType", [
1315
- import_zod3.z.object({
1316
- authorizationType: import_zod3.z.literal("eip3009"),
1317
- signature: import_zod3.z.string().regex(EvmSignatureRegex),
1318
- authorization: ExactEvmPayloadAuthorizationSchema
1319
- }),
1320
- import_zod3.z.object({
1321
- authorizationType: import_zod3.z.literal("permit"),
1322
- signature: import_zod3.z.string().regex(EvmSignatureRegex),
1323
- authorization: PermitEvmPayloadAuthorizationSchema
1324
- }),
1325
- import_zod3.z.object({
1326
- authorizationType: import_zod3.z.literal("permit2"),
1327
- signature: import_zod3.z.string().regex(EvmSignatureRegex),
1328
- authorization: Permit2EvmPayloadAuthorizationSchema
1329
- })
1330
- ]);
1331
- var ExactSvmPayloadSchema = import_zod3.z.object({
1332
- transaction: import_zod3.z.string().regex(Base64EncodedRegex)
1333
- });
1334
- var PaymentPayloadSchema = import_zod3.z.object({
1335
- x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1336
- scheme: import_zod3.z.enum(schemes),
1337
- network: NetworkSchema,
1338
- payload: import_zod3.z.union([ExactEvmPayloadSchema, ExactSvmPayloadSchema])
1339
- });
1340
- var x402ResponseSchema = import_zod3.z.object({
1341
- x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1342
- error: import_zod3.z.enum(ErrorReasons).optional(),
1343
- accepts: import_zod3.z.array(PaymentRequirementsSchema).optional(),
1344
- payer: import_zod3.z.string().regex(MixedAddressRegex).optional()
1345
- });
1346
- var HTTPVerbsSchema = import_zod3.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"]);
1347
- var HTTPRequestStructureSchema = import_zod3.z.object({
1348
- type: import_zod3.z.literal("http"),
1349
- method: HTTPVerbsSchema,
1350
- queryParams: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).optional(),
1351
- bodyType: import_zod3.z.enum(["json", "form-data", "multipart-form-data", "text", "binary"]).optional(),
1352
- bodyFields: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.any()).optional(),
1353
- headerFields: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.any()).optional()
1354
- });
1355
- var RequestStructureSchema = import_zod3.z.discriminatedUnion("type", [
1356
- HTTPRequestStructureSchema
1357
- // MCPRequestStructureSchema,
1358
- // OpenAPIRequestStructureSchema,
1359
- ]);
1360
- var DiscoveredResourceSchema = import_zod3.z.object({
1361
- resource: import_zod3.z.string(),
1362
- type: import_zod3.z.enum(["http"]),
1363
- x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1364
- accepts: import_zod3.z.array(PaymentRequirementsSchema),
1365
- lastUpdated: import_zod3.z.date(),
1366
- metadata: import_zod3.z.record(import_zod3.z.any()).optional()
1367
- });
1368
- var SettleRequestSchema = import_zod3.z.object({
1369
- paymentPayload: PaymentPayloadSchema,
1370
- paymentRequirements: PaymentRequirementsSchema
1371
- });
1372
- var VerifyRequestSchema = import_zod3.z.object({
1373
- paymentPayload: PaymentPayloadSchema,
1374
- paymentRequirements: PaymentRequirementsSchema
1375
- });
1376
- var VerifyResponseSchema = import_zod3.z.object({
1377
- isValid: import_zod3.z.boolean(),
1378
- invalidReason: import_zod3.z.enum(ErrorReasons).optional(),
1379
- payer: EvmOrSvmAddress.optional()
1380
- });
1381
- var SettleResponseSchema = import_zod3.z.object({
1382
- success: import_zod3.z.boolean(),
1383
- errorReason: import_zod3.z.enum(ErrorReasons).optional(),
1384
- payer: EvmOrSvmAddress.optional(),
1385
- transaction: import_zod3.z.string().regex(MixedAddressRegex),
1386
- network: NetworkSchema
1387
- });
1388
- var ListDiscoveryResourcesRequestSchema = import_zod3.z.object({
1389
- type: import_zod3.z.string().optional(),
1390
- limit: import_zod3.z.number().optional(),
1391
- offset: import_zod3.z.number().optional()
1392
- });
1393
- var ListDiscoveryResourcesResponseSchema = import_zod3.z.object({
1394
- x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1395
- items: import_zod3.z.array(DiscoveredResourceSchema),
1396
- pagination: import_zod3.z.object({
1397
- limit: import_zod3.z.number(),
1398
- offset: import_zod3.z.number(),
1399
- total: import_zod3.z.number()
1400
- })
1401
- });
1402
- var SupportedPaymentKindSchema = import_zod3.z.object({
1403
- x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1404
- scheme: import_zod3.z.enum(schemes),
1405
- network: NetworkSchema,
1406
- extra: import_zod3.z.record(import_zod3.z.any()).optional()
1407
- });
1408
- var SupportedPaymentKindsResponseSchema = import_zod3.z.object({
1409
- kinds: import_zod3.z.array(SupportedPaymentKindSchema)
1410
- });
1411
-
1412
- // src/types/verify/facilitator.ts
1413
- var import_zod4 = require("zod");
1414
- var facilitatorRequestSchema = import_zod4.z.object({
1415
- paymentHeader: import_zod4.z.string(),
1416
- paymentRequirements: PaymentRequirementsSchema
1417
- });
1418
-
1419
- // src/shared/evm/usdc.ts
1420
- function getUsdcAddress(client) {
1421
- return config[client.chain.id.toString()].usdcAddress;
1422
- }
1423
- var versionCache = /* @__PURE__ */ new Map();
1424
- async function getVersion(client, tokenAddress) {
1425
- const address = tokenAddress ?? getUsdcAddress(client);
1426
- const cacheKey = `${client.chain.id}-${address.toLowerCase()}`;
1427
- if (versionCache.has(cacheKey)) {
1428
- return versionCache.get(cacheKey);
1429
- }
1430
- let version = "1";
1431
- try {
1432
- const eip712DomainABI = [
1193
+ // src/types/shared/evm/eip7702ABI.ts
1194
+ var EIP7702SellerWalletMinimalAbi = [
1195
+ {
1196
+ inputs: [],
1197
+ name: "InvalidAmount",
1198
+ type: "error"
1199
+ },
1200
+ {
1201
+ inputs: [],
1202
+ name: "NotOwner",
1203
+ type: "error"
1204
+ },
1205
+ {
1206
+ inputs: [],
1207
+ name: "ReentrancyGuardReentrantCall",
1208
+ type: "error"
1209
+ },
1210
+ {
1211
+ inputs: [
1212
+ {
1213
+ internalType: "address",
1214
+ name: "token",
1215
+ type: "address"
1216
+ }
1217
+ ],
1218
+ name: "SafeERC20FailedOperation",
1219
+ type: "error"
1220
+ },
1221
+ {
1222
+ inputs: [],
1223
+ name: "ZeroAddress",
1224
+ type: "error"
1225
+ },
1226
+ {
1227
+ anonymous: false,
1228
+ inputs: [
1229
+ {
1230
+ indexed: true,
1231
+ internalType: "address",
1232
+ name: "beneficiary",
1233
+ type: "address"
1234
+ }
1235
+ ],
1236
+ name: "ConfigUpdated",
1237
+ type: "event"
1238
+ },
1239
+ {
1240
+ anonymous: false,
1241
+ inputs: [
1242
+ {
1243
+ indexed: true,
1244
+ internalType: "address",
1245
+ name: "token",
1246
+ type: "address"
1247
+ },
1248
+ {
1249
+ indexed: true,
1250
+ internalType: "address",
1251
+ name: "payer",
1252
+ type: "address"
1253
+ },
1254
+ {
1255
+ indexed: true,
1256
+ internalType: "address",
1257
+ name: "facilitator",
1258
+ type: "address"
1259
+ },
1260
+ {
1261
+ indexed: false,
1262
+ internalType: "uint256",
1263
+ name: "amount",
1264
+ type: "uint256"
1265
+ },
1266
+ {
1267
+ indexed: false,
1268
+ internalType: "uint256",
1269
+ name: "beneficiaryAmount",
1270
+ type: "uint256"
1271
+ },
1272
+ {
1273
+ indexed: false,
1274
+ internalType: "uint256",
1275
+ name: "feeAmount",
1276
+ type: "uint256"
1277
+ },
1278
+ {
1279
+ indexed: false,
1280
+ internalType: "string",
1281
+ name: "method",
1282
+ type: "string"
1283
+ }
1284
+ ],
1285
+ name: "SettlementExecuted",
1286
+ type: "event"
1287
+ },
1288
+ {
1289
+ stateMutability: "payable",
1290
+ type: "fallback"
1291
+ },
1292
+ {
1293
+ inputs: [],
1294
+ name: "BASIS_POINTS",
1295
+ outputs: [
1296
+ {
1297
+ internalType: "uint96",
1298
+ name: "",
1299
+ type: "uint96"
1300
+ }
1301
+ ],
1302
+ stateMutability: "view",
1303
+ type: "function"
1304
+ },
1305
+ {
1306
+ inputs: [],
1307
+ name: "FEE_BPS",
1308
+ outputs: [
1309
+ {
1310
+ internalType: "uint96",
1311
+ name: "",
1312
+ type: "uint96"
1313
+ }
1314
+ ],
1315
+ stateMutability: "view",
1316
+ type: "function"
1317
+ },
1318
+ {
1319
+ inputs: [],
1320
+ name: "FEE_RECIPIENT",
1321
+ outputs: [
1322
+ {
1323
+ internalType: "address",
1324
+ name: "",
1325
+ type: "address"
1326
+ }
1327
+ ],
1328
+ stateMutability: "view",
1329
+ type: "function"
1330
+ },
1331
+ {
1332
+ inputs: [],
1333
+ name: "getConfig",
1334
+ outputs: [
1335
+ {
1336
+ internalType: "address",
1337
+ name: "beneficiary",
1338
+ type: "address"
1339
+ },
1340
+ {
1341
+ internalType: "bool",
1342
+ name: "initialized",
1343
+ type: "bool"
1344
+ }
1345
+ ],
1346
+ stateMutability: "view",
1347
+ type: "function"
1348
+ },
1349
+ {
1350
+ inputs: [],
1351
+ name: "getEffectiveConfig",
1352
+ outputs: [
1353
+ {
1354
+ internalType: "address",
1355
+ name: "beneficiary",
1356
+ type: "address"
1357
+ },
1358
+ {
1359
+ internalType: "address",
1360
+ name: "feeRecipient",
1361
+ type: "address"
1362
+ },
1363
+ {
1364
+ internalType: "uint96",
1365
+ name: "feeBps",
1366
+ type: "uint96"
1367
+ }
1368
+ ],
1369
+ stateMutability: "view",
1370
+ type: "function"
1371
+ },
1372
+ {
1373
+ inputs: [
1374
+ {
1375
+ internalType: "address",
1376
+ name: "",
1377
+ type: "address"
1378
+ },
1379
+ {
1380
+ internalType: "address",
1381
+ name: "",
1382
+ type: "address"
1383
+ },
1384
+ {
1385
+ internalType: "uint256[]",
1386
+ name: "",
1387
+ type: "uint256[]"
1388
+ },
1389
+ {
1390
+ internalType: "uint256[]",
1391
+ name: "",
1392
+ type: "uint256[]"
1393
+ },
1394
+ {
1395
+ internalType: "bytes",
1396
+ name: "",
1397
+ type: "bytes"
1398
+ }
1399
+ ],
1400
+ name: "onERC1155BatchReceived",
1401
+ outputs: [
1402
+ {
1403
+ internalType: "bytes4",
1404
+ name: "",
1405
+ type: "bytes4"
1406
+ }
1407
+ ],
1408
+ stateMutability: "nonpayable",
1409
+ type: "function"
1410
+ },
1411
+ {
1412
+ inputs: [
1413
+ {
1414
+ internalType: "address",
1415
+ name: "",
1416
+ type: "address"
1417
+ },
1418
+ {
1419
+ internalType: "address",
1420
+ name: "",
1421
+ type: "address"
1422
+ },
1423
+ {
1424
+ internalType: "uint256",
1425
+ name: "",
1426
+ type: "uint256"
1427
+ },
1428
+ {
1429
+ internalType: "uint256",
1430
+ name: "",
1431
+ type: "uint256"
1432
+ },
1433
+ {
1434
+ internalType: "bytes",
1435
+ name: "",
1436
+ type: "bytes"
1437
+ }
1438
+ ],
1439
+ name: "onERC1155Received",
1440
+ outputs: [
1441
+ {
1442
+ internalType: "bytes4",
1443
+ name: "",
1444
+ type: "bytes4"
1445
+ }
1446
+ ],
1447
+ stateMutability: "nonpayable",
1448
+ type: "function"
1449
+ },
1450
+ {
1451
+ inputs: [
1452
+ {
1453
+ internalType: "address",
1454
+ name: "",
1455
+ type: "address"
1456
+ },
1457
+ {
1458
+ internalType: "address",
1459
+ name: "",
1460
+ type: "address"
1461
+ },
1462
+ {
1463
+ internalType: "uint256",
1464
+ name: "",
1465
+ type: "uint256"
1466
+ },
1433
1467
  {
1434
- inputs: [],
1435
- name: "eip712Domain",
1436
- outputs: [
1437
- { name: "fields", type: "bytes1" },
1438
- { name: "name", type: "string" },
1439
- { name: "version", type: "string" },
1440
- { name: "chainId", type: "uint256" },
1441
- { name: "verifyingContract", type: "address" },
1442
- { name: "salt", type: "bytes32" },
1443
- { name: "extensions", type: "uint256[]" }
1444
- ],
1445
- stateMutability: "view",
1446
- type: "function"
1468
+ internalType: "bytes",
1469
+ name: "",
1470
+ type: "bytes"
1447
1471
  }
1448
- ];
1449
- const result = await client.readContract({
1450
- address,
1451
- abi: eip712DomainABI,
1452
- functionName: "eip712Domain"
1453
- });
1454
- version = result[2];
1455
- } catch {
1456
- try {
1457
- const result = await client.readContract({
1458
- address,
1459
- abi: usdcABI,
1460
- functionName: "version"
1461
- });
1462
- version = result;
1463
- } catch {
1464
- console.warn(
1465
- `Neither eip712Domain() nor version() available for token ${address}, using default: ${version}`
1466
- );
1467
- }
1468
- }
1469
- versionCache.set(cacheKey, version);
1470
- return version;
1471
- }
1472
-
1473
- // src/shared/evm/erc20.ts
1474
- async function getERC20Balance(client, erc20Address, address) {
1475
- const balance = await client.readContract({
1476
- address: erc20Address,
1477
- abi: usdcABI,
1478
- functionName: "balanceOf",
1479
- args: [address]
1480
- });
1481
- return balance;
1482
- }
1483
- async function getERC20Allowance(client, erc20Address, owner, spender) {
1484
- const allowance = await client.readContract({
1485
- address: erc20Address,
1486
- abi: usdcABI,
1487
- functionName: "allowance",
1488
- args: [owner, spender]
1489
- });
1490
- return allowance;
1491
- }
1492
-
1493
- // src/shared/svm/transaction.ts
1494
- var import_kit3 = require("@solana/kit");
1495
- var import_token = require("@solana-program/token");
1496
- var import_token_2022 = require("@solana-program/token-2022");
1497
- function decodeTransactionFromPayload(svmPayload) {
1498
- try {
1499
- const base64Encoder = (0, import_kit3.getBase64Encoder)();
1500
- const transactionBytes = base64Encoder.encode(svmPayload.transaction);
1501
- const transactionDecoder = (0, import_kit3.getTransactionDecoder)();
1502
- return transactionDecoder.decode(transactionBytes);
1503
- } catch (error) {
1504
- console.error("error", error);
1505
- throw new Error("invalid_exact_svm_payload_transaction");
1506
- }
1507
- }
1508
- function getTokenPayerFromTransaction(transaction) {
1509
- const compiled = (0, import_kit3.getCompiledTransactionMessageDecoder)().decode(
1510
- transaction.messageBytes
1511
- );
1512
- const staticAccounts = compiled.staticAccounts ?? [];
1513
- const instructions = compiled.instructions ?? [];
1514
- for (const ix of instructions) {
1515
- const programIndex = ix.programAddressIndex;
1516
- const programAddress = staticAccounts[programIndex].toString();
1517
- if (programAddress === import_token.TOKEN_PROGRAM_ADDRESS.toString() || programAddress === import_token_2022.TOKEN_2022_PROGRAM_ADDRESS.toString()) {
1518
- const accountIndices = ix.accountIndices ?? [];
1519
- if (accountIndices.length >= 4) {
1520
- const ownerIndex = accountIndices[3];
1521
- const ownerAddress = staticAccounts[ownerIndex].toString();
1522
- if (ownerAddress) return ownerAddress;
1472
+ ],
1473
+ name: "onERC721Received",
1474
+ outputs: [
1475
+ {
1476
+ internalType: "bytes4",
1477
+ name: "",
1478
+ type: "bytes4"
1523
1479
  }
1524
- }
1525
- }
1526
- return "";
1527
- }
1528
- async function signAndSimulateTransaction(signer, transaction, rpc) {
1529
- const signedTransaction = await (0, import_kit3.partiallySignTransaction)([signer.keyPair], transaction);
1530
- const base64EncodedTransaction = (0, import_kit3.getBase64EncodedWireTransaction)(signedTransaction);
1531
- const simulateTxConfig = {
1532
- sigVerify: true,
1533
- replaceRecentBlockhash: false,
1534
- commitment: "confirmed",
1535
- encoding: "base64",
1536
- accounts: void 0,
1537
- innerInstructions: void 0,
1538
- minContextSlot: void 0
1539
- };
1540
- const simulateResult = await rpc.simulateTransaction(base64EncodedTransaction, simulateTxConfig).send();
1541
- return simulateResult;
1542
- }
1543
-
1544
- // src/schemes/exact/svm/facilitator/settle.ts
1545
- var import_kit5 = require("@solana/kit");
1546
- var import_transaction_confirmation = require("@solana/transaction-confirmation");
1547
-
1548
- // src/schemes/exact/svm/facilitator/verify.ts
1549
- var import_kit4 = require("@solana/kit");
1550
- var import_compute_budget = require("@solana-program/compute-budget");
1551
- var import_token_20222 = require("@solana-program/token-2022");
1552
- var import_token2 = require("@solana-program/token");
1553
- async function verify(signer, payload, paymentRequirements, config2) {
1554
- try {
1555
- verifySchemesAndNetworks(payload, paymentRequirements);
1556
- const svmPayload = payload.payload;
1557
- const decodedTransaction = decodeTransactionFromPayload(svmPayload);
1558
- const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
1559
- await transactionIntrospection(svmPayload, paymentRequirements, config2);
1560
- const simulateResult = await signAndSimulateTransaction(signer, decodedTransaction, rpc);
1561
- if (simulateResult.value?.err) {
1562
- throw new Error(`invalid_exact_svm_payload_transaction_simulation_failed`);
1563
- }
1564
- return {
1565
- isValid: true,
1566
- invalidReason: void 0,
1567
- payer: getTokenPayerFromTransaction(decodedTransaction)
1568
- };
1569
- } catch (error) {
1570
- if (error instanceof Error) {
1571
- if (ErrorReasons.includes(error.message)) {
1572
- return {
1573
- isValid: false,
1574
- invalidReason: error.message,
1575
- payer: (() => {
1576
- try {
1577
- const tx = decodeTransactionFromPayload(payload.payload);
1578
- return getTokenPayerFromTransaction(tx);
1579
- } catch {
1580
- return void 0;
1581
- }
1582
- })()
1583
- };
1480
+ ],
1481
+ stateMutability: "nonpayable",
1482
+ type: "function"
1483
+ },
1484
+ {
1485
+ inputs: [
1486
+ {
1487
+ internalType: "address",
1488
+ name: "token",
1489
+ type: "address"
1490
+ },
1491
+ {
1492
+ internalType: "address",
1493
+ name: "payer",
1494
+ type: "address"
1495
+ },
1496
+ {
1497
+ internalType: "uint256",
1498
+ name: "amount",
1499
+ type: "uint256"
1500
+ },
1501
+ {
1502
+ internalType: "uint256",
1503
+ name: "validAfter",
1504
+ type: "uint256"
1505
+ },
1506
+ {
1507
+ internalType: "uint256",
1508
+ name: "validBefore",
1509
+ type: "uint256"
1510
+ },
1511
+ {
1512
+ internalType: "bytes32",
1513
+ name: "nonce",
1514
+ type: "bytes32"
1515
+ },
1516
+ {
1517
+ internalType: "uint8",
1518
+ name: "v",
1519
+ type: "uint8"
1520
+ },
1521
+ {
1522
+ internalType: "bytes32",
1523
+ name: "r",
1524
+ type: "bytes32"
1525
+ },
1526
+ {
1527
+ internalType: "bytes32",
1528
+ name: "s",
1529
+ type: "bytes32"
1584
1530
  }
1585
- }
1586
- console.error(error);
1587
- return {
1588
- isValid: false,
1589
- invalidReason: "unexpected_verify_error",
1590
- payer: (() => {
1591
- try {
1592
- const tx = decodeTransactionFromPayload(payload.payload);
1593
- return getTokenPayerFromTransaction(tx);
1594
- } catch {
1595
- return void 0;
1596
- }
1597
- })()
1598
- };
1599
- }
1600
- }
1601
- function verifySchemesAndNetworks(payload, paymentRequirements) {
1602
- if (payload.scheme !== SCHEME || paymentRequirements.scheme !== SCHEME) {
1603
- throw new Error("unsupported_scheme");
1604
- }
1605
- if (payload.network !== paymentRequirements.network || !SupportedSVMNetworks.includes(paymentRequirements.network)) {
1606
- throw new Error("invalid_network");
1607
- }
1608
- }
1609
- async function transactionIntrospection(svmPayload, paymentRequirements, config2) {
1610
- const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
1611
- const decodedTransaction = decodeTransactionFromPayload(svmPayload);
1612
- const compiledTransactionMessage = (0, import_kit4.getCompiledTransactionMessageDecoder)().decode(
1613
- decodedTransaction.messageBytes
1614
- );
1615
- const transactionMessage = (0, import_kit4.decompileTransactionMessage)(
1616
- compiledTransactionMessage
1617
- );
1618
- await verifyTransactionInstructions(transactionMessage, paymentRequirements, rpc);
1619
- }
1620
- async function verifyTransactionInstructions(transactionMessage, paymentRequirements, rpc) {
1621
- if (transactionMessage.instructions.length !== 3 && transactionMessage.instructions.length !== 4) {
1622
- throw new Error(`invalid_exact_svm_payload_transaction_instructions_length`);
1623
- }
1624
- verifyComputeLimitInstruction(transactionMessage.instructions[0]);
1625
- verifyComputePriceInstruction(transactionMessage.instructions[1]);
1626
- if (transactionMessage.instructions.length === 3) {
1627
- await verifyTransferInstruction(
1628
- transactionMessage.instructions[2],
1629
- paymentRequirements,
1531
+ ],
1532
+ name: "settleWithERC3009",
1533
+ outputs: [],
1534
+ stateMutability: "nonpayable",
1535
+ type: "function"
1536
+ },
1537
+ {
1538
+ inputs: [
1539
+ {
1540
+ internalType: "address",
1541
+ name: "token",
1542
+ type: "address"
1543
+ },
1630
1544
  {
1631
- txHasCreateDestATAInstruction: false
1545
+ internalType: "address",
1546
+ name: "payer",
1547
+ type: "address"
1632
1548
  },
1633
- rpc
1634
- );
1635
- } else {
1636
- verifyCreateATAInstruction(transactionMessage.instructions[2], paymentRequirements);
1637
- await verifyTransferInstruction(
1638
- transactionMessage.instructions[3],
1639
- paymentRequirements,
1640
1549
  {
1641
- txHasCreateDestATAInstruction: true
1550
+ internalType: "uint256",
1551
+ name: "amount",
1552
+ type: "uint256"
1642
1553
  },
1643
- rpc
1644
- );
1645
- }
1646
- }
1647
- function verifyComputeLimitInstruction(instruction) {
1648
- try {
1649
- if (instruction.programAddress.toString() !== import_compute_budget.COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() || instruction.data?.[0] !== 2) {
1650
- throw new Error(
1651
- `invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction`
1652
- );
1653
- }
1654
- (0, import_compute_budget.parseSetComputeUnitLimitInstruction)(
1655
- instruction
1656
- );
1657
- } catch (error) {
1658
- console.error(error);
1659
- throw new Error(`invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction`);
1660
- }
1661
- }
1662
- function verifyComputePriceInstruction(instruction) {
1663
- if (instruction.programAddress.toString() !== import_compute_budget.COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() || instruction.data?.[0] !== 3) {
1664
- throw new Error(`invalid_exact_svm_payload_transaction_instructions_compute_price_instruction`);
1665
- }
1666
- const parsedInstruction = (0, import_compute_budget.parseSetComputeUnitPriceInstruction)(
1667
- instruction
1668
- );
1669
- if (parsedInstruction.data.microLamports > 5 * 1e6) {
1670
- throw new Error(
1671
- `invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high`
1672
- );
1673
- }
1674
- }
1675
- function verifyCreateATAInstruction(instruction, paymentRequirements) {
1676
- let createATAInstruction;
1677
- try {
1678
- (0, import_kit4.assertIsInstructionWithAccounts)(instruction);
1679
- (0, import_kit4.assertIsInstructionWithData)(instruction);
1680
- createATAInstruction = (0, import_token_20222.parseCreateAssociatedTokenInstruction)({
1681
- ...instruction,
1682
- data: new Uint8Array(instruction.data)
1683
- });
1684
- } catch (error) {
1685
- console.error(error);
1686
- throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction`);
1687
- }
1688
- if (createATAInstruction.accounts.owner.address !== paymentRequirements.payTo) {
1689
- throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee`);
1690
- }
1691
- if (createATAInstruction.accounts.mint.address !== paymentRequirements.asset) {
1692
- throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset`);
1693
- }
1694
- }
1695
- async function verifyTransferInstruction(instruction, paymentRequirements, { txHasCreateDestATAInstruction }, rpc) {
1696
- const tokenInstruction = getValidatedTransferCheckedInstruction(instruction);
1697
- await verifyTransferCheckedInstruction(
1698
- tokenInstruction,
1699
- paymentRequirements,
1700
- {
1701
- txHasCreateDestATAInstruction
1702
- },
1703
- rpc
1704
- );
1705
- }
1706
- async function verifyTransferCheckedInstruction(parsedInstruction, paymentRequirements, { txHasCreateDestATAInstruction }, rpc) {
1707
- const tokenProgramAddress = parsedInstruction.programAddress.toString() === import_token2.TOKEN_PROGRAM_ADDRESS.toString() ? import_token2.TOKEN_PROGRAM_ADDRESS : import_token_20222.TOKEN_2022_PROGRAM_ADDRESS;
1708
- const payToATA = await (0, import_token_20222.findAssociatedTokenPda)({
1709
- mint: paymentRequirements.asset,
1710
- owner: paymentRequirements.payTo,
1711
- tokenProgram: tokenProgramAddress
1712
- });
1713
- if (parsedInstruction.accounts.destination.address !== payToATA[0]) {
1714
- throw new Error(`invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata`);
1715
- }
1716
- const addresses = [parsedInstruction.accounts.source.address, payToATA[0]];
1717
- const maybeAccounts = await (0, import_kit4.fetchEncodedAccounts)(rpc, addresses);
1718
- const missingAccounts = maybeAccounts.filter((a) => !a.exists);
1719
- for (const missingAccount of missingAccounts) {
1720
- if (missingAccount.address === parsedInstruction.accounts.source.address) {
1721
- throw new Error(`invalid_exact_svm_payload_transaction_sender_ata_not_found`);
1722
- }
1723
- if (missingAccount.address === payToATA[0] && !txHasCreateDestATAInstruction) {
1724
- throw new Error(`invalid_exact_svm_payload_transaction_receiver_ata_not_found`);
1725
- }
1726
- }
1727
- const instructionAmount = parsedInstruction.data.amount;
1728
- const paymentRequirementsAmount = BigInt(paymentRequirements.maxAmountRequired);
1729
- if (instructionAmount !== paymentRequirementsAmount) {
1730
- throw new Error(`invalid_exact_svm_payload_transaction_amount_mismatch`);
1554
+ {
1555
+ internalType: "uint256",
1556
+ name: "deadline",
1557
+ type: "uint256"
1558
+ },
1559
+ {
1560
+ internalType: "uint8",
1561
+ name: "v",
1562
+ type: "uint8"
1563
+ },
1564
+ {
1565
+ internalType: "bytes32",
1566
+ name: "r",
1567
+ type: "bytes32"
1568
+ },
1569
+ {
1570
+ internalType: "bytes32",
1571
+ name: "s",
1572
+ type: "bytes32"
1573
+ }
1574
+ ],
1575
+ name: "settleWithPermit",
1576
+ outputs: [],
1577
+ stateMutability: "nonpayable",
1578
+ type: "function"
1579
+ },
1580
+ {
1581
+ inputs: [
1582
+ {
1583
+ internalType: "bytes4",
1584
+ name: "interfaceId",
1585
+ type: "bytes4"
1586
+ }
1587
+ ],
1588
+ name: "supportsInterface",
1589
+ outputs: [
1590
+ {
1591
+ internalType: "bool",
1592
+ name: "",
1593
+ type: "bool"
1594
+ }
1595
+ ],
1596
+ stateMutability: "view",
1597
+ type: "function"
1598
+ },
1599
+ {
1600
+ inputs: [
1601
+ {
1602
+ internalType: "address",
1603
+ name: "beneficiary_",
1604
+ type: "address"
1605
+ }
1606
+ ],
1607
+ name: "updateConfig",
1608
+ outputs: [],
1609
+ stateMutability: "nonpayable",
1610
+ type: "function"
1611
+ },
1612
+ {
1613
+ stateMutability: "payable",
1614
+ type: "receive"
1731
1615
  }
1732
- }
1733
- function getValidatedTransferCheckedInstruction(instruction) {
1734
- try {
1735
- (0, import_kit4.assertIsInstructionWithData)(instruction);
1736
- (0, import_kit4.assertIsInstructionWithAccounts)(instruction);
1737
- } catch (error) {
1738
- console.error(error);
1739
- throw new Error(`invalid_exact_svm_payload_transaction_instructions`);
1616
+ ];
1617
+
1618
+ // src/types/shared/svm/regex.ts
1619
+ var SvmAddressRegex = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
1620
+
1621
+ // src/shared/network.ts
1622
+ function getNetworkId(network) {
1623
+ if (EvmNetworkToChainId.has(network)) {
1624
+ return EvmNetworkToChainId.get(network);
1740
1625
  }
1741
- let tokenInstruction;
1742
- if (instruction.programAddress.toString() === import_token2.TOKEN_PROGRAM_ADDRESS.toString()) {
1743
- const identifiedInstruction = (0, import_token2.identifyTokenInstruction)(instruction);
1744
- if (identifiedInstruction !== import_token2.TokenInstruction.TransferChecked) {
1745
- throw new Error(
1746
- `invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked`
1747
- );
1748
- }
1749
- tokenInstruction = (0, import_token2.parseTransferCheckedInstruction)({
1750
- ...instruction,
1751
- data: new Uint8Array(instruction.data)
1752
- });
1753
- } else if (instruction.programAddress.toString() === import_token_20222.TOKEN_2022_PROGRAM_ADDRESS.toString()) {
1754
- const identifiedInstruction = (0, import_token_20222.identifyToken2022Instruction)(instruction);
1755
- if (identifiedInstruction !== import_token_20222.Token2022Instruction.TransferChecked) {
1756
- throw new Error(
1757
- `invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked`
1758
- );
1759
- }
1760
- tokenInstruction = (0, import_token_20222.parseTransferCheckedInstruction)({
1761
- ...instruction,
1762
- data: new Uint8Array(instruction.data)
1763
- });
1764
- } else {
1765
- throw new Error(`invalid_exact_svm_payload_transaction_not_a_transfer_instruction`);
1626
+ if (SvmNetworkToChainId.has(network)) {
1627
+ return SvmNetworkToChainId.get(network);
1766
1628
  }
1767
- return tokenInstruction;
1629
+ throw new Error(`Unsupported network: ${network}`);
1768
1630
  }
1769
1631
 
1770
- // src/schemes/exact/svm/facilitator/settle.ts
1771
- async function settle(signer, payload, paymentRequirements, config2) {
1772
- const verifyResponse = await verify(signer, payload, paymentRequirements, config2);
1773
- if (!verifyResponse.isValid) {
1774
- return {
1775
- success: false,
1776
- errorReason: verifyResponse.invalidReason,
1777
- network: payload.network,
1778
- transaction: ""
1779
- };
1780
- }
1781
- const svmPayload = payload.payload;
1782
- const decodedTransaction = decodeTransactionFromPayload(svmPayload);
1783
- const signedTransaction = await (0, import_kit5.signTransaction)([signer.keyPair], decodedTransaction);
1784
- const payer = getTokenPayerFromTransaction(decodedTransaction);
1785
- const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
1786
- const rpcSubscriptions = getRpcSubscriptions(
1787
- paymentRequirements.network,
1788
- config2?.svmConfig?.rpcUrl
1789
- );
1790
- try {
1791
- const { success, errorReason, signature } = await sendAndConfirmSignedTransaction(
1792
- signedTransaction,
1793
- rpc,
1794
- rpcSubscriptions
1795
- );
1796
- return {
1797
- success,
1798
- errorReason,
1799
- payer,
1800
- transaction: signature,
1801
- network: payload.network
1802
- };
1803
- } catch (error) {
1804
- console.error("Unexpected error during transaction settlement:", error);
1805
- return {
1806
- success: false,
1807
- errorReason: "unexpected_settle_error",
1808
- network: payload.network,
1809
- transaction: (0, import_kit5.getSignatureFromTransaction)(signedTransaction),
1810
- payer
1811
- };
1812
- }
1813
- }
1814
- async function sendSignedTransaction(signedTransaction, rpc, sendTxConfig = {
1815
- skipPreflight: true,
1816
- encoding: "base64"
1817
- }) {
1818
- const base64EncodedTransaction = (0, import_kit5.getBase64EncodedWireTransaction)(signedTransaction);
1819
- return await rpc.sendTransaction(base64EncodedTransaction, sendTxConfig).send();
1632
+ // src/types/verify/x402Specs.ts
1633
+ var import_zod3 = require("zod");
1634
+ var EvmMaxAtomicUnits = 40;
1635
+ var EvmAddressRegex = /^0x[0-9a-fA-F]{40}$/;
1636
+ var MixedAddressRegex = /^0x[a-fA-F0-9]{40}|[A-Za-z0-9][A-Za-z0-9-]{0,34}[A-Za-z0-9]$/;
1637
+ var HexEncoded64ByteRegex = /^0x[0-9a-fA-F]{64}$/;
1638
+ var EvmSignatureRegex = /^0x[0-9a-fA-F]+$/;
1639
+ var schemes = ["exact"];
1640
+ var x402Versions = [1];
1641
+ var ErrorReasons = [
1642
+ "insufficient_funds",
1643
+ "invalid_exact_evm_payload_authorization_valid_after",
1644
+ "invalid_exact_evm_payload_authorization_valid_before",
1645
+ "invalid_exact_evm_payload_authorization_value",
1646
+ "invalid_exact_evm_payload_signature",
1647
+ "invalid_exact_evm_payload_recipient_mismatch",
1648
+ "invalid_exact_svm_payload_transaction",
1649
+ "invalid_exact_svm_payload_transaction_amount_mismatch",
1650
+ "invalid_exact_svm_payload_transaction_create_ata_instruction",
1651
+ "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee",
1652
+ "invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset",
1653
+ "invalid_exact_svm_payload_transaction_instructions",
1654
+ "invalid_exact_svm_payload_transaction_instructions_length",
1655
+ "invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction",
1656
+ "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction",
1657
+ "invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high",
1658
+ "invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked",
1659
+ "invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked",
1660
+ "invalid_exact_svm_payload_transaction_not_a_transfer_instruction",
1661
+ "invalid_exact_svm_payload_transaction_receiver_ata_not_found",
1662
+ "invalid_exact_svm_payload_transaction_sender_ata_not_found",
1663
+ "invalid_exact_svm_payload_transaction_simulation_failed",
1664
+ "invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata",
1665
+ "invalid_network",
1666
+ "invalid_payload",
1667
+ "invalid_payment_requirements",
1668
+ "invalid_scheme",
1669
+ "invalid_payment",
1670
+ "payment_expired",
1671
+ "unsupported_scheme",
1672
+ "invalid_x402_version",
1673
+ "invalid_transaction_state",
1674
+ "settle_exact_svm_block_height_exceeded",
1675
+ "settle_exact_svm_transaction_confirmation_timed_out",
1676
+ "unexpected_settle_error",
1677
+ "unexpected_verify_error",
1678
+ // New error reasons for Permit and Permit2
1679
+ "unsupported_authorization_type",
1680
+ "invalid_authorization_type",
1681
+ "invalid_permit_signature",
1682
+ "invalid_permit2_signature",
1683
+ "invalid_permit2_witness_signature",
1684
+ "witness_recipient_mismatch",
1685
+ "permit_expired",
1686
+ "permit2_expired",
1687
+ "permit2_not_approved",
1688
+ "invalid_token_address",
1689
+ "invalid_spender_address",
1690
+ "token_mismatch",
1691
+ "insufficient_payment_amount",
1692
+ "insufficient_token_balance",
1693
+ "transaction_failed",
1694
+ "settlement_failed"
1695
+ ];
1696
+ var isInteger = (value) => Number.isInteger(Number(value)) && Number(value) >= 0;
1697
+ var hasMaxLength = (maxLength) => (value) => value.length <= maxLength;
1698
+ var EvmOrSvmAddress = import_zod3.z.string().regex(EvmAddressRegex).or(import_zod3.z.string().regex(SvmAddressRegex));
1699
+ var mixedAddressOrSvmAddress = import_zod3.z.string().regex(MixedAddressRegex).or(import_zod3.z.string().regex(SvmAddressRegex));
1700
+ var PaymentRequirementsSchema = import_zod3.z.object({
1701
+ scheme: import_zod3.z.enum(schemes),
1702
+ network: NetworkSchema,
1703
+ maxAmountRequired: import_zod3.z.string().refine(isInteger),
1704
+ resource: import_zod3.z.string().url(),
1705
+ description: import_zod3.z.string(),
1706
+ mimeType: import_zod3.z.string(),
1707
+ outputSchema: import_zod3.z.record(import_zod3.z.any()).optional(),
1708
+ payTo: EvmOrSvmAddress,
1709
+ maxTimeoutSeconds: import_zod3.z.number().int(),
1710
+ asset: mixedAddressOrSvmAddress,
1711
+ paymentType: import_zod3.z.enum(["eip3009", "permit", "permit2"]).optional(),
1712
+ extra: import_zod3.z.record(import_zod3.z.any()).optional()
1713
+ });
1714
+ var ExactEvmPayloadAuthorizationSchema = import_zod3.z.object({
1715
+ from: import_zod3.z.string().regex(EvmAddressRegex),
1716
+ to: import_zod3.z.string().regex(EvmAddressRegex),
1717
+ value: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1718
+ validAfter: import_zod3.z.string().refine(isInteger),
1719
+ validBefore: import_zod3.z.string().refine(isInteger),
1720
+ nonce: import_zod3.z.string().regex(HexEncoded64ByteRegex)
1721
+ });
1722
+ var PermitEvmPayloadAuthorizationSchema = import_zod3.z.object({
1723
+ owner: import_zod3.z.string().regex(EvmAddressRegex),
1724
+ spender: import_zod3.z.string().regex(EvmAddressRegex),
1725
+ value: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1726
+ deadline: import_zod3.z.string().refine(isInteger),
1727
+ nonce: import_zod3.z.string().refine(isInteger)
1728
+ });
1729
+ var Permit2EvmPayloadAuthorizationSchema = import_zod3.z.object({
1730
+ owner: import_zod3.z.string().regex(EvmAddressRegex),
1731
+ spender: import_zod3.z.string().regex(EvmAddressRegex),
1732
+ token: import_zod3.z.string().regex(EvmAddressRegex),
1733
+ amount: import_zod3.z.string().refine(isInteger).refine(hasMaxLength(EvmMaxAtomicUnits)),
1734
+ deadline: import_zod3.z.string().refine(isInteger),
1735
+ nonce: import_zod3.z.string().refine(isInteger),
1736
+ to: import_zod3.z.string().regex(EvmAddressRegex).optional()
1737
+ // Witness: binds recipient address to signature
1738
+ });
1739
+ var ExactEvmPayloadSchema = import_zod3.z.discriminatedUnion("authorizationType", [
1740
+ import_zod3.z.object({
1741
+ authorizationType: import_zod3.z.literal("eip3009"),
1742
+ signature: import_zod3.z.string().regex(EvmSignatureRegex),
1743
+ authorization: ExactEvmPayloadAuthorizationSchema
1744
+ }),
1745
+ import_zod3.z.object({
1746
+ authorizationType: import_zod3.z.literal("permit"),
1747
+ signature: import_zod3.z.string().regex(EvmSignatureRegex),
1748
+ authorization: PermitEvmPayloadAuthorizationSchema
1749
+ }),
1750
+ import_zod3.z.object({
1751
+ authorizationType: import_zod3.z.literal("permit2"),
1752
+ signature: import_zod3.z.string().regex(EvmSignatureRegex),
1753
+ authorization: Permit2EvmPayloadAuthorizationSchema
1754
+ })
1755
+ ]);
1756
+ var ExactSvmPayloadSchema = import_zod3.z.object({
1757
+ transaction: import_zod3.z.string().regex(Base64EncodedRegex)
1758
+ });
1759
+ var PaymentPayloadSchema = import_zod3.z.object({
1760
+ x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1761
+ scheme: import_zod3.z.enum(schemes),
1762
+ network: NetworkSchema,
1763
+ payload: import_zod3.z.union([ExactEvmPayloadSchema, ExactSvmPayloadSchema])
1764
+ });
1765
+ var x402ResponseSchema = import_zod3.z.object({
1766
+ x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1767
+ error: import_zod3.z.enum(ErrorReasons).optional(),
1768
+ accepts: import_zod3.z.array(PaymentRequirementsSchema).optional(),
1769
+ payer: import_zod3.z.string().regex(MixedAddressRegex).optional()
1770
+ });
1771
+ var HTTPVerbsSchema = import_zod3.z.enum(["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"]);
1772
+ var HTTPRequestStructureSchema = import_zod3.z.object({
1773
+ type: import_zod3.z.literal("http"),
1774
+ method: HTTPVerbsSchema,
1775
+ queryParams: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.string()).optional(),
1776
+ bodyType: import_zod3.z.enum(["json", "form-data", "multipart-form-data", "text", "binary"]).optional(),
1777
+ bodyFields: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.any()).optional(),
1778
+ headerFields: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.any()).optional()
1779
+ });
1780
+ var RequestStructureSchema = import_zod3.z.discriminatedUnion("type", [
1781
+ HTTPRequestStructureSchema
1782
+ // MCPRequestStructureSchema,
1783
+ // OpenAPIRequestStructureSchema,
1784
+ ]);
1785
+ var DiscoveredResourceSchema = import_zod3.z.object({
1786
+ resource: import_zod3.z.string(),
1787
+ type: import_zod3.z.enum(["http"]),
1788
+ x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1789
+ accepts: import_zod3.z.array(PaymentRequirementsSchema),
1790
+ lastUpdated: import_zod3.z.date(),
1791
+ metadata: import_zod3.z.record(import_zod3.z.any()).optional()
1792
+ });
1793
+ var SettleRequestSchema = import_zod3.z.object({
1794
+ paymentPayload: PaymentPayloadSchema,
1795
+ paymentRequirements: PaymentRequirementsSchema
1796
+ });
1797
+ var VerifyRequestSchema = import_zod3.z.object({
1798
+ paymentPayload: PaymentPayloadSchema,
1799
+ paymentRequirements: PaymentRequirementsSchema
1800
+ });
1801
+ var VerifyResponseSchema = import_zod3.z.object({
1802
+ isValid: import_zod3.z.boolean(),
1803
+ invalidReason: import_zod3.z.enum(ErrorReasons).optional(),
1804
+ payer: EvmOrSvmAddress.optional()
1805
+ });
1806
+ var SettleResponseSchema = import_zod3.z.object({
1807
+ success: import_zod3.z.boolean(),
1808
+ errorReason: import_zod3.z.enum(ErrorReasons).optional(),
1809
+ payer: EvmOrSvmAddress.optional(),
1810
+ transaction: import_zod3.z.string().regex(MixedAddressRegex),
1811
+ network: NetworkSchema
1812
+ });
1813
+ var ListDiscoveryResourcesRequestSchema = import_zod3.z.object({
1814
+ type: import_zod3.z.string().optional(),
1815
+ limit: import_zod3.z.number().optional(),
1816
+ offset: import_zod3.z.number().optional()
1817
+ });
1818
+ var ListDiscoveryResourcesResponseSchema = import_zod3.z.object({
1819
+ x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1820
+ items: import_zod3.z.array(DiscoveredResourceSchema),
1821
+ pagination: import_zod3.z.object({
1822
+ limit: import_zod3.z.number(),
1823
+ offset: import_zod3.z.number(),
1824
+ total: import_zod3.z.number()
1825
+ })
1826
+ });
1827
+ var SupportedPaymentKindSchema = import_zod3.z.object({
1828
+ x402Version: import_zod3.z.number().refine((val) => x402Versions.includes(val)),
1829
+ scheme: import_zod3.z.enum(schemes),
1830
+ network: NetworkSchema,
1831
+ extra: import_zod3.z.record(import_zod3.z.any()).optional()
1832
+ });
1833
+ var SupportedPaymentKindsResponseSchema = import_zod3.z.object({
1834
+ kinds: import_zod3.z.array(SupportedPaymentKindSchema)
1835
+ });
1836
+
1837
+ // src/types/verify/facilitator.ts
1838
+ var import_zod4 = require("zod");
1839
+ var facilitatorRequestSchema = import_zod4.z.object({
1840
+ paymentHeader: import_zod4.z.string(),
1841
+ paymentRequirements: PaymentRequirementsSchema
1842
+ });
1843
+
1844
+ // src/shared/evm/usdc.ts
1845
+ function getUsdcAddress(client) {
1846
+ return config[client.chain.id.toString()].usdcAddress;
1820
1847
  }
1821
- async function confirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions) {
1822
- const signature = (0, import_kit5.getSignatureFromTransaction)(signedTransaction);
1823
- const abortController = new AbortController();
1824
- const timeout = setTimeout(() => {
1825
- abortController.abort("Transaction confirmation timed out after 60 seconds");
1826
- }, 6e4);
1848
+ var versionCache = /* @__PURE__ */ new Map();
1849
+ async function getVersion(client, tokenAddress) {
1850
+ const address = tokenAddress ?? getUsdcAddress(client);
1851
+ const cacheKey = `${client.chain.id}-${address.toLowerCase()}`;
1852
+ if (versionCache.has(cacheKey)) {
1853
+ return versionCache.get(cacheKey);
1854
+ }
1855
+ let version = "1";
1827
1856
  try {
1828
- const compiledTransactionMessage = (0, import_kit5.getCompiledTransactionMessageDecoder)().decode(
1829
- signedTransaction.messageBytes
1830
- );
1831
- const decompiledTransactionMessage = await (0, import_kit5.decompileTransactionMessageFetchingLookupTables)(
1832
- compiledTransactionMessage,
1833
- rpc
1834
- );
1835
- (0, import_kit5.assertIsTransactionMessageWithBlockhashLifetime)(decompiledTransactionMessage);
1836
- const signedTransactionWithBlockhashLifetime = {
1837
- ...signedTransaction,
1838
- lifetimeConstraint: decompiledTransactionMessage.lifetimeConstraint
1839
- };
1840
- const commitment = "confirmed";
1841
- const getRecentSignatureConfirmationPromise = (0, import_transaction_confirmation.createRecentSignatureConfirmationPromiseFactory)({
1842
- rpc,
1843
- rpcSubscriptions
1844
- });
1845
- const getBlockHeightExceedencePromise = (0, import_transaction_confirmation.createBlockHeightExceedencePromiseFactory)({
1846
- rpc,
1847
- rpcSubscriptions
1848
- });
1849
- const config2 = {
1850
- abortSignal: abortController.signal,
1851
- commitment,
1852
- getBlockHeightExceedencePromise,
1853
- getRecentSignatureConfirmationPromise
1854
- };
1855
- await (0, import_transaction_confirmation.waitForRecentTransactionConfirmation)({
1856
- ...config2,
1857
- transaction: signedTransactionWithBlockhashLifetime
1857
+ const eip712DomainABI = [
1858
+ {
1859
+ inputs: [],
1860
+ name: "eip712Domain",
1861
+ outputs: [
1862
+ { name: "fields", type: "bytes1" },
1863
+ { name: "name", type: "string" },
1864
+ { name: "version", type: "string" },
1865
+ { name: "chainId", type: "uint256" },
1866
+ { name: "verifyingContract", type: "address" },
1867
+ { name: "salt", type: "bytes32" },
1868
+ { name: "extensions", type: "uint256[]" }
1869
+ ],
1870
+ stateMutability: "view",
1871
+ type: "function"
1872
+ }
1873
+ ];
1874
+ const result = await client.readContract({
1875
+ address,
1876
+ abi: eip712DomainABI,
1877
+ functionName: "eip712Domain"
1858
1878
  });
1859
- return {
1860
- success: true,
1861
- signature
1862
- };
1863
- } catch (error) {
1864
- console.error(error);
1865
- if ((0, import_kit5.isSolanaError)(error, import_kit5.SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {
1866
- return {
1867
- success: false,
1868
- errorReason: "settle_exact_svm_block_height_exceeded",
1869
- signature
1870
- };
1871
- } else if (error instanceof DOMException && error.name === "AbortError") {
1872
- return {
1873
- success: false,
1874
- errorReason: "settle_exact_svm_transaction_confirmation_timed_out",
1875
- signature
1876
- };
1877
- } else {
1878
- throw error;
1879
+ version = result[2];
1880
+ } catch {
1881
+ try {
1882
+ const result = await client.readContract({
1883
+ address,
1884
+ abi: usdcABI,
1885
+ functionName: "version"
1886
+ });
1887
+ version = result;
1888
+ } catch {
1889
+ console.warn(
1890
+ `Neither eip712Domain() nor version() available for token ${address}, using default: ${version}`
1891
+ );
1879
1892
  }
1880
- } finally {
1881
- clearTimeout(timeout);
1882
1893
  }
1894
+ versionCache.set(cacheKey, version);
1895
+ return version;
1883
1896
  }
1884
- async function sendAndConfirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions) {
1885
- await sendSignedTransaction(signedTransaction, rpc);
1886
- return await confirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions);
1887
- }
1888
-
1889
- // src/schemes/exact/svm/client.ts
1890
- var import_kit6 = require("@solana/kit");
1891
- var import_token_20223 = require("@solana-program/token-2022");
1892
- var import_token3 = require("@solana-program/token");
1893
- var import_compute_budget2 = require("@solana-program/compute-budget");
1894
1897
 
1895
- // src/schemes/exact/index.ts
1896
- var SCHEME = "exact";
1898
+ // src/shared/evm/erc20.ts
1899
+ async function getERC20Balance(client, erc20Address, address) {
1900
+ const balance = await client.readContract({
1901
+ address: erc20Address,
1902
+ abi: usdcABI,
1903
+ functionName: "balanceOf",
1904
+ args: [address]
1905
+ });
1906
+ return balance;
1907
+ }
1908
+ async function getERC20Allowance(client, erc20Address, owner, spender) {
1909
+ const allowance = await client.readContract({
1910
+ address: erc20Address,
1911
+ abi: usdcABI,
1912
+ functionName: "allowance",
1913
+ args: [owner, spender]
1914
+ });
1915
+ return allowance;
1916
+ }
1897
1917
 
1898
- // src/types/shared/evm/permitProxyABI.ts
1899
- var permitProxyContractABI = [
1900
- // settleWithPermit - 使用 EIP-2612 Permit 进行结算
1901
- {
1902
- inputs: [
1903
- {
1904
- internalType: "address",
1905
- name: "token",
1906
- type: "address"
1907
- },
1908
- {
1909
- internalType: "address",
1910
- name: "payer",
1911
- type: "address"
1912
- },
1913
- {
1914
- internalType: "address",
1915
- name: "seller",
1916
- type: "address"
1917
- },
1918
- {
1919
- internalType: "uint256",
1920
- name: "amount",
1921
- type: "uint256"
1922
- },
1923
- {
1924
- internalType: "uint256",
1925
- name: "deadline",
1926
- type: "uint256"
1927
- },
1928
- {
1929
- internalType: "uint8",
1930
- name: "v",
1931
- type: "uint8"
1932
- },
1933
- {
1934
- internalType: "bytes32",
1935
- name: "r",
1936
- type: "bytes32"
1937
- },
1938
- {
1939
- internalType: "bytes32",
1940
- name: "s",
1941
- type: "bytes32"
1942
- }
1943
- ],
1944
- name: "settleWithPermit",
1945
- outputs: [],
1946
- stateMutability: "nonpayable",
1947
- type: "function"
1948
- },
1949
- // settleWithERC3009 - 使用 EIP-3009 TransferWithAuthorization 进行结算
1950
- {
1951
- inputs: [
1952
- {
1953
- internalType: "address",
1954
- name: "token",
1955
- type: "address"
1956
- },
1957
- {
1958
- internalType: "address",
1959
- name: "payer",
1960
- type: "address"
1961
- },
1962
- {
1963
- internalType: "address",
1964
- name: "seller",
1965
- type: "address"
1966
- },
1967
- {
1968
- internalType: "uint256",
1969
- name: "amount",
1970
- type: "uint256"
1971
- },
1972
- {
1973
- internalType: "uint256",
1974
- name: "validAfter",
1975
- type: "uint256"
1976
- },
1977
- {
1978
- internalType: "uint256",
1979
- name: "validBefore",
1980
- type: "uint256"
1981
- },
1982
- {
1983
- internalType: "bytes32",
1984
- name: "nonce",
1985
- type: "bytes32"
1986
- },
1987
- {
1988
- internalType: "uint8",
1989
- name: "v",
1990
- type: "uint8"
1991
- },
1992
- {
1993
- internalType: "bytes32",
1994
- name: "r",
1995
- type: "bytes32"
1996
- },
1997
- {
1998
- internalType: "bytes32",
1999
- name: "s",
2000
- type: "bytes32"
2001
- }
2002
- ],
2003
- name: "settleWithERC3009",
2004
- outputs: [],
2005
- stateMutability: "nonpayable",
2006
- type: "function"
2007
- },
2008
- // settleWithERC3009Direct - 直接结算(无手续费)
2009
- {
2010
- inputs: [
2011
- {
2012
- internalType: "address",
2013
- name: "token",
2014
- type: "address"
2015
- },
2016
- {
2017
- internalType: "address",
2018
- name: "payer",
2019
- type: "address"
2020
- },
2021
- {
2022
- internalType: "address",
2023
- name: "seller",
2024
- type: "address"
2025
- },
2026
- {
2027
- internalType: "uint256",
2028
- name: "amount",
2029
- type: "uint256"
2030
- },
2031
- {
2032
- internalType: "uint256",
2033
- name: "validAfter",
2034
- type: "uint256"
2035
- },
2036
- {
2037
- internalType: "uint256",
2038
- name: "validBefore",
2039
- type: "uint256"
2040
- },
2041
- {
2042
- internalType: "bytes32",
2043
- name: "nonce",
2044
- type: "bytes32"
2045
- },
2046
- {
2047
- internalType: "uint8",
2048
- name: "v",
2049
- type: "uint8"
2050
- },
2051
- {
2052
- internalType: "bytes32",
2053
- name: "r",
2054
- type: "bytes32"
2055
- },
2056
- {
2057
- internalType: "bytes32",
2058
- name: "s",
2059
- type: "bytes32"
1918
+ // src/shared/svm/transaction.ts
1919
+ var import_kit3 = require("@solana/kit");
1920
+ var import_token = require("@solana-program/token");
1921
+ var import_token_2022 = require("@solana-program/token-2022");
1922
+ function decodeTransactionFromPayload(svmPayload) {
1923
+ try {
1924
+ const base64Encoder = (0, import_kit3.getBase64Encoder)();
1925
+ const transactionBytes = base64Encoder.encode(svmPayload.transaction);
1926
+ const transactionDecoder = (0, import_kit3.getTransactionDecoder)();
1927
+ return transactionDecoder.decode(transactionBytes);
1928
+ } catch (error) {
1929
+ console.error("error", error);
1930
+ throw new Error("invalid_exact_svm_payload_transaction");
1931
+ }
1932
+ }
1933
+ function getTokenPayerFromTransaction(transaction) {
1934
+ const compiled = (0, import_kit3.getCompiledTransactionMessageDecoder)().decode(
1935
+ transaction.messageBytes
1936
+ );
1937
+ const staticAccounts = compiled.staticAccounts ?? [];
1938
+ const instructions = compiled.instructions ?? [];
1939
+ for (const ix of instructions) {
1940
+ const programIndex = ix.programAddressIndex;
1941
+ const programAddress = staticAccounts[programIndex].toString();
1942
+ if (programAddress === import_token.TOKEN_PROGRAM_ADDRESS.toString() || programAddress === import_token_2022.TOKEN_2022_PROGRAM_ADDRESS.toString()) {
1943
+ const accountIndices = ix.accountIndices ?? [];
1944
+ if (accountIndices.length >= 4) {
1945
+ const ownerIndex = accountIndices[3];
1946
+ const ownerAddress = staticAccounts[ownerIndex].toString();
1947
+ if (ownerAddress) return ownerAddress;
2060
1948
  }
2061
- ],
2062
- name: "settleWithERC3009Direct",
2063
- outputs: [],
2064
- stateMutability: "nonpayable",
2065
- type: "function"
2066
- },
2067
- // Events
2068
- {
2069
- anonymous: false,
2070
- inputs: [
2071
- {
2072
- indexed: true,
2073
- internalType: "address",
2074
- name: "token",
2075
- type: "address"
2076
- },
2077
- {
2078
- indexed: true,
2079
- internalType: "address",
2080
- name: "payer",
2081
- type: "address"
2082
- },
2083
- {
2084
- indexed: true,
2085
- internalType: "address",
2086
- name: "seller",
2087
- type: "address"
2088
- },
2089
- {
2090
- indexed: false,
2091
- internalType: "uint256",
2092
- name: "amount",
2093
- type: "uint256"
2094
- },
2095
- {
2096
- indexed: false,
2097
- internalType: "uint256",
2098
- name: "sellerAmount",
2099
- type: "uint256"
2100
- },
2101
- {
2102
- indexed: false,
2103
- internalType: "uint256",
2104
- name: "feeAmount",
2105
- type: "uint256"
2106
- },
2107
- {
2108
- indexed: false,
2109
- internalType: "string",
2110
- name: "path",
2111
- type: "string"
1949
+ }
1950
+ }
1951
+ return "";
1952
+ }
1953
+ async function signAndSimulateTransaction(signer, transaction, rpc) {
1954
+ const signedTransaction = await (0, import_kit3.partiallySignTransaction)([signer.keyPair], transaction);
1955
+ const base64EncodedTransaction = (0, import_kit3.getBase64EncodedWireTransaction)(signedTransaction);
1956
+ const simulateTxConfig = {
1957
+ sigVerify: true,
1958
+ replaceRecentBlockhash: false,
1959
+ commitment: "confirmed",
1960
+ encoding: "base64",
1961
+ accounts: void 0,
1962
+ innerInstructions: void 0,
1963
+ minContextSlot: void 0
1964
+ };
1965
+ const simulateResult = await rpc.simulateTransaction(base64EncodedTransaction, simulateTxConfig).send();
1966
+ return simulateResult;
1967
+ }
1968
+
1969
+ // src/schemes/exact/svm/facilitator/settle.ts
1970
+ var import_kit5 = require("@solana/kit");
1971
+ var import_transaction_confirmation = require("@solana/transaction-confirmation");
1972
+
1973
+ // src/schemes/exact/svm/facilitator/verify.ts
1974
+ var import_kit4 = require("@solana/kit");
1975
+ var import_compute_budget = require("@solana-program/compute-budget");
1976
+ var import_token_20222 = require("@solana-program/token-2022");
1977
+ var import_token2 = require("@solana-program/token");
1978
+ async function verify(signer, payload, paymentRequirements, config2) {
1979
+ try {
1980
+ verifySchemesAndNetworks(payload, paymentRequirements);
1981
+ const svmPayload = payload.payload;
1982
+ const decodedTransaction = decodeTransactionFromPayload(svmPayload);
1983
+ const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
1984
+ await transactionIntrospection(svmPayload, paymentRequirements, config2);
1985
+ const simulateResult = await signAndSimulateTransaction(signer, decodedTransaction, rpc);
1986
+ if (simulateResult.value?.err) {
1987
+ throw new Error(`invalid_exact_svm_payload_transaction_simulation_failed`);
1988
+ }
1989
+ return {
1990
+ isValid: true,
1991
+ invalidReason: void 0,
1992
+ payer: getTokenPayerFromTransaction(decodedTransaction)
1993
+ };
1994
+ } catch (error) {
1995
+ if (error instanceof Error) {
1996
+ if (ErrorReasons.includes(error.message)) {
1997
+ return {
1998
+ isValid: false,
1999
+ invalidReason: error.message,
2000
+ payer: (() => {
2001
+ try {
2002
+ const tx = decodeTransactionFromPayload(payload.payload);
2003
+ return getTokenPayerFromTransaction(tx);
2004
+ } catch {
2005
+ return void 0;
2006
+ }
2007
+ })()
2008
+ };
2112
2009
  }
2113
- ],
2114
- name: "SettledSplit",
2115
- type: "event"
2116
- },
2117
- {
2118
- anonymous: false,
2119
- inputs: [
2120
- {
2121
- indexed: true,
2122
- internalType: "address",
2123
- name: "token",
2124
- type: "address"
2125
- },
2126
- {
2127
- indexed: true,
2128
- internalType: "address",
2129
- name: "payer",
2130
- type: "address"
2131
- },
2010
+ }
2011
+ console.error(error);
2012
+ return {
2013
+ isValid: false,
2014
+ invalidReason: "unexpected_verify_error",
2015
+ payer: (() => {
2016
+ try {
2017
+ const tx = decodeTransactionFromPayload(payload.payload);
2018
+ return getTokenPayerFromTransaction(tx);
2019
+ } catch {
2020
+ return void 0;
2021
+ }
2022
+ })()
2023
+ };
2024
+ }
2025
+ }
2026
+ function verifySchemesAndNetworks(payload, paymentRequirements) {
2027
+ if (payload.scheme !== SCHEME || paymentRequirements.scheme !== SCHEME) {
2028
+ throw new Error("unsupported_scheme");
2029
+ }
2030
+ if (payload.network !== paymentRequirements.network || !SupportedSVMNetworks.includes(paymentRequirements.network)) {
2031
+ throw new Error("invalid_network");
2032
+ }
2033
+ }
2034
+ async function transactionIntrospection(svmPayload, paymentRequirements, config2) {
2035
+ const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
2036
+ const decodedTransaction = decodeTransactionFromPayload(svmPayload);
2037
+ const compiledTransactionMessage = (0, import_kit4.getCompiledTransactionMessageDecoder)().decode(
2038
+ decodedTransaction.messageBytes
2039
+ );
2040
+ const transactionMessage = (0, import_kit4.decompileTransactionMessage)(
2041
+ compiledTransactionMessage
2042
+ );
2043
+ await verifyTransactionInstructions(transactionMessage, paymentRequirements, rpc);
2044
+ }
2045
+ async function verifyTransactionInstructions(transactionMessage, paymentRequirements, rpc) {
2046
+ if (transactionMessage.instructions.length !== 3 && transactionMessage.instructions.length !== 4) {
2047
+ throw new Error(`invalid_exact_svm_payload_transaction_instructions_length`);
2048
+ }
2049
+ verifyComputeLimitInstruction(transactionMessage.instructions[0]);
2050
+ verifyComputePriceInstruction(transactionMessage.instructions[1]);
2051
+ if (transactionMessage.instructions.length === 3) {
2052
+ await verifyTransferInstruction(
2053
+ transactionMessage.instructions[2],
2054
+ paymentRequirements,
2132
2055
  {
2133
- indexed: true,
2134
- internalType: "address",
2135
- name: "seller",
2136
- type: "address"
2056
+ txHasCreateDestATAInstruction: false
2137
2057
  },
2058
+ rpc
2059
+ );
2060
+ } else {
2061
+ verifyCreateATAInstruction(transactionMessage.instructions[2], paymentRequirements);
2062
+ await verifyTransferInstruction(
2063
+ transactionMessage.instructions[3],
2064
+ paymentRequirements,
2138
2065
  {
2139
- indexed: false,
2140
- internalType: "uint256",
2141
- name: "amount",
2142
- type: "uint256"
2066
+ txHasCreateDestATAInstruction: true
2143
2067
  },
2144
- {
2145
- indexed: false,
2146
- internalType: "string",
2147
- name: "path",
2148
- type: "string"
2149
- }
2150
- ],
2151
- name: "SettledDirect",
2152
- type: "event"
2068
+ rpc
2069
+ );
2070
+ }
2071
+ }
2072
+ function verifyComputeLimitInstruction(instruction) {
2073
+ try {
2074
+ if (instruction.programAddress.toString() !== import_compute_budget.COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() || instruction.data?.[0] !== 2) {
2075
+ throw new Error(
2076
+ `invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction`
2077
+ );
2078
+ }
2079
+ (0, import_compute_budget.parseSetComputeUnitLimitInstruction)(
2080
+ instruction
2081
+ );
2082
+ } catch (error) {
2083
+ console.error(error);
2084
+ throw new Error(`invalid_exact_svm_payload_transaction_instructions_compute_limit_instruction`);
2085
+ }
2086
+ }
2087
+ function verifyComputePriceInstruction(instruction) {
2088
+ if (instruction.programAddress.toString() !== import_compute_budget.COMPUTE_BUDGET_PROGRAM_ADDRESS.toString() || instruction.data?.[0] !== 3) {
2089
+ throw new Error(`invalid_exact_svm_payload_transaction_instructions_compute_price_instruction`);
2090
+ }
2091
+ const parsedInstruction = (0, import_compute_budget.parseSetComputeUnitPriceInstruction)(
2092
+ instruction
2093
+ );
2094
+ if (parsedInstruction.data.microLamports > 5 * 1e6) {
2095
+ throw new Error(
2096
+ `invalid_exact_svm_payload_transaction_instructions_compute_price_instruction_too_high`
2097
+ );
2098
+ }
2099
+ }
2100
+ function verifyCreateATAInstruction(instruction, paymentRequirements) {
2101
+ let createATAInstruction;
2102
+ try {
2103
+ (0, import_kit4.assertIsInstructionWithAccounts)(instruction);
2104
+ (0, import_kit4.assertIsInstructionWithData)(instruction);
2105
+ createATAInstruction = (0, import_token_20222.parseCreateAssociatedTokenInstruction)({
2106
+ ...instruction,
2107
+ data: new Uint8Array(instruction.data)
2108
+ });
2109
+ } catch (error) {
2110
+ console.error(error);
2111
+ throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction`);
2112
+ }
2113
+ if (createATAInstruction.accounts.owner.address !== paymentRequirements.payTo) {
2114
+ throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_payee`);
2153
2115
  }
2154
- ];
2116
+ if (createATAInstruction.accounts.mint.address !== paymentRequirements.asset) {
2117
+ throw new Error(`invalid_exact_svm_payload_transaction_create_ata_instruction_incorrect_asset`);
2118
+ }
2119
+ }
2120
+ async function verifyTransferInstruction(instruction, paymentRequirements, { txHasCreateDestATAInstruction }, rpc) {
2121
+ const tokenInstruction = getValidatedTransferCheckedInstruction(instruction);
2122
+ await verifyTransferCheckedInstruction(
2123
+ tokenInstruction,
2124
+ paymentRequirements,
2125
+ {
2126
+ txHasCreateDestATAInstruction
2127
+ },
2128
+ rpc
2129
+ );
2130
+ }
2131
+ async function verifyTransferCheckedInstruction(parsedInstruction, paymentRequirements, { txHasCreateDestATAInstruction }, rpc) {
2132
+ const tokenProgramAddress = parsedInstruction.programAddress.toString() === import_token2.TOKEN_PROGRAM_ADDRESS.toString() ? import_token2.TOKEN_PROGRAM_ADDRESS : import_token_20222.TOKEN_2022_PROGRAM_ADDRESS;
2133
+ const payToATA = await (0, import_token_20222.findAssociatedTokenPda)({
2134
+ mint: paymentRequirements.asset,
2135
+ owner: paymentRequirements.payTo,
2136
+ tokenProgram: tokenProgramAddress
2137
+ });
2138
+ if (parsedInstruction.accounts.destination.address !== payToATA[0]) {
2139
+ throw new Error(`invalid_exact_svm_payload_transaction_transfer_to_incorrect_ata`);
2140
+ }
2141
+ const addresses = [parsedInstruction.accounts.source.address, payToATA[0]];
2142
+ const maybeAccounts = await (0, import_kit4.fetchEncodedAccounts)(rpc, addresses);
2143
+ const missingAccounts = maybeAccounts.filter((a) => !a.exists);
2144
+ for (const missingAccount of missingAccounts) {
2145
+ if (missingAccount.address === parsedInstruction.accounts.source.address) {
2146
+ throw new Error(`invalid_exact_svm_payload_transaction_sender_ata_not_found`);
2147
+ }
2148
+ if (missingAccount.address === payToATA[0] && !txHasCreateDestATAInstruction) {
2149
+ throw new Error(`invalid_exact_svm_payload_transaction_receiver_ata_not_found`);
2150
+ }
2151
+ }
2152
+ const instructionAmount = parsedInstruction.data.amount;
2153
+ const paymentRequirementsAmount = BigInt(paymentRequirements.maxAmountRequired);
2154
+ if (instructionAmount !== paymentRequirementsAmount) {
2155
+ throw new Error(`invalid_exact_svm_payload_transaction_amount_mismatch`);
2156
+ }
2157
+ }
2158
+ function getValidatedTransferCheckedInstruction(instruction) {
2159
+ try {
2160
+ (0, import_kit4.assertIsInstructionWithData)(instruction);
2161
+ (0, import_kit4.assertIsInstructionWithAccounts)(instruction);
2162
+ } catch (error) {
2163
+ console.error(error);
2164
+ throw new Error(`invalid_exact_svm_payload_transaction_instructions`);
2165
+ }
2166
+ let tokenInstruction;
2167
+ if (instruction.programAddress.toString() === import_token2.TOKEN_PROGRAM_ADDRESS.toString()) {
2168
+ const identifiedInstruction = (0, import_token2.identifyTokenInstruction)(instruction);
2169
+ if (identifiedInstruction !== import_token2.TokenInstruction.TransferChecked) {
2170
+ throw new Error(
2171
+ `invalid_exact_svm_payload_transaction_instruction_not_spl_token_transfer_checked`
2172
+ );
2173
+ }
2174
+ tokenInstruction = (0, import_token2.parseTransferCheckedInstruction)({
2175
+ ...instruction,
2176
+ data: new Uint8Array(instruction.data)
2177
+ });
2178
+ } else if (instruction.programAddress.toString() === import_token_20222.TOKEN_2022_PROGRAM_ADDRESS.toString()) {
2179
+ const identifiedInstruction = (0, import_token_20222.identifyToken2022Instruction)(instruction);
2180
+ if (identifiedInstruction !== import_token_20222.Token2022Instruction.TransferChecked) {
2181
+ throw new Error(
2182
+ `invalid_exact_svm_payload_transaction_instruction_not_token_2022_transfer_checked`
2183
+ );
2184
+ }
2185
+ tokenInstruction = (0, import_token_20222.parseTransferCheckedInstruction)({
2186
+ ...instruction,
2187
+ data: new Uint8Array(instruction.data)
2188
+ });
2189
+ } else {
2190
+ throw new Error(`invalid_exact_svm_payload_transaction_not_a_transfer_instruction`);
2191
+ }
2192
+ return tokenInstruction;
2193
+ }
2194
+
2195
+ // src/schemes/exact/svm/facilitator/settle.ts
2196
+ async function settle(signer, payload, paymentRequirements, config2) {
2197
+ const verifyResponse = await verify(signer, payload, paymentRequirements, config2);
2198
+ if (!verifyResponse.isValid) {
2199
+ return {
2200
+ success: false,
2201
+ errorReason: verifyResponse.invalidReason,
2202
+ network: payload.network,
2203
+ transaction: ""
2204
+ };
2205
+ }
2206
+ const svmPayload = payload.payload;
2207
+ const decodedTransaction = decodeTransactionFromPayload(svmPayload);
2208
+ const signedTransaction = await (0, import_kit5.signTransaction)([signer.keyPair], decodedTransaction);
2209
+ const payer = getTokenPayerFromTransaction(decodedTransaction);
2210
+ const rpc = getRpcClient(paymentRequirements.network, config2?.svmConfig?.rpcUrl);
2211
+ const rpcSubscriptions = getRpcSubscriptions(
2212
+ paymentRequirements.network,
2213
+ config2?.svmConfig?.rpcUrl
2214
+ );
2215
+ try {
2216
+ const { success, errorReason, signature } = await sendAndConfirmSignedTransaction(
2217
+ signedTransaction,
2218
+ rpc,
2219
+ rpcSubscriptions
2220
+ );
2221
+ return {
2222
+ success,
2223
+ errorReason,
2224
+ payer,
2225
+ transaction: signature,
2226
+ network: payload.network
2227
+ };
2228
+ } catch (error) {
2229
+ console.error("Unexpected error during transaction settlement:", error);
2230
+ return {
2231
+ success: false,
2232
+ errorReason: "unexpected_settle_error",
2233
+ network: payload.network,
2234
+ transaction: (0, import_kit5.getSignatureFromTransaction)(signedTransaction),
2235
+ payer
2236
+ };
2237
+ }
2238
+ }
2239
+ async function sendSignedTransaction(signedTransaction, rpc, sendTxConfig = {
2240
+ skipPreflight: true,
2241
+ encoding: "base64"
2242
+ }) {
2243
+ const base64EncodedTransaction = (0, import_kit5.getBase64EncodedWireTransaction)(signedTransaction);
2244
+ return await rpc.sendTransaction(base64EncodedTransaction, sendTxConfig).send();
2245
+ }
2246
+ async function confirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions) {
2247
+ const signature = (0, import_kit5.getSignatureFromTransaction)(signedTransaction);
2248
+ const abortController = new AbortController();
2249
+ const timeout = setTimeout(() => {
2250
+ abortController.abort("Transaction confirmation timed out after 60 seconds");
2251
+ }, 6e4);
2252
+ try {
2253
+ const compiledTransactionMessage = (0, import_kit5.getCompiledTransactionMessageDecoder)().decode(
2254
+ signedTransaction.messageBytes
2255
+ );
2256
+ const decompiledTransactionMessage = await (0, import_kit5.decompileTransactionMessageFetchingLookupTables)(
2257
+ compiledTransactionMessage,
2258
+ rpc
2259
+ );
2260
+ (0, import_kit5.assertIsTransactionMessageWithBlockhashLifetime)(decompiledTransactionMessage);
2261
+ const signedTransactionWithBlockhashLifetime = {
2262
+ ...signedTransaction,
2263
+ lifetimeConstraint: decompiledTransactionMessage.lifetimeConstraint
2264
+ };
2265
+ const commitment = "confirmed";
2266
+ const getRecentSignatureConfirmationPromise = (0, import_transaction_confirmation.createRecentSignatureConfirmationPromiseFactory)({
2267
+ rpc,
2268
+ rpcSubscriptions
2269
+ });
2270
+ const getBlockHeightExceedencePromise = (0, import_transaction_confirmation.createBlockHeightExceedencePromiseFactory)({
2271
+ rpc,
2272
+ rpcSubscriptions
2273
+ });
2274
+ const config2 = {
2275
+ abortSignal: abortController.signal,
2276
+ commitment,
2277
+ getBlockHeightExceedencePromise,
2278
+ getRecentSignatureConfirmationPromise
2279
+ };
2280
+ await (0, import_transaction_confirmation.waitForRecentTransactionConfirmation)({
2281
+ ...config2,
2282
+ transaction: signedTransactionWithBlockhashLifetime
2283
+ });
2284
+ return {
2285
+ success: true,
2286
+ signature
2287
+ };
2288
+ } catch (error) {
2289
+ console.error(error);
2290
+ if ((0, import_kit5.isSolanaError)(error, import_kit5.SOLANA_ERROR__BLOCK_HEIGHT_EXCEEDED)) {
2291
+ return {
2292
+ success: false,
2293
+ errorReason: "settle_exact_svm_block_height_exceeded",
2294
+ signature
2295
+ };
2296
+ } else if (error instanceof DOMException && error.name === "AbortError") {
2297
+ return {
2298
+ success: false,
2299
+ errorReason: "settle_exact_svm_transaction_confirmation_timed_out",
2300
+ signature
2301
+ };
2302
+ } else {
2303
+ throw error;
2304
+ }
2305
+ } finally {
2306
+ clearTimeout(timeout);
2307
+ }
2308
+ }
2309
+ async function sendAndConfirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions) {
2310
+ await sendSignedTransaction(signedTransaction, rpc);
2311
+ return await confirmSignedTransaction(signedTransaction, rpc, rpcSubscriptions);
2312
+ }
2313
+
2314
+ // src/schemes/exact/svm/client.ts
2315
+ var import_kit6 = require("@solana/kit");
2316
+ var import_token_20223 = require("@solana-program/token-2022");
2317
+ var import_token3 = require("@solana-program/token");
2318
+ var import_compute_budget2 = require("@solana-program/compute-budget");
2319
+
2320
+ // src/schemes/exact/index.ts
2321
+ var SCHEME = "exact";
2155
2322
 
2156
2323
  // src/schemes/exact/evm/eip3009/facilitator.ts
2157
2324
  async function verify2(client, payload, paymentRequirements) {
@@ -2217,7 +2384,7 @@ async function verify2(client, payload, paymentRequirements) {
2217
2384
  payer: exactEvmPayload.authorization.from
2218
2385
  };
2219
2386
  }
2220
- if ((0, import_viem2.getAddress)(exactEvmPayload.authorization.to) !== (0, import_viem2.getAddress)(paymentRequirements.payTo) && (0, import_viem2.getAddress)(exactEvmPayload.authorization.to) !== (0, import_viem2.getAddress)(paymentRequirements.extra?.relayer)) {
2387
+ if ((0, import_viem2.getAddress)(exactEvmPayload.authorization.to) !== (0, import_viem2.getAddress)(paymentRequirements.payTo)) {
2221
2388
  return {
2222
2389
  isValid: false,
2223
2390
  invalidReason: "invalid_exact_evm_payload_recipient_mismatch",
@@ -2290,57 +2457,36 @@ async function settle2(wallet, paymentPayload, paymentRequirements) {
2290
2457
  };
2291
2458
  }
2292
2459
  const { signature } = (0, import_viem2.parseErc6492Signature)(payload.signature);
2293
- let tx;
2294
- if (paymentRequirements.extra?.relayer) {
2295
- const sig = (0, import_viem2.hexToSignature)(signature);
2296
- const v = Number(sig.v);
2297
- const r = sig.r;
2298
- const s = sig.s;
2299
- tx = await wallet.writeContract({
2300
- address: paymentRequirements.extra.relayer,
2301
- abi: permitProxyContractABI,
2302
- functionName: "settleWithERC3009",
2303
- args: [
2304
- paymentRequirements.asset,
2305
- // token
2306
- payload.authorization.from,
2307
- // payer
2308
- paymentRequirements.payTo,
2309
- // seller
2310
- BigInt(payload.authorization.value),
2311
- // amount
2312
- BigInt(payload.authorization.validAfter),
2313
- // validAfter
2314
- BigInt(payload.authorization.validBefore),
2315
- // validBefore
2316
- payload.authorization.nonce,
2317
- // nonce
2318
- v,
2319
- // v (uint8)
2320
- r,
2321
- // r (bytes32)
2322
- s
2323
- // s (bytes32)
2324
- ],
2325
- chain: wallet.chain
2326
- });
2327
- } else {
2328
- tx = await wallet.writeContract({
2329
- address: paymentRequirements.asset,
2330
- abi: usdcABI,
2331
- functionName: "transferWithAuthorization",
2332
- args: [
2333
- payload.authorization.from,
2334
- payload.authorization.to,
2335
- BigInt(payload.authorization.value),
2336
- BigInt(payload.authorization.validAfter),
2337
- BigInt(payload.authorization.validBefore),
2338
- payload.authorization.nonce,
2339
- signature
2340
- ],
2341
- chain: wallet.chain
2342
- });
2343
- }
2460
+ const sig = (0, import_viem2.hexToSignature)(signature);
2461
+ const v = Number(sig.v);
2462
+ const r = sig.r;
2463
+ const s = sig.s;
2464
+ const tx = await wallet.writeContract({
2465
+ address: paymentRequirements.payTo,
2466
+ abi: EIP7702SellerWalletMinimalAbi,
2467
+ functionName: "settleWithERC3009",
2468
+ args: [
2469
+ paymentRequirements.asset,
2470
+ // token
2471
+ payload.authorization.from,
2472
+ // payer
2473
+ BigInt(payload.authorization.value),
2474
+ // amount
2475
+ BigInt(payload.authorization.validAfter),
2476
+ // validAfter
2477
+ BigInt(payload.authorization.validBefore),
2478
+ // validBefore
2479
+ payload.authorization.nonce,
2480
+ // nonce
2481
+ v,
2482
+ // v (uint8)
2483
+ r,
2484
+ // r (bytes32)
2485
+ s
2486
+ // s (bytes32)
2487
+ ],
2488
+ chain: wallet.chain
2489
+ });
2344
2490
  const receipt = await wallet.waitForTransactionReceipt({ hash: tx });
2345
2491
  if (receipt.status !== "success") {
2346
2492
  return {
@@ -2443,22 +2589,12 @@ async function verify3(client, payload, paymentRequirements) {
2443
2589
  payer: owner
2444
2590
  };
2445
2591
  }
2446
- if (paymentRequirements.extra?.relayer) {
2447
- if ((0, import_viem4.getAddress)(spender) !== (0, import_viem4.getAddress)(paymentRequirements.extra?.relayer)) {
2448
- return {
2449
- isValid: false,
2450
- invalidReason: "invalid_spender_address",
2451
- payer: owner
2452
- };
2453
- }
2454
- } else {
2455
- if (client.account && (0, import_viem4.getAddress)(spender) !== (0, import_viem4.getAddress)(client.account.address)) {
2456
- return {
2457
- isValid: false,
2458
- invalidReason: "invalid_spender_address",
2459
- payer: owner
2460
- };
2461
- }
2592
+ if ((0, import_viem4.getAddress)(spender) !== (0, import_viem4.getAddress)(paymentRequirements.payTo)) {
2593
+ return {
2594
+ isValid: false,
2595
+ invalidReason: "invalid_spender_address",
2596
+ payer: owner
2597
+ };
2462
2598
  }
2463
2599
  const balance = await getERC20Balance(client, erc20Address, owner);
2464
2600
  if (balance < BigInt(paymentRequirements.maxAmountRequired)) {
@@ -2501,84 +2637,40 @@ async function settle3(wallet, paymentPayload, paymentRequirements) {
2501
2637
  payer: permitPayload.authorization.owner
2502
2638
  };
2503
2639
  }
2504
- const { owner, spender, value, deadline } = permitPayload.authorization;
2640
+ const { owner, value, deadline } = permitPayload.authorization;
2505
2641
  const { v, r, s } = splitSignature(permitPayload.signature);
2506
2642
  const tokenAddress = paymentRequirements.asset;
2507
- const txNonce = await wallet.getTransactionCount({
2508
- address: wallet.account.address
2643
+ const transactionHash = await wallet.writeContract({
2644
+ address: paymentRequirements.payTo,
2645
+ abi: EIP7702SellerWalletMinimalAbi,
2646
+ functionName: "settleWithPermit",
2647
+ args: [
2648
+ tokenAddress,
2649
+ // token
2650
+ owner,
2651
+ // payer
2652
+ BigInt(value),
2653
+ // amount
2654
+ BigInt(deadline),
2655
+ // deadline
2656
+ v,
2657
+ // v
2658
+ r,
2659
+ // r
2660
+ s
2661
+ // s
2662
+ ],
2663
+ chain: wallet.chain
2509
2664
  });
2510
- let transactionHash;
2511
- if (paymentRequirements.extra?.relayer) {
2512
- transactionHash = await wallet.writeContract({
2513
- address: paymentRequirements.extra.relayer,
2514
- abi: permitProxyContractABI,
2515
- functionName: "settleWithPermit",
2516
- args: [
2517
- tokenAddress,
2518
- // token
2519
- owner,
2520
- // payer
2521
- paymentRequirements.payTo,
2522
- // seller
2523
- BigInt(value),
2524
- // amount
2525
- BigInt(deadline),
2526
- // deadline
2527
- v,
2528
- // v
2529
- r,
2530
- // r
2531
- s
2532
- // s
2533
- ],
2534
- chain: wallet.chain,
2535
- nonce: txNonce
2536
- });
2537
- const receipt = await wallet.waitForTransactionReceipt({ hash: transactionHash });
2538
- if (receipt.status !== "success") {
2539
- return {
2540
- success: false,
2541
- errorReason: "transaction_failed",
2542
- transaction: transactionHash,
2543
- network: paymentPayload.network,
2544
- payer: owner
2545
- };
2546
- }
2547
- } else {
2548
- const [permitTx, transferTx] = await Promise.all([
2549
- // Call permit to approve the spender
2550
- wallet.writeContract({
2551
- address: tokenAddress,
2552
- abi: erc20PermitABI,
2553
- functionName: "permit",
2554
- args: [owner, spender, BigInt(value), BigInt(deadline), v, r, s],
2555
- chain: wallet.chain,
2556
- nonce: txNonce
2557
- }),
2558
- // Call transferFrom to transfer tokens to payTo address
2559
- wallet.writeContract({
2560
- address: tokenAddress,
2561
- abi: erc20PermitABI,
2562
- functionName: "transferFrom",
2563
- args: [owner, paymentRequirements.payTo, BigInt(value)],
2564
- chain: wallet.chain,
2565
- nonce: txNonce + 1
2566
- })
2567
- ]);
2568
- const [, receipt] = await Promise.all([
2569
- wallet.waitForTransactionReceipt({ hash: permitTx }),
2570
- wallet.waitForTransactionReceipt({ hash: transferTx })
2571
- ]);
2572
- if (receipt.status !== "success") {
2573
- return {
2574
- success: false,
2575
- errorReason: "transaction_failed",
2576
- transaction: transferTx,
2577
- network: paymentPayload.network,
2578
- payer: owner
2579
- };
2580
- }
2581
- transactionHash = transferTx;
2665
+ const receipt = await wallet.waitForTransactionReceipt({ hash: transactionHash });
2666
+ if (receipt.status !== "success") {
2667
+ return {
2668
+ success: false,
2669
+ errorReason: "transaction_failed",
2670
+ transaction: transactionHash,
2671
+ network: paymentPayload.network,
2672
+ payer: owner
2673
+ };
2582
2674
  }
2583
2675
  return {
2584
2676
  success: true,