@toon-protocol/client 3.2.0 → 3.3.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.
@@ -7,7 +7,7 @@ import {
7
7
  deriveFullIdentity,
8
8
  evmIdentityFromKey,
9
9
  isHiddenServiceUrl
10
- } from "./chunk-7MPONJW5.js";
10
+ } from "./chunk-O6KX7MHD.js";
11
11
  import {
12
12
  validateSocks5hUrl
13
13
  } from "./chunk-32MD3CXE.js";
@@ -181,6 +181,18 @@ function chainUnavailableMessage(wanted, offered, reason) {
181
181
  }
182
182
  return `This client holds no key for any chain this connector settles on (${list}). Supply a \`mnemonic\` \u2014 which derives both an EVM and a Solana key \u2014 or the raw key for one of those chains.`;
183
183
  }
184
+ var TransactionOutcomeError = class extends ToonClientError {
185
+ constructor(message, chain, txHash, outcome, cause) {
186
+ super(message, "TRANSACTION_OUTCOME", cause);
187
+ this.chain = chain;
188
+ this.txHash = txHash;
189
+ this.outcome = outcome;
190
+ this.name = "TransactionOutcomeError";
191
+ }
192
+ chain;
193
+ txHash;
194
+ outcome;
195
+ };
184
196
 
185
197
  // src/btp/protocol.ts
186
198
  var textEncoder = new TextEncoder();
@@ -854,9 +866,9 @@ var IsomorphicBtpClient = class {
854
866
  };
