@toon-protocol/client 4.2.0 → 5.0.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.
@@ -155,7 +155,7 @@ async function probeSocks5Proxy(socksProxy, timeoutMs = 2e3) {
155
155
  socket.destroy();
156
156
  reject(
157
157
  new Error(
158
- `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is unreachable without one: start the Anyone Protocol \`anon\` daemon, or run \`toon\` which can start one for you.`
158
+ `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is unreachable without one: start the Anyone Protocol \`anon\` daemon, or run \`toon-client\` which can start one for you.`
159
159
  )
160
160
  );
161
161
  };
@@ -173,4 +173,4 @@ export {
173
173
  createChainRpcTransport,
174
174
  probeSocks5Proxy
175
175
  };
176
- //# sourceMappingURL=chunk-LJSOTVUT.js.map
176
+ //# sourceMappingURL=chunk-SIDK54Y5.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transport/socks.ts"],"sourcesContent":["/**\n * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.\n *\n * A connector deployed as a hidden service is reachable only through a running\n * `anon` daemon's SOCKS5 port. Three separate things in this client have to go\n * through that port, and — annoyingly — each needs a different object to do it:\n *\n * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in\n * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,\n * which is why the `socks-proxy-agent` this package used to depend on cannot\n * serve this path at all.\n * - **Chain RPC** goes through viem, which calls the *global* `fetch` and accepts\n * no injected one. Its only opening is `http(url, { fetchOptions })`, so it\n * needs the same dispatcher handed to it as a fetch option (ADR 0002).\n * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and\n * therefore takes an `http.Agent` and nothing else.\n *\n * So this module builds one SOCKS connection primitive and wraps it three ways.\n * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.\n *\n * Chain RPC gets a transport of its own per chain ({@link createChainRpcTransport}),\n * authenticating with a fixed SOCKS username so each chain rides one pinned\n * circuit (connector ADR 0073). The same is true whether the connector is a\n * hidden service or a clearnet host that a hidden payer reaches through the\n * proxy (TOON_Network#167).\n *\n * `undici` is an optional dependency for exactly this reason: Node bundles undici\n * internally but exposes it under no specifier (`require('undici')` is\n * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a\n * dispatcher cannot be constructed without the package. A dispatcher built by the\n * userland copy *is* honoured by Node's global `fetch`, which calls\n * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici\n * defines — and that is why the dependency is pinned to **undici 7, not 8**.\n * Node's handler changed shape: Node 22 (undici 6.22) passes the old\n * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)\n * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —\n * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.\n * undici 8 dropped the old shape, and on Node 22 every request through such a\n * dispatcher dies in `assertRequestHandler` with\n * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both\n * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not\n * widen the range to `^8` without re-running those on the oldest supported Node.\n *\n * NODE ONLY. This module is imported dynamically, never statically, from the\n * paths that need it; every Node built-in is pulled in through an ESM-safe\n * `require` built off `import.meta.url`, because this package builds as ESM with\n * these deps external and esbuild rewrites a bare `require` into a `__require`\n * shim that throws. A browser cannot reach a `.anyone` address by any means, so\n * a browser bundler must never follow an edge into this file.\n */\n\nimport { createRequire } from 'node:module';\nimport { validateSocks5hUrl } from './socks-url.js';\nimport type { ChainKind } from '../channel/types.js';\nimport type * as netModule from 'node:net';\nimport type * as streamModule from 'node:stream';\nimport type * as tlsModule from 'node:tls';\nimport type * as httpModule from 'node:http';\nimport type * as httpsModule from 'node:https';\nimport type * as socksModule from 'socks';\nimport type * as undiciModule from 'undici';\nimport type WSModule from 'ws';\n\n// ESM-safe require: this file builds as ESM with `undici`/`socks`/`ws` external,\n// so a bare `require(...)` would become a throwing `__require` shim in the\n// published bundle. Building a real require off `import.meta.url` keeps the\n// synchronous lookups below working. (The same pattern the deleted `socks5.ts`\n// carried, for the same reason — it was found in production.)\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * How long to wait for the proxy to build a circuit to the hidden service.\n *\n * `socks` defaults to 30s, which is too short: an introduction-point circuit to\n * a cold hidden service routinely takes longer, and a too-short connect timeout\n * turns \"slow\" into \"unreachable\".\n */\nexport const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120_000;\n\n/**\n * How long a chain-RPC dial may take through the proxy: the SOCKS handshake, an\n * exit circuit and the TCP connect behind it (connector ADR 0073, decision 4).\n *\n * Far shorter than {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}, because a public RPC\n * is reached over an ordinary exit circuit, not the introduction-point dance a\n * hidden service needs. ADR 0073 measured 3,200 calls through `anon`: the worst\n * one that had to build a fresh circuit took 13s. Twice that, rounded, and a\n * stalled circuit is reported rather than waited on.\n */\nexport const DEFAULT_RPC_CONNECT_TIMEOUT_MS = 20_000;\n\n/**\n * The longest a pooled chain-RPC connection is kept idle (ADR 0073, decision 4).\n *\n * A circuit can die quietly under a kept-alive socket, and the next request on\n * it then hangs until its own timeout. A short idle cap means such a socket is\n * dropped before it is reused. undici keeps a socket for 4s by default but lets a\n * server's `Keep-Alive` header stretch that to ten minutes; this caps the stretch.\n */\nexport const RPC_POOL_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * The fixed SOCKS5 usernames chain RPC authenticates with, one per chain.\n *\n * `anon` (like Tor) isolates streams by SOCKS credentials (`IsolateSOCKSAuth`,\n * on by default): streams that present the same username share a circuit, and\n * streams with different ones never do. So a fixed username per chain gives each\n * chain one circuit that stays pinned until the daemon's own\n * `MaxCircuitDirtiness` rotates it (connector ADR 0073, decision 3). No exit then\n * sees both chains' RPC, neither shares a circuit with the client edge, and no\n * call pays for a new circuit of its own. They differ from the connector's\n * `toon-settlement-*` names, so a payer and a node on one daemon do not share\n * circuits either.\n */\nexport const RPC_SOCKS_USERNAMES: Readonly<Record<ChainKind, string>> = {\n evm: 'toon-client-rpc-evm',\n solana: 'toon-client-rpc-solana',\n};\n\n/**\n * The password sent beside a {@link HiddenServiceTransportOptions.socksUsername}.\n * `anon` checks nothing; the username alone picks the circuit. RFC 1929 still\n * wants one, so it is a constant.\n */\nconst SOCKS_ISOLATION_PASSWORD = 'toon';\n\n/** undici's own idle keep-alive, which {@link HiddenServiceTransportOptions.idleTimeoutMs} only ever lowers. */\nconst UNDICI_DEFAULT_KEEP_ALIVE_MS = 4_000;\n\n/** Options for {@link createHiddenServiceTransport}. */\nexport interface HiddenServiceTransportOptions {\n /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */\n connectTimeoutMs?: number;\n /**\n * A fixed SOCKS5 username to authenticate with, which pins every stream this\n * transport opens to one circuit (`IsolateSOCKSAuth`). Unset means no\n * authentication, and the daemon's default circuit.\n */\n socksUsername?: string;\n /**\n * Upper bound on how long an idle pooled connection is kept, ms. Unset keeps\n * undici's own behaviour.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * The three shapes of one proxy, plus the handle that shuts it down.\n *\n * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}\n * to route a client by hand; pass `socksProxy` instead to have the client build\n * this itself.\n */\nexport interface HiddenServiceTransport {\n /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */\n fetch: typeof fetch;\n /** A `ws` factory bound to the proxy, for the BTP carriage. */\n createWebSocket: (url: string) => unknown;\n /**\n * The undici dispatcher behind `fetch`, for handing to something that insists\n * on calling the global `fetch` itself — viem's HTTP transport, in practice\n * (`http(url, { fetchOptions: { dispatcher } })`).\n */\n dispatcher: unknown;\n /** Close the dispatcher's pool and the websocket agents' sockets. */\n close(): Promise<void>;\n}\n\nexport { validateSocks5hUrl } from './socks-url.js';\n\n/** The one primitive: a TCP socket to `destination`, dialled through the proxy. */\nasync function socksConnect(\n proxy: { host: string; port: number; username?: string },\n destination: { host: string; port: number },\n timeoutMs: number\n): Promise<netModule.Socket> {\n const { SocksClient } = nodeRequire('socks') as typeof socksModule;\n const { socket } = await SocksClient.createConnection({\n proxy: {\n host: proxy.host,\n port: proxy.port,\n type: 5,\n ...(proxy.username !== undefined\n ? { userId: proxy.username, password: SOCKS_ISOLATION_PASSWORD }\n : {}),\n },\n command: 'connect',\n destination,\n timeout: timeoutMs,\n });\n return socket;\n}\n\n/** Default port for a scheme, when the URL does not name one. */\nfunction portFor(protocol: string, port: string | number | null | undefined): number {\n if (port !== undefined && port !== null && port !== '' && Number.isFinite(Number(port))) return Number(port);\n return protocol === 'https:' || protocol === 'wss:' ? 443 : 80;\n}\n\n/**\n * Builds every proxy-bound object this client needs from one `socks5h://` URL.\n *\n * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not\n * installed — they are optional dependencies, so a consumer who never touches\n * a hidden service never pays for them.\n */\nexport function createHiddenServiceTransport(\n socksProxy: string,\n options: HiddenServiceTransportOptions = {}\n): HiddenServiceTransport {\n const proxy = {\n ...validateSocks5hUrl(socksProxy),\n ...(options.socksUsername !== undefined ? { username: options.socksUsername } : {}),\n };\n const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;\n\n const undici = requireOptional<typeof undiciModule>('undici', socksProxy);\n requireOptional<typeof socksModule>('socks', socksProxy);\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // The dispatcher. undici hands its `connect` hook the destination it wants a\n // socket to; we dial that through SOCKS instead of `net.connect`, and wrap it\n // in TLS ourselves when the scheme calls for it (undici's default connector\n // would have done that, and we have replaced it).\n const dispatcher = new undici.Agent({\n // A cap, not a new default: undici's own 4s idle stays when it is shorter,\n // and a server's `Keep-Alive` hint can no longer stretch it past the cap.\n ...(options.idleTimeoutMs !== undefined\n ? {\n keepAliveTimeout: Math.min(UNDICI_DEFAULT_KEEP_ALIVE_MS, options.idleTimeoutMs),\n keepAliveMaxTimeout: options.idleTimeoutMs,\n }\n : {}),\n connect(\n connectOptions: { hostname: string; port?: string | number; protocol?: string; servername?: string },\n callback: (err: Error | null, socket: unknown) => void\n ) {\n const port = portFor(connectOptions.protocol ?? 'http:', connectOptions.port);\n socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {\n socket.setNoDelay(true);\n if (connectOptions.protocol !== 'https:') return callback(null, socket);\n const secure = tls.connect({\n socket,\n servername: connectOptions.servername ?? connectOptions.hostname,\n ALPNProtocols: ['http/1.1'],\n });\n secure.once('secureConnect', () => callback(null, secure));\n secure.once('error', (err) => callback(err, null));\n }, (err: Error) => callback(err, null));\n },\n } as unknown as undiciModule.Agent.Options);\n\n // Node's global `fetch` honours a dispatcher built by this userland undici —\n // the `connect` hook above fires — and returns ordinary global `Response`\n // objects, which `undici.fetch` would not, and callers do compare those\n // against the global class. See the note on the undici 7 pin at the top of\n // this file: this line is what makes the major version load-bearing.\n // `dispatcher` is not in the standard `RequestInit`, and @types/node carries a\n // second copy of undici's types that does not structurally match the userland\n // one — hence the cast. The runtime behaviour is verified, the types are not\n // able to express it.\n const proxiedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n globalThis.fetch(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n\n const agents = createWebSocketAgents(proxy, timeoutMs);\n\n return {\n fetch: proxiedFetch,\n createWebSocket: (url: string) => {\n const WSClass = loadWebSocketClass();\n const secure = url.startsWith('wss:') || url.startsWith('https:');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (WSClass as any)(url, { agent: secure ? agents.https : agents.http });\n },\n dispatcher,\n async close(): Promise<void> {\n agents.http.destroy();\n agents.https.destroy();\n await dispatcher.close();\n },\n };\n}\n\n/**\n * The proxy-bound transport one chain's RPC rides: its own pinned circuit, a\n * connect timeout sized for an exit circuit, and a capped idle pool (connector\n * ADR 0073, decisions 3 and 4).\n *\n * It has no fallback. A proxy that is down fails the call; nothing here, or in\n * the viem and Solana paths that use it, ever dials the RPC directly instead.\n */\nexport function createChainRpcTransport(\n socksProxy: string,\n chain: ChainKind\n): HiddenServiceTransport {\n return createHiddenServiceTransport(socksProxy, {\n connectTimeoutMs: DEFAULT_RPC_CONNECT_TIMEOUT_MS,\n socksUsername: RPC_SOCKS_USERNAMES[chain],\n idleTimeoutMs: RPC_POOL_IDLE_TIMEOUT_MS,\n });\n}\n\n/**\n * `ws` speaks `node:http`, so it wants an `http.Agent` — one per scheme, since\n * an `https.Agent` is what puts TLS on the socket and an `http.Agent` is what\n * must not.\n */\nfunction createWebSocketAgents(\n proxy: { host: string; port: number; username?: string },\n timeoutMs: number\n): { http: httpModule.Agent; https: httpsModule.Agent } {\n const http = nodeRequire('node:http') as typeof httpModule;\n const https = nodeRequire('node:https') as typeof httpsModule;\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // `createConnection` is the whole extension point: everything else about\n // pooling, keep-alive and request framing stays the stock agent's business.\n class SocksHttpAgent extends http.Agent {\n override createConnection(\n opts: httpModule.ClientRequestArgs,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n socksConnect(proxy, { host: String(opts.host), port: portFor('http:', opts.port) }, timeoutMs).then(\n (socket) => callback?.(null, socket),\n (err: Error) => callback?.(err, undefined as unknown as streamModule.Duplex)\n );\n return undefined;\n }\n }\n\n class SocksHttpsAgent extends https.Agent {\n override createConnection(\n opts: httpsModule.RequestOptions,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n const fail = (err: Error): void => callback?.(err, undefined as unknown as streamModule.Duplex);\n socksConnect(proxy, { host: String(opts.host), port: portFor('https:', opts.port) }, timeoutMs).then(\n (socket) => {\n const secure = tls.connect({\n socket,\n servername: opts.servername ?? String(opts.host),\n });\n secure.once('secureConnect', () => callback?.(null, secure));\n secure.once('error', fail);\n },\n fail\n );\n return undefined;\n }\n }\n\n return {\n http: new SocksHttpAgent({ keepAlive: false }),\n https: new SocksHttpsAgent({ keepAlive: false }),\n };\n}\n\n/**\n * CJS/ESM interop: `require('ws')` yields the class directly, `{ default }`, or\n * `{ WebSocket }` depending on loader and bundler. Walk the ladder rather than\n * accepting a namespace object as a constructor and throwing cryptically later.\n */\nfunction loadWebSocketClass(): unknown {\n const mod = nodeRequire('ws') as typeof WSModule | { default?: unknown; WebSocket?: unknown };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const candidate = mod as any;\n const WSClass =\n typeof candidate === 'function'\n ? candidate\n : typeof candidate.default === 'function'\n ? candidate.default\n : typeof candidate.WebSocket === 'function'\n ? candidate.WebSocket\n : null;\n if (WSClass === null) {\n throw new Error(\n \"The BTP carriage over a hidden service needs the `ws` package, and require('ws') \" +\n 'did not yield a constructor on .default, .WebSocket, or the module root.'\n );\n }\n return WSClass;\n}\n\n/** Loads an optional dependency, or explains what to install and why. */\nfunction requireOptional<T>(name: string, socksProxy: string): T {\n try {\n return nodeRequire(name) as T;\n } catch {\n throw new Error(\n `Reaching a hidden service needs the optional dependency \"${name}\", which is not installed. ` +\n `Run \\`npm install ${name}\\`, or drop socksProxy (${socksProxy}) and dial a clearnet connector.`\n );\n }\n}\n\n/**\n * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a\n * client configured for a hidden service must not quietly fall back to clearnet,\n * and finding out at packet time costs a signed claim.\n */\nexport async function probeSocks5Proxy(socksProxy: string, timeoutMs = 2000): Promise<void> {\n const { host, port } = validateSocks5hUrl(socksProxy);\n const net = nodeRequire('node:net') as typeof netModule;\n\n return new Promise<void>((resolve, reject) => {\n const socket = net.createConnection({ host, port }, () => {\n socket.destroy();\n resolve();\n });\n const fail = (why: string): void => {\n socket.destroy();\n reject(\n new Error(\n `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is ` +\n 'unreachable without one: start the Anyone Protocol `anon` daemon, or run ' +\n '`toon` which can start one for you.'\n )\n );\n };\n socket.setTimeout(timeoutMs, ()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AAC;AAAA,EACjD;AACF;AAOA,SAAS,qBAA8B;AACrC,QAAM,MAAM,YAAY,IAAI;AAE5B,QAAM,YAAY;AAClB,QAAM,UACJ,OAAO,cAAc,aACjB,YACA,OAAO,UAAU,YAAY,aAC3B,UAAU,UACV,OAAO,UAAU,cAAc,aAC7B,UAAU,YACV;AACV,MAAI,YAAY,MAAM;AACpB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,gBAAmB,MAAc,YAAuB;AAC/D,MAAI;AACF,WAAO,YAAY,IAAI;AAAA,EACzB,QAAQ;AACN,UAAM,IAAI;AAAA,MACR,4DAA4D,IAAI,gDACzC,IAAI,2BAA2B,UAAU;AAAA,IAClE;AAAA,EACF;AACF;AAOA,eAAsB,iBAAiB,YAAoB,YAAY,KAAqB;AAC1F,QAAM,EAAE,MAAM,KAAK,IAAI,mBAAmB,UAAU;AACpD,QAAM,MAAM,YAAY,UAAU;AAElC,SAAO,IAAI,QAAc,CAAC,SAAS,WAAW;AAC5C,UAAM,SAAS,IAAI,iBAAiB,EAAE,MAAM,KAAK,GAAG,MAAM;AACxD,aAAO,QAAQ;AACf,cAAQ;AAAA,IACV,CAAC;AACD,UAAM,OAAO,CAAC,QAAsB;AAClC,aAAO,QAAQ;AACf;AAAA,QACE,IAAI;AAAA,UACF,sBAAsB,IAAI,IAAI,IAAI,KAAK,GAAG;AAAA,QAG5C;AAAA,MACF;AAAA,IACF;AACA,WAAO,WAAW,WAAW,MAAM,KAAK,mBAAmB,SAAS,IAAI,CAAC;AACzE,WAAO,GAAG,SAAS,CAAC,QAAQ,KAAK,IAAI,OAAO,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/transport/socks.ts"],"sourcesContent":["/**\n * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.\n *\n * A connector deployed as a hidden service is reachable only through a running\n * `anon` daemon's SOCKS5 port. Three separate things in this client have to go\n * through that port, and — annoyingly — each needs a different object to do it:\n *\n * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in\n * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,\n * which is why the `socks-proxy-agent` this package used to depend on cannot\n * serve this path at all.\n * - **Chain RPC** goes through viem, which calls the *global* `fetch` and accepts\n * no injected one. Its only opening is `http(url, { fetchOptions })`, so it\n * needs the same dispatcher handed to it as a fetch option (ADR 0002).\n * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and\n * therefore takes an `http.Agent` and nothing else.\n *\n * So this module builds one SOCKS connection primitive and wraps it three ways.\n * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.\n *\n * Chain RPC gets a transport of its own per chain ({@link createChainRpcTransport}),\n * authenticating with a fixed SOCKS username so each chain rides one pinned\n * circuit (connector ADR 0073). The same is true whether the connector is a\n * hidden service or a clearnet host that a hidden payer reaches through the\n * proxy (TOON_Network#167).\n *\n * `undici` is an optional dependency for exactly this reason: Node bundles undici\n * internally but exposes it under no specifier (`require('undici')` is\n * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a\n * dispatcher cannot be constructed without the package. A dispatcher built by the\n * userland copy *is* honoured by Node's global `fetch`, which calls\n * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici\n * defines — and that is why the dependency is pinned to **undici 7, not 8**.\n * Node's handler changed shape: Node 22 (undici 6.22) passes the old\n * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)\n * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —\n * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.\n * undici 8 dropped the old shape, and on Node 22 every request through such a\n * dispatcher dies in `assertRequestHandler` with\n * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both\n * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not\n * widen the range to `^8` without re-running those on the oldest supported Node.\n *\n * NODE ONLY. This module is imported dynamically, never statically, from the\n * paths that need it; every Node built-in is pulled in through an ESM-safe\n * `require` built off `import.meta.url`, because this package builds as ESM with\n * these deps external and esbuild rewrites a bare `require` into a `__require`\n * shim that throws. A browser cannot reach a `.anyone` address by any means, so\n * a browser bundler must never follow an edge into this file.\n */\n\nimport { createRequire } from 'node:module';\nimport { validateSocks5hUrl } from './socks-url.js';\nimport type { ChainKind } from '../channel/types.js';\nimport type * as netModule from 'node:net';\nimport type * as streamModule from 'node:stream';\nimport type * as tlsModule from 'node:tls';\nimport type * as httpModule from 'node:http';\nimport type * as httpsModule from 'node:https';\nimport type * as socksModule from 'socks';\nimport type * as undiciModule from 'undici';\nimport type WSModule from 'ws';\n\n// ESM-safe require: this file builds as ESM with `undici`/`socks`/`ws` external,\n// so a bare `require(...)` would become a throwing `__require` shim in the\n// published bundle. Building a real require off `import.meta.url` keeps the\n// synchronous lookups below working. (The same pattern the deleted `socks5.ts`\n// carried, for the same reason — it was found in production.)\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * How long to wait for the proxy to build a circuit to the hidden service.\n *\n * `socks` defaults to 30s, which is too short: an introduction-point circuit to\n * a cold hidden service routinely takes longer, and a too-short connect timeout\n * turns \"slow\" into \"unreachable\".\n */\nexport const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120_000;\n\n/**\n * How long a chain-RPC dial may take through the proxy: the SOCKS handshake, an\n * exit circuit and the TCP connect behind it (connector ADR 0073, decision 4).\n *\n * Far shorter than {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}, because a public RPC\n * is reached over an ordinary exit circuit, not the introduction-point dance a\n * hidden service needs. ADR 0073 measured 3,200 calls through `anon`: the worst\n * one that had to build a fresh circuit took 13s. Twice that, rounded, and a\n * stalled circuit is reported rather than waited on.\n */\nexport const DEFAULT_RPC_CONNECT_TIMEOUT_MS = 20_000;\n\n/**\n * The longest a pooled chain-RPC connection is kept idle (ADR 0073, decision 4).\n *\n * A circuit can die quietly under a kept-alive socket, and the next request on\n * it then hangs until its own timeout. A short idle cap means such a socket is\n * dropped before it is reused. undici keeps a socket for 4s by default but lets a\n * server's `Keep-Alive` header stretch that to ten minutes; this caps the stretch.\n */\nexport const RPC_POOL_IDLE_TIMEOUT_MS = 30_000;\n\n/**\n * The fixed SOCKS5 usernames chain RPC authenticates with, one per chain.\n *\n * `anon` (like Tor) isolates streams by SOCKS credentials (`IsolateSOCKSAuth`,\n * on by default): streams that present the same username share a circuit, and\n * streams with different ones never do. So a fixed username per chain gives each\n * chain one circuit that stays pinned until the daemon's own\n * `MaxCircuitDirtiness` rotates it (connector ADR 0073, decision 3). No exit then\n * sees both chains' RPC, neither shares a circuit with the client edge, and no\n * call pays for a new circuit of its own. They differ from the connector's\n * `toon-settlement-*` names, so a payer and a node on one daemon do not share\n * circuits either.\n */\nexport const RPC_SOCKS_USERNAMES: Readonly<Record<ChainKind, string>> = {\n evm: 'toon-client-rpc-evm',\n solana: 'toon-client-rpc-solana',\n};\n\n/**\n * The password sent beside a {@link HiddenServiceTransportOptions.socksUsername}.\n * `anon` checks nothing; the username alone picks the circuit. RFC 1929 still\n * wants one, so it is a constant.\n */\nconst SOCKS_ISOLATION_PASSWORD = 'toon';\n\n/** undici's own idle keep-alive, which {@link HiddenServiceTransportOptions.idleTimeoutMs} only ever lowers. */\nconst UNDICI_DEFAULT_KEEP_ALIVE_MS = 4_000;\n\n/** Options for {@link createHiddenServiceTransport}. */\nexport interface HiddenServiceTransportOptions {\n /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */\n connectTimeoutMs?: number;\n /**\n * A fixed SOCKS5 username to authenticate with, which pins every stream this\n * transport opens to one circuit (`IsolateSOCKSAuth`). Unset means no\n * authentication, and the daemon's default circuit.\n */\n socksUsername?: string;\n /**\n * Upper bound on how long an idle pooled connection is kept, ms. Unset keeps\n * undici's own behaviour.\n */\n idleTimeoutMs?: number;\n}\n\n/**\n * The three shapes of one proxy, plus the handle that shuts it down.\n *\n * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}\n * to route a client by hand; pass `socksProxy` instead to have the client build\n * this itself.\n */\nexport interface HiddenServiceTransport {\n /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */\n fetch: typeof fetch;\n /** A `ws` factory bound to the proxy, for the BTP carriage. */\n createWebSocket: (url: string) => unknown;\n /**\n * The undici dispatcher behind `fetch`, for handing to something that insists\n * on calling the global `fetch` itself — viem's HTTP transport, in practice\n * (`http(url, { fetchOptions: { dispatcher } })`).\n */\n dispatcher: unknown;\n /** Close the dispatcher's pool and the websocket agents' sockets. */\n close(): Promise<void>;\n}\n\nexport { validateSocks5hUrl } from './socks-url.js';\n\n/** The one primitive: a TCP socket to `destination`, dialled through the proxy. */\nasync function socksConnect(\n proxy: { host: string; port: number; username?: string },\n destination: { host: string; port: number },\n timeoutMs: number\n): Promise<netModule.Socket> {\n const { SocksClient } = nodeRequire('socks') as typeof socksModule;\n const { socket } = await SocksClient.createConnection({\n proxy: {\n host: proxy.host,\n port: proxy.port,\n type: 5,\n ...(proxy.username !== undefined\n ? { userId: proxy.username, password: SOCKS_ISOLATION_PASSWORD }\n : {}),\n },\n command: 'connect',\n destination,\n timeout: timeoutMs,\n });\n return socket;\n}\n\n/** Default port for a scheme, when the URL does not name one. */\nfunction portFor(protocol: string, port: string | number | null | undefined): number {\n if (port !== undefined && port !== null && port !== '' && Number.isFinite(Number(port))) return Number(port);\n return protocol === 'https:' || protocol === 'wss:' ? 443 : 80;\n}\n\n/**\n * Builds every proxy-bound object this client needs from one `socks5h://` URL.\n *\n * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not\n * installed — they are optional dependencies, so a consumer who never touches\n * a hidden service never pays for them.\n */\nexport function createHiddenServiceTransport(\n socksProxy: string,\n options: HiddenServiceTransportOptions = {}\n): HiddenServiceTransport {\n const proxy = {\n ...validateSocks5hUrl(socksProxy),\n ...(options.socksUsername !== undefined ? { username: options.socksUsername } : {}),\n };\n const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;\n\n const undici = requireOptional<typeof undiciModule>('undici', socksProxy);\n requireOptional<typeof socksModule>('socks', socksProxy);\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // The dispatcher. undici hands its `connect` hook the destination it wants a\n // socket to; we dial that through SOCKS instead of `net.connect`, and wrap it\n // in TLS ourselves when the scheme calls for it (undici's default connector\n // would have done that, and we have replaced it).\n const dispatcher = new undici.Agent({\n // A cap, not a new default: undici's own 4s idle stays when it is shorter,\n // and a server's `Keep-Alive` hint can no longer stretch it past the cap.\n ...(options.idleTimeoutMs !== undefined\n ? {\n keepAliveTimeout: Math.min(UNDICI_DEFAULT_KEEP_ALIVE_MS, options.idleTimeoutMs),\n keepAliveMaxTimeout: options.idleTimeoutMs,\n }\n : {}),\n connect(\n connectOptions: { hostname: string; port?: string | number; protocol?: string; servername?: string },\n callback: (err: Error | null, socket: unknown) => void\n ) {\n const port = portFor(connectOptions.protocol ?? 'http:', connectOptions.port);\n socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {\n socket.setNoDelay(true);\n if (connectOptions.protocol !== 'https:') return callback(null, socket);\n const secure = tls.connect({\n socket,\n servername: connectOptions.servername ?? connectOptions.hostname,\n ALPNProtocols: ['http/1.1'],\n });\n secure.once('secureConnect', () => callback(null, secure));\n secure.once('error', (err) => callback(err, null));\n }, (err: Error) => callback(err, null));\n },\n } as unknown as undiciModule.Agent.Options);\n\n // Node's global `fetch` honours a dispatcher built by this userland undici —\n // the `connect` hook above fires — and returns ordinary global `Response`\n // objects, which `undici.fetch` would not, and callers do compare those\n // against the global class. See the note on the undici 7 pin at the top of\n // this file: this line is what makes the major version load-bearing.\n // `dispatcher` is not in the standard `RequestInit`, and @types/node carries a\n // second copy of undici's types that does not structurally match the userland\n // one — hence the cast. The runtime behaviour is verified, the types are not\n // able to express it.\n const proxiedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n globalThis.fetch(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n\n const agents = createWebSocketAgents(proxy, timeoutMs);\n\n return {\n fetch: proxiedFetch,\n createWebSocket: (url: string) => {\n const WSClass = loadWebSocketClass();\n const secure = url.startsWith('wss:') || url.startsWith('https:');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (WSClass as any)(url, { agent: secure ? agents.https : agents.http });\n },\n dispatcher,\n async close(): Promise<void> {\n agents.http.destroy();\n agents.https.destroy();\n await dispatcher.close();\n },\n };\n}\n\n/**\n * The proxy-bound transport one chain's RPC rides: its own pinned circuit, a\n * connect timeout sized for an exit circuit, and a capped idle pool (connector\n * ADR 0073, decisions 3 and 4).\n *\n * It has no fallback. A proxy that is down fails the call; nothing here, or in\n * the viem and Solana paths that use it, ever dials the RPC directly instead.\n */\nexport function createChainRpcTransport(\n socksProxy: string,\n chain: ChainKind\n): HiddenServiceTransport {\n return createHiddenServiceTransport(socksProxy, {\n connectTimeoutMs: DEFAULT_RPC_CONNECT_TIMEOUT_MS,\n socksUsername: RPC_SOCKS_USERNAMES[chain],\n idleTimeoutMs: RPC_POOL_IDLE_TIMEOUT_MS,\n });\n}\n\n/**\n * `ws` speaks `node:http`, so it wants an `http.Agent` — one per scheme, since\n * an `https.Agent` is what puts TLS on the socket and an `http.Agent` is what\n * must not.\n */\nfunction createWebSocketAgents(\n proxy: { host: string; port: number; username?: string },\n timeoutMs: number\n): { http: httpModule.Agent; https: httpsModule.Agent } {\n const http = nodeRequire('node:http') as typeof httpModule;\n const https = nodeRequire('node:https') as typeof httpsModule;\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // `createConnection` is the whole extension point: everything else about\n // pooling, keep-alive and request framing stays the stock agent's business.\n class SocksHttpAgent extends http.Agent {\n override createConnection(\n opts: httpModule.ClientRequestArgs,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n socksConnect(proxy, { host: String(opts.host), port: portFor('http:', opts.port) }, timeoutMs).then(\n (socket) => callback?.(null, socket),\n (err: Error) => callback?.(err, undefined as unknown as streamModule.Duplex)\n );\n return undefined;\n }\n }\n\n class SocksHttpsAgent extends https.Agent {\n override createConnection(\n opts: httpsModule.RequestOptions,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n const fail = (err: Error): void => callback?.(err, undefined as unknown as streamModule.Duplex);\n socksConnect(proxy, { host: String(opts.host), port: portFor('https:', opts.port) }, timeoutMs).then(\n (socket) => {\n const secure = tls.connect({\n socket,\n servername: opts.servername ?? String(opts.host),\n });\n secure.once('secureConnect', () => callback?.(null, secure));\n secure.once('error', fail);\n },\n fail\n );\n return undefined;\n }\n }\n\n return {\n http: new SocksHttpAgent({ keepAlive: false }),\n https: new SocksHttpsAgent({ keepAlive: false }),\n };\n}\n\n/**\n * CJS/ESM interop: `require('ws')` yields the class directly, `{ default }`, or\n * `{ WebSocket }` depending on loader and bundler. Walk the ladder rather than\n * accepting a namespace object as a constructor and throwing cryptically later.\n */\nfunction loadWebSocketClass(): unknown {\n const mod = nodeRequire('ws') as typeof WSModule | { default?: unknown; WebSocket?: unknown };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const candidate = mod as any;\n const WSClass =\n typeof candidate === 'function'\n ? candidate\n : typeof candidate.default === 'function'\n ? candidate.default\n : typeof candidate.WebSocket === 'function'\n ? candidate.WebSocket\n : null;\n if (WSClass === null) {\n throw new Error(\n \"The BTP carriage over a hidden service needs the `ws` package, and require('ws') \" +\n 'did not yield a constructor on .default, .WebSocket, or the module root.'\n );\n }\n return WSClass;\n}\n\n/** Loads an optional dependency, or explains what to install and why. */\nfunction requireOptional<T>(name: string, socksProxy: string): T {\n try {\n return nodeRequire(name) as T;\n } catch {\n throw new Error(\n `Reaching a hidden service needs the optional dependency \"${name}\", which is not installed. ` +\n `Run \\`npm install ${name}\\`, or drop socksProxy (${socksProxy}) and dial a clearnet connector.`\n );\n }\n}\n\n/**\n * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a\n * client configured for a hidden service must not quietly fall back to clearnet,\n * and finding out at packet time costs a signed claim.\n */\nexport async function probeSocks5Proxy(socksProxy: string, timeoutMs = 2000): Promise<void> {\n const { host, port } = validateSocks5hUrl(socksProxy);\n const net = nodeRequire('node:net') as typeof netModule;\n\n return new Promise<void>((resolve, reject) => {\n const socket = net.createConnection({ host, port }, () => {\n socket.destroy();\n resolve();\n });\n const fail = (why: string): void => {\n socket.destroy();\n reject(\n new Error(\n `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is ` +\n 'unreachable without one: start the Anyone Protocol `anon` daemon, or run ' +\n '`toon-client` which can start one for you.'\n )\n );\n };\n socket.setTimeout(timeoutMs, () => fail(`timed out after ${timeoutMs}ms`));\n socket.on('error', (err) => fail(err.message));\n });\n}\n"],"mappings":";;;;;AAmDA,SAAS,qBAAqB;AAiB9B,IAAM,cAAc,cAAc,YAAY,GAAG;AAS1C,IAAM,gCAAgC;AAYtC,IAAM,iCAAiC;AAUvC,IAAM,2BAA2B;AAejC,IAAM,sBAA2D;AAAA,EACtE,KAAK;AAAA,EACL,QAAQ;AACV;AAOA,IAAM,2BAA2B;AAGjC,IAAM,+BAA+B;AA4CrC,eAAe,aACb,OACA,aACA,WAC2B;AAC3B,QAAM,EAAE,YAAY,IAAI,YAAY,OAAO;AAC3C,QAAM,EAAE,OAAO,IAAI,MAAM,YAAY,iBAAiB;AAAA,IACpD,OAAO;AAAA,MACL,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM;AAAA,MACZ,MAAM;AAAA,MACN,GAAI,MAAM,aAAa,SACnB,EAAE,QAAQ,MAAM,UAAU,UAAU,yBAAyB,IAC7D,CAAC;AAAA,IACP;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA,SAAS;AAAA,EACX,CAAC;AACD,SAAO;AACT;AAGA,SAAS,QAAQ,UAAkB,MAAkD;AACnF,MAAI,SAAS,UAAa,SAA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AAC;AACD,UAAM,OAAO,CAAC,QAAsB;AAClC,aAAO,QAAQ;AACf;AAAA,QACE,IAAI;AAAA,UACF,sBAAsB,IAAI,IAAI,IAAI,KAAK,GAAG;AAAA,QAG5C;AAAA,MACF;AAAA,IACF;AACA,WAAO,WAAW,WAAW,MAAM,KAAK,mBAAmB,SAAS,IAAI,CAAC;AACzE,WAAO,GAAG,SAAS,CAAC,QAAQ,KAAK,IAAI,OAAO,CAAC;AAAA,EAC/C,CAAC;AACH;","names":[]}
package/dist/cli/main.js CHANGED
@@ -300,7 +300,7 @@ function parseCommandLine(argv) {
300
300
  }
