@dexterai/x402 3.0.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,903 +1 @@
1
- // src/adapters/solana.ts
2
- import {
3
- PublicKey,
4
- Connection,
5
- TransactionMessage,
6
- VersionedTransaction,
7
- ComputeBudgetProgram
8
- } from "@solana/web3.js";
9
- import {
10
- getAssociatedTokenAddress,
11
- getAccount,
12
- createTransferCheckedInstruction,
13
- getMint,
14
- TOKEN_PROGRAM_ID,
15
- TOKEN_2022_PROGRAM_ID
16
- } from "@solana/spl-token";
17
- var SOLANA_MAINNET = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
18
- var SOLANA_DEVNET = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
19
- var SOLANA_TESTNET = "solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z";
20
- var DEFAULT_RPC_URLS = {
21
- [SOLANA_MAINNET]: "https://api.dexter.cash/api/solana/rpc",
22
- [SOLANA_DEVNET]: "https://api.devnet.solana.com",
23
- [SOLANA_TESTNET]: "https://api.testnet.solana.com"
24
- };
25
- var DEFAULT_COMPUTE_UNIT_LIMIT = 12e3;
26
- var DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS = 1;
27
- function isSolanaWallet(wallet) {
28
- if (!wallet || typeof wallet !== "object") return false;
29
- const w = wallet;
30
- return "publicKey" in w && "signTransaction" in w && typeof w.signTransaction === "function";
31
- }
32
- var SolanaAdapter = class {
33
- name = "Solana";
34
- networks = [SOLANA_MAINNET, SOLANA_DEVNET, SOLANA_TESTNET];
35
- config;
36
- log;
37
- constructor(config = {}) {
38
- this.config = config;
39
- this.log = config.verbose ? console.log.bind(console, "[x402:solana]") : () => {
40
- };
41
- }
42
- canHandle(network) {
43
- if (this.networks.includes(network)) return true;
44
- if (network === "solana") return true;
45
- if (network === "solana-devnet") return true;
46
- if (network === "solana-testnet") return true;
47
- if (network.startsWith("solana:")) return true;
48
- return false;
49
- }
50
- getDefaultRpcUrl(network) {
51
- if (this.config.rpcUrls?.[network]) {
52
- return this.config.rpcUrls[network];
53
- }
54
- if (DEFAULT_RPC_URLS[network]) {
55
- return DEFAULT_RPC_URLS[network];
56
- }
57
- if (network === "solana") return DEFAULT_RPC_URLS[SOLANA_MAINNET];
58
- if (network === "solana-devnet") return DEFAULT_RPC_URLS[SOLANA_DEVNET];
59
- if (network === "solana-testnet") return DEFAULT_RPC_URLS[SOLANA_TESTNET];
60
- return DEFAULT_RPC_URLS[SOLANA_MAINNET];
61
- }
62
- getAddress(wallet) {
63
- if (!isSolanaWallet(wallet)) return null;
64
- return wallet.publicKey?.toBase58() ?? null;
65
- }
66
- isConnected(wallet) {
67
- if (!isSolanaWallet(wallet)) return false;
68
- return wallet.publicKey !== null;
69
- }
70
- async getBalance(accept, wallet, rpcUrl) {
71
- if (!isSolanaWallet(wallet) || !wallet.publicKey) {
72
- return 0;
73
- }
74
- const url = rpcUrl || this.getDefaultRpcUrl(accept.network);
75
- const connection = new Connection(url, "confirmed");
76
- const userPubkey = new PublicKey(wallet.publicKey.toBase58());
77
- const mintPubkey = new PublicKey(accept.asset);
78
- try {
79
- const mintInfo = await connection.getAccountInfo(mintPubkey, "confirmed");
80
- const programId = mintInfo?.owner.toBase58() === TOKEN_2022_PROGRAM_ID.toBase58() ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
81
- const ata = await getAssociatedTokenAddress(
82
- mintPubkey,
83
- userPubkey,
84
- false,
85
- programId
86
- );
87
- const account = await getAccount(connection, ata, void 0, programId);
88
- const decimals = accept.extra?.decimals ?? 6;
89
- return Number(account.amount) / Math.pow(10, decimals);
90
- } catch (err) {
91
- if (err && typeof err === "object" && "name" in err && (err.name === "TokenAccountNotFoundError" || err.name === "TokenInvalidAccountOwnerError")) {
92
- return 0;
93
- }
94
- throw err;
95
- }
96
- }
97
- async buildTransaction(accept, wallet, rpcUrl) {
98
- if (!isSolanaWallet(wallet)) {
99
- throw new Error("Invalid Solana wallet");
100
- }
101
- if (!wallet.publicKey) {
102
- throw new Error("Wallet not connected");
103
- }
104
- const url = rpcUrl || this.getDefaultRpcUrl(accept.network);
105
- const connection = new Connection(url, "confirmed");
106
- const userPubkey = new PublicKey(wallet.publicKey.toBase58());
107
- const { payTo, asset, extra } = accept;
108
- const amount = accept.amount ?? accept.maxAmountRequired;
109
- if (!amount) {
110
- throw new Error("Missing amount in payment requirements");
111
- }
112
- if (!extra?.feePayer) {
113
- throw new Error("Missing feePayer in payment requirements");
114
- }
115
- const feePayerPubkey = new PublicKey(extra.feePayer);
116
- const mintPubkey = new PublicKey(asset);
117
- const destinationPubkey = new PublicKey(payTo);
118
- this.log("Building transaction:", {
119
- from: userPubkey.toBase58(),
120
- to: payTo,
121
- amount,
122
- asset,
123
- feePayer: extra.feePayer
124
- });
125
- const instructions = [];
126
- instructions.push(
127
- ComputeBudgetProgram.setComputeUnitLimit({
128
- units: DEFAULT_COMPUTE_UNIT_LIMIT
129
- })
130
- );
131
- instructions.push(
132
- ComputeBudgetProgram.setComputeUnitPrice({
133
- microLamports: DEFAULT_COMPUTE_UNIT_PRICE_MICROLAMPORTS
134
- })
135
- );
136
- const mintInfo = await connection.getAccountInfo(mintPubkey, "confirmed");
137
- if (!mintInfo) {
138
- throw new Error(`Token mint ${asset} not found`);
139
- }
140
- const programId = mintInfo.owner.toBase58() === TOKEN_2022_PROGRAM_ID.toBase58() ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
141
- const mint = await getMint(connection, mintPubkey, void 0, programId);
142
- if (typeof extra?.decimals === "number" && mint.decimals !== extra.decimals) {
143
- this.log(
144
- `Decimals mismatch: requirements say ${extra.decimals}, mint says ${mint.decimals}`
145
- );
146
- }
147
- const sourceAta = await getAssociatedTokenAddress(
148
- mintPubkey,
149
- userPubkey,
150
- false,
151
- programId
152
- );
153
- const destinationAta = await getAssociatedTokenAddress(
154
- mintPubkey,
155
- destinationPubkey,
156
- false,
157
- programId
158
- );
159
- const sourceAtaInfo = await connection.getAccountInfo(sourceAta, "confirmed");
160
- if (!sourceAtaInfo) {
161
- throw new Error(
162
- `No token account found for ${asset}. Please ensure you have USDC in your wallet.`
163
- );
164
- }
165
- const destAtaInfo = await connection.getAccountInfo(destinationAta, "confirmed");
166
- if (!destAtaInfo) {
167
- throw new Error(
168
- `Seller token account not found. The seller (${payTo}) must have a USDC account.`
169
- );
170
- }
171
- const amountBigInt = BigInt(amount);
172
- instructions.push(
173
- createTransferCheckedInstruction(
174
- sourceAta,
175
- mintPubkey,
176
- destinationAta,
177
- userPubkey,
178
- amountBigInt,
179
- mint.decimals,
180
- [],
181
- programId
182
- )
183
- );
184
- const { blockhash } = await connection.getLatestBlockhash("confirmed");
185
- const message = new TransactionMessage({
186
- payerKey: feePayerPubkey,
187
- recentBlockhash: blockhash,
188
- instructions
189
- }).compileToV0Message();
190
- const transaction = new VersionedTransaction(message);
191
- const signedTx = await wallet.signTransaction(transaction);
192
- this.log("Transaction signed successfully");
193
- return {
194
- serialized: Buffer.from(signedTx.serialize()).toString("base64")
195
- };
196
- }
197
- };
198
- function createSolanaAdapter(config) {
199
- return new SolanaAdapter(config);
200
- }
201
-
202
- // src/adapters/evm.ts
203
- var PERMIT2_ADDRESS = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
204
- var X402_EXACT_PERMIT2_PROXY = "0x402085c248EeA27D92E8b30b2C58ed07f9E20001";
205
- var PERMIT2_WITNESS_TYPES = {
206
- PermitWitnessTransferFrom: [
207
- { name: "permitted", type: "TokenPermissions" },
208
- { name: "spender", type: "address" },
209
- { name: "nonce", type: "uint256" },
210
- { name: "deadline", type: "uint256" },
211
- { name: "witness", type: "Witness" }
212
- ],
213
- TokenPermissions: [
214
- { name: "token", type: "address" },
215
- { name: "amount", type: "uint256" }
216
- ],
217
- Witness: [
218
- { name: "to", type: "address" },
219
- { name: "validAfter", type: "uint256" }
220
- ]
221
- };
222
- var MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
223
- var BASE_MAINNET = "eip155:8453";
224
- var BASE_SEPOLIA = "eip155:84532";
225
- var ARBITRUM_ONE = "eip155:42161";
226
- var POLYGON = "eip155:137";
227
- var OPTIMISM = "eip155:10";
228
- var AVALANCHE = "eip155:43114";
229
- var BSC_MAINNET = "eip155:56";
230
- var SKALE_BASE = "eip155:1187947933";
231
- var SKALE_BASE_SEPOLIA = "eip155:324705682";
232
- var ETHEREUM_MAINNET = "eip155:1";
233
- var BSC_USDT = "0x55d398326f99059fF775485246999027B3197955";
234
- var BSC_USDC = "0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d";
235
- var CHAIN_IDS = {
236
- [BSC_MAINNET]: 56,
237
- [BASE_MAINNET]: 8453,
238
- [BASE_SEPOLIA]: 84532,
239
- [ARBITRUM_ONE]: 42161,
240
- [POLYGON]: 137,
241
- [OPTIMISM]: 10,
242
- [AVALANCHE]: 43114,
243
- [SKALE_BASE]: 1187947933,
244
- [SKALE_BASE_SEPOLIA]: 324705682,
245
- [ETHEREUM_MAINNET]: 1
246
- };
247
- var DEFAULT_RPC_URLS2 = {
248
- [BSC_MAINNET]: "https://bsc-dataseed1.binance.org",
249
- [BASE_MAINNET]: "https://api.dexter.cash/api/base/rpc",
250
- [BASE_SEPOLIA]: "https://sepolia.base.org",
251
- [ARBITRUM_ONE]: "https://arb1.arbitrum.io/rpc",
252
- [POLYGON]: "https://polygon-rpc.com",
253
- [OPTIMISM]: "https://mainnet.optimism.io",
254
- [AVALANCHE]: "https://api.avax.network/ext/bc/C/rpc",
255
- [SKALE_BASE]: "https://skale-base.skalenodes.com/v1/base",
256
- [SKALE_BASE_SEPOLIA]: "https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",
257
- [ETHEREUM_MAINNET]: "https://eth.llamarpc.com"
258
- };
259
- var USDC_ADDRESSES = {
260
- [BSC_MAINNET]: BSC_USDC,
261
- [BASE_MAINNET]: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
262
- [BASE_SEPOLIA]: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
263
- [ARBITRUM_ONE]: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
264
- [POLYGON]: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",
265
- [OPTIMISM]: "0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",
266
- [AVALANCHE]: "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",
267
- [SKALE_BASE]: "0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",
268
- [SKALE_BASE_SEPOLIA]: "0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",
269
- [ETHEREUM_MAINNET]: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
270
- };
271
- var BSC_STABLECOIN_ADDRESSES = {
272
- [BSC_USDT]: { symbol: "USDT", decimals: 18 },
273
- [BSC_USDC]: { symbol: "USDC", decimals: 18 }
274
- };
275
- function isEvmWallet(wallet) {
276
- if (!wallet || typeof wallet !== "object") return false;
277
- const w = wallet;
278
- return "address" in w && typeof w.address === "string" && w.address.startsWith("0x");
279
- }
280
- var EvmAdapter = class {
281
- name = "EVM";
282
- networks = [BSC_MAINNET, BASE_MAINNET, BASE_SEPOLIA, ETHEREUM_MAINNET, ARBITRUM_ONE];
283
- config;
284
- log;
285
- constructor(config = {}) {
286
- this.config = config;
287
- this.log = config.verbose ? console.log.bind(console, "[x402:evm]") : () => {
288
- };
289
- }
290
- canHandle(network) {
291
- if (this.networks.includes(network)) return true;
292
- if (network === "base") return true;
293
- if (network === "bsc") return true;
294
- if (network === "ethereum") return true;
295
- if (network === "arbitrum") return true;
296
- if (network.startsWith("eip155:")) return true;
297
- return false;
298
- }
299
- getDefaultRpcUrl(network) {
300
- if (this.config.rpcUrls?.[network]) {
301
- return this.config.rpcUrls[network];
302
- }
303
- if (DEFAULT_RPC_URLS2[network]) {
304
- return DEFAULT_RPC_URLS2[network];
305
- }
306
- if (network === "base") return DEFAULT_RPC_URLS2[BASE_MAINNET];
307
- if (network === "bsc") return DEFAULT_RPC_URLS2[BSC_MAINNET];
308
- if (network === "ethereum") return DEFAULT_RPC_URLS2[ETHEREUM_MAINNET];
309
- if (network === "arbitrum") return DEFAULT_RPC_URLS2[ARBITRUM_ONE];
310
- return DEFAULT_RPC_URLS2[BASE_MAINNET];
311
- }
312
- getAddress(wallet) {
313
- if (!isEvmWallet(wallet)) return null;
314
- return wallet.address;
315
- }
316
- isConnected(wallet) {
317
- if (!isEvmWallet(wallet)) return false;
318
- return !!wallet.address;
319
- }
320
- getChainId(network) {
321
- if (CHAIN_IDS[network]) return CHAIN_IDS[network];
322
- if (network.startsWith("eip155:")) {
323
- const chainIdStr = network.split(":")[1];
324
- return parseInt(chainIdStr, 10);
325
- }
326
- if (network === "base") return 8453;
327
- if (network === "bsc") return 56;
328
- if (network === "ethereum") return 1;
329
- if (network === "arbitrum") return 42161;
330
- return 8453;
331
- }
332
- async getBalance(accept, wallet, rpcUrl) {
333
- if (!isEvmWallet(wallet) || !wallet.address) {
334
- return 0;
335
- }
336
- const url = rpcUrl || this.getDefaultRpcUrl(accept.network);
337
- try {
338
- const data = this.encodeBalanceOf(wallet.address);
339
- const response = await fetch(url, {
340
- method: "POST",
341
- headers: { "Content-Type": "application/json" },
342
- body: JSON.stringify({
343
- jsonrpc: "2.0",
344
- id: 1,
345
- method: "eth_call",
346
- params: [
347
- {
348
- to: accept.asset,
349
- data
350
- },
351
- "latest"
352
- ]
353
- })
354
- });
355
- if (!response.ok) {
356
- throw new Error(`RPC request failed: ${response.status}`);
357
- }
358
- const result = await response.json();
359
- if (result.error) {
360
- throw new Error(`RPC error: ${JSON.stringify(result.error)}`);
361
- }
362
- if (!result.result || result.result === "0x") {
363
- return 0;
364
- }
365
- const balance = BigInt(result.result);
366
- const decimals = accept.extra?.decimals ?? 6;
367
- return Number(balance) / Math.pow(10, decimals);
368
- } catch (err) {
369
- throw err;
370
- }
371
- }
372
- encodeBalanceOf(address) {
373
- const selector = "0x70a08231";
374
- const paddedAddress = address.slice(2).toLowerCase().padStart(64, "0");
375
- return selector + paddedAddress;
376
- }
377
- async buildTransaction(accept, wallet, rpcUrl) {
378
- if (!isEvmWallet(wallet)) {
379
- throw new Error("Invalid EVM wallet");
380
- }
381
- if (!wallet.address) {
382
- throw new Error("Wallet not connected");
383
- }
384
- if (accept.scheme === "exact-approval") {
385
- return this.buildApprovalTransaction(accept, wallet, rpcUrl);
386
- }
387
- if (accept.extra?.assetTransferMethod === "permit2") {
388
- return this.buildPermit2Transaction(accept, wallet, rpcUrl);
389
- }
390
- const { payTo, asset, extra } = accept;
391
- const amount = accept.amount ?? accept.maxAmountRequired;
392
- if (!amount) {
393
- throw new Error("Missing amount in payment requirements");
394
- }
395
- this.log("Building EVM transaction:", {
396
- from: wallet.address,
397
- to: payTo,
398
- amount,
399
- asset,
400
- network: accept.network
401
- });
402
- const chainId = this.getChainId(accept.network);
403
- const domain = {
404
- name: extra?.name ?? "USD Coin",
405
- version: extra?.version ?? "2",
406
- chainId: BigInt(chainId),
407
- verifyingContract: asset
408
- };
409
- const types = {
410
- TransferWithAuthorization: [
411
- { name: "from", type: "address" },
412
- { name: "to", type: "address" },
413
- { name: "value", type: "uint256" },
414
- { name: "validAfter", type: "uint256" },
415
- { name: "validBefore", type: "uint256" },
416
- { name: "nonce", type: "bytes32" }
417
- ]
418
- };
419
- const nonceBytes = new Uint8Array(32);
420
- (globalThis.crypto ?? (await import("crypto")).webcrypto).getRandomValues(nonceBytes);
421
- const nonce = "0x" + [...nonceBytes].map((b) => b.toString(16).padStart(2, "0")).join("");
422
- const now = Math.floor(Date.now() / 1e3);
423
- const authorization = {
424
- from: wallet.address,
425
- to: payTo,
426
- value: amount,
427
- // string
428
- validAfter: String(now - 600),
429
- // 10 minutes before (matching upstream)
430
- validBefore: String(now + (accept.maxTimeoutSeconds || 60)),
431
- nonce
432
- };
433
- const message = {
434
- from: wallet.address,
435
- to: payTo,
436
- value: BigInt(amount),
437
- validAfter: BigInt(now - 600),
438
- validBefore: BigInt(now + (accept.maxTimeoutSeconds || 60)),
439
- nonce
440
- };
441
- if (!wallet.signTypedData) {
442
- throw new Error("Wallet does not support signTypedData (EIP-712)");
443
- }
444
- const signature = await wallet.signTypedData({
445
- domain,
446
- types,
447
- primaryType: "TransferWithAuthorization",
448
- message
449
- });
450
- this.log("EIP-712 signature obtained");
451
- const payload = {
452
- authorization,
453
- signature
454
- };
455
- return {
456
- serialized: JSON.stringify(payload),
457
- signature
458
- };
459
- }
460
- // ===========================================================================
461
- // exact-approval: BSC and other chains without EIP-3009
462
- // ===========================================================================
463
- /**
464
- * Build a payment transaction for chains that use the approval-based scheme.
465
- * The facilitator's /supported response provides the EIP-712 domain and types
466
- * in accept.extra, so the client doesn't hardcode any contract addresses.
467
- */
468
- async buildApprovalTransaction(accept, wallet, rpcUrl) {
469
- const { payTo, asset, extra } = accept;
470
- const amount = accept.amount ?? accept.maxAmountRequired;
471
- if (!amount) {
472
- throw new Error("Missing amount in payment requirements");
473
- }
474
- const facilitatorContract = extra?.facilitatorContract;
475
- if (!facilitatorContract) {
476
- throw new Error(
477
- "exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this."
478
- );
479
- }
480
- if (!wallet.signTypedData) {
481
- throw new Error("Wallet does not support signTypedData (EIP-712)");
482
- }
483
- this.log("Building approval-based transaction:", {
484
- from: wallet.address,
485
- to: payTo,
486
- amount,
487
- asset,
488
- network: accept.network,
489
- facilitatorContract
490
- });
491
- const url = rpcUrl || this.getDefaultRpcUrl(accept.network);
492
- const fee = extra?.fee ?? "0";
493
- const totalNeeded = BigInt(amount) + BigInt(fee);
494
- const currentAllowance = await this.readAllowance(url, asset, wallet.address, facilitatorContract);
495
- if (currentAllowance < totalNeeded) {
496
- if (!wallet.sendTransaction) {
497
- throw new Error(
498
- "BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support."
499
- );
500
- }
501
- const approvalAmount = this.calculateApprovalAmount(amount, fee, extra?.approvalStrategy);
502
- this.log(`Approving ${approvalAmount} for ${facilitatorContract} (current allowance: ${currentAllowance})`);
503
- const approveTxHash = await wallet.sendTransaction({
504
- to: asset,
505
- data: this.encodeApprove(facilitatorContract, approvalAmount),
506
- value: 0n
507
- });
508
- this.log(`Approval tx sent: ${approveTxHash}`);
509
- await this.waitForReceipt(url, approveTxHash);
510
- this.log("Approval confirmed");
511
- } else {
512
- this.log("Sufficient allowance, skipping approval");
513
- }
514
- const nonceBytes = new Uint8Array(16);
515
- (globalThis.crypto ?? (await import("crypto")).webcrypto).getRandomValues(nonceBytes);
516
- const nonce = [...nonceBytes].reduce((acc, b) => acc * 256n + BigInt(b), 0n).toString();
517
- const paymentIdBytes = new Uint8Array(32);
518
- (globalThis.crypto ?? (await import("crypto")).webcrypto).getRandomValues(paymentIdBytes);
519
- const paymentId = "0x" + [...paymentIdBytes].map((b) => b.toString(16).padStart(2, "0")).join("");
520
- const now = Math.floor(Date.now() / 1e3);
521
- const deadline = now + (accept.maxTimeoutSeconds || 300);
522
- const eip712Domain = extra?.eip712Domain;
523
- const domain = eip712Domain ? {
524
- name: eip712Domain.name,
525
- version: eip712Domain.version,
526
- chainId: BigInt(eip712Domain.chainId),
527
- verifyingContract: eip712Domain.verifyingContract
528
- } : {
529
- name: "DexterBSCFacilitator",
530
- version: "1",
531
- chainId: BigInt(this.getChainId(accept.network)),
532
- verifyingContract: facilitatorContract
533
- };
534
- const types = extra?.eip712Types ?? {
535
- Payment: [
536
- { name: "from", type: "address" },
537
- { name: "to", type: "address" },
538
- { name: "token", type: "address" },
539
- { name: "amount", type: "uint256" },
540
- { name: "fee", type: "uint256" },
541
- { name: "nonce", type: "uint256" },
542
- { name: "deadline", type: "uint256" },
543
- { name: "paymentId", type: "bytes32" }
544
- ]
545
- };
546
- const message = {
547
- from: wallet.address,
548
- to: payTo,
549
- token: asset,
550
- amount: BigInt(amount),
551
- fee: BigInt(fee),
552
- nonce: BigInt(nonce),
553
- deadline: BigInt(deadline),
554
- paymentId
555
- };
556
- const signature = await wallet.signTypedData({
557
- domain,
558
- types,
559
- primaryType: "Payment",
560
- message
561
- });
562
- this.log("EIP-712 Payment signature obtained");
563
- const payload = {
564
- from: wallet.address,
565
- to: payTo,
566
- token: asset,
567
- amount,
568
- fee,
569
- nonce,
570
- deadline,
571
- paymentId,
572
- signature
573
- };
574
- return {
575
- serialized: JSON.stringify(payload),
576
- signature
577
- };
578
- }
579
- // ===========================================================================
580
- // Permit2: Universal ERC-20 payments via Uniswap's Permit2 contract
581
- // ===========================================================================
582
- /**
583
- * Build a Permit2 payment transaction. Used when the facilitator signals
584
- * assetTransferMethod: "permit2" in extra (e.g., BSC where EIP-3009 is unavailable).
585
- *
586
- * Flow:
587
- * 1. Check if token has approved the Permit2 contract. If not, approve(Permit2, maxUint256).
588
- * 2. Sign EIP-712 PermitWitnessTransferFrom against the Permit2 contract.
589
- * 3. Return { permit2Authorization, signature } payload for the facilitator.
590
- */
591
- async buildPermit2Transaction(accept, wallet, rpcUrl) {
592
- const { payTo, asset } = accept;
593
- const amount = accept.amount ?? accept.maxAmountRequired;
594
- if (!amount) {
595
- throw new Error("Missing amount in payment requirements");
596
- }
597
- if (!wallet.signTypedData) {
598
- throw new Error("Wallet does not support signTypedData (EIP-712)");
599
- }
600
- this.log("Building Permit2 transaction:", {
601
- from: wallet.address,
602
- to: payTo,
603
- amount,
604
- asset,
605
- network: accept.network
606
- });
607
- const url = rpcUrl || this.getDefaultRpcUrl(accept.network);
608
- const currentAllowance = await this.readAllowance(url, asset, wallet.address, PERMIT2_ADDRESS);
609
- let approvalExtension;
610
- if (currentAllowance < BigInt(amount)) {
611
- const approveData = this.encodeApprove(PERMIT2_ADDRESS, MAX_UINT256);
612
- if (wallet.signTransaction) {
613
- this.log(`Signing Permit2 approval for relay (current allowance: ${currentAllowance})`);
614
- const chainId2 = this.getChainId(accept.network);
615
- const gasPrice = await this.readGasPrice(url);
616
- const nonce2 = await this.readNonce(url, wallet.address);
617
- const signedTx = await wallet.signTransaction({
618
- to: asset,
619
- data: approveData,
620
- chainId: chainId2,
621
- gas: 50000n,
622
- // standard ERC-20 approve
623
- gasPrice,
624
- nonce: nonce2
625
- });
626
- approvalExtension = {
627
- erc20ApprovalGasSponsoring: {
628
- info: {
629
- from: wallet.address,
630
- asset,
631
- spender: PERMIT2_ADDRESS,
632
- amount: MAX_UINT256.toString(),
633
- signedTransaction: signedTx,
634
- version: "1"
635
- }
636
- }
637
- };
638
- this.log("Permit2 approval signed for facilitator relay");
639
- } else if (wallet.sendTransaction) {
640
- this.log(`Approving Permit2 directly (current allowance: ${currentAllowance})`);
641
- const approveTxHash = await wallet.sendTransaction({
642
- to: asset,
643
- data: approveData,
644
- value: 0n
645
- });
646
- this.log(`Permit2 approval tx sent: ${approveTxHash}`);
647
- await this.waitForReceipt(url, approveTxHash);
648
- this.log("Permit2 approval confirmed");
649
- } else {
650
- throw new Error(
651
- "Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support."
652
- );
653
- }
654
- } else {
655
- this.log("Sufficient Permit2 allowance, skipping approval");
656
- }
657
- const nonceBytes = new Uint8Array(32);
658
- (globalThis.crypto ?? (await import("crypto")).webcrypto).getRandomValues(nonceBytes);
659
- const nonce = [...nonceBytes].reduce((acc, b) => acc * 256n + BigInt(b), 0n);
660
- const now = Math.floor(Date.now() / 1e3);
661
- const validAfter = now - 600;
662
- const deadline = now + (accept.maxTimeoutSeconds || 300);
663
- const chainId = this.getChainId(accept.network);
664
- const domain = {
665
- name: "Permit2",
666
- chainId: BigInt(chainId),
667
- verifyingContract: PERMIT2_ADDRESS
668
- };
669
- const message = {
670
- permitted: {
671
- token: asset,
672
- amount: BigInt(amount)
673
- },
674
- spender: X402_EXACT_PERMIT2_PROXY,
675
- nonce,
676
- deadline: BigInt(deadline),
677
- witness: {
678
- to: payTo,
679
- validAfter: BigInt(validAfter)
680
- }
681
- };
682
- const signature = await wallet.signTypedData({
683
- domain,
684
- types: PERMIT2_WITNESS_TYPES,
685
- primaryType: "PermitWitnessTransferFrom",
686
- message
687
- });
688
- this.log("Permit2 PermitWitnessTransferFrom signature obtained");
689
- const payload = {
690
- signature,
691
- permit2Authorization: {
692
- from: wallet.address,
693
- permitted: {
694
- token: asset,
695
- amount
696
- },
697
- spender: X402_EXACT_PERMIT2_PROXY,
698
- nonce: nonce.toString(),
699
- deadline: String(deadline),
700
- witness: {
701
- to: payTo,
702
- validAfter: String(validAfter)
703
- }
704
- }
705
- };
706
- return {
707
- serialized: JSON.stringify(payload),
708
- signature,
709
- extensions: approvalExtension
710
- };
711
- }
712
- /**
713
- * Read ERC-20 allowance via raw eth_call (no viem dependency needed).
714
- */
715
- async readAllowance(rpcUrl, token, owner, spender) {
716
- const selector = "0xdd62ed3e";
717
- const paddedOwner = owner.slice(2).toLowerCase().padStart(64, "0");
718
- const paddedSpender = spender.slice(2).toLowerCase().padStart(64, "0");
719
- const data = selector + paddedOwner + paddedSpender;
720
- try {
721
- const response = await fetch(rpcUrl, {
722
- method: "POST",
723
- headers: { "Content-Type": "application/json" },
724
- body: JSON.stringify({
725
- jsonrpc: "2.0",
726
- id: 1,
727
- method: "eth_call",
728
- params: [{ to: token, data }, "latest"]
729
- })
730
- });
731
- const result = await response.json();
732
- if (result.error || !result.result || result.result === "0x") return 0n;
733
- return BigInt(result.result);
734
- } catch {
735
- return 0n;
736
- }
737
- }
738
- /**
739
- * Encode ERC-20 approve(address,uint256) calldata.
740
- */
741
- encodeApprove(spender, amount) {
742
- const selector = "0x095ea7b3";
743
- const paddedSpender = spender.slice(2).toLowerCase().padStart(64, "0");
744
- const paddedAmount = amount.toString(16).padStart(64, "0");
745
- return selector + paddedSpender + paddedAmount;
746
- }
747
- /**
748
- * Wait for a transaction receipt by polling eth_getTransactionReceipt.
749
- */
750
- async waitForReceipt(rpcUrl, txHash, timeoutMs = 3e4) {
751
- const start = Date.now();
752
- while (Date.now() - start < timeoutMs) {
753
- try {
754
- const response = await fetch(rpcUrl, {
755
- method: "POST",
756
- headers: { "Content-Type": "application/json" },
757
- body: JSON.stringify({
758
- jsonrpc: "2.0",
759
- id: 1,
760
- method: "eth_getTransactionReceipt",
761
- params: [txHash]
762
- })
763
- });
764
- const result = await response.json();
765
- if (result.result) {
766
- if (result.result.status === "0x0") {
767
- throw new Error(`Approval transaction reverted: ${txHash}`);
768
- }
769
- return;
770
- }
771
- } catch (err) {
772
- if (err instanceof Error && err.message.includes("reverted")) throw err;
773
- }
774
- await new Promise((r) => setTimeout(r, 2e3));
775
- }
776
- throw new Error(`Approval transaction receipt timeout after ${timeoutMs}ms: ${txHash}`);
777
- }
778
- /**
779
- * Read gas price via eth_gasPrice RPC call.
780
- */
781
- async readGasPrice(rpcUrl) {
782
- try {
783
- const response = await fetch(rpcUrl, {
784
- method: "POST",
785
- headers: { "Content-Type": "application/json" },
786
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_gasPrice", params: [] })
787
- });
788
- const result = await response.json();
789
- return result.result ? BigInt(result.result) : 50000000n;
790
- } catch {
791
- return 50000000n;
792
- }
793
- }
794
- /**
795
- * Read transaction count (nonce) via eth_getTransactionCount RPC call.
796
- */
797
- async readNonce(rpcUrl, address) {
798
- try {
799
- const response = await fetch(rpcUrl, {
800
- method: "POST",
801
- headers: { "Content-Type": "application/json" },
802
- body: JSON.stringify({
803
- jsonrpc: "2.0",
804
- id: 1,
805
- method: "eth_getTransactionCount",
806
- params: [address, "latest"]
807
- })
808
- });
809
- const result = await response.json();
810
- return result.result ? parseInt(result.result, 16) : 0;
811
- } catch {
812
- return 0;
813
- }
814
- }
815
- /**
816
- * Calculate how much to approve based on the facilitator's approval strategy.
817
- * Buffered approvals reduce the number of on-chain approval txs for micropayments.
818
- */
819
- calculateApprovalAmount(paymentAmount, fee, strategy) {
820
- const total = BigInt(paymentAmount) + BigInt(fee);
821
- if (!strategy || strategy.mode === "exact") {
822
- return total;
823
- }
824
- const multiple = BigInt(strategy.defaultMultiple ?? 10);
825
- const buffered = total * multiple;
826
- if (strategy.maxCapUsd) {
827
- const decimals = this.inferDecimals(paymentAmount);
828
- const maxCap = BigInt(Math.floor(strategy.maxCapUsd * Math.pow(10, decimals)));
829
- if (buffered > maxCap) return maxCap;
830
- }
831
- if (strategy.exactAboveUsd) {
832
- const decimals = this.inferDecimals(paymentAmount);
833
- const threshold = BigInt(Math.floor(strategy.exactAboveUsd * Math.pow(10, decimals)));
834
- if (BigInt(paymentAmount) > threshold) return total;
835
- }
836
- return buffered;
837
- }
838
- /**
839
- * Infer token decimals from payment amount magnitude.
840
- * BSC stablecoins use 18 decimals, all others use 6.
841
- * A $1 payment is 1000000 (6 dec) or 1000000000000000000 (18 dec).
842
- * If the amount has > 12 digits, it's almost certainly 18 decimals.
843
- */
844
- inferDecimals(amount) {
845
- return amount.length > 12 ? 18 : 6;
846
- }
847
- };
848
- function createEvmAdapter(config) {
849
- return new EvmAdapter(config);
850
- }
851
-
852
- // src/adapters/index.ts
853
- function isKnownUSDC(asset) {
854
- if (asset === "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v") return true;
855
- if (asset === "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU") return true;
856
- const lc = asset.toLowerCase();
857
- for (const addr of Object.values(USDC_ADDRESSES)) {
858
- if (addr.toLowerCase() === lc) return true;
859
- }
860
- for (const addr of Object.keys(BSC_STABLECOIN_ADDRESSES)) {
861
- if (addr.toLowerCase() === lc) return true;
862
- }
863
- return false;
864
- }
865
- function createDefaultAdapters(verbose = false) {
866
- return [
867
- createSolanaAdapter({ verbose }),
868
- createEvmAdapter({ verbose })
869
- ];
870
- }
871
- function findAdapter(adapters, network) {
872
- return adapters.find((adapter) => adapter.canHandle(network));
873
- }
874
- export {
875
- ARBITRUM_ONE,
876
- AVALANCHE,
877
- BASE_MAINNET,
878
- BASE_SEPOLIA,
879
- BSC_MAINNET,
880
- BSC_STABLECOIN_ADDRESSES,
881
- BSC_USDC,
882
- BSC_USDT,
883
- ETHEREUM_MAINNET,
884
- EvmAdapter,
885
- OPTIMISM,
886
- PERMIT2_ADDRESS,
887
- POLYGON,
888
- SKALE_BASE,
889
- SKALE_BASE_SEPOLIA,
890
- SOLANA_DEVNET,
891
- SOLANA_MAINNET,
892
- SOLANA_TESTNET,
893
- SolanaAdapter,
894
- USDC_ADDRESSES,
895
- X402_EXACT_PERMIT2_PROXY,
896
- createDefaultAdapters,
897
- createEvmAdapter,
898
- createSolanaAdapter,
899
- findAdapter,
900
- isEvmWallet,
901
- isKnownUSDC,
902
- isSolanaWallet
903
- };
1
+ import{PublicKey as P,Connection as nt,TransactionMessage as ct,VersionedTransaction as dt,ComputeBudgetProgram as rt}from"@solana/web3.js";import{getAssociatedTokenAddress as H,getAccount as pt,createTransferCheckedInstruction as ut,getMint as ft,TOKEN_PROGRAM_ID as ot,TOKEN_2022_PROGRAM_ID as W}from"@solana/spl-token";var U="solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",F="solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1",j="solana:4uhcVJyU9pJkvQyS88uRDiswHXSCkY3z",x={[U]:"https://api.dexter.cash/api/solana/rpc",[F]:"https://api.devnet.solana.com",[j]:"https://api.testnet.solana.com"},lt=12e3,mt=1;function k(c){if(!c||typeof c!="object")return!1;let t=c;return"publicKey"in t&&"signTransaction"in t&&typeof t.signTransaction=="function"}var K=class{name="Solana";networks=[U,F,j];config;log;constructor(t={}){this.config=t,this.log=t.verbose?console.log.bind(console,"[x402:solana]"):()=>{}}canHandle(t){return!!(this.networks.includes(t)||t==="solana"||t==="solana-devnet"||t==="solana-testnet"||t.startsWith("solana:"))}getDefaultRpcUrl(t){return this.config.rpcUrls?.[t]?this.config.rpcUrls[t]:x[t]?x[t]:t==="solana"?x[U]:t==="solana-devnet"?x[F]:t==="solana-testnet"?x[j]:x[U]}getAddress(t){return k(t)?t.publicKey?.toBase58()??null:null}isConnected(t){return k(t)?t.publicKey!==null:!1}async getBalance(t,e,a){if(!k(e)||!e.publicKey)return 0;let i=a||this.getDefaultRpcUrl(t.network),n=new nt(i,"confirmed"),s=new P(e.publicKey.toBase58()),r=new P(t.asset);try{let d=(await n.getAccountInfo(r,"confirmed"))?.owner.toBase58()===W.toBase58()?W:ot,p=await H(r,s,!1,d),g=await pt(n,p,void 0,d),u=t.extra?.decimals??6;return Number(g.amount)/Math.pow(10,u)}catch(o){if(o&&typeof o=="object"&&"name"in o&&(o.name==="TokenAccountNotFoundError"||o.name==="TokenInvalidAccountOwnerError"))return 0;throw o}}async buildTransaction(t,e,a){if(!k(e))throw new Error("Invalid Solana wallet");if(!e.publicKey)throw new Error("Wallet not connected");let i=a||this.getDefaultRpcUrl(t.network),n=new nt(i,"confirmed"),s=new P(e.publicKey.toBase58()),{payTo:r,asset:o,extra:d}=t,p=t.amount??t.maxAmountRequired;if(!p)throw new Error("Missing amount in payment requirements");if(!d?.feePayer)throw new Error("Missing feePayer in payment requirements");let g=new P(d.feePayer),u=new P(o),f=new P(r);this.log("Building transaction:",{from:s.toBase58(),to:r,amount:p,asset:o,feePayer:d.feePayer});let l=[];l.push(rt.setComputeUnitLimit({units:lt})),l.push(rt.setComputeUnitPrice({microLamports:mt}));let A=await n.getAccountInfo(u,"confirmed");if(!A)throw new Error(`Token mint ${o} not found`);let m=A.owner.toBase58()===W.toBase58()?W:ot,T=await ft(n,u,void 0,m);typeof d?.decimals=="number"&&T.decimals!==d.decimals&&this.log(`Decimals mismatch: requirements say ${d.decimals}, mint says ${T.decimals}`);let h=await H(u,s,!1,m),y=await H(u,f,!1,m);if(!await n.getAccountInfo(h,"confirmed"))throw new Error(`No token account found for ${o}. Please ensure you have USDC in your wallet.`);if(!await n.getAccountInfo(y,"confirmed"))throw new Error(`Seller token account not found. The seller (${r}) must have a USDC account.`);let _=BigInt(p);l.push(ut(h,u,y,s,_,T.decimals,[],m));let{blockhash:I}=await n.getLatestBlockhash("confirmed"),N=new ct({payerKey:g,recentBlockhash:I,instructions:l}).compileToV0Message(),E=new dt(N),C=await e.signTransaction(E);return this.log("Transaction signed successfully"),{serialized:Buffer.from(C.serialize()).toString("base64")}}};function X(c){return new K(c)}var M="0x000000000022D473030F116dDEE9F6B43aC78BA3",Y="0x402085c248EeA27D92E8b30b2C58ed07f9E20001",gt={PermitWitnessTransferFrom:[{name:"permitted",type:"TokenPermissions"},{name:"spender",type:"address"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"witness",type:"Witness"}],TokenPermissions:[{name:"token",type:"address"},{name:"amount",type:"uint256"}],Witness:[{name:"to",type:"address"},{name:"validAfter",type:"uint256"}]},at=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),v="eip155:8453",L="eip155:84532",B="eip155:42161",$="eip155:137",V="eip155:10",J="eip155:43114",D="eip155:56",z="eip155:1187947933",G="eip155:324705682",R="eip155:1",it="0x55d398326f99059fF775485246999027B3197955",Z="0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d",st={[D]:56,[v]:8453,[L]:84532,[B]:42161,[$]:137,[V]:10,[J]:43114,[z]:1187947933,[G]:324705682,[R]:1},b={[D]:"https://bsc-dataseed1.binance.org",[v]:"https://api.dexter.cash/api/base/rpc",[L]:"https://sepolia.base.org",[B]:"https://arb1.arbitrum.io/rpc",[$]:"https://polygon-rpc.com",[V]:"https://mainnet.optimism.io",[J]:"https://api.avax.network/ext/bc/C/rpc",[z]:"https://skale-base.skalenodes.com/v1/base",[G]:"https://base-sepolia-testnet.skalenodes.com/v1/jubilant-horrible-ancha",[R]:"https://eth.llamarpc.com"},Q={[D]:Z,[v]:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",[L]:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",[B]:"0xaf88d065e77c8cC2239327C5EDb3A432268e5831",[$]:"0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",[V]:"0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85",[J]:"0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E",[z]:"0x85889c8c714505E0c94b30fcfcF64fE3Ac8FCb20",[G]:"0x2e08028E3C4c2356572E096d8EF835cD5C6030bD",[R]:"0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"},tt={[it]:{symbol:"USDT",decimals:18},[Z]:{symbol:"USDC",decimals:18}};function O(c){if(!c||typeof c!="object")return!1;let t=c;return"address"in t&&typeof t.address=="string"&&t.address.startsWith("0x")}var q=class{name="EVM";networks=[D,v,L,R,B];config;log;constructor(t={}){this.config=t,this.log=t.verbose?console.log.bind(console,"[x402:evm]"):()=>{}}canHandle(t){return!!(this.networks.includes(t)||t==="base"||t==="bsc"||t==="ethereum"||t==="arbitrum"||t.startsWith("eip155:"))}getDefaultRpcUrl(t){return this.config.rpcUrls?.[t]?this.config.rpcUrls[t]:b[t]?b[t]:t==="base"?b[v]:t==="bsc"?b[D]:t==="ethereum"?b[R]:t==="arbitrum"?b[B]:b[v]}getAddress(t){return O(t)?t.address:null}isConnected(t){return O(t)?!!t.address:!1}getChainId(t){if(st[t])return st[t];if(t.startsWith("eip155:")){let e=t.split(":")[1];return parseInt(e,10)}return t==="base"?8453:t==="bsc"?56:t==="ethereum"?1:t==="arbitrum"?42161:8453}async getBalance(t,e,a){if(!O(e)||!e.address)return 0;let i=a||this.getDefaultRpcUrl(t.network);try{let n=this.encodeBalanceOf(e.address),s=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:t.asset,data:n},"latest"]})});if(!s.ok)throw new Error(`RPC request failed: ${s.status}`);let r=await s.json();if(r.error)throw new Error(`RPC error: ${JSON.stringify(r.error)}`);if(!r.result||r.result==="0x")return 0;let o=BigInt(r.result),d=t.extra?.decimals??6;return Number(o)/Math.pow(10,d)}catch(n){throw n}}encodeBalanceOf(t){let e="0x70a08231",a=t.slice(2).toLowerCase().padStart(64,"0");return e+a}async buildTransaction(t,e,a){if(!O(e))throw new Error("Invalid EVM wallet");if(!e.address)throw new Error("Wallet not connected");if(t.scheme==="exact-approval")return this.buildApprovalTransaction(t,e,a);if(t.extra?.assetTransferMethod==="permit2")return this.buildPermit2Transaction(t,e,a);let{payTo:i,asset:n,extra:s}=t,r=t.amount??t.maxAmountRequired;if(!r)throw new Error("Missing amount in payment requirements");this.log("Building EVM transaction:",{from:e.address,to:i,amount:r,asset:n,network:t.network});let o=this.getChainId(t.network),d={name:s?.name??"USD Coin",version:s?.version??"2",chainId:BigInt(o),verifyingContract:n},p={TransferWithAuthorization:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"value",type:"uint256"},{name:"validAfter",type:"uint256"},{name:"validBefore",type:"uint256"},{name:"nonce",type:"bytes32"}]},g=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(g);let u="0x"+[...g].map(h=>h.toString(16).padStart(2,"0")).join(""),f=Math.floor(Date.now()/1e3),l={from:e.address,to:i,value:r,validAfter:String(f-600),validBefore:String(f+(t.maxTimeoutSeconds||60)),nonce:u},A={from:e.address,to:i,value:BigInt(r),validAfter:BigInt(f-600),validBefore:BigInt(f+(t.maxTimeoutSeconds||60)),nonce:u};if(!e.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");let m=await e.signTypedData({domain:d,types:p,primaryType:"TransferWithAuthorization",message:A});return this.log("EIP-712 signature obtained"),{serialized:JSON.stringify({authorization:l,signature:m}),signature:m}}async buildApprovalTransaction(t,e,a){let{payTo:i,asset:n,extra:s}=t,r=t.amount??t.maxAmountRequired;if(!r)throw new Error("Missing amount in payment requirements");let o=s?.facilitatorContract;if(!o)throw new Error("exact-approval scheme requires extra.facilitatorContract from the facilitator. The /supported endpoint should provide this.");if(!e.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building approval-based transaction:",{from:e.address,to:i,amount:r,asset:n,network:t.network,facilitatorContract:o});let d=a||this.getDefaultRpcUrl(t.network),p=s?.fee??"0",g=BigInt(r)+BigInt(p),u=await this.readAllowance(d,n,e.address,o);if(u<g){if(!e.sendTransaction)throw new Error("BSC payments require a wallet that supports sendTransaction for the one-time token approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.");let E=this.calculateApprovalAmount(r,p,s?.approvalStrategy);this.log(`Approving ${E} for ${o} (current allowance: ${u})`);let C=await e.sendTransaction({to:n,data:this.encodeApprove(o,E),value:0n});this.log(`Approval tx sent: ${C}`),await this.waitForReceipt(d,C),this.log("Approval confirmed")}else this.log("Sufficient allowance, skipping approval");let f=new Uint8Array(16);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(f);let l=[...f].reduce((E,C)=>E*256n+BigInt(C),0n).toString(),A=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(A);let m="0x"+[...A].map(E=>E.toString(16).padStart(2,"0")).join(""),h=Math.floor(Date.now()/1e3)+(t.maxTimeoutSeconds||300),y=s?.eip712Domain,w=y?{name:y.name,version:y.version,chainId:BigInt(y.chainId),verifyingContract:y.verifyingContract}:{name:"DexterBSCFacilitator",version:"1",chainId:BigInt(this.getChainId(t.network)),verifyingContract:o},S=s?.eip712Types??{Payment:[{name:"from",type:"address"},{name:"to",type:"address"},{name:"token",type:"address"},{name:"amount",type:"uint256"},{name:"fee",type:"uint256"},{name:"nonce",type:"uint256"},{name:"deadline",type:"uint256"},{name:"paymentId",type:"bytes32"}]},_={from:e.address,to:i,token:n,amount:BigInt(r),fee:BigInt(p),nonce:BigInt(l),deadline:BigInt(h),paymentId:m},I=await e.signTypedData({domain:w,types:S,primaryType:"Payment",message:_});this.log("EIP-712 Payment signature obtained");let N={from:e.address,to:i,token:n,amount:r,fee:p,nonce:l,deadline:h,paymentId:m,signature:I};return{serialized:JSON.stringify(N),signature:I}}async buildPermit2Transaction(t,e,a){let{payTo:i,asset:n}=t,s=t.amount??t.maxAmountRequired;if(!s)throw new Error("Missing amount in payment requirements");if(!e.signTypedData)throw new Error("Wallet does not support signTypedData (EIP-712)");this.log("Building Permit2 transaction:",{from:e.address,to:i,amount:s,asset:n,network:t.network});let r=a||this.getDefaultRpcUrl(t.network),o=await this.readAllowance(r,n,e.address,M),d;if(o<BigInt(s)){let w=this.encodeApprove(M,at);if(e.signTransaction){this.log(`Signing Permit2 approval for relay (current allowance: ${o})`);let S=this.getChainId(t.network),_=await this.readGasPrice(r),I=await this.readNonce(r,e.address),N=await e.signTransaction({to:n,data:w,chainId:S,gas:50000n,gasPrice:_,nonce:I});d={erc20ApprovalGasSponsoring:{info:{from:e.address,asset:n,spender:M,amount:at.toString(),signedTransaction:N,version:"1"}}},this.log("Permit2 approval signed for facilitator relay")}else if(e.sendTransaction){this.log(`Approving Permit2 directly (current allowance: ${o})`);let S=await e.sendTransaction({to:n,data:w,value:0n});this.log(`Permit2 approval tx sent: ${S}`),await this.waitForReceipt(r,S),this.log("Permit2 approval confirmed")}else throw new Error("Permit2 payments require a wallet that supports signTransaction or sendTransaction for the one-time Permit2 approval. Use createEvmKeypairWallet() or a browser wallet with transaction support.")}else this.log("Sufficient Permit2 allowance, skipping approval");let p=new Uint8Array(32);(globalThis.crypto??(await import("crypto")).webcrypto).getRandomValues(p);let g=[...p].reduce((w,S)=>w*256n+BigInt(S),0n),u=Math.floor(Date.now()/1e3),f=u-600,l=u+(t.maxTimeoutSeconds||300),A=this.getChainId(t.network),m={name:"Permit2",chainId:BigInt(A),verifyingContract:M},T={permitted:{token:n,amount:BigInt(s)},spender:Y,nonce:g,deadline:BigInt(l),witness:{to:i,validAfter:BigInt(f)}},h=await e.signTypedData({domain:m,types:gt,primaryType:"PermitWitnessTransferFrom",message:T});this.log("Permit2 PermitWitnessTransferFrom signature obtained");let y={signature:h,permit2Authorization:{from:e.address,permitted:{token:n,amount:s},spender:Y,nonce:g.toString(),deadline:String(l),witness:{to:i,validAfter:String(f)}}};return{serialized:JSON.stringify(y),signature:h,extensions:d}}async readAllowance(t,e,a,i){let n="0xdd62ed3e",s=a.slice(2).toLowerCase().padStart(64,"0"),r=i.slice(2).toLowerCase().padStart(64,"0"),o=n+s+r;try{let p=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_call",params:[{to:e,data:o},"latest"]})})).json();return p.error||!p.result||p.result==="0x"?0n:BigInt(p.result)}catch{return 0n}}encodeApprove(t,e){let a="0x095ea7b3",i=t.slice(2).toLowerCase().padStart(64,"0"),n=e.toString(16).padStart(64,"0");return a+i+n}async waitForReceipt(t,e,a=3e4){let i=Date.now();for(;Date.now()-i<a;){try{let s=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionReceipt",params:[e]})})).json();if(s.result){if(s.result.status==="0x0")throw new Error(`Approval transaction reverted: ${e}`);return}}catch(n){if(n instanceof Error&&n.message.includes("reverted"))throw n}await new Promise(n=>setTimeout(n,2e3))}throw new Error(`Approval transaction receipt timeout after ${a}ms: ${e}`)}async readGasPrice(t){try{let a=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_gasPrice",params:[]})})).json();return a.result?BigInt(a.result):50000000n}catch{return 50000000n}}async readNonce(t,e){try{let i=await(await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"eth_getTransactionCount",params:[e,"latest"]})})).json();return i.result?parseInt(i.result,16):0}catch{return 0}}calculateApprovalAmount(t,e,a){let i=BigInt(t)+BigInt(e);if(!a||a.mode==="exact")return i;let n=BigInt(a.defaultMultiple??10),s=i*n;if(a.maxCapUsd){let r=this.inferDecimals(t),o=BigInt(Math.floor(a.maxCapUsd*Math.pow(10,r)));if(s>o)return o}if(a.exactAboveUsd){let r=this.inferDecimals(t),o=BigInt(Math.floor(a.exactAboveUsd*Math.pow(10,r)));if(BigInt(t)>o)return i}return s}inferDecimals(t){return t.length>12?18:6}};function et(c){return new q(c)}function bt(c){if(c==="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"||c==="4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU")return!0;let t=c.toLowerCase();for(let e of Object.values(Q))if(e.toLowerCase()===t)return!0;for(let e of Object.keys(tt))if(e.toLowerCase()===t)return!0;return!1}function vt(c=!1){return[X({verbose:c}),et({verbose:c})]}function It(c,t){return c.find(e=>e.canHandle(t))}export{B as ARBITRUM_ONE,J as AVALANCHE,v as BASE_MAINNET,L as BASE_SEPOLIA,D as BSC_MAINNET,tt as BSC_STABLECOIN_ADDRESSES,Z as BSC_USDC,it as BSC_USDT,R as ETHEREUM_MAINNET,q as EvmAdapter,V as OPTIMISM,M as PERMIT2_ADDRESS,$ as POLYGON,z as SKALE_BASE,G as SKALE_BASE_SEPOLIA,F as SOLANA_DEVNET,U as SOLANA_MAINNET,j as SOLANA_TESTNET,K as SolanaAdapter,Q as USDC_ADDRESSES,Y as X402_EXACT_PERMIT2_PROXY,vt as createDefaultAdapters,et as createEvmAdapter,X as createSolanaAdapter,It as findAdapter,O as isEvmWallet,bt as isKnownUSDC,k as isSolanaWallet};