855
867
  this.ws.onclose = () => {
856
868
  this._isConnected = false;
857
- for (const [id, pending] of this.pendingRequests) {
858
- clearTimeout(pending.timeoutId);
859
- pending.reject(new BtpConnectionError("Connection closed"));
869
+ for (const [id, pending2] of this.pendingRequests) {
870
+ clearTimeout(pending2.timeoutId);
871
+ pending2.reject(new BtpConnectionError("Connection closed"));
860
872
  this.pendingRequests.delete(id);
861
873
  }
862
874
  this.failInFlightInbound("Connection closed before inbound request could be answered");
@@ -869,9 +881,9 @@ var IsomorphicBtpClient = class {
869
881
  this.ws.close();
870
882
  this.ws = null;
871
883
  }
872
- for (const [id, pending] of this.pendingRequests) {
873
- clearTimeout(pending.timeoutId);
874
- pending.reject(new BtpConnectionError("Disconnected"));
884
+ for (const [id, pending2] of this.pendingRequests) {
885
+ clearTimeout(pending2.timeoutId);
886
+ pending2.reject(new BtpConnectionError("Disconnected"));
875
887
  this.pendingRequests.delete(id);
876
888
  }
877
889
  this.failInFlightInbound("Disconnected before inbound request could be answered");
@@ -1027,27 +1039,27 @@ var IsomorphicBtpClient = class {
1027
1039
  const data = this.toUint8Array(raw);
1028
1040
  const message = parseBtpMessage(data);
1029
1041
  if (message.type === BTPMessageType.RESPONSE || message.type === BTPMessageType.ERROR) {
1030
- const pending = this.pendingRequests.get(message.requestId);
1031
- if (!pending) return;
1032
- clearTimeout(pending.timeoutId);
1042
+ const pending2 = this.pendingRequests.get(message.requestId);
1043
+ if (!pending2) return;
1044
+ clearTimeout(pending2.timeoutId);
1033
1045
  this.pendingRequests.delete(message.requestId);
1034
1046
  if (message.type === BTPMessageType.ERROR) {
1035
1047
  const errData = message.data;
1036
- pending.reject(
1048
+ pending2.reject(
1037
1049
  new BtpConnectionError(`BTP error: ${errData.code} ${errData.name}`)
1038
1050
  );
1039
1051
  return;
1040
1052
  }
1041
1053
  const msgData = message.data;
1042
1054
  if (!msgData.ilpPacket || msgData.ilpPacket.length === 0) {
1043
- pending.reject(
1055
+ pending2.reject(
1044
1056
  new BtpConnectionError(
1045
1057
  `BTP RESPONSE ${message.requestId} carried no ILP packet`
1046
1058
  )
1047
1059
  );
1048
1060
  return;
1049
1061
  }
1050
- pending.resolve({
1062
+ pending2.resolve({
1051
1063
  packet: deserializeIlpPacket(msgData.ilpPacket),
1052
1064
  // Everything riding beside the packet — `toon-accumulated-cost` on a
1053
1065
  // REJECT, `payment-required` on a greeting, `claim-ack` — handed to
@@ -3089,8 +3101,8 @@ var ChannelManager = class _ChannelManager {
3089
3101
  */
3090
3102
  async ensureChannel(connector, terms, options = {}) {
3091
3103
  const key = _ChannelManager.bindingKey(connector, terms);
3092
- const pending = this.pendingOpens.get(key);
3093
- if (pending) return pending;
3104
+ const pending2 = this.pendingOpens.get(key);
3105
+ if (pending2) return pending2;
3094
3106
  const existing = this.resolveChannel(connector, terms);
3095
3107
  if (existing) return existing;
3096
3108
  if (!this.channelClient) {
@@ -3653,19 +3665,72 @@ import { ed25519 as ed255192 } from "@noble/curves/ed25519.js";
3653
3665
 
3654
3666
  // src/transport/rpc.ts
3655
3667
  import { http } from "viem";
3668
+ var PROXIED_RPC_DEFAULTS = {
3669
+ timeout: 3e4,
3670
+ retryCount: 3,
3671
+ retryDelay: 500
3672
+ };
3656
3673
  function rpcTransport(url, dispatcher, options = {}) {
3657
- const { timeout, retryCount } = options;
3674
+ const { timeout, retryCount, retryDelay } = dispatcher === void 0 ? options : { ...PROXIED_RPC_DEFAULTS, ...definedOnly(options) };
3658
3675
  return http(url, {
3659
3676
  ...timeout !== void 0 ? { timeout } : {},
3660
3677
  ...retryCount !== void 0 ? { retryCount } : {},
3678
+ ...retryDelay !== void 0 ? { retryDelay } : {},
3661
3679
  ...dispatcher !== void 0 ? { fetchOptions: { dispatcher } } : {}
3662
3680
  });
3663
3681
  }
3682
+ function definedOnly(options) {
3683
+ return Object.fromEntries(
3684
+ Object.entries(options).filter(([, value]) => value !== void 0)
3685
+ );
3686
+ }
3664
3687
  function rpcFetch(dispatcher, fetchImpl = globalThis.fetch) {
3665
3688
  if (dispatcher === void 0) return fetchImpl;
3666
3689
  return ((input, init) => fetchImpl(input, { ...init, dispatcher }));
3667
3690
  }
3668
3691
 
3692
+ // src/channel/evm/receipt.ts
3693
+ import {
3694
+ WaitForTransactionReceiptTimeoutError
3695
+ } from "viem";
3696
+ var RECEIPT_TIMEOUT_MS = 18e4;
3697
+ var RETRY_DELAY_MS = 1e3;
3698
+ async function waitForReceipt(client, hash, options = {}) {
3699
+ const timeoutMs = options.timeoutMs ?? RECEIPT_TIMEOUT_MS;
3700
+ const retryDelayMs = options.retryDelayMs ?? RETRY_DELAY_MS;
3701
+ const deadline = Date.now() + timeoutMs;
3702
+ let lastError;
3703
+ for (; ; ) {
3704
+ const remaining = deadline - Date.now();
3705
+ if (remaining <= 0) {
3706
+ throw pending(hash, timeoutMs, lastError);
3707
+ }
3708
+ try {
3709
+ return await client.waitForTransactionReceipt({
3710
+ hash,
3711
+ timeout: remaining
3712
+ });
3713
+ } catch (err) {
3714
+ if (err instanceof WaitForTransactionReceiptTimeoutError) {
3715
+ throw pending(hash, timeoutMs, lastError);
3716
+ }
3717
+ lastError = err;
3718
+ }
3719
+ await new Promise(
3720
+ (resolve) => setTimeout(resolve, Math.min(retryDelayMs, deadline - Date.now()))
3721
+ );
3722
+ }
3723
+ }
3724
+ function pending(hash, timeoutMs, lastError) {
3725
+ return new TransactionOutcomeError(
3726
+ `Transaction ${hash} was sent, but no receipt was seen within ${timeoutMs}ms. It may still be mined. Look the hash up before sending anything that would repeat it.` + (lastError instanceof Error ? ` Last RPC error: ${lastError.message}` : ""),
3727
+ "evm",
3728
+ hash,
3729
+ "unknown",
3730
+ lastError instanceof Error ? lastError : void 0
3731
+ );
3732
+ }
3733
+
3669
3734
  // src/channel/evm/TokenNetworkClient.ts
3670
3735
  import {
3671
3736
  createPublicClient,
@@ -4084,9 +4149,7 @@ var TokenNetworkClient = class {
4084
4149
  chain: this.walletClient.chain,
4085
4150
  account: this.signer.account
4086
4151
  });
4087
- const receipt = await this.publicClient.waitForTransactionReceipt({
4088
- hash: openHash
4089
- });
4152
+ const receipt = await waitForReceipt(this.publicClient, openHash);
4090
4153
  const channelId = readOpenedChannelId(receipt);
4091
4154
  if (channelId === void 0) {
4092
4155
  throw new ConfigError(
@@ -4121,7 +4184,7 @@ var TokenNetworkClient = class {
4121
4184
  chain: this.walletClient.chain,
4122
4185
  account: this.signer.account
4123
4186
  });
4124
- await this.publicClient.waitForTransactionReceipt({ hash });
4187
+ await waitForReceipt(this.publicClient, hash);
4125
4188
  return { txHash: hash, depositTotal: newTotal };
4126
4189
  }
4127
4190
  /**
@@ -4139,7 +4202,7 @@ var TokenNetworkClient = class {
4139
4202
  chain: this.walletClient.chain,
4140
4203
  account: this.signer.account
4141
4204
  });
4142
- await this.publicClient.waitForTransactionReceipt({ hash });
4205
+ await waitForReceipt(this.publicClient, hash);
4143
4206
  const record = await this.readChannel(tokenNetwork, channelId);
4144
4207
  return {
4145
4208
  txHash: hash,
@@ -4162,7 +4225,7 @@ var TokenNetworkClient = class {
4162
4225
  chain: this.walletClient.chain,
4163
4226
  account: this.signer.account
4164
4227
  });
4165
- await this.publicClient.waitForTransactionReceipt({ hash });
4228
+ await waitForReceipt(this.publicClient, hash);
4166
4229
  return { txHash: hash };
4167
4230
  }
4168
4231
  // ─── Private ──────────────────────────────────────────────────────────────
@@ -4183,7 +4246,7 @@ var TokenNetworkClient = class {
4183
4246
  chain: this.walletClient.chain,
4184
4247
  account: this.signer.account
4185
4248
  });
4186
- await this.publicClient.waitForTransactionReceipt({ hash });
4249
+ await waitForReceipt(this.publicClient, hash);
4187
4250
  }
4188
4251
  /**
4189
4252
  * Poll until the RPC reports the just-opened channel (non-zero `participant1`).
@@ -4223,7 +4286,7 @@ var TokenNetworkClient = class {
4223
4286
  chain: this.walletClient.chain,
4224
4287
  account: this.signer.account
4225
4288
  });
4226
- await this.publicClient.waitForTransactionReceipt({ hash });
4289
+ await waitForReceipt(this.publicClient, hash);
4227
4290
  return;
4228
4291
  } catch (err) {
4229
4292
  if (attempt2 >= depositRetries || !isInvalidChannelStateRevert(err)) throw err;
@@ -4441,8 +4504,54 @@ function resolveRpcTarget(target) {
4441
4504
  if (typeof target === "string") return { url: target, fetchImpl: globalThis.fetch };
4442
4505
  return { url: target.url, fetchImpl: target.fetchImpl ?? globalThis.fetch };
4443
4506
  }
4507
+ var SOLANA_RPC_RETRY_DELAYS_MS = [250, 500, 1e3];
4508
+ var RETRYABLE_HTTP_STATUS = /* @__PURE__ */ new Set([403, 408, 413, 429, 500, 502, 503, 504]);
4509
+ var MAX_RETRY_AFTER_MS = 1e4;
4510
+ var SOLANA_RPC_TIMEOUT_MS = 3e4;
4511
+ var SolanaRpcTransportError = class extends NetworkError {
4512
+ constructor(method, attempts, mayHaveArrived, cause) {
4513
+ super(
4514
+ `Solana RPC [${method}] got no answer after ${attempts} tries: ` + (cause instanceof Error ? cause.message : String(cause)),
4515
+ cause instanceof Error ? cause : void 0
4516
+ );
4517
+ this.method = method;
4518
+ this.attempts = attempts;
4519
+ this.mayHaveArrived = mayHaveArrived;
4520
+ this.name = "SolanaRpcTransportError";
4521
+ }
4522
+ method;
4523
+ attempts;
4524
+ mayHaveArrived;
4525
+ };
4526
+ var SolanaRpcHttpError = class extends Error {
4527
+ constructor(status, retryAfterMs2) {
4528
+ super(`HTTP ${status}`);
4529
+ this.status = status;
4530
+ this.retryAfterMs = retryAfterMs2;
4531
+ this.name = "SolanaRpcHttpError";
4532
+ }
4533
+ status;
4534
+ retryAfterMs;
4535
+ };
4444
4536
  async function solanaRpc(rpcUrl, method, params = []) {
4445
4537
  const { url, fetchImpl } = resolveRpcTarget(rpcUrl);
4538
+ let mayHaveArrived = false;
4539
+ for (let attempt2 = 0; ; attempt2++) {
4540
+ try {
4541
+ return await solanaRpcOnce(url, fetchImpl, method, params);
4542
+ } catch (err) {
4543
+ if (err instanceof SolanaRpcError) throw err;
4544
+ mayHaveArrived ||= !failedBeforeSending(err);
4545
+ const retryable = !(err instanceof SolanaRpcHttpError) || RETRYABLE_HTTP_STATUS.has(err.status);
4546
+ const delay = err instanceof SolanaRpcHttpError && err.retryAfterMs !== void 0 ? err.retryAfterMs : SOLANA_RPC_RETRY_DELAYS_MS[attempt2];
4547
+ if (!retryable || attempt2 >= SOLANA_RPC_RETRY_DELAYS_MS.length || delay === void 0 || delay > MAX_RETRY_AFTER_MS) {
4548
+ throw new SolanaRpcTransportError(method, attempt2 + 1, mayHaveArrived, err);
4549
+ }
4550
+ await sleep3(delay);
4551
+ }
4552
+ }
4553
+ }
4554
+ async function solanaRpcOnce(url, fetchImpl, method, params) {
4446
4555
  const res = await fetchImpl(url, {
4447
4556
  method: "POST",
4448
4557
  headers: { "Content-Type": "application/json" },
@@ -4452,19 +4561,43 @@ async function solanaRpc(rpcUrl, method, params = []) {
4452
4561
  params,
4453
4562
  id: rpcIdCounter++
4454
4563
  }),
4455
- signal: AbortSignal.timeout(3e4)
4564
+ signal: AbortSignal.timeout(SOLANA_RPC_TIMEOUT_MS)
4456
4565
  });
4566
+ if (res.ok === false) {
4567
+ throw new SolanaRpcHttpError(res.status, retryAfterMs(res.headers?.get("retry-after")));
4568
+ }
4457
4569
  const json = await res.json();
4458
4570
  if (json.error) {
4459
4571
  throw new SolanaRpcError(method, json.error.code, json.error.message);
4460
4572
  }
4461
4573
  return json.result;
4462
4574
  }
4463
- async function getLatestBlockhash(rpcUrl) {
4575
+ function retryAfterMs(header) {
4576
+ if (header === null || header === void 0 || !/^\d+$/.test(header.trim())) return void 0;
4577
+ return Number.parseInt(header.trim(), 10) * 1e3;
4578
+ }
4579
+ function failedBeforeSending(err) {
4580
+ let e = err;
4581
+ for (let depth = 0; e instanceof Error && depth < 5; depth++) {
4582
+ const code = e.code;
4583
+ if (e.name === "SocksClientError") return true;
4584
+ if (code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EAI_AGAIN") return true;
4585
+ if (code === "UND_ERR_CONNECT_TIMEOUT") return true;
4586
+ e = e.cause;
4587
+ }
4588
+ return false;
4589
+ }
4590
+ function sleep3(ms) {
4591
+ return new Promise((resolve) => setTimeout(resolve, ms));
4592
+ }
4593
+ async function getLatestBlockhashWithExpiry(rpcUrl) {
4464
4594
  const result = await solanaRpc(rpcUrl, "getLatestBlockhash", [
4465
4595
  { commitment: "confirmed" }
4466
4596
  ]);
4467
- return result.value.blockhash;
4597
+ return {
4598
+ blockhash: result.value.blockhash,
4599
+ lastValidBlockHeight: result.value.lastValidBlockHeight
4600
+ };
4468
4601
  }
4469
4602
  async function getAccountInfo(rpcUrl, pubkey) {
4470
4603
  const result = await solanaRpc(rpcUrl, "getAccountInfo", [
@@ -4517,26 +4650,64 @@ async function assertOpenFunding(opts) {
4517
4650
  );
4518
4651
  }
4519
4652
  }
4520
- async function waitForConfirmation(rpcUrl, signature, timeoutMs = 3e4) {
4521
- const start = Date.now();
4522
- while (Date.now() - start < timeoutMs) {
4523
- const result = await solanaRpc(rpcUrl, "getSignatureStatuses", [
4524
- [signature]
4525
- ]);
4526
- const status = result.value[0];
4527
- if (status?.confirmationStatus === "confirmed" || status?.confirmationStatus === "finalized") {
4528
- if (status.err) {
4529
- throw new Error(
4530
- `Transaction ${signature} failed: ${JSON.stringify(status.err)}`
4653
+ var CONFIRM_TIMEOUT_MS = RECEIPT_TIMEOUT_MS;
4654
+ async function waitForConfirmation(rpcUrl, signature, options = {}) {
4655
+ const { lastValidBlockHeight, pollIntervalMs = 500 } = options;
4656
+ const timeoutMs = options.timeoutMs ?? (lastValidBlockHeight !== void 0 ? CONFIRM_TIMEOUT_MS : 3e4);
4657
+ const deadline = Date.now() + timeoutMs;
4658
+ let lastError;
4659
+ let failedPolls = 0;
4660
+ for (; ; ) {
4661
+ try {
4662
+ if (await isConfirmed(rpcUrl, signature)) return;
4663
+ if (lastValidBlockHeight !== void 0) {
4664
+ const height = Number(
4665
+ await solanaRpc(rpcUrl, "getBlockHeight", [{ commitment: "confirmed" }])
4531
4666
  );
4667
+ if (height > lastValidBlockHeight && !await isConfirmed(rpcUrl, signature)) {
4668
+ throw new TransactionOutcomeError(
4669
+ `Transaction ${signature} expired: block height ${height} is past its blockhash's last valid height ${lastValidBlockHeight}, and it never appeared, so it cannot land. It is safe to build and send it again.`,
4670
+ "solana",
4671
+ signature,
4672
+ "expired"
4673
+ );
4674
+ }
4532
4675
  }
4533
- return;
4676
+ } catch (err) {
4677
+ if (err instanceof TransactionOutcomeError) throw err;
4678
+ lastError = err;
4679
+ failedPolls += 1;
4680
+ }
4681
+ if (Date.now() >= deadline) {
4682
+ throw new TransactionOutcomeError(
4683
+ `Transaction ${signature} was not seen confirmed within ${timeoutMs}ms, and the RPC could not say whether it can still land. Look the signature up before sending anything that would repeat it.` + (lastError instanceof Error ? ` Last RPC error: ${lastError.message}` : ""),
4684
+ "solana",
4685
+ signature,
4686
+ "unknown",
4687
+ lastError instanceof Error ? lastError : void 0
4688
+ );
4534
4689
  }
4535
- await new Promise((r) => setTimeout(r, 500));
4690
+ await sleep3(pollIntervalMs * 2 ** Math.min(failedPolls, 3));
4536
4691
  }
4537
- throw new Error(
4538
- `Transaction ${signature} not confirmed within ${timeoutMs}ms`
4539
- );
4692
+ }
4693
+ async function isConfirmed(rpcUrl, signature) {
4694
+ const result = await solanaRpc(rpcUrl, "getSignatureStatuses", [[signature]]);
4695
+ const status = result.value[0];
4696
+ if (status?.confirmationStatus !== "confirmed" && status?.confirmationStatus !== "finalized") {
4697
+ return false;
4698
+ }
4699
+ if (status.err) {
4700
+ throw new TransactionOutcomeError(
4701
+ `Transaction ${signature} failed: ${JSON.stringify(status.err)}`,
4702
+ "solana",
4703
+ signature,
4704
+ "failed"
4705
+ );
4706
+ }
4707
+ return true;
4708
+ }
4709
+ function isAlreadyProcessed(err) {
4710
+ return /already been processed|AlreadyProcessed/i.test(err.rpcMessage);
4540
4711
  }
4541
4712
  function compactU16Size(value) {
4542
4713
  if (value > 65535) {
@@ -4557,8 +4728,8 @@ function writeCompactU16(buf, offset, value) {
4557
4728
  }
4558
4729
  return offset;
4559
4730
  }
4560
- async function buildAndSendTransaction(rpcUrl, feePayer, instructions, additionalSigners = []) {
4561
- const blockhash = await getLatestBlockhash(rpcUrl);
4731
+ async function buildAndSendTransaction(rpcUrl, feePayer, instructions, additionalSigners = [], confirmation = {}) {
4732
+ const { blockhash, lastValidBlockHeight } = await getLatestBlockhashWithExpiry(rpcUrl);
4562
4733
  const feePayerPubkey = base58Encode(feePayer.publicKey);
4563
4734
  const accountMap = /* @__PURE__ */ new Map();
4564
4735
  accountMap.set(feePayerPubkey, {
@@ -4657,15 +4828,27 @@ async function buildAndSendTransaction(rpcUrl, feePayer, instructions, additiona
4657
4828
  }
4658
4829
  tx.set(finalMessage, txOffset);
4659
4830
  const txBase64 = Buffer.from(tx).toString("base64");
4660
- const txSig = await solanaRpc(rpcUrl, "sendTransaction", [
4661
- txBase64,
4662
- {
4663
- encoding: "base64",
4664
- skipPreflight: false,
4665
- preflightCommitment: "confirmed"
4666
- }
4667
- ]);
4668
- await waitForConfirmation(rpcUrl, txSig);
4831
+ let txSig;
4832
+ try {
4833
+ txSig = await solanaRpc(rpcUrl, "sendTransaction", [
4834
+ txBase64,
4835
+ {
4836
+ encoding: "base64",
4837
+ skipPreflight: false,
4838
+ preflightCommitment: "confirmed"
4839
+ }
4840
+ ]);
4841
+ } catch (err) {
4842
+ const alreadyOnChain = err instanceof SolanaRpcError && isAlreadyProcessed(err);
4843
+ const answerLost = err instanceof SolanaRpcTransportError && err.mayHaveArrived;
4844
+ if (!alreadyOnChain && !answerLost) throw err;
4845
+ const firstSignature = compactU16Size(signatures.length);
4846
+ txSig = base58Encode(tx.subarray(firstSignature, firstSignature + 64));
4847
+ }
4848
+ await waitForConfirmation(rpcUrl, txSig, {
4849
+ ...confirmation,
4850
+ ...lastValidBlockHeight !== void 0 ? { lastValidBlockHeight } : {}
4851
+ });
4669
4852
  return txSig;
4670
4853
  }
4671
4854
  var STATE_MAP2 = ["opened", "closed", "settled"];
@@ -6413,7 +6596,7 @@ function resolveConfig(config) {
6413
6596
  connectorIsHiddenService,
6414
6597
  socksProxy,
6415
6598
  proxyRpc: config.proxyRpc ?? true,
6416
- rpcDispatcher: void 0,
6599
+ chainRpc: void 0,
6417
6600
  settlementTimeout,
6418
6601
  autoOpenChannel: config.autoOpenChannel ?? true,
6419
6602
  timeoutMs,
@@ -6474,11 +6657,6 @@ function resolveSocksProxy(socksProxy, connector, connectorIsHiddenService) {
6474
6657
  `connector ${JSON.stringify(connector)} is a hidden service, which is reachable only through a SOCKS5h proxy. Set \`socksProxy\` to a running Anyone Protocol \`anon\` daemon (e.g. "socks5h://127.0.0.1:9050"), or use the \`toon\` CLI, which can start one for you.`
6475
6658
  );
6476
6659
  }
6477
- if (!connectorIsHiddenService) {
6478
- throw new ConfigError(
6479
- `socksProxy is set, but connector ${JSON.stringify(connector)} is a clearnet address, so nothing would ride the proxy. Point \`connector\` at the node's .anyone address, or drop \`socksProxy\`.`
6480
- );
6481
- }
6482
6660
  try {
6483
6661
  validateSocks5hUrl(socksProxy);
6484
6662
  } catch (error) {
@@ -6900,20 +7078,22 @@ function parseEvmChainId2(chainKey) {
6900
7078
  }
6901
7079
  var RPC_TIMEOUT_ENV = "TOON_WALLET_RPC_TIMEOUT_MS";
6902
7080
  var DEFAULT_RPC_TIMEOUT_MS = 8e3;
6903
- function rpcTimeoutMs() {
7081
+ var DEFAULT_PROXIED_RPC_TIMEOUT_MS = PROXIED_RPC_DEFAULTS.timeout;
7082
+ function rpcTimeoutMs(proxied = false) {
6904
7083
  const raw = typeof process !== "undefined" ? process.env?.[RPC_TIMEOUT_ENV] : void 0;
6905
7084
  const n = raw === void 0 || raw === "" ? NaN : Number(raw);
6906
- return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;
7085
+ if (Number.isFinite(n) && n >= 0) return n;
7086
+ return proxied ? DEFAULT_PROXIED_RPC_TIMEOUT_MS : DEFAULT_RPC_TIMEOUT_MS;
6907
7087
  }
6908
- function rpcAbortSignal() {
6909
- const ms = rpcTimeoutMs();
7088
+ function rpcAbortSignal(proxied = false) {
7089
+ const ms = rpcTimeoutMs(proxied);
6910
7090
  return ms > 0 ? AbortSignal.timeout(ms) : void 0;
6911
7091
  }
6912
7092
  async function readEvmTokenBalance(opts) {
6913
7093
  const chainId = parseEvmChainId2(opts.chainKey);
6914
7094
  const client = createPublicClient2({
6915
7095
  transport: rpcTransport(opts.rpcUrl, opts.rpcDispatcher, {
6916
- ...rpcTimeoutMs() ? { timeout: rpcTimeoutMs() } : {},
7096
+ ...rpcTimeoutMs(opts.rpcDispatcher !== void 0) ? { timeout: rpcTimeoutMs(opts.rpcDispatcher !== void 0) } : {},
6917
7097
  retryCount: 1
6918
7098
  }),
6919
7099
  chain: defineChain2({
@@ -6939,7 +7119,7 @@ async function readEvmNativeBalance(opts) {
6939
7119
  const chainId = parseEvmChainId2(opts.chainKey);
6940
7120
  const client = createPublicClient2({
6941
7121
  transport: rpcTransport(opts.rpcUrl, opts.rpcDispatcher, {
6942
- ...rpcTimeoutMs() ? { timeout: rpcTimeoutMs() } : {},
7122
+ ...rpcTimeoutMs(opts.rpcDispatcher !== void 0) ? { timeout: rpcTimeoutMs(opts.rpcDispatcher !== void 0) } : {},
6943
7123
  retryCount: 1
6944
7124
  }),
6945
7125
  chain: defineChain2({
@@ -6963,7 +7143,7 @@ async function readSolanaNativeBalance(opts) {
6963
7143
  method: "getBalance",
6964
7144
  params: [opts.owner, { commitment: "confirmed" }]
6965
7145
  }),
6966
- signal: rpcAbortSignal()
7146
+ signal: rpcAbortSignal(opts.proxied)
6967
7147
  });
6968
7148
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
6969
7149
  const json = await res.json();
@@ -6982,7 +7162,7 @@ async function readSolanaTokenBalance(opts) {
6982
7162
  method: "getTokenAccountsByOwner",
6983
7163
  params: [opts.owner, { mint: opts.mint }, { encoding: "jsonParsed", commitment: "confirmed" }]
6984
7164
  }),
6985
- signal: rpcAbortSignal()
7165
+ signal: rpcAbortSignal(opts.proxied)
6986
7166
  });
6987
7167
  if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);
6988
7168
  const json = await res.json();
@@ -7022,7 +7202,7 @@ function finalizeChain(out, errors) {
7022
7202
  if (out.native === void 0 && out.tokens.length === 0) out.unreadable = true;
7023
7203
  }
7024
7204
  async function readWalletBalances(sources) {
7025
- const { fetchImpl } = sources;
7205
+ const { fetchImpl, solanaProxied: proxied } = sources;
7026
7206
  const tasks = [];
7027
7207
  if (sources.evm) {
7028
7208
  const { chainKey, rpcUrl, owner, tokenAddress, rpcDispatcher } = sources.evm;
@@ -7048,8 +7228,8 @@ async function readWalletBalances(sources) {
7048
7228
  const out = { chain: "solana", chainKey, address: owner, tokens: [] };
7049
7229
  const errors = [];
7050
7230
  const [nativeR, tokenR] = await Promise.allSettled([
7051
- readSolanaNativeBalance({ rpcUrl, owner, fetchImpl }),
7052
- tokenMint ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl }) : Promise.resolve(void 0)
7231
+ readSolanaNativeBalance({ rpcUrl, owner, fetchImpl, proxied }),
7232
+ tokenMint ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl, proxied }) : Promise.resolve(void 0)
7053
7233
  ]);
7054
7234
  foldNative(out, nativeR, errors);
7055
7235
  if (tokenR.status === "fulfilled" && tokenR.value && tokenR.value.asset === void 0) {
@@ -7188,9 +7368,7 @@ async function sendEvmTransfer(cfg, params, amount) {
7188
7368
  const readDest2 = () => publicClient.getBalance({ address: to });
7189
7369
  const before2 = await readDest2();
7190
7370
  const txHash2 = await walletClient.sendTransaction({ to, value: amount });
7191
- const receipt2 = await publicClient.waitForTransactionReceipt({
7192
- hash: txHash2
7193
- });
7371
+ const receipt2 = await waitForReceipt(publicClient, txHash2);
7194
7372
  if (receipt2.status === "reverted") {
7195
7373
  throw new TransferNotDeliveredError(
7196
7374
  `EVM native transfer ${txHash2} reverted on-chain \u2014 no funds reached ${to}.`
@@ -7237,9 +7415,7 @@ async function sendEvmTransfer(cfg, params, amount) {
7237
7415
  functionName: "transfer",
7238
7416
  args: [to, amount]
7239
7417
  });
7240
- const receipt = await publicClient.waitForTransactionReceipt({
7241
- hash: txHash
7242
- });
7418
+ const receipt = await waitForReceipt(publicClient, txHash);
7243
7419
  if (receipt.status === "reverted") {
7244
7420
  throw new TransferNotDeliveredError(
7245
7421
  `EVM token transfer ${txHash} reverted on-chain \u2014 no funds reached ${to}.`
@@ -7472,7 +7648,10 @@ async function fundWallet(faucetUrl, address, chain, options = {}) {
7472
7648
  // src/client/wallet-facade.ts
7473
7649
  function solanaRpcFetch(config) {
7474
7650
  if (config.socksProxy === void 0) return config.fetch;
7475
- return config.rpcDispatcher !== void 0 ? config.fetch : globalThis.fetch;
7651
+ return config.chainRpc?.solana.fetch ?? globalThis.fetch;
7652
+ }
7653
+ function evmRpcDispatcher(config) {
7654
+ return config.chainRpc !== void 0 ? { rpcDispatcher: config.chainRpc.evm.dispatcher } : {};
7476
7655
  }
7477
7656
  var ClientWalletFacade = class {
7478
7657
  deps;
@@ -7493,7 +7672,8 @@ var ClientWalletFacade = class {
7493
7672
  const settlements = await this.settlements();
7494
7673
  const wanted = chain !== void 0 ? [chain] : ["evm", "solana"];
7495
7674
  const sources = {
7496
- fetchImpl: solanaRpcFetch(config)
7675
+ fetchImpl: solanaRpcFetch(config),
7676
+ ...config.chainRpc !== void 0 ? { solanaProxied: true } : {}
7497
7677
  };
7498
7678
  for (const kind of wanted) {
7499
7679
  const entry = settlements.get(kind);
@@ -7502,7 +7682,7 @@ var ClientWalletFacade = class {
7502
7682
  chainKey: entry?.chain ?? "evm",
7503
7683
  rpcUrl: config.rpcUrls.evm,
7504
7684
  owner: config.identity.evm.address,
7505
- ...config.rpcDispatcher !== void 0 ? { rpcDispatcher: config.rpcDispatcher } : {},
7685
+ ...evmRpcDispatcher(config),
7506
7686
  ...entry?.tokenAddress ? { tokenAddress: entry.tokenAddress } : {}
7507
7687
  };
7508
7688
  }
@@ -7543,14 +7723,14 @@ var ClientWalletFacade = class {
7543
7723
  chainKey: entry?.kind === "evm" ? entry.chain : "evm",
7544
7724
  rpcUrl: config.rpcUrls.evm,
7545
7725
  signer: this.signer(),
7546
- ...config.rpcDispatcher !== void 0 ? { rpcDispatcher: config.rpcDispatcher } : {},
7726
+ ...evmRpcDispatcher(config),
7547
7727
  ...entry?.tokenAddress ? { tokenAddress: entry.tokenAddress } : {}
7548
7728
  }
7549
7729
  } : {},
7550
7730
  ...config.identity.solana ? {
7551
7731
  solana: {
7552
7732
  rpcUrl: config.rpcUrls.solana,
7553
- ...config.rpcDispatcher !== void 0 ? { rpcFetch: solanaRpcFetch(config) } : {},
7733
+ ...config.chainRpc !== void 0 ? { rpcFetch: config.chainRpc.solana.fetch } : {},
7554
7734
  keypair: config.identity.solana.secretKey,
7555
7735
  ...entry?.tokenAddress ? { tokenMint: entry.tokenAddress } : {}
7556
7736
  }
@@ -8257,13 +8437,14 @@ var ToonClient = class _ToonClient {
8257
8437
  const client = new OnChainChannelClient({
8258
8438
  evmSigner: new EvmSigner(this.requireEvmKey()),
8259
8439
  chainRpcUrls,
8260
- ...this.config.rpcDispatcher !== void 0 ? { rpcDispatcher: this.config.rpcDispatcher } : {},
8440
+ ...this.config.chainRpc !== void 0 ? { rpcDispatcher: this.config.chainRpc.evm.dispatcher } : {},
8261
8441
  ...this.config.identity.solana ? {
8262
8442
  solanaConfig: {
8263
8443
  rpcUrl: this.config.rpcUrls.solana,
8264
- // Same condition as the EVM dispatcher: proxied only when there is
8265
- // a proxy and the caller has not opted RPC out of it.
8266
- ...this.config.rpcDispatcher !== void 0 ? { rpcFetch: this.config.fetch } : {},
8444
+ // Same condition as the EVM dispatcher, and its own circuit:
8445
+ // proxied only when there is a proxy and the caller has not opted
8446
+ // RPC out of it. Never `config.fetch`, which may be the caller's.
8447
+ ...this.config.chainRpc !== void 0 ? { rpcFetch: this.config.chainRpc.solana.fetch } : {},
8267
8448
  keypair: this.config.identity.solana.secretKey,
8268
8449
  // The DEFAULT only. Each channel opens under the program its own
8269
8450
  // terms name, because ADR 0053 binds that program into the signed
@@ -8441,16 +8622,27 @@ function httpEndpointOf(description, connector) {
8441
8622
  async function openHiddenService(resolved, config) {
8442
8623
  const socksProxy = resolved.socksProxy;
8443
8624
  if (socksProxy === void 0) return void 0;
8444
- const { createHiddenServiceTransport, probeSocks5Proxy } = await import("./socks-CCMHMB35.js");
8625
+ const { createChainRpcTransport, createHiddenServiceTransport, probeSocks5Proxy } = await import("./socks-K6QOOWJ5.js");
8445
8626
  await probeSocks5Proxy(socksProxy);
8446
- const transport = createHiddenServiceTransport(socksProxy);
8627
+ const edge = createHiddenServiceTransport(socksProxy);
8628
+ const rpc = resolved.proxyRpc ? {
8629
+ evm: createChainRpcTransport(socksProxy, "evm"),
8630
+ solana: createChainRpcTransport(socksProxy, "solana")
8631
+ } : void 0;
8447
8632
  return {
8448
- transport,
8633
+ transport: {
8634
+ async close() {
8635
+ await Promise.all([edge.close(), rpc?.evm.close(), rpc?.solana.close()]);
8636
+ }
8637
+ },
8449
8638
  config: {
8450
8639
  ...resolved,
8451
- fetch: config.fetch ?? transport.fetch,
8452
- createWebSocket: config.createWebSocket ?? transport.createWebSocket,
8453
- rpcDispatcher: resolved.proxyRpc ? transport.dispatcher : void 0
8640
+ fetch: config.fetch ?? edge.fetch,
8641
+ createWebSocket: config.createWebSocket ?? edge.createWebSocket,
8642
+ chainRpc: rpc === void 0 ? void 0 : {
8643
+ evm: { dispatcher: rpc.evm.dispatcher, fetch: rpc.evm.fetch },
8644
+ solana: { dispatcher: rpc.solana.dispatcher, fetch: rpc.solana.fetch }
8645
+ }
8454
8646
  }
8455
8647
  };
8456
8648
  }
@@ -8477,6 +8669,7 @@ export {
8477
8669
  TransferUnsupportedError,
8478
8670
  isInsufficientGasError,
8479
8671
  chainUnavailableMessage,
8672
+ TransactionOutcomeError,
8480
8673
  BTPMessageType,
8481
8674
  ILPPacketType,
8482
8675
  serializeIlpPrepare,
@@ -8540,6 +8733,7 @@ export {
8540
8733
  sameSettlementAddress,
8541
8734
  counterpartyMatch,
8542
8735
  ChannelManager,
8736
+ PROXIED_RPC_DEFAULTS,
8543
8737
  rpcTransport,
8544
8738
  rpcFetch,
8545
8739
  TOKEN_NETWORK_ABI,
@@ -8550,6 +8744,7 @@ export {
8550
8744
  MIN_SETTLEMENT_TIMEOUT_SECONDS,
8551
8745
  TokenNetworkClient,
8552
8746
  parseEvmChainId,
8747
+ SolanaRpcTransportError,
8553
8748
  OnChainChannelClient,
8554
8749
  SolanaSigner,
8555
8750
  OerErrorKind,
@@ -8612,4 +8807,4 @@ export {
8612
8807
  toEnvelopeRequest,
8613
8808
  ToonClient
8614
8809
  };
8615
- //# sourceMappingURL=chunk-ZHWYFPOP.js.map
8810
+ //# sourceMappingURL=chunk-G36D22II.js.map