@toon-protocol/client 4.0.0 → 4.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.
@@ -619,6 +619,10 @@ function parseBatchSettlementTerms(raw) {
619
619
  if (!receiverAuthorizer) return void 0;
620
620
  const name = str(r["name"]);
621
621
  const version = str(r["version"]);
622
+ const method = r["assetTransferMethod"];
623
+ if (method !== void 0 && method !== "eip3009" && method !== "permit2")
624
+ return void 0;
625
+ const facilitator = httpUrl(r["facilitator"]);
622
626
  return {
623
627
  chain: "evm",
624
628
  network,
@@ -628,7 +632,9 @@ function parseBatchSettlementTerms(raw) {
628
632
  receiverAuthorizer,
629
633
  withdrawDelay,
630
634
  ...name !== void 0 ? { name } : {},
631
- ...version !== void 0 ? { version } : {}
635
+ ...version !== void 0 ? { version } : {},
636
+ ...method !== void 0 ? { assetTransferMethod: method } : {},
637
+ ...facilitator !== void 0 ? { facilitator } : {}
632
638
  }
633
639
  };
634
640
  }
@@ -681,6 +687,15 @@ function str(value) {
681
687
  function isPositiveInteger(value) {
682
688
  return typeof value === "number" && Number.isInteger(value) && value > 0;
683
689
  }
690
+ function httpUrl(value) {
691
+ if (typeof value !== "string") return void 0;
692
+ try {
693
+ const url = new URL(value);
694
+ return url.protocol === "https:" || url.protocol === "http:" ? value : void 0;
695
+ } catch {
696
+ return void 0;
697
+ }
698
+ }
684
699
 
685
700
  // src/connector/x402.ts
686
701
  function readString(obj, keys) {
@@ -3613,7 +3628,8 @@ function resolveConfig(config) {
3613
3628
  senderId: config.senderId,
3614
3629
  deposit,
3615
3630
  facilitatorUrl: config.facilitatorUrl,
3616
- depositMethod: config.depositMethod ?? "eip3009",
3631
+ depositMethod: config.depositMethod,
3632
+ depositGas: config.depositGas ?? "auto",
3617
3633
  connectorIsHiddenService,
3618
3634
  socksProxy,
3619
3635
  proxyRpc: config.proxyRpc ?? true,
@@ -5343,6 +5359,7 @@ var ClientChannelFacade = class {
5343
5359
  manager.markSettled(channel.channelId, now);
5344
5360
  return { channelId: channel.channelId };
5345
5361
  }
5362
+ await requireGas("ETH", clients.address, clients.nativeBalance(), "close");
5346
5363
  const started2 = await initiateEvmBatchWithdraw(clients, channel);
5347
5364
  manager.markClosing(channel.channelId, now, started2.finalizeAfter);
5348
5365
  return {
@@ -5363,6 +5380,12 @@ var ClientChannelFacade = class {
5363
5380
  manager.markClosing(channel.channelId, now, settleableAt);
5364
5381
  return { channelId: channel.channelId, settleableAt };
5365
5382
  }
5383
+ await requireGas(
5384
+ "SOL",
5385
+ base58Encode(solana.signer.publicKey),
5386
+ getLamports(solana.rpc, base58Encode(solana.signer.publicKey)),
5387
+ "close"
5388
+ );
5366
5389
  const started = await requestSvmBatchClose(
5367
5390
  solana.rpc,
5368
5391
  solana.signer,
@@ -5389,6 +5412,7 @@ var ClientChannelFacade = class {
5389
5412
  manager.markSettled(channel.channelId, now);
5390
5413
  return { channelId: channel.channelId };
5391
5414
  }
5415
+ await requireGas("ETH", clients.address, clients.nativeBalance(), "settle");
5392
5416
  const { transaction: transaction2 } = await finalizeEvmBatchWithdraw(
5393
5417
  clients,
5394
5418
  channel,
@@ -5407,6 +5431,12 @@ var ClientChannelFacade = class {
5407
5431
  }
5408
5432
  const sealedByConnector = state.status === "sealed";
5409
5433
  if (!due && !sealedByConnector) return void 0;
5434
+ await requireGas(
5435
+ "SOL",
5436
+ base58Encode(solana.signer.publicKey),
5437
+ getLamports(solana.rpc, base58Encode(solana.signer.publicKey)),
5438
+ "settle"
5439
+ );
5410
5440
  const { transaction } = await withdrawSvmBatchChannel(
5411
5441
  solana.rpc,
5412
5442
  solana.signer,
@@ -5457,7 +5487,9 @@ var ClientChannelFacade = class {
5457
5487
  const walletClient = createWalletClient({ account, chain, transport });
5458
5488
  return {
5459
5489
  publicClient,
5460
- walletClient
5490
+ walletClient,
5491
+ address: account.address,
5492
+ nativeBalance: () => publicClient.getBalance({ address: account.address })
5461
5493
  };
5462
5494
  }
5463
5495
  requireSolana() {
@@ -5472,6 +5504,12 @@ var ClientChannelFacade = class {
5472
5504
  return this.deps.now?.() ?? BigInt(Math.floor(Date.now() / 1e3));
5473
5505
  }
5474
5506
  };
5507
+ async function requireGas(gas, address, balance, step) {
5508
+ if (await balance > 0n) return;
5509
+ throw new InsufficientBalanceError(
5510
+ `leaving a channel needs ${gas} for the fee, and ${address} holds none. Opening and paying never did, so a wallet funded only with USDC has none yet: send it a little ${gas}, then run ${step} again.`
5511
+ );
5512
+ }
5475
5513
  function toHexKey(key2) {
5476
5514
  return `0x${Buffer.from(key2).toString("hex")}`;
5477
5515
  }
@@ -6248,7 +6286,287 @@ var ClientWalletFacade = class {
6248
6286
 
6249
6287
  // src/client/ToonClient.ts
6250
6288
  import { privateKeyToAccount as privateKeyToAccount3 } from "viem/accounts";
6251
- import { createPublicClient as createPublicClient4, toHex as toHex4 } from "viem";
6289
+ import { createPublicClient as createPublicClient5, toHex as toHex4 } from "viem";
6290
+
6291
+ // src/channel/batch-settlement/deposit-gas.ts
6292
+ import {
6293
+ createPublicClient as createPublicClient4,
6294
+ createWalletClient as createWalletClient3,
6295
+ defineChain as defineChain4,
6296
+ encodeAbiParameters as encodeAbiParameters2,
6297
+ encodeFunctionData,
6298
+ getAddress as getAddress2,
6299
+ maxUint256,
6300
+ parseErc6492Signature,
6301
+ parseSignature
6302
+ } from "viem";
6303
+ var EIP2612_GAS_SPONSORING = "eip2612GasSponsoring";
6304
+ var ERC20_APPROVAL_GAS_SPONSORING = "erc20ApprovalGasSponsoring";
6305
+ var ERC20_APPROVE_GAS_LIMIT = 70000n;
6306
+ var DEFAULT_MAX_FEE_PER_GAS = 1000000000n;
6307
+ var DEFAULT_MAX_PRIORITY_FEE_PER_GAS = 100000000n;
6308
+ var CHANNEL_CONFIG_COMPONENTS = [
6309
+ { name: "payer", type: "address" },
6310
+ { name: "payerAuthorizer", type: "address" },
6311
+ { name: "receiver", type: "address" },
6312
+ { name: "receiverAuthorizer", type: "address" },
6313
+ { name: "token", type: "address" },
6314
+ { name: "withdrawDelay", type: "uint40" },
6315
+ { name: "salt", type: "bytes32" }
6316
+ ];
6317
+ var X402_BATCH_SETTLEMENT_DEPOSIT_ABI = [
6318
+ {
6319
+ type: "function",
6320
+ name: "deposit",
6321
+ stateMutability: "nonpayable",
6322
+ inputs: [
6323
+ { name: "config", type: "tuple", components: CHANNEL_CONFIG_COMPONENTS },
6324
+ { name: "amount", type: "uint128" },
6325
+ { name: "collector", type: "address" },
6326
+ { name: "collectorData", type: "bytes" }
6327
+ ],
6328
+ outputs: []
6329
+ }
6330
+ ];
6331
+ var ERC20_PERMIT2_ABI = [
6332
+ {
6333
+ type: "function",
6334
+ name: "allowance",
6335
+ stateMutability: "view",
6336
+ inputs: [
6337
+ { name: "owner", type: "address" },
6338
+ { name: "spender", type: "address" }
6339
+ ],
6340
+ outputs: [{ type: "uint256" }]
6341
+ },
6342
+ {
6343
+ type: "function",
6344
+ name: "approve",
6345
+ stateMutability: "nonpayable",
6346
+ inputs: [
6347
+ { name: "spender", type: "address" },
6348
+ { name: "amount", type: "uint256" }
6349
+ ],
6350
+ outputs: [{ type: "bool" }]
6351
+ },
6352
+ {
6353
+ type: "function",
6354
+ name: "nonces",
6355
+ stateMutability: "view",
6356
+ inputs: [{ name: "owner", type: "address" }],
6357
+ outputs: [{ type: "uint256" }]
6358
+ }
6359
+ ];
6360
+ var EIP2612_PERMIT_TYPES = {
6361
+ Permit: [
6362
+ { name: "owner", type: "address" },
6363
+ { name: "spender", type: "address" },
6364
+ { name: "value", type: "uint256" },
6365
+ { name: "nonce", type: "uint256" },
6366
+ { name: "deadline", type: "uint256" }
6367
+ ]
6368
+ };
6369
+ function evmWalletAccess(params) {
6370
+ const { account } = params;
6371
+ const transport = rpcTransport(params.rpcUrl, params.dispatcher);
6372
+ const reader = createPublicClient4({ transport });
6373
+ let writer;
6374
+ const wallet = () => writer ??= reader.getChainId().then(
6375
+ (id) => createWalletClient3({
6376
+ account,
6377
+ transport,
6378
+ chain: defineChain4({
6379
+ id,
6380
+ name: `eip155:${id}`,
6381
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
6382
+ rpcUrls: { default: { http: [params.rpcUrl] } }
6383
+ })
6384
+ })
6385
+ );
6386
+ return {
6387
+ getBalance: () => reader.getBalance({ address: account.address }),
6388
+ getTransactionCount: () => reader.getTransactionCount({ address: account.address, blockTag: "pending" }),
6389
+ estimateFeesPerGas: () => reader.estimateFeesPerGas(),
6390
+ signTransaction: (tx) => account.signTransaction(tx),
6391
+ writeContract: async (q) => (await wallet()).writeContract(q),
6392
+ waitForTransactionReceipt: ({ hash }) => reader.waitForTransactionReceipt({ hash })
6393
+ };
6394
+ }
6395
+ async function permit2Allowance(reader, token, owner) {
6396
+ return await reader.readContract({
6397
+ address: getAddress2(token),
6398
+ abi: ERC20_PERMIT2_ABI,
6399
+ functionName: "allowance",
6400
+ args: [getAddress2(owner), PERMIT2_ADDRESS]
6401
+ });
6402
+ }
6403
+ async function eip2612Nonce(reader, token, owner) {
6404
+ try {
6405
+ return await reader.readContract({
6406
+ address: getAddress2(token),
6407
+ abi: ERC20_PERMIT2_ABI,
6408
+ functionName: "nonces",
6409
+ args: [getAddress2(owner)]
6410
+ });
6411
+ } catch {
6412
+ return void 0;
6413
+ }
6414
+ }
6415
+ async function facilitatorExtensions(facilitatorUrl, fetchImpl = fetch) {
6416
+ const url = `${facilitatorUrl.replace(/\/+$/, "")}/supported`;
6417
+ let body;
6418
+ try {
6419
+ const response = await fetchImpl(url);
6420
+ body = await response.json();
6421
+ } catch (err) {
6422
+ throw new NetworkError(
6423
+ `facilitator ${url} did not answer`,
6424
+ err instanceof Error ? err : void 0
6425
+ );
6426
+ }
6427
+ const extensions = body?.extensions;
6428
+ return Array.isArray(extensions) ? extensions.filter((e) => typeof e === "string") : [];
6429
+ }
6430
+ async function signEip2612GasSponsoring(params) {
6431
+ const owner = getAddress2(params.payer.address);
6432
+ const asset = getAddress2(params.token);
6433
+ const signature = await params.payer.signTypedData({
6434
+ domain: {
6435
+ name: params.name,
6436
+ version: params.version,
6437
+ chainId: params.chainId,
6438
+ verifyingContract: asset
6439
+ },
6440
+ types: EIP2612_PERMIT_TYPES,
6441
+ primaryType: "Permit",
6442
+ message: {
6443
+ owner,
6444
+ spender: PERMIT2_ADDRESS,
6445
+ value: params.amount,
6446
+ nonce: params.nonce,
6447
+ deadline: BigInt(params.deadline)
6448
+ }
6449
+ });
6450
+ return {
6451
+ [EIP2612_GAS_SPONSORING]: {
6452
+ info: {
6453
+ from: owner,
6454
+ asset,
6455
+ spender: PERMIT2_ADDRESS,
6456
+ amount: params.amount.toString(),
6457
+ nonce: params.nonce.toString(),
6458
+ deadline: params.deadline,
6459
+ signature,
6460
+ version: "1"
6461
+ }
6462
+ }
6463
+ };
6464
+ }
6465
+ async function signErc20ApprovalGasSponsoring(params) {
6466
+ const asset = getAddress2(params.token);
6467
+ let maxFeePerGas = DEFAULT_MAX_FEE_PER_GAS;
6468
+ let maxPriorityFeePerGas = DEFAULT_MAX_PRIORITY_FEE_PER_GAS;
6469
+ try {
6470
+ ({ maxFeePerGas, maxPriorityFeePerGas } = await params.wallet.estimateFeesPerGas());
6471
+ } catch {
6472
+ }
6473
+ const signedTransaction = await params.wallet.signTransaction({
6474
+ to: asset,
6475
+ data: encodeFunctionData({
6476
+ abi: ERC20_PERMIT2_ABI,
6477
+ functionName: "approve",
6478
+ args: [PERMIT2_ADDRESS, maxUint256]
6479
+ }),
6480
+ nonce: await params.wallet.getTransactionCount(),
6481
+ gas: ERC20_APPROVE_GAS_LIMIT,
6482
+ maxFeePerGas,
6483
+ maxPriorityFeePerGas,
6484
+ chainId: params.chainId,
6485
+ type: "eip1559"
6486
+ });
6487
+ return {
6488
+ [ERC20_APPROVAL_GAS_SPONSORING]: {
6489
+ info: {
6490
+ from: getAddress2(params.payerAddress),
6491
+ asset,
6492
+ spender: PERMIT2_ADDRESS,
6493
+ amount: maxUint256.toString(),
6494
+ signedTransaction,
6495
+ version: "1"
6496
+ }
6497
+ }
6498
+ };
6499
+ }
6500
+ async function approvePermit2(wallet, token) {
6501
+ const hash = await wallet.writeContract({
6502
+ address: getAddress2(token),
6503
+ abi: ERC20_PERMIT2_ABI,
6504
+ functionName: "approve",
6505
+ args: [PERMIT2_ADDRESS, maxUint256]
6506
+ });
6507
+ await landed(wallet, hash, "the Permit2 approval");
6508
+ return hash;
6509
+ }
6510
+ function erc3009CollectorData(payload) {
6511
+ const auth = payload.deposit.authorization.erc3009Authorization;
6512
+ const { signature } = parseErc6492Signature(auth.signature);
6513
+ return encodeAbiParameters2(
6514
+ [{ type: "uint256" }, { type: "uint256" }, { type: "uint256" }, { type: "bytes" }],
6515
+ [BigInt(auth.validAfter), BigInt(auth.validBefore), BigInt(auth.salt), signature]
6516
+ );
6517
+ }
6518
+ function permit2CollectorData(payload, eip2612PermitData2 = "0x") {
6519
+ const auth = payload.deposit.authorization.permit2Authorization;
6520
+ const { signature } = parseErc6492Signature(auth.signature);
6521
+ return encodeAbiParameters2(
6522
+ [{ type: "uint256" }, { type: "uint256" }, { type: "bytes" }, { type: "bytes" }],
6523
+ [BigInt(auth.nonce), BigInt(auth.deadline), signature, eip2612PermitData2]
6524
+ );
6525
+ }
6526
+ function eip2612PermitData(info) {
6527
+ const { v, r, s, yParity } = parseSignature(info.signature);
6528
+ return encodeAbiParameters2(
6529
+ [
6530
+ { type: "uint256" },
6531
+ { type: "uint256" },
6532
+ { type: "uint8" },
6533
+ { type: "bytes32" },
6534
+ { type: "bytes32" }
6535
+ ],
6536
+ [BigInt(info.amount), BigInt(info.deadline), Number(v ?? BigInt(27 + (yParity ?? 0))), r, s]
6537
+ );
6538
+ }
6539
+ async function depositDirectly(wallet, payload, method) {
6540
+ const config = payload.channelConfig;
6541
+ const collectorData = method === "eip3009" ? erc3009CollectorData(payload) : permit2CollectorData(payload);
6542
+ const hash = await wallet.writeContract({
6543
+ address: X402_BATCH_SETTLEMENT_ADDRESS,
6544
+ abi: X402_BATCH_SETTLEMENT_DEPOSIT_ABI,
6545
+ functionName: "deposit",
6546
+ args: [
6547
+ {
6548
+ payer: getAddress2(config.payer),
6549
+ payerAuthorizer: getAddress2(config.payerAuthorizer),
6550
+ receiver: getAddress2(config.receiver),
6551
+ receiverAuthorizer: getAddress2(config.receiverAuthorizer),
6552
+ token: getAddress2(config.token),
6553
+ withdrawDelay: config.withdrawDelay,
6554
+ salt: config.salt
6555
+ },
6556
+ BigInt(payload.deposit.amount),
6557
+ method === "eip3009" ? ERC3009_DEPOSIT_COLLECTOR_ADDRESS : PERMIT2_DEPOSIT_COLLECTOR_ADDRESS,
6558
+ collectorData
6559
+ ]
6560
+ });
6561
+ await landed(wallet, hash, "the deposit");
6562
+ return hash;
6563
+ }
6564
+ async function landed(wallet, hash, what) {
6565
+ const receipt = await wallet.waitForTransactionReceipt({ hash });
6566
+ if (receipt.status !== "success") {
6567
+ throw new TransactionOutcomeError(`${what} ${hash} reverted`, "evm", hash, "failed");
6568
+ }
6569
+ }
6252
6570
 
6253
6571
  // src/channel/batch-settlement/facilitator.ts
6254
6572
  async function settleDeposit(params) {
@@ -6270,7 +6588,12 @@ async function settleDeposit(params) {
6270
6588
  headers: { "content-type": "application/json" },
6271
6589
  body: JSON.stringify({
6272
6590
  x402Version: 2,
6273
- paymentPayload: { x402Version: 2, accepted: offer, payload },
6591
+ paymentPayload: {
6592
+ x402Version: 2,
6593
+ accepted: offer,
6594
+ payload,
6595
+ ...params.extensions ? { extensions: params.extensions } : {}
6596
+ },
6274
6597
  paymentRequirements: offer
6275
6598
  })
6276
6599
  });
@@ -6828,15 +7151,22 @@ var BatchSettlementPayer = class {
6828
7151
  }
6829
7152
  manager.confirmDeposit(channel.channelId, before + amount);
6830
7153
  }
7154
+ /**
7155
+ * Put a deposit of `amount`, carrying the voucher for `voucherAmount`, on
7156
+ * chain — through the facilitator, or from the payer's own ETH, as
7157
+ * `depositGas` and what is available decide (toon-client#695).
7158
+ */
6831
7159
  async evmSettle(evm, offer, channel, amount, voucherAmount) {
6832
7160
  if (channel.chain !== "evm") throw new Error("unreachable");
6833
- const facilitatorUrl = evm.facilitatorUrl ?? defaultFacilitatorFor(offer.network);
6834
- if (!facilitatorUrl) {
7161
+ const mode = evm.depositGas ?? "auto";
7162
+ const method = evm.depositMethod ?? offer.extra.assetTransferMethod ?? "eip3009";
7163
+ const facilitatorUrl = mode === "self" || evm.facilitatorUrl === "" ? void 0 : evm.facilitatorUrl ?? offer.extra.facilitator ?? defaultFacilitatorFor(offer.network);
7164
+ if (facilitatorUrl === void 0 && mode === "facilitator") {
6835
7165
  throw new ConfigError(
6836
- `depositing into a channel on ${offer.network} needs \`facilitatorUrl\`: the x402 facilitator that relays the deposit and pays its gas`
7166
+ `depositing into a channel on ${offer.network} needs \`facilitatorUrl\`: the x402 facilitator that relays the deposit and pays its gas. This connector names none.`
6837
7167
  );
6838
7168
  }
6839
- const build = evm.depositMethod === "permit2" ? buildPermit2Deposit : buildEip3009Deposit;
7169
+ const build = method === "permit2" ? buildPermit2Deposit : buildEip3009Deposit;
6840
7170
  const payload = await build({
6841
7171
  payer: evm.account,
6842
7172
  ...evm.voucherSigner ? { voucherSigner: evm.voucherSigner } : {},
@@ -6848,23 +7178,105 @@ var BatchSettlementPayer = class {
6848
7178
  amount,
6849
7179
  voucherAmount
6850
7180
  });
7181
+ let extensions;
7182
+ if (method === "permit2" && evm.reader) {
7183
+ const allowance = await permit2Allowance(evm.reader, offer.asset, evm.account.address);
7184
+ if (allowance < amount) {
7185
+ extensions = facilitatorUrl ? await this.sponsoredApproval(evm, offer, facilitatorUrl, amount, payload) : void 0;
7186
+ if (extensions === void 0) {
7187
+ if (mode === "facilitator") {
7188
+ throw new FacilitatorError(
7189
+ `${offer.asset} has no ERC-3009, so its deposit goes through Permit2, which needs a one-time approval from ${evm.account.address}; the facilitator sponsors none, and depositGas 'facilitator' will not spend this wallet's ETH on it.`,
7190
+ "permit2_allowance_required"
7191
+ );
7192
+ }
7193
+ await this.payOwnGas(evm, `a one-time Permit2 approval of ${offer.asset}`, facilitatorUrl);
7194
+ await approvePermit2(this.requireWallet(evm), offer.asset);
7195
+ }
7196
+ }
7197
+ }
7198
+ if (facilitatorUrl === void 0) {
7199
+ await this.payOwnGas(evm, "the deposit", facilitatorUrl, offer.network);
7200
+ await depositDirectly(this.requireWallet(evm), payload, method);
7201
+ return;
7202
+ }
6851
7203
  try {
6852
7204
  await settleDeposit({
6853
7205
  facilitatorUrl,
6854
7206
  offer,
6855
7207
  payload,
7208
+ ...extensions ? { extensions } : {},
6856
7209
  ...this.config.fetch ? { fetchImpl: this.config.fetch } : {}
6857
7210
  });
6858
7211
  } catch (err) {
6859
- if (err instanceof FacilitatorError && err.reason.includes("permit2_allowance")) {
6860
- throw new FacilitatorError(
6861
- `${offer.asset} has no Permit2 allowance from ${evm.account.address}. A Permit2 deposit needs a one-time \`approve(Permit2, \u2026)\` from the payer, which costs native gas unless the facilitator sponsors it; approve once, or use a token with ERC-3009 and \`depositMethod: "eip3009"\`.`,
6862
- err.reason,
6863
- err
6864
- );
7212
+ const retry = mode === "auto" && extensions === void 0 && facilitatorCannotHandle(err) && await holdsEth(evm.wallet);
7213
+ if (!retry) throw explainPermit2(err, offer, evm);
7214
+ await depositDirectly(this.requireWallet(evm), payload, method);
7215
+ }
7216
+ }
7217
+ /**
7218
+ * One of x402's gas-sponsoring extensions for a Permit2 approval, when the
7219
+ * facilitator offers one this token can use; `undefined` otherwise.
7220
+ */
7221
+ async sponsoredApproval(evm, offer, facilitatorUrl, amount, payload) {
7222
+ let offered;
7223
+ try {
7224
+ offered = await facilitatorExtensions(facilitatorUrl, this.config.fetch);
7225
+ } catch {
7226
+ return void 0;
7227
+ }
7228
+ const chainId = evmChainIdOf(offer.network);
7229
+ if (offered.includes(EIP2612_GAS_SPONSORING) && offer.extra.name && offer.extra.version) {
7230
+ const nonce = await eip2612Nonce(this.requireReader(evm), offer.asset, evm.account.address);
7231
+ if (nonce !== void 0) {
7232
+ const auth = payload.deposit.authorization.permit2Authorization;
7233
+ return signEip2612GasSponsoring({
7234
+ payer: evm.account,
7235
+ token: offer.asset,
7236
+ name: offer.extra.name,
7237
+ version: offer.extra.version,
7238
+ chainId,
7239
+ nonce,
7240
+ amount,
7241
+ deadline: auth.deadline
7242
+ });
6865
7243
  }
6866
- throw err;
6867
7244
  }
7245
+ if (offered.includes(ERC20_APPROVAL_GAS_SPONSORING) && evm.wallet) {
7246
+ return signErc20ApprovalGasSponsoring({
7247
+ payerAddress: evm.account.address,
7248
+ wallet: evm.wallet,
7249
+ token: offer.asset,
7250
+ chainId
7251
+ });
7252
+ }
7253
+ return void 0;
7254
+ }
7255
+ /** Refuse, naming what would work, unless the payer holds ETH to pay `what` with. */
7256
+ async payOwnGas(evm, what, facilitatorUrl, network) {
7257
+ const wallet = evm.wallet;
7258
+ const eth = wallet ? await wallet.getBalance() : 0n;
7259
+ if (eth > 0n) return;
7260
+ if (network !== void 0 && facilitatorUrl === void 0 && evm.depositGas !== "self") {
7261
+ throw new ConfigError(
7262
+ `depositing into a channel on ${network} needs either \`facilitatorUrl\` \u2014 an x402 facilitator that pays the gas, which this connector names none of \u2014 or ETH in ${evm.account.address} to deposit directly.`
7263
+ );
7264
+ }
7265
+ throw new InsufficientBalanceError(
7266
+ `${what} costs gas, ${facilitatorUrl ? "the facilitator does not sponsor it, " : ""}and ${evm.account.address} holds no ETH to pay for it. Send it a little ETH, or use a ` + (what.includes("Permit2") ? "facilitator that sponsors Permit2 approvals." : "facilitator.")
7267
+ );
7268
+ }
7269
+ requireReader(evm) {
7270
+ if (!evm.reader) {
7271
+ throw new ConfigError("this payer has no EVM reader to read the token with");
7272
+ }
7273
+ return evm.reader;
7274
+ }
7275
+ requireWallet(evm) {
7276
+ if (!evm.wallet) {
7277
+ throw new ConfigError("paying a deposit's gas from this wallet needs its EVM chain access");
7278
+ }
7279
+ return evm.wallet;
6868
7280
  }
6869
7281
  // ─── Solana ──────────────────────────────────────────────────────────────
6870
7282
  /**
@@ -6975,7 +7387,7 @@ var BatchSettlementPayer = class {
6975
7387
  };
6976
7388
  function isDefinitiveRefusal(err) {
6977
7389
  if (err instanceof FacilitatorError)
6978
- return err.reason !== "unreadable_response";
7390
+ return err.reason !== "unreadable_response" && err.reason !== "settlement_pending";
6979
7391
  if (err instanceof SponsorRefusedError) return err.status !== 502;
6980
7392
  return false;
6981
7393
  }
@@ -6992,6 +7404,29 @@ async function currentSlot(rpc) {
6992
7404
  ]);
6993
7405
  return BigInt(slot);
6994
7406
  }
7407
+ function explainPermit2(err, offer, evm) {
7408
+ if (err instanceof FacilitatorError && err.reason.includes("permit2_allowance")) {
7409
+ return new FacilitatorError(
7410
+ `${offer.asset} has no Permit2 allowance from ${evm.account.address}. A Permit2 deposit needs a one-time \`approve(Permit2, \u2026)\` from the payer, which costs native gas unless the facilitator sponsors it; hold a little ETH, use a facilitator that sponsors approvals, or use a token with ERC-3009.`,
7411
+ err.reason,
7412
+ err
7413
+ );
7414
+ }
7415
+ return err;
7416
+ }
7417
+ function facilitatorCannotHandle(err) {
7418
+ if (err instanceof NetworkError) return true;
7419
+ if (!(err instanceof FacilitatorError)) return false;
7420
+ return err.reason === "unreadable_response" || err.reason.startsWith("unsupported_");
7421
+ }
7422
+ async function holdsEth(wallet) {
7423
+ if (!wallet) return false;
7424
+ try {
7425
+ return await wallet.getBalance() > 0n;
7426
+ } catch {
7427
+ return false;
7428
+ }
7429
+ }
6995
7430
 
6996
7431
  // src/channel/batch-settlement/manager.ts
6997
7432
  var KEY_PREFIX = "batch|";
@@ -7231,13 +7666,13 @@ var BatchChannelManager = class _BatchChannelManager {
7231
7666
  * holds at least that much; the payer then asks `claim-state` for the
7232
7667
  * connector's own figure (connector#1364), which replaces this floor.
7233
7668
  */
7234
- restoreWatermark(channelId, landed) {
7669
+ restoreWatermark(channelId, landed2) {
7235
7670
  if (this.store.load(channelId)) return;
7236
7671
  this.store.save(channelId, {
7237
7672
  nonce: 0,
7238
- cumulativeAmount: landed,
7239
- signedCeiling: landed,
7240
- provenFloor: landed
7673
+ cumulativeAmount: landed2,
7674
+ signedCeiling: landed2,
7675
+ provenFloor: landed2
7241
7676
  });
7242
7677
  }
7243
7678
  /**
@@ -7246,14 +7681,14 @@ var BatchChannelManager = class _BatchChannelManager {
7246
7681
  * connector has banked at least that much, so it is a floor, never a ceiling:
7247
7682
  * a figure below what this client counts moves nothing.
7248
7683
  */
7249
- recoverFromChain(channelId, landed) {
7684
+ recoverFromChain(channelId, landed2) {
7250
7685
  const entry = this.entry(channelId);
7251
- if (landed <= entry.cumulativeAmount) return;
7686
+ if (landed2 <= entry.cumulativeAmount) return;
7252
7687
  this.store.save(channelId, {
7253
7688
  ...entry,
7254
- cumulativeAmount: landed,
7255
- provenFloor: max(entry.provenFloor, landed),
7256
- signedCeiling: entry.signedCeiling === void 0 || landed > entry.signedCeiling ? landed : entry.signedCeiling
7689
+ cumulativeAmount: landed2,
7690
+ provenFloor: max(entry.provenFloor, landed2),
7691
+ signedCeiling: entry.signedCeiling === void 0 || landed2 > entry.signedCeiling ? landed2 : entry.signedCeiling
7257
7692
  });
7258
7693
  }
7259
7694
  /**
@@ -7633,8 +8068,14 @@ var ToonClient = class _ToonClient {
7633
8068
  evm: {
7634
8069
  account: chains.evm.account,
7635
8070
  ...init.config.facilitatorUrl !== void 0 ? { facilitatorUrl: init.config.facilitatorUrl } : {},
7636
- depositMethod: init.config.depositMethod,
7637
- reader: lazyEvmReader(init.config)
8071
+ ...init.config.depositMethod !== void 0 ? { depositMethod: init.config.depositMethod } : {},
8072
+ depositGas: init.config.depositGas,
8073
+ reader: lazyEvmReader(init.config),
8074
+ wallet: evmWalletAccess({
8075
+ rpcUrl: init.config.rpcUrls.evm,
8076
+ account: chains.evm.account,
8077
+ dispatcher: init.config.chainRpc?.evm.dispatcher
8078
+ })
7638
8079
  }
7639
8080
  } : {},
7640
8081
  ...chains.solana !== void 0 ? { solana: chains.solana } : {},
@@ -8065,7 +8506,7 @@ function lazyEvmReader(config) {
8065
8506
  let client;
8066
8507
  return {
8067
8508
  readContract: (params) => {
8068
- client ??= createPublicClient4({
8509
+ client ??= createPublicClient5({
8069
8510
  transport: rpcTransport(config.rpcUrls.evm, config.chainRpc?.evm.dispatcher)
8070
8511
  });
8071
8512
  return client.readContract(params);
@@ -8257,6 +8698,20 @@ export {
8257
8698
  fundWallet,
8258
8699
  EvmSigner,
8259
8700
  ClientWalletFacade,
8701
+ EIP2612_GAS_SPONSORING,
8702
+ ERC20_APPROVAL_GAS_SPONSORING,
8703
+ X402_BATCH_SETTLEMENT_DEPOSIT_ABI,
8704
+ evmWalletAccess,
8705
+ permit2Allowance,
8706
+ eip2612Nonce,
8707
+ facilitatorExtensions,
8708
+ signEip2612GasSponsoring,
8709
+ signErc20ApprovalGasSponsoring,
8710
+ approvePermit2,
8711
+ erc3009CollectorData,
8712
+ permit2CollectorData,
8713
+ eip2612PermitData,
8714
+ depositDirectly,
8260
8715
  settleDeposit,
8261
8716
  evmVoucherClaim,
8262
8717
  solanaVoucherClaim,
@@ -8274,4 +8729,4 @@ export {
8274
8729
  toEnvelopeRequest,
8275
8730
  ToonClient
8276
8731
  };
8277
- //# sourceMappingURL=chunk-CG3OXV74.js.map
8732
+ //# sourceMappingURL=chunk-4WH4G747.js.map