301
301
  const spec = COMMANDS[command];
302
302
  if (spec === void 0) {
303
- throw new UsageError(`unknown command '${command}'. Run 'toon help' for the list.`);
303
+ throw new UsageError(`unknown command '${command}'. Run 'toon-client help' for the list.`);
304
304
  }
305
305
  const rest = positionals.slice(1);
306
306
  if (!boolOption(values, "help")) {
@@ -334,7 +334,7 @@ function columns(rows) {
334
334
  function usage(command) {
335
335
  if (command !== void 0 && command in COMMANDS) {
336
336
  const spec = COMMANDS[command];
337
- const parts = [`toon ${spec.usage}`, "", spec.summary];
337
+ const parts = [`toon-client ${spec.usage}`, "", spec.summary];
338
338
  if (spec.details) parts.push("", ...spec.details);
339
339
  const opts = spec.options.map(
340
340
  (name) => optionLine(name, COMMAND_OPTIONS[name])
@@ -348,9 +348,9 @@ function usage(command) {
348
348
  return parts.join("\n");
349
349
  }
350
350
  return [
351
- "toon \u2014 pay for an HTTP request, per request, from an x402 payment channel.",
351
+ "toon-client \u2014 pay for an HTTP request, per request, from an x402 payment channel.",
352
352
  "",
353
- "Usage: toon <command> [options]",
353
+ "Usage: toon-client <command> [options]",
354
354
  "",
355
355
  "Commands:",
356
356
  columns(
@@ -364,7 +364,7 @@ function usage(command) {
364
364
  " TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE,",
365
365
  " TOON_SOCKS, TOON_FACILITATOR, TOON_DEPOSIT_GAS, TOON_DEPOSIT_METHOD.",
366
366
  "",
367
- "Run 'toon help <command>' for one command in detail."
367
+ "Run 'toon-client help <command>' for one command in detail."
368
368
  ].join("\n");
369
369
  }
370
370
 
@@ -422,7 +422,7 @@ async function resolvePassword(options) {
422
422
  }
423
423
  function readKeystore(path, password) {
424
424
  if (!existsSync(path)) {
425
- throw new CliConfigError(`no keystore at ${path}`, "Run 'toon init' to create one.");
425
+ throw new CliConfigError(`no keystore at ${path}`, "Run 'toon-client init' to create one.");
426
426
  }
427
427
  try {
428
428
  return openKeystore(path, password);
@@ -482,8 +482,8 @@ function resolveSettings(values, env, options = {}) {
482
482
  connector = DEVNET.store.url;
483
483
  connectorSource = "default";
484
484
  warnings.push(
485
- `toon: no connector given, using the devnet store node ${DEVNET.store.url}.
486
- Set --connector or ${CONNECTOR_ENV} to talk to another node.`
485
+ `toon-client: no connector given, using the devnet store node ${DEVNET.store.url}.
486
+ Set --connector or ${CONNECTOR_ENV} to talk to another node.`
487
487
  );
488
488
  }
489
489
  const chain = parseChain(stringOption(values, "chain"), "--chain") ?? parseChain(env[CHAIN_ENV], CHAIN_ENV);
@@ -540,6 +540,7 @@ async function resolveKeyMaterial(settings, deps, options = {}) {
540
540
  from: "env"
541
541
  };
542
542
  }
543
+ if (options.keyless === true) return { kind: "ephemeral" };
543
544
  if (keystoreExists(settings.keystorePath)) {
544
545
  const { password } = await resolvePassword({
545
546
  message: `Password for ${settings.keystorePath}: `,
@@ -556,10 +557,9 @@ async function resolveKeyMaterial(settings, deps, options = {}) {
556
557
  from: "keystore"
557
558
  };
558
559
  }
559
- if (options.keyless === true) return { kind: "ephemeral" };
560
560
  throw new CliConfigError(
561
561
  `no keys: ${MNEMONIC_ENV} is unset and there is no keystore at ${settings.keystorePath}`,
562
- "Run 'toon init' to create one, or set TOON_MNEMONIC."
562
+ "Run 'toon-client init' to create one, or set TOON_MNEMONIC."
563
563
  );
564
564
  }
565
565
  function buildClientConfig(settings, keys) {
@@ -588,7 +588,7 @@ function buildClientConfig(settings, keys) {
588
588
  };
589
589
  }
590
590
  async function defaultCreateClient(config) {
591
- const module = await import("../client-L75P6SOK.js");
591
+ const module = await import("../client-WCAXMQWM.js");
592
592
  const factory = module.ToonClient;
593
593
  if (factory === void 0) {
594
594
  throw new Error(
@@ -638,7 +638,7 @@ var Context = class {
638
638
  async withProxy(settings) {
639
639
  if (settings.socksProxy !== void 0) return settings;
640
640
  if (!isHiddenServiceUrl(settings.connector)) return settings;
641
- const log = (message) => this.out.warn(`toon: ${message}`);
641
+ const log = (message) => this.out.warn(`toon-client: ${message}`);
642
642
  log(`${settings.connector} is a hidden service; starting a local anon daemon`);
643
643
  const start = this.deps.startAnon ?? defaultStartAnon;
644
644
  this.managedAnon = await start(log);
@@ -652,7 +652,7 @@ var Context = class {
652
652
  }
653
653
  };
654
654
  async function defaultStartAnon(log) {
655
- const { startManagedAnon } = await import("../anon-daemon-ZFBL6EYA.js");
655
+ const { startManagedAnon } = await import("../anon-daemon-5PIPY36T.js");
656
656
  return startManagedAnon({ log });
657
657
  }
658
658
 
@@ -895,7 +895,7 @@ async function run2(ctx) {
895
895
  }
896
896
  ctx.out.render(connectorView === void 0 ? channels : { channels, connector: connectorView }, () => {
897
897
  if (channels.length === 0) {
898
- ctx.out.line("No channel with this node yet. Open one with 'toon channel open', or pay for a request.");
898
+ ctx.out.line("No channel with this node yet. Open one with 'toon-client channel open', or pay for a request.");
899
899
  return;
900
900
  }
901
901
  for (const state of channels) {
@@ -919,7 +919,7 @@ async function run3(ctx) {
919
919
  ctx.out.render({ connector: client.connector, channels: entries }, () => {
920
920
  if (entries.length === 0) {
921
921
  ctx.out.line("This connector reports no channels for your account.");
922
- ctx.out.line("Open one with 'toon channel open', or pay for a request.");
922
+ ctx.out.line("Open one with 'toon-client channel open', or pay for a request.");
923
923
  return;
924
924
  }
925
925
  for (const entry of entries) {
@@ -1045,7 +1045,7 @@ async function run5(ctx) {
1045
1045
  ["address", result.address]
1046
1046
  ]);
1047
1047
  ctx.out.line();
1048
- ctx.out.line("Check it landed with 'toon balances'.");
1048
+ ctx.out.line("Check it landed with 'toon-client balances'.");
1049
1049
  });
1050
1050
  return 0;
1051
1051
  }
@@ -1173,8 +1173,8 @@ async function run7(ctx) {
1173
1173
  ]);
1174
1174
  ctx.out.line();
1175
1175
  ctx.out.line("Next: fund it, then open a channel.");
1176
- ctx.out.line(" toon faucet");
1177
- ctx.out.line(" toon channel open --deposit 100000");
1176
+ ctx.out.line(" toon-client faucet");
1177
+ ctx.out.line(" toon-client channel open --deposit 100000");
1178
1178
  }
1179
1179
  );
1180
1180
  return 0;
@@ -1312,14 +1312,14 @@ function refusalHint(result, asset) {
1312
1312
  }
1313
1313
  return [
1314
1314
  "The connector answered with terms instead of doing the work, which means it saw no",
1315
- "usable claim. Check the channel with 'toon channel status --connector-view'."
1315
+ "usable claim. Check the channel with 'toon-client channel status --connector-view'."
1316
1316
  ];
1317
1317
  }
1318
1318
  case "F03":
1319
1319
  return cost === void 0 ? ["The claim did not advance far enough to cover the route."] : [
1320
1320
  `The route costs ${cost}. Either the claim did not advance by that much, or the`,
1321
1321
  "channel has no room left for it \u2014 add collateral with",
1322
- "'toon channel deposit <base units>', then send again."
1322
+ "'toon-client channel deposit <base units>', then send again."
1323
1323
  ];
1324
1324
  case "F01":
1325
1325
  if (result.refusedBy === "path") {
@@ -1330,12 +1330,12 @@ function refusalHint(result, asset) {
1330
1330
  }
1331
1331
  return [
1332
1332
  "The connector would not take the voucher: it names a channel it cannot see, or an amount",
1333
- "it has already banked. Compare the two watermarks with 'toon channel status --connector-view'."
1333
+ "it has already banked. Compare the two watermarks with 'toon-client channel status --connector-view'."
1334
1334
  ];
1335
1335
  case "F02":
1336
1336
  return [
1337
1337
  "No route to that destination over this carriage. Check what this node actually serves",
1338
- "with 'toon describe', and which carriage it wants."
1338
+ "with 'toon-client describe', and which carriage it wants."
1339
1339
  ];
1340
1340
  case "F00":
1341
1341
  return [
@@ -1343,7 +1343,7 @@ function refusalHint(result, asset) {
1343
1343
  "the route handler, so it cannot be absolute, contain `..`, or name a host."
1344
1344
  ];
1345
1345
  case "F06":
1346
- return ["No claim was attached. Open a channel with 'toon channel open --deposit 100000'."];
1346
+ return ["No claim was attached. Open a channel with 'toon-client channel open --deposit 100000'."];
1347
1347
  default:
1348
1348
  if (result.code.startsWith("T")) {
1349
1349
  return ["A temporary refusal \u2014 the path asked you to try again shortly."];
@@ -1634,21 +1634,21 @@ function exitCodeFor(error) {
1634
1634
  }
1635
1635
  function reportError(error, stderr) {
1636
1636
  if (error instanceof UsageError) {
1637
- stderr(`toon: ${error.message}`);
1637
+ stderr(`toon-client: ${error.message}`);
1638
1638
  stderr("");
1639
1639
  stderr(usage(error.command));
1640
1640
  return EXIT.usage;
1641
1641
  }
1642
1642
  if (error instanceof CliConfigError) {
1643
- stderr(`toon: ${error.message}`);
1644
- if (error.hint !== void 0) stderr(` ${error.hint}`);
1643
+ stderr(`toon-client: ${error.message}`);
1644
+ if (error.hint !== void 0) stderr(` ${error.hint}`);
1645
1645
  return EXIT.usage;
1646
1646
  }
1647
1647
  const code = exitCodeFor(error);
1648
1648
  const message = error instanceof Error ? error.message : String(error);
1649
- stderr(`toon: ${message}`);
1649
+ stderr(`toon-client: ${message}`);
1650
1650
  if (code === EXIT.network) {
1651
- stderr(" The connector or the chain RPC could not be reached. Check the URL and try again.");
1651
+ stderr(" The connector or the chain RPC could not be reached. Check the URL and try again.");
1652
1652
  }
1653
1653
  if (code === EXIT.unexpected && error instanceof Error && error.stack !== void 0) {
1654
1654
  stderr(error.stack);
@@ -1747,7 +1747,7 @@ async function runCli(argv, options = {}) {
1747
1747
  try {
1748
1748
  await client.close();
1749
1749
  } catch (error) {
1750
- out.warn(`toon: closing the client failed: ${error instanceof Error ? error.message : String(error)}`);
1750
+ out.warn(`toon-client: closing the client failed: ${error instanceof Error ? error.message : String(error)}`);
1751
1751
  }
1752
1752
  }
1753
1753
  context?.stopManagedAnon();