@toon-protocol/client 5.1.1 → 5.2.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.
@@ -0,0 +1,67 @@
1
+ import {
2
+ CANARY_HOST,
3
+ CANARY_PORT
4
+ } from "./chunk-KWUYZQBN.js";
5
+ import {
6
+ ProxyBypassError,
7
+ rpcTransport
8
+ } from "./chunk-ABOW5ZCE.js";
9
+ import "./chunk-32MD3CXE.js";
10
+
11
+ // src/transport/canary.ts
12
+ var CANARY_TIMEOUT_MS = 5e3;
13
+ var CANARY_HTTP_URL = `http://${CANARY_HOST}:${CANARY_PORT}/`;
14
+ var CANARY_WS_URL = `ws://${CANARY_HOST}:${CANARY_PORT}/`;
15
+ async function proveProxy(targets) {
16
+ const { edge, rpc, overrides = {} } = targets;
17
+ await check("client-edge", edge, async () => {
18
+ await (overrides.clientEdgeFetch ?? edge.fetch)(CANARY_HTTP_URL, {
19
+ signal: AbortSignal.timeout(CANARY_TIMEOUT_MS)
20
+ });
21
+ });
22
+ if (rpc !== void 0) {
23
+ await check("evm-rpc", rpc.evm, async () => {
24
+ const build = overrides.evmRpcTransport ?? rpcTransport;
25
+ const transport = build({ url: CANARY_HTTP_URL, fetch: rpc.evm.fetch, proxied: true }, {
26
+ timeout: CANARY_TIMEOUT_MS,
27
+ retryCount: 0
28
+ })({});
29
+ await transport.request({ method: "eth_chainId" });
30
+ });
31
+ await check("solana-rpc", rpc.solana, async () => {
32
+ await (overrides.solanaRpcFetch ?? rpc.solana.fetch)(CANARY_HTTP_URL, {
33
+ signal: AbortSignal.timeout(CANARY_TIMEOUT_MS)
34
+ });
35
+ });
36
+ }
37
+ await check("btp", edge, () => dialWebSocket((overrides.createWebSocket ?? edge.createWebSocket)(CANARY_WS_URL)));
38
+ }
39
+ async function check(path, transport, send) {
40
+ const before = transport.canaryHits();
41
+ try {
42
+ await send();
43
+ } catch {
44
+ }
45
+ if (transport.canaryHits() === before) throw new ProxyBypassError(path);
46
+ }
47
+ function dialWebSocket(socket) {
48
+ const ws = socket;
49
+ return new Promise((resolve) => {
50
+ const timer = setTimeout(done, CANARY_TIMEOUT_MS);
51
+ function done() {
52
+ clearTimeout(timer);
53
+ try {
54
+ (ws.terminate ?? ws.close).call(ws);
55
+ } catch {
56
+ }
57
+ resolve();
58
+ }
59
+ ws.on("error", done);
60
+ ws.once("close", done);
61
+ ws.once("open", done);
62
+ });
63
+ }
64
+ export {
65
+ proveProxy
66
+ };
67
+ //# sourceMappingURL=canary-FYKD66CX.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport/canary.ts"],"sourcesContent":["/**\n * The canary of ADR 0005: proof, before a hidden payer starts, that every path it\n * hands a proxy to honours it.\n *\n * One request goes down each path, through the very object real traffic will\n * use, to a closed loopback port. The proxy hook on that path recognises the\n * destination, counts it and refuses the dial. A path whose hook never counted\n * the canary ignored its hook — a proxy bypass — and its real traffic would have\n * dialled clearnet. Either way the canary leaves nothing on the wire.\n *\n * NODE ONLY, for the same reason `./socks.js` is: it is imported dynamically\n * beside it.\n */\nimport { ProxyBypassError, type ProxiedPath } from '../client/errors.js';\nimport { rpcTransport } from './rpc.js';\nimport { CANARY_HOST, CANARY_PORT, type HiddenServiceTransport } from './socks.js';\n\n/** How long a canary may take. A refused or bypassed dial answers at once. */\nconst CANARY_TIMEOUT_MS = 5_000;\n\nconst CANARY_HTTP_URL = `http://${CANARY_HOST}:${CANARY_PORT}/`;\nconst CANARY_WS_URL = `ws://${CANARY_HOST}:${CANARY_PORT}/`;\n\n/**\n * Path objects to test in place of the transports' own. For tests that need a\n * deliberately broken path (a fetch that drops its dispatcher, a viem transport\n * without `fetchFn`, a websocket without its agent). Never set in production.\n *\n * @internal\n */\nexport interface CanaryPathOverrides {\n clientEdgeFetch?: typeof fetch;\n evmRpcTransport?: typeof rpcTransport;\n solanaRpcFetch?: typeof fetch;\n createWebSocket?: (url: string) => unknown;\n}\n\nexport interface CanaryTargets {\n edge: HiddenServiceTransport;\n /** Absent when `proxyRpc` is `false`: no RPC canary runs. */\n rpc?: { evm: HiddenServiceTransport; solana: HiddenServiceTransport };\n overrides?: CanaryPathOverrides;\n}\n\n/**\n * Sends the canaries, in order, and throws {@link ProxyBypassError} for the first\n * path whose proxy hook did not see its canary.\n */\nexport async function proveProxy(targets: CanaryTargets): Promise<void> {\n const { edge, rpc, overrides = {} } = targets;\n\n await check('client-edge', edge, async () => {\n await (overrides.clientEdgeFetch ?? edge.fetch)(CANARY_HTTP_URL, {\n signal: AbortSignal.timeout(CANARY_TIMEOUT_MS),\n });\n });\n\n if (rpc !== undefined) {\n await check('evm-rpc', rpc.evm, async () => {\n const build = overrides.evmRpcTransport ?? rpcTransport;\n const transport = build({ url: CANARY_HTTP_URL, fetch: rpc.evm.fetch, proxied: true }, {\n timeout: CANARY_TIMEOUT_MS,\n retryCount: 0,\n })({});\n await transport.request({ method: 'eth_chainId' });\n });\n await check('solana-rpc', rpc.solana, async () => {\n await (overrides.solanaRpcFetch ?? rpc.solana.fetch)(CANARY_HTTP_URL, {\n signal: AbortSignal.timeout(CANARY_TIMEOUT_MS),\n });\n });\n }\n\n await check('btp', edge, () => dialWebSocket((overrides.createWebSocket ?? edge.createWebSocket)(CANARY_WS_URL)));\n}\n\n/** Runs one canary and compares the hook's count before and after. */\nasync function check(\n path: ProxiedPath,\n transport: HiddenServiceTransport,\n send: () => Promise<void>\n): Promise<void> {\n const before = transport.canaryHits();\n try {\n await send();\n } catch {\n // A refused canary rejects; so does a bypassed one that found a closed port.\n // Only the hook's count tells them apart.\n }\n if (transport.canaryHits() === before) throw new ProxyBypassError(path);\n}\n\n/** Resolves when the socket has failed, closed or opened; then tears it down. */\nfunction dialWebSocket(socket: unknown): Promise<void> {\n const ws = socket as {\n once(event: string, listener: () => void): void;\n on(event: string, listener: () => void): void;\n terminate?(): void;\n close(): void;\n };\n return new Promise<void>((resolve) => {\n const timer = setTimeout(done, CANARY_TIMEOUT_MS);\n function done(): void {\n clearTimeout(timer);\n try {\n (ws.terminate ?? ws.close).call(ws);\n } catch {\n // Already closed.\n }\n resolve();\n }\n ws.on('error', done);\n ws.once('close', done);\n ws.once('open', done);\n });\n}\n"],"mappings":";;;;;;;;;;;AAkBA,IAAM,oBAAoB;AAE1B,IAAM,kBAAkB,UAAU,WAAW,IAAI,WAAW;AAC5D,IAAM,gBAAgB,QAAQ,WAAW,IAAI,WAAW;AA2BxD,eAAsB,WAAW,SAAuC;AACtE,QAAM,EAAE,MAAM,KAAK,YAAY,CAAC,EAAE,IAAI;AAEtC,QAAM,MAAM,eAAe,MAAM,YAAY;AAC3C,WAAO,UAAU,mBAAmB,KAAK,OAAO,iBAAiB;AAAA,MAC/D,QAAQ,YAAY,QAAQ,iBAAiB;AAAA,IAC/C,CAAC;AAAA,EACH,CAAC;AAED,MAAI,QAAQ,QAAW;AACrB,UAAM,MAAM,WAAW,IAAI,KAAK,YAAY;AAC1C,YAAM,QAAQ,UAAU,mBAAmB;AAC3C,YAAM,YAAY,MAAM,EAAE,KAAK,iBAAiB,OAAO,IAAI,IAAI,OAAO,SAAS,KAAK,GAAG;AAAA,QACrF,SAAS;AAAA,QACT,YAAY;AAAA,MACd,CAAC,EAAE,CAAC,CAAC;AACL,YAAM,UAAU,QAAQ,EAAE,QAAQ,cAAc,CAAC;AAAA,IACnD,CAAC;AACD,UAAM,MAAM,cAAc,IAAI,QAAQ,YAAY;AAChD,aAAO,UAAU,kBAAkB,IAAI,OAAO,OAAO,iBAAiB;AAAA,QACpE,QAAQ,YAAY,QAAQ,iBAAiB;AAAA,MAC/C,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AAEA,QAAM,MAAM,OAAO,MAAM,MAAM,eAAe,UAAU,mBAAmB,KAAK,iBAAiB,aAAa,CAAC,CAAC;AAClH;AAGA,eAAe,MACb,MACA,WACA,MACe;AACf,QAAM,SAAS,UAAU,WAAW;AACpC,MAAI;AACF,UAAM,KAAK;AAAA,EACb,QAAQ;AAAA,EAGR;AACA,MAAI,UAAU,WAAW,MAAM,OAAQ,OAAM,IAAI,iBAAiB,IAAI;AACxE;AAGA,SAAS,cAAc,QAAgC;AACrD,QAAM,KAAK;AAMX,SAAO,IAAI,QAAc,CAAC,YAAY;AACpC,UAAM,QAAQ,WAAW,MAAM,iBAAiB;AAChD,aAAS,OAAa;AACpB,mBAAa,KAAK;AAClB,UAAI;AACF,SAAC,GAAG,aAAa,GAAG,OAAO,KAAK,EAAE;AAAA,MACpC,QAAQ;AAAA,MAER;AACA,cAAQ;AAAA,IACV;AACA,OAAG,GAAG,SAAS,IAAI;AACnB,OAAG,KAAK,SAAS,IAAI;AACrB,OAAG,KAAK,QAAQ,IAAI;AAAA,EACtB,CAAC;AACH;","names":[]}
@@ -0,0 +1,299 @@
1
+ // src/client/errors.ts
2
+ var ToonClientError = class extends Error {
3
+ constructor(message, code, cause) {
4
+ super(message, { cause });
5
+ this.code = code;
6
+ this.name = "ToonClientError";
7
+ }
8
+ code;
9
+ };
10
+ var NetworkError = class extends ToonClientError {
11
+ /** The URL that could not be reached, when the failure was reaching one. */
12
+ endpoint;
13
+ constructor(message, cause, endpoint) {
14
+ super(message, "NETWORK_ERROR", cause);
15
+ this.name = "NetworkError";
16
+ if (endpoint !== void 0) this.endpoint = endpoint;
17
+ }
18
+ };
19
+ function describeEndpoint(url, source) {
20
+ if (source === "published") {
21
+ return `${url} (the endpoint the connector published in its self-description)`;
22
+ }
23
+ if (typeof source === "object") {
24
+ const published = source.override.published;
25
+ return published === void 0 ? `${url} (carriage endpoint override; the connector publishes none)` : `${url} (carriage endpoint override; the connector publishes ${published})`;
26
+ }
27
+ return url;
28
+ }
29
+ var ConnectorError = class extends ToonClientError {
30
+ constructor(message, cause) {
31
+ super(message, "CONNECTOR_ERROR", cause);
32
+ this.name = "ConnectorError";
33
+ }
34
+ };
35
+ var ValidationError = class extends ToonClientError {
36
+ constructor(message, cause) {
37
+ super(message, "VALIDATION_ERROR", cause);
38
+ this.name = "ValidationError";
39
+ }
40
+ };
41
+ var ConfigError = class extends ToonClientError {
42
+ constructor(message, cause) {
43
+ super(message, "CONFIG", cause);
44
+ this.name = "ConfigError";
45
+ }
46
+ };
47
+ var ChainUnavailableError = class extends ToonClientError {
48
+ /** The CAIP-2 networks the node publishes (`eip155:84532`, `solana:EtWT…`). */
49
+ offered;
50
+ constructor(message, offered, cause) {
51
+ super(message, "CHAIN_UNAVAILABLE", cause);
52
+ this.name = "ChainUnavailableError";
53
+ this.offered = [...offered];
54
+ }
55
+ };
56
+ var ChannelNotOpenError = class extends ToonClientError {
57
+ constructor(message, cause) {
58
+ super(message, "CHANNEL_NOT_OPEN", cause);
59
+ this.name = "ChannelNotOpenError";
60
+ }
61
+ };
62
+ var RouteNotPricedError = class extends ToonClientError {
63
+ constructor(message, cause) {
64
+ super(message, "ROUTE_NOT_PRICED", cause);
65
+ this.name = "RouteNotPricedError";
66
+ }
67
+ };
68
+ var BeforePayRefusedError = class extends ToonClientError {
69
+ /** The reason the hook returned, verbatim. */
70
+ reason;
71
+ /** The route the refused packet was addressed to. */
72
+ destination;
73
+ /** The resolved price the hook was shown, in base units. */
74
+ amount;
75
+ constructor(reason, destination, amount) {
76
+ super(
77
+ `beforePay refused this send to "${destination}" for ${amount.toString()}: ${reason}`,
78
+ "BEFORE_PAY_REFUSED"
79
+ );
80
+ this.name = "BeforePayRefusedError";
81
+ this.reason = reason;
82
+ this.destination = destination;
83
+ this.amount = amount;
84
+ }
85
+ };
86
+ var PaymentRequiredError = class extends ToonClientError {
87
+ /** The route's terms, parsed from the x402 challenge body. */
88
+ terms;
89
+ constructor(message, terms, cause) {
90
+ super(message, "PAYMENT_REQUIRED", cause);
91
+ this.name = "PaymentRequiredError";
92
+ this.terms = terms;
93
+ }
94
+ };
95
+ var TransportRequiredError = class extends ToonClientError {
96
+ /** The carriage the node requires, when the refusal named one. */
97
+ required;
98
+ /** The route's terms, when the refusal carried them. */
99
+ terms;
100
+ constructor(message, options = {}) {
101
+ super(message, "TRANSPORT_REQUIRED", options.cause);
102
+ this.name = "TransportRequiredError";
103
+ this.required = options.required;
104
+ this.terms = options.terms;
105
+ }
106
+ };
107
+ var ProxyBypassError = class _ProxyBypassError extends ToonClientError {
108
+ /** The path whose proxy hook was never reached. */
109
+ path;
110
+ constructor(path) {
111
+ super(_ProxyBypassError.messageFor(path), "PROXY_BYPASS");
112
+ this.name = "ProxyBypassError";
113
+ this.path = path;
114
+ }
115
+ static messageFor(path) {
116
+ const refusal = "Refusing to start: it would reach its destination without the SOCKS proxy.";
117
+ switch (path) {
118
+ case "client-edge":
119
+ case "solana-rpc":
120
+ return `The ${path} path ignored its proxy. ${refusal} The installed undici is not honoured by this Node's fetch; install undici@^7.`;
121
+ case "evm-rpc":
122
+ return `The evm-rpc path ignored its proxy. ${refusal} The installed viem ignores \`fetchFn\`; upgrade viem to ^2.37.2.`;
123
+ case "btp":
124
+ return `The btp path ignored its proxy. ${refusal} \`ws\` ignored its agent.`;
125
+ }
126
+ }
127
+ };
128
+ var ChannelFundingError = class extends ToonClientError {
129
+ retryable = true;
130
+ constructor(message, cause) {
131
+ super(message, "CHANNEL_FUNDING", cause);
132
+ this.name = "ChannelFundingError";
133
+ }
134
+ };
135
+ var ChannelResumeError = class extends ToonClientError {
136
+ constructor(message, cause) {
137
+ super(message, "CHANNEL_RESUME", cause);
138
+ this.name = "ChannelResumeError";
139
+ }
140
+ };
141
+ var InsufficientBalanceError = class extends ToonClientError {
142
+ constructor(message, cause) {
143
+ super(message, "INSUFFICIENT_BALANCE", cause);
144
+ this.name = "InsufficientBalanceError";
145
+ }
146
+ };
147
+ var StaleRpcReadError = class extends ToonClientError {
148
+ retryable = true;
149
+ constructor(message, cause) {
150
+ super(message, "STALE_RPC_READ", cause);
151
+ this.name = "StaleRpcReadError";
152
+ }
153
+ };
154
+ var UnknownChainError = class extends ToonClientError {
155
+ constructor(message, cause) {
156
+ super(message, "UNKNOWN_CHAIN", cause);
157
+ this.name = "UnknownChainError";
158
+ }
159
+ };
160
+ var InvalidAddressError = class extends ToonClientError {
161
+ constructor(message, cause) {
162
+ super(message, "INVALID_ADDRESS", cause);
163
+ this.name = "InvalidAddressError";
164
+ }
165
+ };
166
+ var TransferNotDeliveredError = class extends ToonClientError {
167
+ constructor(message, cause) {
168
+ super(message, "TRANSFER_NOT_DELIVERED", cause);
169
+ this.name = "TransferNotDeliveredError";
170
+ }
171
+ };
172
+ var TransferUnsupportedError = class extends ToonClientError {
173
+ constructor(message, cause) {
174
+ super(message, "TRANSFER_UNSUPPORTED", cause);
175
+ this.name = "TransferUnsupportedError";
176
+ }
177
+ };
178
+ var FacilitatorError = class extends ToonClientError {
179
+ constructor(message, reason, cause) {
180
+ super(message, "FACILITATOR", cause);
181
+ this.reason = reason;
182
+ this.name = "FacilitatorError";
183
+ }
184
+ reason;
185
+ };
186
+ var SponsorRefusedError = class extends ToonClientError {
187
+ /**
188
+ * @param status the endpoint's HTTP status. `502` is its "failed" class — a
189
+ * co-signed open that was sent and did not confirm — so, unlike every other
190
+ * refusal, it does not prove nothing landed.
191
+ */
192
+ constructor(message, reason, status, cause) {
193
+ super(message, "SPONSOR_REFUSED", cause);
194
+ this.reason = reason;
195
+ this.status = status;
196
+ this.name = "SponsorRefusedError";
197
+ }
198
+ reason;
199
+ status;
200
+ };
201
+ var INSUFFICIENT_GAS_MARKERS = [
202
+ "exceeds the balance of the account",
203
+ "insufficient funds for gas",
204
+ "insufficient funds for intrinsic transaction cost",
205
+ "insufficient funds for transfer"
206
+ ];
207
+ function isInsufficientGasError(err) {
208
+ const parts = [];
209
+ let cur = err;
210
+ for (let i = 0; i < 10 && cur != null; i++) {
211
+ parts.push(cur instanceof Error ? cur.message : String(cur));
212
+ cur = cur instanceof Error ? cur.cause : void 0;
213
+ }
214
+ const text = parts.join(" | ").toLowerCase();
215
+ return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));
216
+ }
217
+ function chainUnavailableMessage(wanted, offered, reason) {
218
+ const list = offered.length > 0 ? offered.join(", ") : "(none)";
219
+ if (reason === "none") {
220
+ return "This connector publishes no settlement chains at all, so there is no channel to open and nothing can be paid for. Check that it is configured with a settlement backend.";
221
+ }
222
+ if (reason === "not-offered") {
223
+ return `This connector does not settle on "${String(wanted)}". It settles on: ${list}. Set \`chain\` to 'evm' or 'solana' to match one of those, or leave it unset to take the first one this client holds a key for.`;
224
+ }
225
+ 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.`;
226
+ }
227
+ var TransactionOutcomeError = class extends ToonClientError {
228
+ constructor(message, chain, txHash, outcome, cause) {
229
+ super(message, "TRANSACTION_OUTCOME", cause);
230
+ this.chain = chain;
231
+ this.txHash = txHash;
232
+ this.outcome = outcome;
233
+ this.name = "TransactionOutcomeError";
234
+ }
235
+ chain;
236
+ txHash;
237
+ outcome;
238
+ };
239
+
240
+ // src/transport/rpc.ts
241
+ import { http } from "viem";
242
+ var PROXIED_RPC_DEFAULTS = {
243
+ timeout: 3e4,
244
+ retryCount: 3,
245
+ retryDelay: 500
246
+ };
247
+ var directFetch = (input, init) => globalThis.fetch(input, init);
248
+ function rpcTransport(route, options = {}) {
249
+ const { timeout, retryCount, retryDelay } = route.proxied === true ? { ...PROXIED_RPC_DEFAULTS, ...definedOnly(options) } : options;
250
+ return http(route.url, {
251
+ ...timeout !== void 0 ? { timeout } : {},
252
+ ...retryCount !== void 0 ? { retryCount } : {},
253
+ ...retryDelay !== void 0 ? { retryDelay } : {},
254
+ fetchFn: route.fetch
255
+ });
256
+ }
257
+ function definedOnly(options) {
258
+ return Object.fromEntries(
259
+ Object.entries(options).filter(([, value]) => value !== void 0)
260
+ );
261
+ }
262
+ function rpcFetch(dispatcher, fetchImpl = globalThis.fetch) {
263
+ if (dispatcher === void 0) return fetchImpl;
264
+ return ((input, init) => fetchImpl(input, { ...init, dispatcher }));
265
+ }
266
+
267
+ export {
268
+ ToonClientError,
269
+ NetworkError,
270
+ describeEndpoint,
271
+ ConnectorError,
272
+ ValidationError,
273
+ ConfigError,
274
+ ChainUnavailableError,
275
+ ChannelNotOpenError,
276
+ RouteNotPricedError,
277
+ BeforePayRefusedError,
278
+ PaymentRequiredError,
279
+ TransportRequiredError,
280
+ ProxyBypassError,
281
+ ChannelFundingError,
282
+ ChannelResumeError,
283
+ InsufficientBalanceError,
284
+ StaleRpcReadError,
285
+ UnknownChainError,
286
+ InvalidAddressError,
287
+ TransferNotDeliveredError,
288
+ TransferUnsupportedError,
289
+ FacilitatorError,
290
+ SponsorRefusedError,
291
+ isInsufficientGasError,
292
+ chainUnavailableMessage,
293
+ TransactionOutcomeError,
294
+ PROXIED_RPC_DEFAULTS,
295
+ directFetch,
296
+ rpcTransport,
297
+ rpcFetch
298
+ };
299
+ //# sourceMappingURL=chunk-ABOW5ZCE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client/errors.ts","../src/transport/rpc.ts"],"sourcesContent":["/**\n * Everything this client throws.\n *\n * ## The rule that orders this file\n *\n * **A reject is returned as `fulfilled: false`; it is never thrown.** Everything\n * declared here happened either *before* the packet went out — a missing key, a\n * route with no price, a chain this client holds no key for, a greeting demanding\n * payment or a different carriage — or *on chain*, where a transaction of the\n * caller's own reverted. Nothing here is the connector's verdict on a packet that\n * actually travelled.\n *\n * That split is not stylistic. A refusal is an outcome the wire is designed to\n * produce (`client-edge-spec.md` §1.3's five-step gate ends in a REJECT, not a\n * transport failure), and it carries facts a caller wants — what the path cost,\n * which claim was spent, who refused. Flattening it into an exception would throw\n * those away and would put the ordinary case of \"you underpaid, here is the\n * price\" onto the same path as \"your RPC is unreachable\".\n *\n * The one edge: {@link PaymentRequiredError} and {@link TransportRequiredError}\n * are *thrown by the transports* when the connector answers HTTP `402` rather\n * than routing at all, because at that layer there is no packet outcome to\n * return. {@link ../client/send.js}'s pipeline catches both and converts them\n * into a {@link ../client/types.js!SendRefused} with `refusedBy: 'edge'`, so a\n * caller of {@link ../client/ToonClient.js!ToonClient.send} still never sees a\n * refusal as an exception.\n */\nimport type { PaymentTerms, ChainKind } from './types.js';\n\n/**\n * Base error class for all TOON client errors.\n */\nexport class ToonClientError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'ToonClientError';\n }\n}\n\n/**\n * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).\n * These errors trigger retry logic with exponential backoff.\n */\nexport class NetworkError extends ToonClientError {\n /** The URL that could not be reached, when the failure was reaching one. */\n readonly endpoint?: string;\n\n constructor(message: string, cause?: Error, endpoint?: string) {\n super(message, 'NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n if (endpoint !== undefined) this.endpoint = endpoint;\n }\n}\n\n/** Where a packet-path URL came from: the caller's config, or the node's self-description. */\nexport type EndpointSource =\n | 'configured'\n | 'published'\n /** The caller's `carriageEndpoints` replaced what the connector published (`published`, when it did). */\n | { override: { published?: string } };\n\n/** `url`, plus a note when the node (not the caller) chose it, or when the caller replaced the node's. */\nexport function describeEndpoint(url: string, source?: EndpointSource): string {\n if (source === 'published') {\n return `${url} (the endpoint the connector published in its self-description)`;\n }\n if (typeof source === 'object') {\n const published = source.override.published;\n return published === undefined\n ? `${url} (carriage endpoint override; the connector publishes none)`\n : `${url} (carriage endpoint override; the connector publishes ${published})`;\n }\n return url;\n}\n\n/**\n * Connector error for a transport-level failure at the client edge: a `4xx`\n * that is not a greeting, or a `5xx`.\n *\n * Deliberately NOT how an ILP reject arrives. `client-edge-spec.md` §1.1 gives\n * `POST /ilp` a `200` for both a FULFILL and a REJECT, and reserves non-2xx for\n * the request never having become a packet at all (400 undecodable, 401 bad\n * `ILP-Peer-Id`, 413 over 2 MiB). So this class means \"the connector did not\n * process a packet\", never \"the connector refused one\".\n */\nexport class ConnectorError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONNECTOR_ERROR', cause);\n this.name = 'ConnectorError';\n }\n}\n\n/**\n * Validation error for invalid input parameters.\n * These errors are thrown before making any HTTP requests.\n */\nexport class ValidationError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'VALIDATION_ERROR', cause);\n this.name = 'ValidationError';\n }\n}\n\n// ─── Configuration and capability ───────────────────────────────────────────\n\n/**\n * The configuration this client was handed cannot produce a working client, and\n * no amount of retrying will change that: no key material, a connector URL that\n * is not a URL, a negative deposit — or a fact this client checked against the\n * chain and found to disagree with what the node published.\n *\n * That last case is the one worth naming. `self-description-spec.md` ND-07 says\n * a node proves each settlement entry against a live chain before publishing it,\n * so a `tokenNetwork` that the `TokenNetworkRegistry` does not agree is the token\n * network for that token is a contradiction between two authorities, not a\n * recoverable condition. Signing a claim under the wrong `verifyingContract`\n * produces a signature that verifies against nothing, and the only symptom is a\n * refused claim — so it is caught here, before any collateral is locked.\n */\nexport class ConfigError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONFIG', cause);\n this.name = 'ConfigError';\n }\n}\n\n/**\n * The node settles on chains, but not on one this client holds a key for — or\n * not on the one {@link ../client/types.js!ToonClientConfig.chain} named.\n *\n * Carries {@link offered}, the networks the node *does* publish in its\n * `batchSettlements[]`, because the remedy is always to pick one of them (or to\n * configure a key for one) and a message that only says \"no\" makes the caller go\n * read the self-description by hand to find out what would have worked.\n */\nexport class ChainUnavailableError extends ToonClientError {\n /** The CAIP-2 networks the node publishes (`eip155:84532`, `solana:EtWT…`). */\n readonly offered: string[];\n\n constructor(message: string, offered: string[], cause?: Error) {\n super(message, 'CHAIN_UNAVAILABLE', cause);\n this.name = 'ChainUnavailableError';\n this.offered = [...offered];\n }\n}\n\n/**\n * An operation needs an open payment channel and there is not one.\n *\n * Thrown rather than returned because it is a precondition, not a verdict: no\n * packet is formed, no claim is signed and nothing reaches the connector. The\n * usual cause is `autoOpenChannel: false` with nothing opened yet, or a\n * `deposit`/`close`/`settle` called before `open`.\n */\nexport class ChannelNotOpenError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_NOT_OPEN', cause);\n this.name = 'ChannelNotOpenError';\n }\n}\n\n/**\n * The destination is not a route this connector prices, so there is no amount to\n * put on a packet.\n *\n * `GET /ilp/routes/price` answered `404` — which is an *answer*, not a failure\n * (see {@link ../connector/ConnectorEdgeClient.js!ConnectorEdgeClient.getRoutePrice}):\n * this connector does not terminate that destination. Pass\n * {@link ../client/types.js!SendOptions.amount} explicitly to send anyway, which\n * is what a *forwarded* destination needs — its price lives at the connector that\n * terminates it, not at the one being posted to.\n */\nexport class RouteNotPricedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'ROUTE_NOT_PRICED', cause);\n this.name = 'RouteNotPricedError';\n }\n}\n\n/**\n * The caller's own {@link ../client/types.js!SendOptions.beforePay} refused this\n * send, and nothing was paid.\n *\n * Thrown rather than returned, and that is consistent with this file's rule\n * rather than an exception to it: a {@link ../client/types.js!SendRefused} is\n * the *connector's* verdict on a packet that travelled, and here no packet\n * exists. The price was resolved, the hook said no, and the pipeline stopped\n * before a channel was ensured or a voucher was signed — which is the whole\n * point of the hook, since a signed voucher is a bearer instrument that cannot\n * be recalled.\n *\n * A distinct class rather than a {@link ValidationError} because the two are\n * acted on differently: a `ValidationError` says this client could not use an\n * argument, while this says the caller's own rule rejected a request this client\n * was perfectly able to send. {@link reason} is the hook's string, unedited, so\n * the caller reads back exactly what its own check said.\n */\nexport class BeforePayRefusedError extends ToonClientError {\n /** The reason the hook returned, verbatim. */\n readonly reason: string;\n /** The route the refused packet was addressed to. */\n readonly destination: string;\n /** The resolved price the hook was shown, in base units. */\n readonly amount: bigint;\n\n constructor(reason: string, destination: string, amount: bigint) {\n super(\n `beforePay refused this send to \"${destination}\" for ${amount.toString()}: ${reason}`,\n 'BEFORE_PAY_REFUSED'\n );\n this.name = 'BeforePayRefusedError';\n this.reason = reason;\n this.destination = destination;\n this.amount = amount;\n }\n}\n\n// ─── Greetings: refusals raised before the packet was routed ────────────────\n\n/**\n * The connector answered an unpaid (or insufficiently paid) request with its\n * terms instead of routing it — HTTP `402`, `client-edge-spec.md` §1.4.\n *\n * The terms are the point: {@link terms} carries the route's price and the\n * chains it settles on, which is everything needed to open a channel and pay.\n * This is the greeting a first-contact client is *supposed* to receive.\n *\n * Thrown by the transport, where there is no packet outcome to return; converted\n * by {@link ../client/send.js} into a `SendRefused` with\n * `code: 'PAYMENT_REQUIRED'` and `refusedBy: 'edge'`, so a `send()` caller sees\n * an outcome rather than an exception. Catch it directly only when driving a\n * transport by hand.\n */\nexport class PaymentRequiredError extends ToonClientError {\n /** The route's terms, parsed from the x402 challenge body. */\n readonly terms: PaymentTerms;\n\n constructor(message: string, terms: PaymentTerms, cause?: Error) {\n super(message, 'PAYMENT_REQUIRED', cause);\n this.name = 'PaymentRequiredError';\n this.terms = terms;\n }\n}\n\n/**\n * The route refuses the carriage this request arrived on.\n *\n * A node may pin a route to one transport — the devnet relay's `g.toon.relay` is\n * BTP-only — and it says so two ways: in its self-description's\n * `requiredTransport`, and in the greeting it answers a wrong-carriage request\n * with (`extra.requiredTransport`, or an `F02` on BTP). Distinct from\n * {@link PaymentRequiredError} because the remedy is different: paying more will\n * never help, and re-sending over the other carriage always will.\n *\n * {@link required} is the carriage the node insists on, when it named one.\n */\nexport class TransportRequiredError extends ToonClientError {\n /** The carriage the node requires, when the refusal named one. */\n readonly required: 'http' | 'btp' | undefined;\n /** The route's terms, when the refusal carried them. */\n readonly terms: PaymentTerms | undefined;\n\n constructor(\n message: string,\n options: { required?: 'http' | 'btp'; terms?: PaymentTerms; cause?: Error } = {}\n ) {\n super(message, 'TRANSPORT_REQUIRED', options.cause);\n this.name = 'TransportRequiredError';\n this.required = options.required;\n this.terms = options.terms;\n }\n}\n\n/** The four paths a hidden payer hands its proxy to. */\nexport type ProxiedPath = 'client-edge' | 'evm-rpc' | 'solana-rpc' | 'btp';\n\n/**\n * Thrown by `ToonClient.create` when a hidden payer's canary shows that one path\n * ignores its proxy hook, so that path would dial clearnet and name the payer\n * (ADR 0005). Nothing has been sent: the canary targets a closed loopback port.\n * {@link path} says which path, and the message says how to fix it.\n */\nexport class ProxyBypassError extends ToonClientError {\n /** The path whose proxy hook was never reached. */\n readonly path: ProxiedPath;\n\n constructor(path: ProxiedPath) {\n super(ProxyBypassError.messageFor(path), 'PROXY_BYPASS');\n this.name = 'ProxyBypassError';\n this.path = path;\n }\n\n private static messageFor(path: ProxiedPath): string {\n const refusal = 'Refusing to start: it would reach its destination without the SOCKS proxy.';\n switch (path) {\n case 'client-edge':\n case 'solana-rpc':\n return (\n `The ${path} path ignored its proxy. ${refusal} The installed undici is not honoured ` +\n \"by this Node's fetch; install undici@^7.\"\n );\n case 'evm-rpc':\n return (\n `The evm-rpc path ignored its proxy. ${refusal} The installed viem ignores ` +\n '`fetchFn`; upgrade viem to ^2.37.2.'\n );\n case 'btp':\n return `The btp path ignored its proxy. ${refusal} \\`ws\\` ignored its agent.`;\n }\n }\n}\n\n// ─── On-chain and channel lifecycle ─────────────────────────────────────────\n\n/**\n * Thrown when the one-time on-chain payment-channel OPEN reverts because the\n * local settlement wallet has no native gas to pay for its own\n * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN\n * only — per-write settlement rides the packet and never spends gas. We remap\n * ONLY this case so callers get an actionable message (fund the wallet) instead\n * of the raw viem \"...exceeds the balance of the account\" string (toon-meta#65).\n * Retryable once the wallet is funded; the underlying viem/RPC error is\n * preserved as `cause`.\n */\nexport class ChannelFundingError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_FUNDING', cause);\n this.name = 'ChannelFundingError';\n }\n}\n\n/**\n * Thrown when a persisted connector→channel binding names a channel whose CLAIM\n * WATERMARK (nonce + cumulative amount) is missing from the channel store.\n *\n * Resuming it anyway would re-track the live channel at nonce 0, and the\n * connector rejects every claim that does not strictly advance the nonce it has\n * already banked (`client-edge-spec.md` §1.3 step 2) — the `F01` failure from the\n * live measurement runs. Opening a fresh channel instead would silently strand\n * the collateral in the existing one. Neither is safe to do quietly, so this is a\n * hard error: the operator decides (settle the old channel, or restore the\n * watermark file). Never delete a channel store for a live channel.\n */\nexport class ChannelResumeError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_RESUME', cause);\n this.name = 'ChannelResumeError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when the sender cannot\n * cover the requested amount (plus, where applicable, the chain's own transaction\n * fee) on the source chain. A PREFLIGHT failure — thrown before any transaction\n * is built or submitted, so it never costs gas/fees.\n */\nexport class InsufficientBalanceError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'INSUFFICIENT_BALANCE', cause);\n this.name = 'InsufficientBalanceError';\n }\n}\n\n/**\n * Thrown when an EVM RPC never converges on a just-confirmed channel open —\n * the read-after-write hole behind `sepolia.base.org`'s load balancer, whose\n * replicas can serve a state that predates the `openChannel` receipt, making\n * the follow-up `setTotalDeposit` revert `InvalidChannelState()` (#489).\n */\nexport class StaleRpcReadError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'STALE_RPC_READ', cause);\n this.name = 'StaleRpcReadError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when `chain` is not one\n * this client can send on — either an unrecognized chain identifier, or a\n * recognized chain the client instance has no configuration for. Distinct from\n * {@link InvalidAddressError} (the chain is fine, the destination isn't) and from\n * {@link ChainUnavailableError} (this client is fine, the *node* does not settle\n * there).\n */\nexport class UnknownChainError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'UNKNOWN_CHAIN', cause);\n this.name = 'UnknownChainError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when the destination\n * address is malformed for the target chain (wrong format, wrong length, invalid\n * charset) — checked BEFORE any transaction is built, so a typo never costs\n * gas/fees or risks sending funds into a black hole.\n */\nexport class InvalidAddressError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'INVALID_ADDRESS', cause);\n this.name = 'InvalidAddressError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} when a send was ACCEPTED\n * by the chain (a landed, non-reverted transaction / a node-accepted payment)\n * but the destination's observed balance never rose by the sent amount within\n * the bounded wait. This is the failure {@link ../wallet/transfer.js!sendTransfer}\n * exists to catch: the devnet faucet's Solana leg has been observed returning\n * success with a real transaction signature while delivering 0 lamports\n * (toon-protocol/connector#691) — trusting the send call's return value alone\n * would report a funded destination that in fact holds nothing.\n */\nexport class TransferNotDeliveredError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'TRANSFER_NOT_DELIVERED', cause);\n this.name = 'TransferNotDeliveredError';\n }\n}\n\n/**\n * Thrown by {@link ../wallet/transfer.js!sendTransfer} for a chain/asset\n * combination that is not implemented yet — today, a settlement token on a chain\n * whose token path this client does not build.\n */\nexport class TransferUnsupportedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'TRANSFER_UNSUPPORTED', cause);\n this.name = 'TransferUnsupportedError';\n }\n}\n\n/**\n * An x402 facilitator answered, and refused to settle an x402 `batch-settlement`\n * deposit (connector ADR 0074). {@link reason} is its own `errorReason` verbatim\n * — `invalid_batch_settlement_evm_…` — because each one names a different remedy:\n * a zero voucher on a fresh channel, a missing Permit2 approval, an expired\n * authorization. Nothing reached a connector, and no channel was funded.\n *\n * A facilitator that did not answer is a {@link NetworkError}, not this.\n */\nexport class FacilitatorError extends ToonClientError {\n constructor(\n message: string,\n public readonly reason: string,\n cause?: Error\n ) {\n super(message, 'FACILITATOR', cause);\n this.name = 'FacilitatorError';\n }\n}\n\n/**\n * The receiving connector's Solana sponsor endpoint answered, and did not open\n * the x402 `batch-settlement` channel (connector ADR 0074 decision 9).\n * {@link reason} is its own refusal name — `token_program_unsupported`,\n * `cluster_rent_threshold_unsupported`, `sponsor_busy`, … — because each names\n * a different remedy. Nothing was spent: the endpoint signs and sends nothing\n * until every check passes.\n */\nexport class SponsorRefusedError extends ToonClientError {\n /**\n * @param status the endpoint's HTTP status. `502` is its \"failed\" class — a\n * co-signed open that was sent and did not confirm — so, unlike every other\n * refusal, it does not prove nothing landed.\n */\n constructor(\n message: string,\n public readonly reason: string,\n public readonly status?: number,\n cause?: Error\n ) {\n super(message, 'SPONSOR_REFUSED', cause);\n this.name = 'SponsorRefusedError';\n }\n}\n\n// ─── Error classification helpers ───────────────────────────────────────────\n\n/**\n * Substrings that mark an insufficient-native-gas revert from an on-chain\n * channel-open tx. viem surfaces the node's message verbatim and the exact\n * phrasing varies by RPC (anvil/geth/hardhat), so we match a set of known\n * markers case-insensitively.\n */\nconst INSUFFICIENT_GAS_MARKERS = [\n 'exceeds the balance of the account',\n 'insufficient funds for gas',\n 'insufficient funds for intrinsic transaction cost',\n 'insufficient funds for transfer',\n];\n\n/**\n * True when `err` (or any error in its nested `cause` chain) is an\n * insufficient-native-gas revert. viem wraps the node error one or more levels\n * deep, so the whole chain is flattened and scanned.\n */\nexport function isInsufficientGasError(err: unknown): boolean {\n const parts: string[] = [];\n let cur: unknown = err;\n for (let i = 0; i < 10 && cur != null; i++) {\n parts.push(cur instanceof Error ? cur.message : String(cur));\n cur = cur instanceof Error ? (cur as { cause?: unknown }).cause : undefined;\n }\n const text = parts.join(' | ').toLowerCase();\n return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));\n}\n\n/**\n * Build the message a {@link ChainUnavailableError} carries, naming what the node\n * offered so the remedy is in the error rather than in the docs.\n */\nexport function chainUnavailableMessage(\n wanted: ChainKind | undefined,\n offered: string[],\n reason: 'no-key' | 'not-offered' | 'none'\n): string {\n const list = offered.length > 0 ? offered.join(', ') : '(none)';\n if (reason === 'none') {\n return (\n 'This connector publishes no settlement chains at all, so there is no ' +\n 'channel to open and nothing can be paid for. Check that it is configured ' +\n 'with a settlement backend.'\n );\n }\n if (reason === 'not-offered') {\n return (\n `This connector does not settle on \"${String(wanted)}\". It settles on: ` +\n `${list}. Set \\`chain\\` to 'evm' or 'solana' to match one of those, or ` +\n 'leave it unset to take the first one this client holds a key for.'\n );\n }\n return (\n `This client holds no key for any chain this connector settles on (${list}). ` +\n 'Supply a `mnemonic` — which derives both an EVM and a Solana key — or the ' +\n 'raw key for one of those chains.'\n );\n}\n\n/**\n * A chain write that was sent and did not end confirmed and clean. It names the\n * transaction, so whoever handles it can look the transaction up before doing\n * anything that would repeat it (connector ADR 0073, decision 5).\n *\n * - `failed`: it landed and its execution failed. Nothing to reconcile.\n * - `expired`: Solana only. Its blockhash is past `lastValidBlockHeight` and it\n * never appeared, so it cannot land. Safe to send again.\n * - `unknown`: no answer settled it before the deadline, usually because the RPC\n * stopped answering. It may still land. Repeating it blindly can do the thing\n * twice. A Solana deposit is incremental, so a repeated one deposits twice.\n *\n * Distinct from a {@link NetworkError}: that one means the request may never\n * have reached the chain. This one means it did, or may have.\n */\nexport class TransactionOutcomeError extends ToonClientError {\n constructor(\n message: string,\n readonly chain: ChainKind,\n readonly txHash: string,\n readonly outcome: 'failed' | 'expired' | 'unknown',\n cause?: Error\n ) {\n super(message, 'TRANSACTION_OUTCOME', cause);\n this.name = 'TransactionOutcomeError';\n }\n}\n","/**\n * The one place viem is told to send chain RPC through the hidden-service proxy.\n *\n * viem's HTTP transport takes an injected `fetchFn` (viem `^2.37.2`). Handing it\n * the proxied fetch means chain traffic joins the packet traffic inside the\n * overlay (ADR 0002) through the same fetch the canary tests (ADR 0005).\n *\n * Browser-safe: this module imports nothing but viem. The proxied fetch itself is\n * built in `./socks.js`, which is Node-only and dynamically imported.\n */\nimport { http } from 'viem';\n\n/** Options a caller already wanted, independent of any proxy. */\nexport interface RpcTransportOptions {\n timeout?: number;\n retryCount?: number;\n retryDelay?: number;\n}\n\n/**\n * What a proxied RPC request gets when its caller names nothing else, sized\n * from connector ADR 0073's measurements through `anon` (decisions 4 and 5).\n *\n * - `timeout` 30s, not viem's 10s. The worst call measured that needed a new\n * circuit took 13s. Under 10s that one would have been reported as a failure,\n * and retried on another new circuit.\n * - `retryDelay` 500ms, not viem's 150ms. viem already retries 403, 408, 429,\n * 5xx and dropped connections. Exit IPs are shared, so a 429 is the error to\n * expect, and retrying it at 150ms mostly earns another one.\n * - `retryCount` 3, viem's own.\n */\nexport const PROXIED_RPC_DEFAULTS = {\n timeout: 30_000,\n retryCount: 3,\n retryDelay: 500,\n} as const satisfies Required<RpcTransportOptions>;\n\n/**\n * Where one chain's JSON-RPC goes and what it goes through: the URL, and the\n * `fetch` that dials it. Both are required. A chain RPC call site cannot compile\n * without the fetch it should use, so a hidden payer cannot reach clearnet by\n * leaving one out (ADR 0005).\n *\n * The client decides it once, in its chain-access layer, and every internal\n * layer below takes it whole. The only defaults to the global `fetch` left are\n * at public helpers, for a direct caller on clearnet; the client always passes\n * its own route to them.\n */\nexport interface ChainRpcRoute {\n url: string;\n fetch: typeof fetch;\n /**\n * The `fetch` rides the hidden-service proxy, so a request gets\n * {@link PROXIED_RPC_DEFAULTS} under anything the caller set explicitly.\n */\n proxied?: boolean;\n}\n\n/**\n * The global `fetch`, looked up per call. This is the deliberately direct\n * route: a clearnet client's, a public helper's default, and a hidden payer's\n * with `proxyRpc: false` (ADR 0002). Choose it by name, at the one place that\n * decides.\n */\nexport const directFetch: typeof fetch = (input, init) => globalThis.fetch(input, init);\n\n/**\n * A viem HTTP transport over `route`.\n *\n * A proxied route also brings {@link PROXIED_RPC_DEFAULTS}, under anything the\n * caller set explicitly.\n */\nexport function rpcTransport(\n route: ChainRpcRoute,\n options: RpcTransportOptions = {}\n): ReturnType<typeof http> {\n const { timeout, retryCount, retryDelay } =\n route.proxied === true ? { ...PROXIED_RPC_DEFAULTS, ...definedOnly(options) } : options;\n return http(route.url, {\n ...(timeout !== undefined ? { timeout } : {}),\n ...(retryCount !== undefined ? { retryCount } : {}),\n ...(retryDelay !== undefined ? { retryDelay } : {}),\n fetchFn: route.fetch,\n });\n}\n\n/** `options` without its `undefined` members, so a spread cannot erase a default. */\nfunction definedOnly(options: RpcTransportOptions): RpcTransportOptions {\n return Object.fromEntries(\n Object.entries(options).filter(([, value]) => value !== undefined)\n ) as RpcTransportOptions;\n}\n\n/**\n * `fetch` bound to `dispatcher`, for a JSON-RPC path that calls `fetch` itself\n * rather than going through viem — Solana's, in practice.\n */\nexport function rpcFetch(dispatcher: unknown | undefined, fetchImpl: typeof fetch = globalThis.fetch): typeof fetch {\n if (dispatcher === undefined) return fetchImpl;\n return ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n fetchImpl(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n}\n"],"mappings":";AAgCO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MAChB,OACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHR;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAMO,IAAM,eAAN,cAA2B,gBAAgB;AAAA;AAAA,EAEvC;AAAA,EAET,YAAY,SAAiB,OAAe,UAAmB;AAC7D,UAAM,SAAS,iBAAiB,KAAK;AACrC,SAAK,OAAO;AACZ,QAAI,aAAa,OAAW,MAAK,WAAW;AAAA,EAC9C;AACF;AAUO,SAAS,iBAAiB,KAAa,QAAiC;AAC7E,MAAI,WAAW,aAAa;AAC1B,WAAO,GAAG,GAAG;AAAA,EACf;AACA,MAAI,OAAO,WAAW,UAAU;AAC9B,UAAM,YAAY,OAAO,SAAS;AAClC,WAAO,cAAc,SACjB,GAAG,GAAG,gEACN,GAAG,GAAG,yDAAyD,SAAS;AAAA,EAC9E;AACA,SAAO;AACT;AAYO,IAAM,iBAAN,cAA6B,gBAAgB;AAAA,EAClD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,mBAAmB,KAAK;AACvC,SAAK,OAAO;AAAA,EACd;AACF;AAMO,IAAM,kBAAN,cAA8B,gBAAgB;AAAA,EACnD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,oBAAoB,KAAK;AACxC,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,IAAM,cAAN,cAA0B,gBAAgB;A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