@toon-protocol/client 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,10 +6,23 @@ import {
6
6
  import { createRequire } from "module";
7
7
  var nodeRequire = createRequire(import.meta.url);
8
8
  var DEFAULT_HS_CONNECT_TIMEOUT_MS = 12e4;
9
+ var DEFAULT_RPC_CONNECT_TIMEOUT_MS = 2e4;
10
+ var RPC_POOL_IDLE_TIMEOUT_MS = 3e4;
11
+ var RPC_SOCKS_USERNAMES = {
12
+ evm: "toon-client-rpc-evm",
13
+ solana: "toon-client-rpc-solana"
14
+ };
15
+ var SOCKS_ISOLATION_PASSWORD = "toon";
16
+ var UNDICI_DEFAULT_KEEP_ALIVE_MS = 4e3;
9
17
  async function socksConnect(proxy, destination, timeoutMs) {
10
18
  const { SocksClient } = nodeRequire("socks");
11
19
  const { socket } = await SocksClient.createConnection({
12
- proxy: { host: proxy.host, port: proxy.port, type: 5 },
20
+ proxy: {
21
+ host: proxy.host,
22
+ port: proxy.port,
23
+ type: 5,
24
+ ...proxy.username !== void 0 ? { userId: proxy.username, password: SOCKS_ISOLATION_PASSWORD } : {}
25
+ },
13
26
  command: "connect",
14
27
  destination,
15
28
  timeout: timeoutMs
@@ -21,12 +34,21 @@ function portFor(protocol, port) {
21
34
  return protocol === "https:" || protocol === "wss:" ? 443 : 80;
22
35
  }
23
36
  function createHiddenServiceTransport(socksProxy, options = {}) {
24
- const proxy = validateSocks5hUrl(socksProxy);
37
+ const proxy = {
38
+ ...validateSocks5hUrl(socksProxy),
39
+ ...options.socksUsername !== void 0 ? { username: options.socksUsername } : {}
40
+ };
25
41
  const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;
26
42
  const undici = requireOptional("undici", socksProxy);
27
43
  requireOptional("socks", socksProxy);
28
44
  const tls = nodeRequire("node:tls");
29
45
  const dispatcher = new undici.Agent({
46
+ // A cap, not a new default: undici's own 4s idle stays when it is shorter,
47
+ // and a server's `Keep-Alive` hint can no longer stretch it past the cap.
48
+ ...options.idleTimeoutMs !== void 0 ? {
49
+ keepAliveTimeout: Math.min(UNDICI_DEFAULT_KEEP_ALIVE_MS, options.idleTimeoutMs),
50
+ keepAliveMaxTimeout: options.idleTimeoutMs
51
+ } : {},
30
52
  connect(connectOptions, callback) {
31
53
  const port = portFor(connectOptions.protocol ?? "http:", connectOptions.port);
32
54
  socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {
@@ -59,6 +81,13 @@ function createHiddenServiceTransport(socksProxy, options = {}) {
59
81
  }
60
82
  };
61
83
  }
84
+ function createChainRpcTransport(socksProxy, chain) {
85
+ return createHiddenServiceTransport(socksProxy, {
86
+ connectTimeoutMs: DEFAULT_RPC_CONNECT_TIMEOUT_MS,
87
+ socksUsername: RPC_SOCKS_USERNAMES[chain],
88
+ idleTimeoutMs: RPC_POOL_IDLE_TIMEOUT_MS
89
+ });
90
+ }
62
91
  function createWebSocketAgents(proxy, timeoutMs) {
63
92
  const http = nodeRequire("node:http");
64
93
  const https = nodeRequire("node:https");
@@ -137,7 +166,11 @@ async function probeSocks5Proxy(socksProxy, timeoutMs = 2e3) {
137
166
 
138
167
  export {
139
168
  DEFAULT_HS_CONNECT_TIMEOUT_MS,
169
+ DEFAULT_RPC_CONNECT_TIMEOUT_MS,
170
+ RPC_POOL_IDLE_TIMEOUT_MS,
171
+ RPC_SOCKS_USERNAMES,
140
172
  createHiddenServiceTransport,
173
+ createChainRpcTransport,
141
174
  probeSocks5Proxy
142
175
  };
143
- //# sourceMappingURL=chunk-GOLBDUNV.js.map
176
+ //# sourceMappingURL=chunk-LJSOTVUT.js.map
@@ -0,0 +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, () => 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,U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A,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":[]}
@@ -200,9 +200,9 @@ var DEVNET = {
200
200
  chainId: 84532,
201
201
  rpcUrl: "https://sepolia.base.org",
202
202
  tokenNetworkRegistry: "0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5",
203
- tokenNetwork: "0xe9E05dfecfe165266C88d73e61D483612651952a",
204
- /** Mock USDC, 6 decimals, ungated `mint()`. */
205
- tokenAddress: "0x49beE1Bca5d15Fb0963117923403F9498119a9Ce",
203
+ tokenNetwork: "0x1B4606218ceE5Bf02B546e416905F4D3FC8a0249",
204
+ /** Devnet USDC: Circle FiatToken v2.2 (ERC-3009, EIP-2612), 6 decimals, minter-gated — fund via the faucet (connector#1337). */
205
+ tokenAddress: "0x0C996d7c934c79a6255254875607Fe69df25C0E1",
206
206
  decimals: 6
207
207
  },
208
208
  /** Solana devnet — the public cluster, not a local validator. */
@@ -236,4 +236,4 @@ export {
236
236
  DEVNET,
237
237
  defaultRpcUrl
238
238
  };
239
- //# sourceMappingURL=chunk-7MPONJW5.js.map
239
+ //# sourceMappingURL=chunk-O6KX7MHD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transport/hs-hostname.ts","../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * Hidden-service hostname validation for the Anyone Protocol network.\n *\n * The `anon` binary routes hidden-service hostnames under the **`.anyone`** TLD\n * ONLY. A `<host>.anon` name is NOT recognized as a hidden service — anon treats\n * it as a clearnet name and tries to exit-resolve it, which fails\n * (`resolve failed` / `HostUnreachable`). Only `<host>.anyone` triggers anon's\n * `parse_extended_hostname: Anyone dns address lookup` and is validated.\n *\n * Historically this client accepted BOTH `.anon` and `.anyone`, so a `.anon`\n * address was silently accepted and then failed deep in the transport with an\n * opaque error. This module makes `.anyone` the single accepted HS TLD and\n * rejects the near-misses up front with an actionable message.\n *\n * `.onion` is a near-miss too, and a more tempting one: it is a real hidden\n * service, just on a network this client does not dial. We route through `anon`,\n * not `tor`, so accepting a `.onion` address would repeat the exact mistake\n * `.anon` taught us — an address we cannot reach, failing late and cryptically.\n *\n * This is a pure, browser-safe helper (no Node built-ins) so it can be imported\n * from any path, including config validation.\n */\n\n/**\n * A `<host>.anyone` hidden-service hostname. The label is base32 (`a-z2-7`),\n * matching the on-wire onion-style address alphabet anon uses.\n */\nexport const HS_HOSTNAME_REGEX = /^[a-z2-7]+\\.anyone$/;\n\n/** Max length of an HS hostname (defensive bound against pathological input). */\nexport const HS_HOSTNAME_MAX_LENGTH = 80;\n\n/**\n * Returns true iff `s` is a routable `.anyone` hidden-service hostname.\n * Does NOT accept `.anon` or `.onion` (see {@link assertRoutableHsHostname}).\n */\nexport function isRoutableHsHostname(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n s.length <= HS_HOSTNAME_MAX_LENGTH &&\n HS_HOSTNAME_REGEX.test(s)\n );\n}\n\n/**\n * Returns true iff `url` addresses a hidden service — i.e. its host is a\n * routable `.anyone` address.\n *\n * Takes a URL string rather than a hostname because that is what a caller\n * actually holds: a `connector` config value, an `httpEndpoint` off a\n * self-description. A string that is not a URL at all is not a hidden service.\n */\nexport function isHiddenServiceUrl(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n try {\n return isRoutableHsHostname(new URL(url).hostname);\n } catch {\n return false;\n }\n}\n\n/**\n * Validates that `hostname` is a routable `.anyone` hidden-service address.\n *\n * - `<host>.anyone` → returns the hostname unchanged.\n * - `<host>.anon` → throws, pointing at `.anyone` (anon does NOT route\n * `.anon`; it is treated as a clearnet address and fails `HostUnreachable`).\n * - `<host>.onion` → throws, naming the network mismatch: that is Tor, and\n * this client dials the Anyone Protocol.\n * - anything else → throws a generic format error.\n *\n * @throws {Error} if the hostname is not a routable `.anyone` HS address.\n */\nexport function assertRoutableHsHostname(hostname: unknown): string {\n if (typeof hostname === 'string' && /\\.anon$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is not a routable hidden-service address; use the .anyone TLD ` +\n `(e.g. \"${hostname.replace(/\\.anon$/, '.anyone')}\"). ` +\n 'The anon daemon only resolves hidden services under .anyone — a .anon ' +\n 'name is treated as a clearnet address and fails (HostUnreachable).'\n );\n }\n if (typeof hostname === 'string' && /\\.onion$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is a Tor hidden service, which this client does not dial. ` +\n 'Packets are routed through the Anyone Protocol `anon` daemon, whose ' +\n 'hidden services live under the .anyone TLD.'\n );\n }\n if (!isRoutableHsHostname(hostname)) {\n throw new Error(\n `Invalid hidden-service hostname: ${JSON.stringify(hostname)}. ` +\n `Expected a base32 .anyone address matching ${HS_HOSTNAME_REGEX}.`\n );\n }\n return hostname;\n}\n","/**\n * One BIP-39 phrase → an EVM key and a Solana key.\n *\n * ## Which path an EVM key comes from\n *\n * There are two, and the difference is historical rather than cryptographic.\n *\n * - **`standard`** — `m/44'/60'/0'/0/{accountIndex}`, BIP-44's registered coin\n * type for Ethereum. This is what every wallet derives, so the same phrase\n * typed into MetaMask or a hardware wallet produces the same address: the\n * channel wallet can be inspected, topped up or swept without this package.\n * New keystores use it.\n *\n * - **`legacy`** — `m/44'/1237'/0'/0/{accountIndex}`, Nostr's coin type. Before\n * 1.0 this client derived one secp256k1 key and used it for both a Nostr\n * identity and an EVM account, so the EVM key sat on Nostr's path. The Nostr\n * half is gone, but the addresses are not: they hold channels with real\n * collateral. A keystore written before 1.0 records no scheme and is read as\n * `legacy`, so nothing moves under an existing deployment.\n *\n * Solana is unaffected — `m/44'/501'/{accountIndex}'/0'`, SLIP-0010, all\n * hardened, which is what Phantom and the Solana CLI derive.\n */\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { base58Encode } from '../utils/base58.js';\nimport type { DerivedIdentity } from './types.js';\n\n/** How a mnemonic becomes an EVM key. See this module's own docs. */\nexport type KeyDerivationScheme = 'standard' | 'legacy';\n\n/** BIP-44 coin type 60: Ethereum, and every EVM chain by convention. */\nconst EVM_COIN_TYPE_STANDARD = 60;\n/** BIP-44 coin type 1237: Nostr. What this client used before 1.0. */\nconst EVM_COIN_TYPE_LEGACY = 1237;\n\n/** Generate a new 12-word BIP-39 mnemonic. */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/** Is this a well-formed BIP-39 phrase with a valid checksum? */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/** Maximum valid BIP-32 non-hardened child index (2^31 − 1). */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `accountIndex must be an integer in [0, ${MAX_BIP32_INDEX}]; got ${String(accountIndex)}`\n );\n }\n}\n\n/** The BIP-44 path an EVM key is derived at, under a given scheme. */\nexport function evmDerivationPath(\n scheme: KeyDerivationScheme,\n accountIndex = 0\n): string {\n const coinType =\n scheme === 'legacy' ? EVM_COIN_TYPE_LEGACY : EVM_COIN_TYPE_STANDARD;\n return `m/44'/${String(coinType)}'/0'/0/${String(accountIndex)}`;\n}\n\nfunction deriveEvmKey(\n seed: Uint8Array,\n scheme: KeyDerivationScheme,\n accountIndex: number\n): DerivedIdentity['evm'] {\n const child = HDKey.fromMasterSeed(seed).derive(\n evmDerivationPath(scheme, accountIndex)\n );\n if (!child.privateKey) {\n throw new Error('Failed to derive an EVM private key from the seed');\n }\n return evmIdentityFromKey(new Uint8Array(child.privateKey));\n}\n\n/** The account an existing secp256k1 secret belongs to. */\nexport function evmIdentityFromKey(\n privateKey: Uint8Array\n): DerivedIdentity['evm'] {\n const account = privateKeyToAccount(toHex(privateKey));\n return { privateKey, address: account.address };\n}\n\n/**\n * SLIP-0010 Ed25519 derivation at `m/44'/501'/{accountIndex}'/0'`.\n *\n * Ed25519 has no non-hardened derivation, so every level is hardened and the\n * chain code is carried by hand rather than through `HDKey` (which implements\n * BIP-32 for secp256k1).\n */\nfunction deriveSolanaKey(\n seed: Uint8Array,\n accountIndex: number\n): DerivedIdentity['solana'] {\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes = ed25519.getPublicKey(key);\n // A Solana secret key is the 32-byte seed followed by its public key.\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n return { secretKey: keypair, publicKey: base58Encode(publicKeyBytes) };\n}\n\nexport interface DeriveIdentityOptions {\n accountIndex?: number;\n /** Default `'standard'`. */\n scheme?: KeyDerivationScheme;\n}\n\n/**\n * Derive both chain keys from a mnemonic.\n *\n * The seed is zeroed before returning; the derived keys are not, because they\n * are the return value.\n */\nexport function deriveFullIdentity(\n mnemonic: string,\n options: DeriveIdentityOptions | number = {}\n): DerivedIdentity {\n // `deriveFullIdentity(mnemonic, 3)` used to mean account index 3.\n const opts: DeriveIdentityOptions =\n typeof options === 'number' ? { accountIndex: options } : options;\n const accountIndex = opts.accountIndex ?? 0;\n const scheme = opts.scheme ?? 'standard';\n assertValidAccountIndex(accountIndex);\n\n const seed = mnemonicToSeedSync(mnemonic);\n try {\n return {\n evm: deriveEvmKey(seed, scheme, accountIndex),\n solana: deriveSolanaKey(seed, accountIndex),\n };\n } finally {\n seed.fill(0);\n }\n}\n\n/**\n * A random identity, for tests and ephemeral use. The keys are unrelated to\n * each other and to any mnemonic, so nothing here can be recovered from a\n * phrase — generate a mnemonic instead if the keys need to outlive the process.\n */\nexport function generateRandomIdentity(): DerivedIdentity {\n const evmKey = secp256k1.utils.randomSecretKey();\n const solanaSeed = ed25519.utils.randomSecretKey();\n const solanaPublic = ed25519.getPublicKey(solanaSeed);\n const keypair = new Uint8Array(64);\n keypair.set(solanaSeed, 0);\n keypair.set(solanaPublic, 32);\n return {\n evm: evmIdentityFromKey(evmKey),\n solana: { secretKey: keypair, publicKey: base58Encode(solanaPublic) },\n };\n}\n","/**\n * Base58 (Bitcoin alphabet) — the encoding every Solana address, program id,\n * mint and signature-free pubkey arrives in.\n *\n * A thin wrapper over `@scure/base` rather than a hand-rolled implementation:\n * the same audited primitive already sits under `@scure/bip32`, so this adds no\n * install weight, and base58 decoding is exactly the kind of loop where a\n * hand-rolled version is wrong only for inputs you did not test.\n *\n * Replaces `@toon-protocol/core`'s `base58Encode`/`base58Decode`.\n */\nimport { base58 } from '@scure/base';\n\n/** Encode raw bytes as base58. */\nexport function base58Encode(bytes: Uint8Array): string {\n return base58.encode(bytes);\n}\n\n/**\n * Decode base58 text to raw bytes.\n *\n * Throws on any character outside the alphabet — a Solana pubkey that fails to\n * decode is a caller error worth surfacing, never something to coerce.\n */\nexport function base58Decode(text: string): Uint8Array {\n return base58.decode(text);\n}\n","/**\n * Well-known values for the public TOON devnet.\n *\n * **These are conveniences, never authorities.** Every settlement fact a client\n * actually pays against — the chain, the counterparty address, the token\n * network, the mint, the decimals — comes from the connector's own `GET /ilp`,\n * because the connector proved each of them against a live chain when it booted\n * (`self-description-spec.md` ND-07). Two declarations of one fact is how a\n * mainnet node comes to be described as devnet, so nothing here is ever\n * consulted in preference to the document a node answers with.\n *\n * What they are good for: a default RPC endpoint, a default faucet, and a URL to\n * put in an example so it can be run rather than adapted.\n *\n * Everything below is a **testnet**. Base Sepolia and Solana devnet carry no\n * real value, and the USDC is a mock mint anyone can draw from the faucet.\n */\n\n/** A connector on the public devnet. */\nexport interface DevnetNode {\n /** Client-edge base URL — `GET /ilp` here returns everything else. */\n url: string;\n /** The route this node terminates. */\n route: string;\n /** That route's base price, in base units of the settlement asset (USDC, 6dp). */\n price: bigint;\n /**\n * Added per kibibyte of sealed payload, on a route that meters by size. A\n * packet on such a route always costs strictly more than `price`.\n */\n pricePerKib?: bigint;\n /** Set when the route accepts only one carriage. */\n requiredTransport?: 'http' | 'btp';\n}\n\nexport const DEVNET = {\n /**\n * The store node: an Arweave-backed object store behind `g.toon.store`, and\n * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per\n * kibibyte of sealed payload, so no packet on it costs only `price`.\n */\n store: {\n url: 'https://proxy.ario.devnet.toonprotocol.dev',\n route: 'g.toon.store',\n price: 1000n,\n pricePerKib: 10n,\n } satisfies DevnetNode,\n\n /**\n * The gas station behind `g.toon.gas`, priced flat at 1000 base units.\n * Reachable directly, or through the relay at `g.toon.relay.gas`.\n */\n gas: {\n url: 'https://proxy.gas.devnet.toonprotocol.dev',\n route: 'g.toon.gas',\n price: 1000n,\n } satisfies DevnetNode,\n\n /**\n * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is\n * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms\n * document an unpaid request gets, carrying `extra.requiredTransport`.\n */\n relay: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay',\n price: 1n,\n requiredTransport: 'btp',\n } satisfies DevnetNode,\n\n /**\n * The relay's ephemeral lane, priced at **zero** — the one route on the devnet\n * that exercises the whole wire while holding no funds and no channel. Not\n * carriage-pinned, unlike `g.toon.relay` beside it.\n */\n ephemeral: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay.ephemeral',\n price: 0n,\n } satisfies DevnetNode,\n\n /** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */\n faucet: 'https://faucet.devnet.toonprotocol.dev',\n\n /** Base Sepolia. The registry is the stable address; the token network is resolved from it. */\n evm: {\n chainId: 84532,\n rpcUrl: 'https://sepolia.base.org',\n tokenNetworkRegistry: '0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5',\n tokenNetwork: '0xe9E05dfecfe165266C88d73e61D483612651952a',\n /** Mock USDC, 6 decimals, ungated `mint()`. */\n tokenAddress: '0x49beE1Bca5d15Fb0963117923403F9498119a9Ce',\n decimals: 6,\n },\n\n /** Solana devnet — the public cluster, not a local validator. */\n solana: {\n rpcUrl: 'https://api.devnet.solana.com',\n /** The deployed `payment-channel` program. Bound into every claim (ADR 0053). */\n programId: '2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip',\n /** Mock USDC SPL mint, 6 decimals. */\n tokenAddress: '34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU',\n decimals: 6,\n },\n} as const;\n\n/** The default RPC URL for a chain when a caller configures none. */\nexport function defaultRpcUrl(chain: 'evm' | 'solana'): string {\n return chain === 'evm' ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;\n}\n"],"mappings":";AA2BO,IAAM,oBAAoB;AAG1B,IAAM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;AAAA;AAAA;AAAA;AAAA;AAAA,EAMpB,OAAO;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,KAAK;AAAA,IACH,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,IACP,mBAAmB;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAW;AAAA,IACT,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA;AAAA,EAGA,QAAQ;AAAA;AAAA,EAGR,KAAK;AAAA,IACH,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,sBAAsB;AAAA,IACtB,cAAc;AAAA;AAAA,IAEd,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,QAAQ;AAAA;AAAA,IAER,WAAW;AAAA;AAAA,IAEX,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,cAAc,OAAiC;AAC7D,SAAO,UAAU,QAAQ,OAAO,IAAI,SAAS,OAAO,OAAO;AAC7D;","names":[]}
1
+ {"version":3,"sources":["../src/transport/hs-hostname.ts","../src/keys/KeyDerivation.ts","../src/utils/base58.ts","../src/presets.ts"],"sourcesContent":["/**\n * Hidden-service hostname validation for the Anyone Protocol network.\n *\n * The `anon` binary routes hidden-service hostnames under the **`.anyone`** TLD\n * ONLY. A `<host>.anon` name is NOT recognized as a hidden service — anon treats\n * it as a clearnet name and tries to exit-resolve it, which fails\n * (`resolve failed` / `HostUnreachable`). Only `<host>.anyone` triggers anon's\n * `parse_extended_hostname: Anyone dns address lookup` and is validated.\n *\n * Historically this client accepted BOTH `.anon` and `.anyone`, so a `.anon`\n * address was silently accepted and then failed deep in the transport with an\n * opaque error. This module makes `.anyone` the single accepted HS TLD and\n * rejects the near-misses up front with an actionable message.\n *\n * `.onion` is a near-miss too, and a more tempting one: it is a real hidden\n * service, just on a network this client does not dial. We route through `anon`,\n * not `tor`, so accepting a `.onion` address would repeat the exact mistake\n * `.anon` taught us — an address we cannot reach, failing late and cryptically.\n *\n * This is a pure, browser-safe helper (no Node built-ins) so it can be imported\n * from any path, including config validation.\n */\n\n/**\n * A `<host>.anyone` hidden-service hostname. The label is base32 (`a-z2-7`),\n * matching the on-wire onion-style address alphabet anon uses.\n */\nexport const HS_HOSTNAME_REGEX = /^[a-z2-7]+\\.anyone$/;\n\n/** Max length of an HS hostname (defensive bound against pathological input). */\nexport const HS_HOSTNAME_MAX_LENGTH = 80;\n\n/**\n * Returns true iff `s` is a routable `.anyone` hidden-service hostname.\n * Does NOT accept `.anon` or `.onion` (see {@link assertRoutableHsHostname}).\n */\nexport function isRoutableHsHostname(s: unknown): s is string {\n return (\n typeof s === 'string' &&\n s.length <= HS_HOSTNAME_MAX_LENGTH &&\n HS_HOSTNAME_REGEX.test(s)\n );\n}\n\n/**\n * Returns true iff `url` addresses a hidden service — i.e. its host is a\n * routable `.anyone` address.\n *\n * Takes a URL string rather than a hostname because that is what a caller\n * actually holds: a `connector` config value, an `httpEndpoint` off a\n * self-description. A string that is not a URL at all is not a hidden service.\n */\nexport function isHiddenServiceUrl(url: unknown): boolean {\n if (typeof url !== 'string') return false;\n try {\n return isRoutableHsHostname(new URL(url).hostname);\n } catch {\n return false;\n }\n}\n\n/**\n * Validates that `hostname` is a routable `.anyone` hidden-service address.\n *\n * - `<host>.anyone` → returns the hostname unchanged.\n * - `<host>.anon` → throws, pointing at `.anyone` (anon does NOT route\n * `.anon`; it is treated as a clearnet address and fails `HostUnreachable`).\n * - `<host>.onion` → throws, naming the network mismatch: that is Tor, and\n * this client dials the Anyone Protocol.\n * - anything else → throws a generic format error.\n *\n * @throws {Error} if the hostname is not a routable `.anyone` HS address.\n */\nexport function assertRoutableHsHostname(hostname: unknown): string {\n if (typeof hostname === 'string' && /\\.anon$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is not a routable hidden-service address; use the .anyone TLD ` +\n `(e.g. \"${hostname.replace(/\\.anon$/, '.anyone')}\"). ` +\n 'The anon daemon only resolves hidden services under .anyone — a .anon ' +\n 'name is treated as a clearnet address and fails (HostUnreachable).'\n );\n }\n if (typeof hostname === 'string' && /\\.onion$/.test(hostname)) {\n throw new Error(\n `\"${hostname}\" is a Tor hidden service, which this client does not dial. ` +\n 'Packets are routed through the Anyone Protocol `anon` daemon, whose ' +\n 'hidden services live under the .anyone TLD.'\n );\n }\n if (!isRoutableHsHostname(hostname)) {\n throw new Error(\n `Invalid hidden-service hostname: ${JSON.stringify(hostname)}. ` +\n `Expected a base32 .anyone address matching ${HS_HOSTNAME_REGEX}.`\n );\n }\n return hostname;\n}\n","/**\n * One BIP-39 phrase → an EVM key and a Solana key.\n *\n * ## Which path an EVM key comes from\n *\n * There are two, and the difference is historical rather than cryptographic.\n *\n * - **`standard`** — `m/44'/60'/0'/0/{accountIndex}`, BIP-44's registered coin\n * type for Ethereum. This is what every wallet derives, so the same phrase\n * typed into MetaMask or a hardware wallet produces the same address: the\n * channel wallet can be inspected, topped up or swept without this package.\n * New keystores use it.\n *\n * - **`legacy`** — `m/44'/1237'/0'/0/{accountIndex}`, Nostr's coin type. Before\n * 1.0 this client derived one secp256k1 key and used it for both a Nostr\n * identity and an EVM account, so the EVM key sat on Nostr's path. The Nostr\n * half is gone, but the addresses are not: they hold channels with real\n * collateral. A keystore written before 1.0 records no scheme and is read as\n * `legacy`, so nothing moves under an existing deployment.\n *\n * Solana is unaffected — `m/44'/501'/{accountIndex}'/0'`, SLIP-0010, all\n * hardened, which is what Phantom and the Solana CLI derive.\n */\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hmac } from '@noble/hashes/hmac';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { base58Encode } from '../utils/base58.js';\nimport type { DerivedIdentity } from './types.js';\n\n/** How a mnemonic becomes an EVM key. See this module's own docs. */\nexport type KeyDerivationScheme = 'standard' | 'legacy';\n\n/** BIP-44 coin type 60: Ethereum, and every EVM chain by convention. */\nconst EVM_COIN_TYPE_STANDARD = 60;\n/** BIP-44 coin type 1237: Nostr. What this client used before 1.0. */\nconst EVM_COIN_TYPE_LEGACY = 1237;\n\n/** Generate a new 12-word BIP-39 mnemonic. */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/** Is this a well-formed BIP-39 phrase with a valid checksum? */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/** Maximum valid BIP-32 non-hardened child index (2^31 − 1). */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `accountIndex must be an integer in [0, ${MAX_BIP32_INDEX}]; got ${String(accountIndex)}`\n );\n }\n}\n\n/** The BIP-44 path an EVM key is derived at, under a given scheme. */\nexport function evmDerivationPath(\n scheme: KeyDerivationScheme,\n accountIndex = 0\n): string {\n const coinType =\n scheme === 'legacy' ? EVM_COIN_TYPE_LEGACY : EVM_COIN_TYPE_STANDARD;\n return `m/44'/${String(coinType)}'/0'/0/${String(accountIndex)}`;\n}\n\nfunction deriveEvmKey(\n seed: Uint8Array,\n scheme: KeyDerivationScheme,\n accountIndex: number\n): DerivedIdentity['evm'] {\n const child = HDKey.fromMasterSeed(seed).derive(\n evmDerivationPath(scheme, accountIndex)\n );\n if (!child.privateKey) {\n throw new Error('Failed to derive an EVM private key from the seed');\n }\n return evmIdentityFromKey(new Uint8Array(child.privateKey));\n}\n\n/** The account an existing secp256k1 secret belongs to. */\nexport function evmIdentityFromKey(\n privateKey: Uint8Array\n): DerivedIdentity['evm'] {\n const account = privateKeyToAccount(toHex(privateKey));\n return { privateKey, address: account.address };\n}\n\n/**\n * SLIP-0010 Ed25519 derivation at `m/44'/501'/{accountIndex}'/0'`.\n *\n * Ed25519 has no non-hardened derivation, so every level is hardened and the\n * chain code is carried by hand rather than through `HDKey` (which implements\n * BIP-32 for secp256k1).\n */\nfunction deriveSolanaKey(\n seed: Uint8Array,\n accountIndex: number\n): DerivedIdentity['solana'] {\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes = ed25519.getPublicKey(key);\n // A Solana secret key is the 32-byte seed followed by its public key.\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n return { secretKey: keypair, publicKey: base58Encode(publicKeyBytes) };\n}\n\nexport interface DeriveIdentityOptions {\n accountIndex?: number;\n /** Default `'standard'`. */\n scheme?: KeyDerivationScheme;\n}\n\n/**\n * Derive both chain keys from a mnemonic.\n *\n * The seed is zeroed before returning; the derived keys are not, because they\n * are the return value.\n */\nexport function deriveFullIdentity(\n mnemonic: string,\n options: DeriveIdentityOptions | number = {}\n): DerivedIdentity {\n // `deriveFullIdentity(mnemonic, 3)` used to mean account index 3.\n const opts: DeriveIdentityOptions =\n typeof options === 'number' ? { accountIndex: options } : options;\n const accountIndex = opts.accountIndex ?? 0;\n const scheme = opts.scheme ?? 'standard';\n assertValidAccountIndex(accountIndex);\n\n const seed = mnemonicToSeedSync(mnemonic);\n try {\n return {\n evm: deriveEvmKey(seed, scheme, accountIndex),\n solana: deriveSolanaKey(seed, accountIndex),\n };\n } finally {\n seed.fill(0);\n }\n}\n\n/**\n * A random identity, for tests and ephemeral use. The keys are unrelated to\n * each other and to any mnemonic, so nothing here can be recovered from a\n * phrase — generate a mnemonic instead if the keys need to outlive the process.\n */\nexport function generateRandomIdentity(): DerivedIdentity {\n const evmKey = secp256k1.utils.randomSecretKey();\n const solanaSeed = ed25519.utils.randomSecretKey();\n const solanaPublic = ed25519.getPublicKey(solanaSeed);\n const keypair = new Uint8Array(64);\n keypair.set(solanaSeed, 0);\n keypair.set(solanaPublic, 32);\n return {\n evm: evmIdentityFromKey(evmKey),\n solana: { secretKey: keypair, publicKey: base58Encode(solanaPublic) },\n };\n}\n","/**\n * Base58 (Bitcoin alphabet) — the encoding every Solana address, program id,\n * mint and signature-free pubkey arrives in.\n *\n * A thin wrapper over `@scure/base` rather than a hand-rolled implementation:\n * the same audited primitive already sits under `@scure/bip32`, so this adds no\n * install weight, and base58 decoding is exactly the kind of loop where a\n * hand-rolled version is wrong only for inputs you did not test.\n *\n * Replaces `@toon-protocol/core`'s `base58Encode`/`base58Decode`.\n */\nimport { base58 } from '@scure/base';\n\n/** Encode raw bytes as base58. */\nexport function base58Encode(bytes: Uint8Array): string {\n return base58.encode(bytes);\n}\n\n/**\n * Decode base58 text to raw bytes.\n *\n * Throws on any character outside the alphabet — a Solana pubkey that fails to\n * decode is a caller error worth surfacing, never something to coerce.\n */\nexport function base58Decode(text: string): Uint8Array {\n return base58.decode(text);\n}\n","/**\n * Well-known values for the public TOON devnet.\n *\n * **These are conveniences, never authorities.** Every settlement fact a client\n * actually pays against — the chain, the counterparty address, the token\n * network, the mint, the decimals — comes from the connector's own `GET /ilp`,\n * because the connector proved each of them against a live chain when it booted\n * (`self-description-spec.md` ND-07). Two declarations of one fact is how a\n * mainnet node comes to be described as devnet, so nothing here is ever\n * consulted in preference to the document a node answers with.\n *\n * What they are good for: a default RPC endpoint, a default faucet, and a URL to\n * put in an example so it can be run rather than adapted.\n *\n * Everything below is a **testnet**. Base Sepolia and Solana devnet carry no\n * real value, and the USDC is a mock mint anyone can draw from the faucet.\n */\n\n/** A connector on the public devnet. */\nexport interface DevnetNode {\n /** Client-edge base URL — `GET /ilp` here returns everything else. */\n url: string;\n /** The route this node terminates. */\n route: string;\n /** That route's base price, in base units of the settlement asset (USDC, 6dp). */\n price: bigint;\n /**\n * Added per kibibyte of sealed payload, on a route that meters by size. A\n * packet on such a route always costs strictly more than `price`.\n */\n pricePerKib?: bigint;\n /** Set when the route accepts only one carriage. */\n requiredTransport?: 'http' | 'btp';\n}\n\nexport const DEVNET = {\n /**\n * The store node: an Arweave-backed object store behind `g.toon.store`, and\n * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per\n * kibibyte of sealed payload, so no packet on it costs only `price`.\n */\n store: {\n url: 'https://proxy.ario.devnet.toonprotocol.dev',\n route: 'g.toon.store',\n price: 1000n,\n pricePerKib: 10n,\n } satisfies DevnetNode,\n\n /**\n * The gas station behind `g.toon.gas`, priced flat at 1000 base units.\n * Reachable directly, or through the relay at `g.toon.relay.gas`.\n */\n gas: {\n url: 'https://proxy.gas.devnet.toonprotocol.dev',\n route: 'g.toon.gas',\n price: 1000n,\n } satisfies DevnetNode,\n\n /**\n * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is\n * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms\n * document an unpaid request gets, carrying `extra.requiredTransport`.\n */\n relay: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay',\n price: 1n,\n requiredTransport: 'btp',\n } satisfies DevnetNode,\n\n /**\n * The relay's ephemeral lane, priced at **zero** — the one route on the devnet\n * that exercises the whole wire while holding no funds and no channel. Not\n * carriage-pinned, unlike `g.toon.relay` beside it.\n */\n ephemeral: {\n url: 'https://proxy.relay.devnet.toonprotocol.dev',\n route: 'g.toon.relay.ephemeral',\n price: 0n,\n } satisfies DevnetNode,\n\n /** Test funds. `POST /api/base-sepolia/request` and `/api/solana/usdc-request`. */\n faucet: 'https://faucet.devnet.toonprotocol.dev',\n\n /** Base Sepolia. The registry is the stable address; the token network is resolved from it. */\n evm: {\n chainId: 84532,\n rpcUrl: 'https://sepolia.base.org',\n tokenNetworkRegistry: '0x0c41D9D424d6B075A3cEa1068a694f7847a8CCa5',\n tokenNetwork: '0x1B4606218ceE5Bf02B546e416905F4D3FC8a0249',\n /** Devnet USDC: Circle FiatToken v2.2 (ERC-3009, EIP-2612), 6 decimals, minter-gated — fund via the faucet (connector#1337). */\n tokenAddress: '0x0C996d7c934c79a6255254875607Fe69df25C0E1',\n decimals: 6,\n },\n\n /** Solana devnet — the public cluster, not a local validator. */\n solana: {\n rpcUrl: 'https://api.devnet.solana.com',\n /** The deployed `payment-channel` program. Bound into every claim (ADR 0053). */\n programId: '2aEVJ8koKD8LTZrLRSGtAtU7LBt4e7QjjCgf1kzQ7Rip',\n /** Mock USDC SPL mint, 6 decimals. */\n tokenAddress: '34eSxY7qxQ4GzyhDJ8GpUcTz1WWzruGbJbR8q6TtxfQU',\n decimals: 6,\n },\n} as const;\n\n/** The default RPC URL for a chain when a caller configures none. */\nexport function defaultRpcUrl(chain: 'evm' | 'solana'): string {\n return chain === 'evm' ? DEVNET.evm.rpcUrl : DEVNET.solana.rpcUrl;\n}\n"],"mappings":";AA2BO,IAAM,oBAAoB;AAG1B,IAAM,yBAAyB;AAM/B,SAAS,qBAAqB,GAAyB;AAC5D,SACE,OAAO,MAAM,YACb,EAAE,UAAU,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AAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,KAAK;AAAA,IACH,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,OAAO;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,IACP,mBAAmB;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,WAAW;AAAA,IACT,KAAK;AAAA,IACL,OAAO;AAAA,IACP,OAAO;AAAA,EACT;AAAA;AAAA,EAGA,QAAQ;AAAA;AAAA,EAGR,KAAK;AAAA,IACH,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,sBAAsB;AAAA,IACtB,cAAc;AAAA;AAAA,IAEd,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AAAA;AAAA,EAGA,QAAQ;AAAA,IACN,QAAQ;AAAA;AAAA,IAER,WAAW;AAAA;AAAA,IAEX,cAAc;AAAA,IACd,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,cAAc,OAAiC;AAC7D,SAAO,UAAU,QAAQ,OAAO,IAAI,SAAS,OAAO,OAAO;AAC7D;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  generateMnemonic,
3
3
  validateMnemonic
4
- } from "./chunk-7MPONJW5.js";
4
+ } from "./chunk-O6KX7MHD.js";
5
5
 
6
6
  // src/keys/keystore-node.ts
7
7
  import {
@@ -163,4 +163,4 @@ export {
163
163
  loadKeystore,
164
164
  writeKeystoreFile
165
165
  };
166
- //# sourceMappingURL=chunk-4I3JQ7KA.js.map
166
+ //# sourceMappingURL=chunk-PTTRHLYV.js.map
package/dist/cli/main.js CHANGED
@@ -3,14 +3,14 @@ import {
3
3
  generateKeystore,
4
4
  importKeystore,
5
5
  openKeystore
6
- } from "../chunk-4I3JQ7KA.js";
6
+ } from "../chunk-PTTRHLYV.js";
7
7
  import {
8
8
  DEVNET,
9
9
  deriveFullIdentity,
10
10
  evmDerivationPath,
11
11
  generateRandomIdentity,
12
12
  isHiddenServiceUrl
13
- } from "../chunk-7MPONJW5.js";
13
+ } from "../chunk-O6KX7MHD.js";
14
14
 
15
15
  // src/cli/main.ts
16
16
  import { homedir as homedir3 } from "os";
@@ -542,7 +542,7 @@ function buildClientConfig(settings, keys) {
542
542
  };
543
543
  }
544
544
  async function defaultCreateClient(config) {
545
- const module = await import("../client-SCEP67S5.js");
545
+ const module = await import("../client-FFEFAMJ4.js");
546
546
  const factory = module.ToonClient;
547
547
  if (factory === void 0) {
548
548
  throw new Error(
@@ -19,6 +19,7 @@ import {
19
19
  StaleRpcReadError,
20
20
  ToonClient,
21
21
  ToonClientError,
22
+ TransactionOutcomeError,
22
23
  TransferNotDeliveredError,
23
24
  TransferUnsupportedError,
24
25
  TransportRequiredError,
@@ -31,8 +32,8 @@ import {
31
32
  send,
32
33
  settlementToTerms,
33
34
  toEnvelopeRequest
34
- } from "./chunk-ZHWYFPOP.js";
35
- import "./chunk-7MPONJW5.js";
35
+ } from "./chunk-G36D22II.js";
36
+ import "./chunk-O6KX7MHD.js";
36
37
  import "./chunk-32MD3CXE.js";
37
38
  export {
38
39
  BeforePayRefusedError,
@@ -55,6 +56,7 @@ export {
55
56
  StaleRpcReadError,
56
57
  ToonClient,
57
58
  ToonClientError,
59
+ TransactionOutcomeError,
58
60
  TransferNotDeliveredError,
59
61
  TransferUnsupportedError,
60
62
  TransportRequiredError,
@@ -68,4 +70,4 @@ export {
68
70
  settlementToTerms,
69
71
  toEnvelopeRequest
70
72
  };
71
- //# sourceMappingURL=client-SCEP67S5.js.map
73
+ //# sourceMappingURL=client-FFEFAMJ4.js.map
@@ -0,0 +1,301 @@
1
+ /**
2
+ * The on-chain channel port: what the client needs a chain to be able to do,
3
+ * independent of which chain it is.
4
+ *
5
+ * These types were `@toon-protocol/core`'s `ConnectorChannelClient` family,
6
+ * whose names still carried the retired admin-API model — a channel opened by
7
+ * `POST /admin/channels` on the connector. That is not how a channel comes into
8
+ * existence any more, and the naming mattered: **a connector has no endpoint
9
+ * that opens a channel** (`self-description-spec.md` ND-03). The client opens,
10
+ * funds, closes and settles the channel itself, directly on chain, and the
11
+ * connector discovers it by reading the chain
12
+ * ([ADR 0052](https://github.com/toon-protocol/connector/blob/main/docs/adr/0052-permissionless-payment-is-guaranteed-and-a-claim-is-what-authorises.md)).
13
+ * So this is a port over *chains*, not over the connector.
14
+ */
15
+ /** Which settlement family a channel lives in. Mina is gone (connector ADR 0002). */
16
+ type ChainKind = 'evm' | 'solana';
17
+ /**
18
+ * Everything needed to open one channel, as read off the connector's own
19
+ * self-description (`GET /ilp` → `settlements[]`) rather than configured.
20
+ *
21
+ * The connector proved each of these against a live chain at startup
22
+ * (`self-description-spec.md` ND-07), which is why they are taken from the
23
+ * document instead of from a preset: two declarations of one fact is how a
24
+ * mainnet node comes to describe itself as devnet.
25
+ */
26
+ interface ChannelTerms {
27
+ kind: ChainKind;
28
+ /** The chain key exactly as published: `evm:84532`, or `solana`. */
29
+ chain: string;
30
+ /** EVM only: the numeric chain id parsed out of `chain`. The EIP-712 domain's `chainId`. */
31
+ chainId?: number;
32
+ /**
33
+ * The connector's own settlement address — the counterparty this channel is
34
+ * opened *with*. `0x…` on EVM, base58 on Solana.
35
+ */
36
+ counterparty: string;
37
+ /** ERC-20 address, or the SPL mint. */
38
+ token: string;
39
+ /** Base units per whole token, as the connector reports it. */
40
+ decimals: number;
41
+ /** EVM: the `TokenNetwork` — the EIP-712 `verifyingContract` a claim is signed under. */
42
+ tokenNetwork?: string;
43
+ /** EVM: the `TokenNetworkRegistry` that minted the `TokenNetwork`; the stable address. */
44
+ tokenNetworkRegistry?: string;
45
+ /** Solana: the settlement program the channel account lives under, bound into every claim (ADR 0053). */
46
+ programId?: string;
47
+ }
48
+ /** Parameters for opening a channel on chain. */
49
+ interface OpenChannelParams {
50
+ terms: ChannelTerms;
51
+ /** Initial collateral, in the token's base units. */
52
+ initialDeposit?: bigint;
53
+ /**
54
+ * Challenge period in seconds. The EVM `TokenNetwork` enforces a one-hour
55
+ * floor; the Solana program takes it as the channel's `challenge_duration`.
56
+ */
57
+ settlementTimeout?: number;
58
+ }
59
+ /** What opening produced. */
60
+ interface OpenChannelResult {
61
+ /** `0x…` 32 bytes on EVM; the channel account's base58 pubkey on Solana. */
62
+ channelId: string;
63
+ status: ChannelStatus;
64
+ /** The transaction that opened it. Absent when an existing channel was adopted. */
65
+ txHash?: string;
66
+ /** On-chain collateral after opening, when the opener read it back. */
67
+ depositTotal?: bigint;
68
+ }
69
+ /**
70
+ * Where a channel is in its lifecycle.
71
+ *
72
+ * `opening` is real and worth distinguishing: the opening transaction is
73
+ * submitted but not yet confirmed, so the channel does not exist for anyone
74
+ * reading the chain — including the connector, which resolves a claim's channel
75
+ * by reading it. A claim signed in that window is refused as naming an unknown
76
+ * channel, and the remedy is to wait rather than to re-sign.
77
+ */
78
+ type ChannelStatus = 'opening' | 'open' | 'closed' | 'settled' | 'missing';
79
+ /** A channel as the chain currently reports it. */
80
+ interface OnChainChannelStatus {
81
+ channelId: string;
82
+ status: ChannelStatus;
83
+ /** The chain key this channel lives on, when the reader knows it. */
84
+ chain?: string;
85
+ /** This participant's collateral, in base units. */
86
+ deposit?: bigint;
87
+ /** Unix seconds the channel was closed, when it is closed. */
88
+ closedAt?: bigint;
89
+ /** Unix seconds after which `settle` is permitted. */
90
+ settleableAt?: bigint;
91
+ }
92
+ /**
93
+ * One chain's implementation of the lifecycle.
94
+ *
95
+ * Every method here is a transaction the *client* signs and pays gas for. None
96
+ * of them talks to a connector.
97
+ */
98
+ interface ChannelClient {
99
+ openChannel(params: OpenChannelParams): Promise<OpenChannelResult>;
100
+ /**
101
+ * Add collateral. `currentDeposit` is the channel's present total, which EVM
102
+ * needs because `setTotalDeposit` takes the new cumulative figure rather than
103
+ * a delta — a contract shape that makes a lost or duplicated call harmless.
104
+ */
105
+ depositToChannel(channelId: string, amount: bigint, opts: {
106
+ currentDeposit: bigint;
107
+ }): Promise<{
108
+ txHash?: string;
109
+ depositTotal: bigint;
110
+ }>;
111
+ /** Start the challenge period. */
112
+ closeChannel(channelId: string): Promise<{
113
+ txHash?: string;
114
+ closedAt: bigint;
115
+ settlementTimeout: bigint;
116
+ settleableAt: bigint;
117
+ }>;
118
+ /** Pay out and finish. Only permitted once the challenge period has elapsed. */
119
+ settleChannel(channelId: string): Promise<{
120
+ txHash?: string;
121
+ }>;
122
+ getChannelState(channelId: string): Promise<OnChainChannelStatus>;
123
+ }
124
+
125
+ /**
126
+ * `socks5h://` URL parsing, kept apart from the transport that uses it.
127
+ *
128
+ * Config validation has to reject a bad proxy URL, and config validation runs
129
+ * everywhere — including in a browser, where `./socks.js` must never be loaded
130
+ * (it reaches for `node:module` on the first line). This module is pure.
131
+ */
132
+ /**
133
+ * Parses and validates a `socks5h://` URL.
134
+ *
135
+ * Enforces the `socks5h://` scheme, not `socks5://`: the trailing `h` means the
136
+ * *proxy* resolves the hostname. Under plain `socks5://` the client resolves it
137
+ * locally first, which for a `.anyone` address means shipping the hidden service
138
+ * you are about to talk to into a plaintext DNS query — the exact fact the
139
+ * hidden service exists to withhold. Mirrors the connector's `transport/socks-url.ts`.
140
+ */
141
+ declare function validateSocks5hUrl(socksProxy: string): {
142
+ host: string;
143
+ port: number;
144
+ };
145
+
146
+ /**
147
+ * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.
148
+ *
149
+ * A connector deployed as a hidden service is reachable only through a running
150
+ * `anon` daemon's SOCKS5 port. Three separate things in this client have to go
151
+ * through that port, and — annoyingly — each needs a different object to do it:
152
+ *
153
+ * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in
154
+ * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,
155
+ * which is why the `socks-proxy-agent` this package used to depend on cannot
156
+ * serve this path at all.
157
+ * - **Chain RPC** goes through viem, which calls the *global* `fetch` and accepts
158
+ * no injected one. Its only opening is `http(url, { fetchOptions })`, so it
159
+ * needs the same dispatcher handed to it as a fetch option (ADR 0002).
160
+ * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and
161
+ * therefore takes an `http.Agent` and nothing else.
162
+ *
163
+ * So this module builds one SOCKS connection primitive and wraps it three ways.
164
+ * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.
165
+ *
166
+ * Chain RPC gets a transport of its own per chain ({@link createChainRpcTransport}),
167
+ * authenticating with a fixed SOCKS username so each chain rides one pinned
168
+ * circuit (connector ADR 0073). The same is true whether the connector is a
169
+ * hidden service or a clearnet host that a hidden payer reaches through the
170
+ * proxy (TOON_Network#167).
171
+ *
172
+ * `undici` is an optional dependency for exactly this reason: Node bundles undici
173
+ * internally but exposes it under no specifier (`require('undici')` is
174
+ * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a
175
+ * dispatcher cannot be constructed without the package. A dispatcher built by the
176
+ * userland copy *is* honoured by Node's global `fetch`, which calls
177
+ * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici
178
+ * defines — and that is why the dependency is pinned to **undici 7, not 8**.
179
+ * Node's handler changed shape: Node 22 (undici 6.22) passes the old
180
+ * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)
181
+ * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —
182
+ * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.
183
+ * undici 8 dropped the old shape, and on Node 22 every request through such a
184
+ * dispatcher dies in `assertRequestHandler` with
185
+ * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both
186
+ * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not
187
+ * widen the range to `^8` without re-running those on the oldest supported Node.
188
+ *
189
+ * NODE ONLY. This module is imported dynamically, never statically, from the
190
+ * paths that need it; every Node built-in is pulled in through an ESM-safe
191
+ * `require` built off `import.meta.url`, because this package builds as ESM with
192
+ * these deps external and esbuild rewrites a bare `require` into a `__require`
193
+ * shim that throws. A browser cannot reach a `.anyone` address by any means, so
194
+ * a browser bundler must never follow an edge into this file.
195
+ */
196
+
197
+ /**
198
+ * How long to wait for the proxy to build a circuit to the hidden service.
199
+ *
200
+ * `socks` defaults to 30s, which is too short: an introduction-point circuit to
201
+ * a cold hidden service routinely takes longer, and a too-short connect timeout
202
+ * turns "slow" into "unreachable".
203
+ */
204
+ declare const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120000;
205
+ /**
206
+ * How long a chain-RPC dial may take through the proxy: the SOCKS handshake, an
207
+ * exit circuit and the TCP connect behind it (connector ADR 0073, decision 4).
208
+ *
209
+ * Far shorter than {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}, because a public RPC
210
+ * is reached over an ordinary exit circuit, not the introduction-point dance a
211
+ * hidden service needs. ADR 0073 measured 3,200 calls through `anon`: the worst
212
+ * one that had to build a fresh circuit took 13s. Twice that, rounded, and a
213
+ * stalled circuit is reported rather than waited on.
214
+ */
215
+ declare const DEFAULT_RPC_CONNECT_TIMEOUT_MS = 20000;
216
+ /**
217
+ * The longest a pooled chain-RPC connection is kept idle (ADR 0073, decision 4).
218
+ *
219
+ * A circuit can die quietly under a kept-alive socket, and the next request on
220
+ * it then hangs until its own timeout. A short idle cap means such a socket is
221
+ * dropped before it is reused. undici keeps a socket for 4s by default but lets a
222
+ * server's `Keep-Alive` header stretch that to ten minutes; this caps the stretch.
223
+ */
224
+ declare const RPC_POOL_IDLE_TIMEOUT_MS = 30000;
225
+ /**
226
+ * The fixed SOCKS5 usernames chain RPC authenticates with, one per chain.
227
+ *
228
+ * `anon` (like Tor) isolates streams by SOCKS credentials (`IsolateSOCKSAuth`,
229
+ * on by default): streams that present the same username share a circuit, and
230
+ * streams with different ones never do. So a fixed username per chain gives each
231
+ * chain one circuit that stays pinned until the daemon's own
232
+ * `MaxCircuitDirtiness` rotates it (connector ADR 0073, decision 3). No exit then
233
+ * sees both chains' RPC, neither shares a circuit with the client edge, and no
234
+ * call pays for a new circuit of its own. They differ from the connector's
235
+ * `toon-settlement-*` names, so a payer and a node on one daemon do not share
236
+ * circuits either.
237
+ */
238
+ declare const RPC_SOCKS_USERNAMES: Readonly<Record<ChainKind, string>>;
239
+ /** Options for {@link createHiddenServiceTransport}. */
240
+ interface HiddenServiceTransportOptions {
241
+ /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */
242
+ connectTimeoutMs?: number;
243
+ /**
244
+ * A fixed SOCKS5 username to authenticate with, which pins every stream this
245
+ * transport opens to one circuit (`IsolateSOCKSAuth`). Unset means no
246
+ * authentication, and the daemon's default circuit.
247
+ */
248
+ socksUsername?: string;
249
+ /**
250
+ * Upper bound on how long an idle pooled connection is kept, ms. Unset keeps
251
+ * undici's own behaviour.
252
+ */
253
+ idleTimeoutMs?: number;
254
+ }
255
+ /**
256
+ * The three shapes of one proxy, plus the handle that shuts it down.
257
+ *
258
+ * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}
259
+ * to route a client by hand; pass `socksProxy` instead to have the client build
260
+ * this itself.
261
+ */
262
+ interface HiddenServiceTransport {
263
+ /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */
264
+ fetch: typeof fetch;
265
+ /** A `ws` factory bound to the proxy, for the BTP carriage. */
266
+ createWebSocket: (url: string) => unknown;
267
+ /**
268
+ * The undici dispatcher behind `fetch`, for handing to something that insists
269
+ * on calling the global `fetch` itself — viem's HTTP transport, in practice
270
+ * (`http(url, { fetchOptions: { dispatcher } })`).
271
+ */
272
+ dispatcher: unknown;
273
+ /** Close the dispatcher's pool and the websocket agents' sockets. */
274
+ close(): Promise<void>;
275
+ }
276
+
277
+ /**
278
+ * Builds every proxy-bound object this client needs from one `socks5h://` URL.
279
+ *
280
+ * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not
281
+ * installed — they are optional dependencies, so a consumer who never touches
282
+ * a hidden service never pays for them.
283
+ */
284
+ declare function createHiddenServiceTransport(socksProxy: string, options?: HiddenServiceTransportOptions): HiddenServiceTransport;
285
+ /**
286
+ * The proxy-bound transport one chain's RPC rides: its own pinned circuit, a
287
+ * connect timeout sized for an exit circuit, and a capped idle pool (connector
288
+ * ADR 0073, decisions 3 and 4).
289
+ *
290
+ * It has no fallback. A proxy that is down fails the call; nothing here, or in
291
+ * the viem and Solana paths that use it, ever dials the RPC directly instead.
292
+ */
293
+ declare function createChainRpcTransport(socksProxy: string, chain: ChainKind): HiddenServiceTransport;
294
+ /**
295
+ * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a
296
+ * client configured for a hidden service must not quietly fall back to clearnet,
297
+ * and finding out at packet time costs a signed claim.
298
+ */
299
+ declare function probeSocks5Proxy(socksProxy: string, timeoutMs?: number): Promise<void>;
300
+
301
+ export { type ChainKind as C, DEFAULT_HS_CONNECT_TIMEOUT_MS as D, type HiddenServiceTransport as H, type OnChainChannelStatus as O, RPC_POOL_IDLE_TIMEOUT_MS as R, type ChannelStatus as a, type ChannelTerms as b, type ChannelClient as c, type OpenChannelResult as d, type OpenChannelParams as e, type HiddenServiceTransportOptions as f, DEFAULT_RPC_CONNECT_TIMEOUT_MS as g, RPC_SOCKS_USERNAMES as h, createChainRpcTransport as i, createHiddenServiceTransport as j, probeSocks5Proxy as p, validateSocks5hUrl as v };