@toon-protocol/client 4.0.0 → 4.1.1

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,107 @@ 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
- offer,
7206
+ // The facilitator checks the payload against the requirements' method,
7207
+ // so they name the one signed, which the caller may have overridden.
7208
+ offer: { ...offer, extra: { ...offer.extra, assetTransferMethod: method } },
6855
7209
  payload,
7210
+ ...extensions ? { extensions } : {},
6856
7211
  ...this.config.fetch ? { fetchImpl: this.config.fetch } : {}
6857
7212
  });
6858
7213
  } 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
- );
7214
+ const retry = mode === "auto" && extensions === void 0 && facilitatorCannotHandle(err) && await holdsEth(evm.wallet);
7215
+ if (!retry) throw explainPermit2(err, offer, evm);
7216
+ await depositDirectly(this.requireWallet(evm), payload, method);
7217
+ }
7218
+ }
7219
+ /**
7220
+ * One of x402's gas-sponsoring extensions for a Permit2 approval, when the
7221
+ * facilitator offers one this token can use; `undefined` otherwise.
7222
+ */
7223
+ async sponsoredApproval(evm, offer, facilitatorUrl, amount, payload) {
7224
+ let offered;
7225
+ try {
7226
+ offered = await facilitatorExtensions(facilitatorUrl, this.config.fetch);
7227
+ } catch {
7228
+ return void 0;
7229
+ }
7230
+ const chainId = evmChainIdOf(offer.network);
7231
+ if (offered.includes(EIP2612_GAS_SPONSORING) && offer.extra.name && offer.extra.version) {
7232
+ const nonce = await eip2612Nonce(this.requireReader(evm), offer.asset, evm.account.address);
7233
+ if (nonce !== void 0) {
7234
+ const auth = payload.deposit.authorization.permit2Authorization;
7235
+ return signEip2612GasSponsoring({
7236
+ payer: evm.account,
7237
+ token: offer.asset,
7238
+ name: offer.extra.name,
7239
+ version: offer.extra.version,
7240
+ chainId,
7241
+ nonce,
7242
+ amount,
7243
+ deadline: auth.deadline
7244
+ });
6865
7245
  }
6866
- throw err;
6867
7246
  }
7247
+ if (offered.includes(ERC20_APPROVAL_GAS_SPONSORING) && evm.wallet) {
7248
+ return signErc20ApprovalGasSponsoring({
7249
+ payerAddress: evm.account.address,
7250
+ wallet: evm.wallet,
7251
+ token: offer.asset,
7252
+ chainId
7253
+ });
7254
+ }
7255
+ return void 0;
7256
+ }
7257
+ /** Refuse, naming what would work, unless the payer holds ETH to pay `what` with. */
7258
+ async payOwnGas(evm, what, facilitatorUrl, network) {
7259
+ const wallet = evm.wallet;
7260
+ const eth = wallet ? await wallet.getBalance() : 0n;
7261
+ if (eth > 0n) return;
7262
+ if (network !== void 0 && facilitatorUrl === void 0 && evm.depositGas !== "self") {
7263
+ throw new ConfigError(
7264
+ `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.`
7265
+ );
7266
+ }
7267
+ throw new InsufficientBalanceError(
7268
+ `${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.")
7269
+ );
7270
+ }
7271
+ requireReader(evm) {
7272
+ if (!evm.reader) {
7273
+ throw new ConfigError("this payer has no EVM reader to read the token with");
7274
+ }
7275
+ return evm.reader;
7276
+ }
7277
+ requireWallet(evm) {
7278
+ if (!evm.wallet) {
7279
+ throw new ConfigError("paying a deposit's gas from this wallet needs its EVM chain access");
7280
+ }
7281
+ return evm.wallet;
6868
7282
  }
6869
7283
  // ─── Solana ──────────────────────────────────────────────────────────────
6870
7284
  /**
@@ -6975,7 +7389,7 @@ var BatchSettlementPayer = class {
6975
7389
  };
6976
7390
  function isDefinitiveRefusal(err) {
6977
7391
  if (err instanceof FacilitatorError)
6978
- return err.reason !== "unreadable_response";
7392
+ return err.reason !== "unreadable_response" && err.reason !== "settlement_pending";
6979
7393
  if (err instanceof SponsorRefusedError) return err.status !== 502;
6980
7394
  return false;
6981
7395
  }
@@ -6992,6 +7406,29 @@ async function currentSlot(rpc) {
6992
7406
  ]);
6993
7407
  return BigInt(slot);
6994
7408
  }
7409
+ function explainPermit2(err, offer, evm) {
7410
+ if (err instanceof FacilitatorError && err.reason.includes("permit2_allowance")) {
7411
+ return new FacilitatorError(
7412
+ `${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.`,
7413
+ err.reason,
7414
+ err
7415
+ );
7416
+ }
7417
+ return err;
7418
+ }
7419
+ function facilitatorCannotHandle(err) {
7420
+ if (err instanceof NetworkError) return true;
7421
+ if (!(err instanceof FacilitatorError)) return false;
7422
+ return err.reason === "unreadable_response" || err.reason.startsWith("unsupported_");
7423
+ }
7424
+ async function holdsEth(wallet) {
7425
+ if (!wallet) return false;
7426
+ try {
7427
+ return await wallet.getBalance() > 0n;
7428
+ } catch {
7429
+ return false;
7430
+ }
7431
+ }
6995
7432
 
6996
7433
  // src/channel/batch-settlement/manager.ts
6997
7434
  var KEY_PREFIX = "batch|";
@@ -7231,13 +7668,13 @@ var BatchChannelManager = class _BatchChannelManager {
7231
7668
  * holds at least that much; the payer then asks `claim-state` for the
7232
7669
  * connector's own figure (connector#1364), which replaces this floor.
7233
7670
  */
7234
- restoreWatermark(channelId, landed) {
7671
+ restoreWatermark(channelId, landed2) {
7235
7672
  if (this.store.load(channelId)) return;
7236
7673
  this.store.save(channelId, {
7237
7674
  nonce: 0,
7238
- cumulativeAmount: landed,
7239
- signedCeiling: landed,
7240
- provenFloor: landed
7675
+ cumulativeAmount: landed2,
7676
+ signedCeiling: landed2,
7677
+ provenFloor: landed2
7241
7678
  });
7242
7679
  }
7243
7680
  /**
@@ -7246,14 +7683,14 @@ var BatchChannelManager = class _BatchChannelManager {
7246
7683
  * connector has banked at least that much, so it is a floor, never a ceiling:
7247
7684
  * a figure below what this client counts moves nothing.
7248
7685
  */
7249
- recoverFromChain(channelId, landed) {
7686
+ recoverFromChain(channelId, landed2) {
7250
7687
  const entry = this.entry(channelId);
7251
- if (landed <= entry.cumulativeAmount) return;
7688
+ if (landed2 <= entry.cumulativeAmount) return;
7252
7689
  this.store.save(channelId, {
7253
7690
  ...entry,
7254
- cumulativeAmount: landed,
7255
- provenFloor: max(entry.provenFloor, landed),
7256
- signedCeiling: entry.signedCeiling === void 0 || landed > entry.signedCeiling ? landed : entry.signedCeiling
7691
+ cumulativeAmount: landed2,
7692
+ provenFloor: max(entry.provenFloor, landed2),
7693
+ signedCeiling: entry.signedCeiling === void 0 || landed2 > entry.signedCeiling ? landed2 : entry.signedCeiling
7257
7694
  });
7258
7695
  }
7259
7696
  /**
@@ -7633,8 +8070,14 @@ var ToonClient = class _ToonClient {
7633
8070
  evm: {
7634
8071
  account: chains.evm.account,
7635
8072
  ...init.config.facilitatorUrl !== void 0 ? { facilitatorUrl: init.config.facilitatorUrl } : {},
7636
- depositMethod: init.config.depositMethod,
7637
- reader: lazyEvmReader(init.config)
8073
+ ...init.config.depositMethod !== void 0 ? { depositMethod: init.config.depositMethod } : {},
8074
+ depositGas: init.config.depositGas,
8075
+ reader: lazyEvmReader(init.config),
8076
+ wallet: evmWalletAccess({
8077
+ rpcUrl: init.config.rpcUrls.evm,
8078
+ account: chains.evm.account,
8079
+ dispatcher: init.config.chainRpc?.evm.dispatcher
8080
+ })
7638
8081
  }
7639
8082
  } : {},
7640
8083
  ...chains.solana !== void 0 ? { solana: chains.solana } : {},
@@ -8065,7 +8508,7 @@ function lazyEvmReader(config) {
8065
8508
  let client;
8066
8509
  return {
8067
8510
  readContract: (params) => {
8068
- client ??= createPublicClient4({
8511
+ client ??= createPublicClient5({
8069
8512
  transport: rpcTransport(config.rpcUrls.evm, config.chainRpc?.evm.dispatcher)
8070
8513
  });
8071
8514
  return client.readContract(params);
@@ -8257,6 +8700,20 @@ export {
8257
8700
  fundWallet,
8258
8701
  EvmSigner,
8259
8702
  ClientWalletFacade,
8703
+ EIP2612_GAS_SPONSORING,
8704
+ ERC20_APPROVAL_GAS_SPONSORING,
8705
+ X402_BATCH_SETTLEMENT_DEPOSIT_ABI,
8706
+ evmWalletAccess,
8707
+ permit2Allowance,
8708
+ eip2612Nonce,
8709
+ facilitatorExtensions,
8710
+ signEip2612GasSponsoring,
8711
+ signErc20ApprovalGasSponsoring,
8712
+ approvePermit2,
8713
+ erc3009CollectorData,
8714
+ permit2CollectorData,
8715
+ eip2612PermitData,
8716
+ depositDirectly,
8260
8717
  settleDeposit,
8261
8718
  evmVoucherClaim,
8262
8719
  solanaVoucherClaim,
@@ -8274,4 +8731,4 @@ export {
8274
8731
  toEnvelopeRequest,
8275
8732
  ToonClient
8276
8733
  };
8277
- //# sourceMappingURL=chunk-CG3OXV74.js.map
8734
+ //# sourceMappingURL=chunk-SS3GGBUE.js.map