@toon-protocol/client 3.2.0 → 4.0.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/main.ts","../../src/cli/args.ts","../../src/cli/context.ts","../../src/cli/keystore.ts","../../src/cli/output.ts","../../src/cli/commands/balances.ts","../../src/cli/commands/channel.ts","../../src/cli/commands/claim-state.ts","../../src/cli/commands/describe.ts","../../src/cli/commands/faucet.ts","../../src/cli/commands/identity.ts","../../src/cli/commands/init.ts","../../src/cli/commands/price.ts","../../src/cli/commands/probe.ts","../../src/cli/commands/send.ts","../../src/cli/commands/transfer.ts","../../src/cli/commands/index.ts","../../src/cli/stdin.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * The `toon` command.\n *\n * Dispatch, and the translation of everything that can go wrong into an exit\n * code a script can branch on:\n *\n * | code | meaning |\n * |------|---------|\n * | 0 | it worked — including a FULFILL whose app answered `404` |\n * | 1 | an unexpected error; this is the bug bucket |\n * | 2 | usage or configuration: something you typed or did not set |\n * | 3 | the packet was **refused** — a normal outcome, printed in full |\n * | 4 | funding or channel: no channel, no collateral, no gas |\n * | 5 | the connector or a chain RPC could not be reached |\n * | 6 | payment or a particular carriage is required |\n *\n * The mapping reads each error's `code` string rather than testing `instanceof`,\n * and that is deliberate: the error taxonomy lives in `client/errors.ts` and\n * grows there, so a CLI that imported every class by name would have to be\n * edited every time one was added — and would fail to *compile* against a build\n * that had not added it yet. Matching on the documented code string means a new\n * error lands with the right exit code the moment it carries the right code, and\n * an unrecognised one falls into 1, which is exactly what \"unexpected\" means.\n */\nimport { homedir } from 'node:os';\nimport { readFileSync, realpathSync } from 'node:fs';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n CliConfigError,\n UsageError,\n boolOption,\n parseCommandLine,\n usage,\n} from './args.js';\nimport { Context, resolveSettings, type CliDependencies } from './context.js';\nimport { Output, type Writer } from './output.js';\nimport { RUNNERS } from './commands/index.js';\nimport { isInteractive, promptHidden, readStdin } from './stdin.js';\n\n/** Exit codes, named. */\nexport const EXIT = {\n ok: 0,\n unexpected: 1,\n usage: 2,\n refused: 3,\n funding: 4,\n network: 5,\n paymentRequired: 6,\n} as const;\n\n/** Error `code` strings that mean \"you typed or configured something wrong\". */\nconst USAGE_CODES = new Set([\n 'USAGE',\n 'CONFIG',\n 'VALIDATION_ERROR',\n 'UNKNOWN_CHAIN',\n 'INVALID_ADDRESS',\n 'INVALID_DESTINATION',\n 'CHAIN_UNAVAILABLE',\n 'ROUTE_NOT_PRICED',\n 'TRANSFER_UNSUPPORTED',\n]);\n\n/** …\"there is no channel, or nothing in it\". */\nconst FUNDING_CODES = new Set([\n 'CHANNEL_FUNDING',\n 'CHANNEL_RESUME',\n 'CHANNEL_NOT_OPEN',\n 'INSUFFICIENT_BALANCE',\n 'TRANSFER_NOT_DELIVERED',\n]);\n\n/** …\"the far end could not be reached, or would not answer sensibly\". */\nconst NETWORK_CODES = new Set(['NETWORK_ERROR', 'CONNECTOR_ERROR', 'STALE_RPC_READ']);\n\n/** …\"pay, or come back over the other carriage\". */\nconst PAYMENT_CODES = new Set([\n 'PAYMENT_REQUIRED',\n 'TRANSPORT_REQUIRED',\n 'HTTP_402_REQUIRES_BTP',\n 'HTTP_401_REQUIRES_BTP',\n]);\n\n/** Socket-level failures, which arrive as a `cause` rather than as a `code`. */\nconst SYSCALL_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\n/** The `code` an error carries, if it carries a string one. */\nfunction errorCode(error: unknown): string | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const code = (error as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\n/**\n * Is this a socket failure in disguise?\n *\n * `fetch` reports a refused connection as a bare `TypeError: fetch failed` whose\n * real cause is nested one or two levels down, so the chain is walked rather\n * than the top-level error inspected. Getting this right is what separates\n * \"your connector is not running\" (5) from \"this is a bug\" (1).\n */\nfunction isTransportFailure(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 8 && current != null; depth += 1) {\n const code = errorCode(current);\n if (code !== undefined && SYSCALL_CODES.has(code)) return true;\n if (current instanceof TypeError && /fetch failed|network|socket/i.test(current.message)) {\n return true;\n }\n current = current instanceof Error ? (current as { cause?: unknown }).cause : undefined;\n }\n return false;\n}\n\n/** Which exit code an error deserves. See this module's own table. */\nexport function exitCodeFor(error: unknown): number {\n const code = errorCode(error);\n if (code !== undefined) {\n if (USAGE_CODES.has(code)) return EXIT.usage;\n if (FUNDING_CODES.has(code)) return EXIT.funding;\n if (NETWORK_CODES.has(code)) return EXIT.network;\n if (PAYMENT_CODES.has(code)) return EXIT.paymentRequired;\n // The connector-edge taxonomy names one cause per code; every one of them\n // is \"the connector answered something unusable\", which is a network-side\n // problem from here.\n if (code.endsWith('_HTTP_STATUS') || code.endsWith('_MALFORMED')) return EXIT.network;\n }\n if (isTransportFailure(error)) return EXIT.network;\n return EXIT.unexpected;\n}\n\n/**\n * Print an error the way a person can act on, and return its exit code.\n *\n * Always writes, `--quiet` notwithstanding: quiet suppresses progress, not the\n * reason a command produced nothing.\n */\nexport function reportError(error: unknown, stderr: Writer): number {\n if (error instanceof UsageError) {\n stderr(`toon: ${error.message}`);\n stderr('');\n stderr(usage(error.command));\n return EXIT.usage;\n }\n if (error instanceof CliConfigError) {\n stderr(`toon: ${error.message}`);\n if (error.hint !== undefined) stderr(` ${error.hint}`);\n return EXIT.usage;\n }\n\n const code = exitCodeFor(error);\n const message = error instanceof Error ? error.message : String(error);\n stderr(`toon: ${message}`);\n if (code === EXIT.network) {\n stderr(' The connector or the chain RPC could not be reached. Check the URL and try again.');\n }\n if (code === EXIT.unexpected && error instanceof Error && error.stack !== undefined) {\n // Nothing recognised this, so the stack is the only useful thing left.\n stderr(error.stack);\n }\n return code;\n}\n\n/** This package's version, read at runtime so nothing has to be generated. */\nexport function packageVersion(): string {\n try {\n const url = new URL('../../package.json', import.meta.url);\n const parsed: unknown = JSON.parse(readFileSync(url, 'utf8'));\n const version = (parsed as { version?: unknown }).version;\n return typeof version === 'string' ? version : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * Commands that never reach a connector at all.\n *\n * `init` writes a keystore and `identity` derives addresses from a phrase;\n * both are pure local key work. Telling someone which node we would have\n * defaulted to is noise on those, and worse than noise — it implies a network\n * call that is not about to happen.\n */\nconst OFFLINE_COMMANDS = new Set(['init', 'identity']);\n\n/**\n * Should the connector-resolution note be suppressed for this invocation?\n *\n * Two cases. The command takes no connector at all ({@link OFFLINE_COMMANDS}),\n * or its own argument names one: `describe <url>` and `price <dest> <url>` do,\n * and when they do the \"no connector given, using the devnet node\" note is not\n * merely noise — it is wrong. Either way it is suppressed rather than printed\n * and then contradicted.\n */\nfunction overridesConnector(command: string, positionals: string[]): boolean {\n if (OFFLINE_COMMANDS.has(command)) return true;\n if (command === 'describe') return positionals[0] !== undefined;\n if (command === 'price') return positionals[1] !== undefined;\n return false;\n}\n\nexport interface RunOptions {\n stdout?: Writer;\n stderr?: Writer;\n /** Overrides for anything that touches the outside world. Tests supply all of it. */\n deps?: Partial<CliDependencies>;\n}\n\n/** Everything the CLI needs from the world, with the real implementations. */\nfunction defaultDependencies(overrides: Partial<CliDependencies> = {}): CliDependencies {\n const interactive = overrides.prompt === undefined && isInteractive();\n return {\n env: process.env,\n home: homedir(),\n readFile: (path: string) => readFileSync(path, 'utf8'),\n readFileBytes: (path: string) => new Uint8Array(readFileSync(path)),\n readStdin: () => readStdin(),\n // A prompt is offered only when there is a terminal to prompt on; otherwise\n // it stays `undefined` and the password resolution says so plainly instead\n // of hanging on a pipe that will never answer.\n ...(interactive ? { prompt: (message: string) => promptHidden(message) } : {}),\n ...overrides,\n };\n}\n\n/**\n * Run one command line and return its exit code.\n *\n * Never throws, never calls `process.exit`: everything is a return value, which\n * is what makes the whole surface testable.\n */\nexport async function runCli(argv: string[], options: RunOptions = {}): Promise<number> {\n const stdout = options.stdout ?? ((text: string) => process.stdout.write(`${text}\\n`));\n const stderr = options.stderr ?? ((text: string) => process.stderr.write(`${text}\\n`));\n let out = new Output({ stdout, stderr });\n let context: Context | undefined;\n\n try {\n const line = parseCommandLine(argv);\n out = new Output({\n json: boolOption(line.values, 'json'),\n quiet: boolOption(line.values, 'quiet'),\n stdout,\n stderr,\n });\n\n if (boolOption(line.values, 'version')) {\n const version = packageVersion();\n out.render({ version }, () => {\n out.line(version);\n });\n return EXIT.ok;\n }\n\n // Help is an answer, so it goes to stdout — and it goes there directly,\n // bypassing `--json`, because help is prose and `--json` promises a\n // document about a connector, not about this program.\n if (line.command === undefined) {\n stdout(usage());\n return EXIT.ok;\n }\n if (line.command === 'help') {\n stdout(usage(line.positionals[0]));\n return EXIT.ok;\n }\n if (boolOption(line.values, 'help')) {\n stdout(usage(line.command));\n return EXIT.ok;\n }\n\n const deps = defaultDependencies(options.deps);\n const { settings, warnings } = resolveSettings(line.values, deps.env, { home: deps.home });\n if (!overridesConnector(line.command, line.positionals)) {\n for (const warning of warnings) out.warn(warning);\n }\n\n const runner = RUNNERS[line.command];\n if (runner === undefined) {\n throw new UsageError(`'${line.command}' has no implementation`, line.command);\n }\n\n context = new Context({\n command: line.command,\n positionals: line.positionals,\n values: line.values,\n settings,\n out,\n deps,\n });\n\n return await runner(context);\n } catch (error) {\n return reportError(error, stderr);\n } finally {\n // Release the BTP socket and flush the watermark, whatever happened. A\n // failure to close is reported and then dropped: it must never replace the\n // outcome the command already produced.\n const client = context?.openClient;\n if (client !== undefined) {\n try {\n await client.close();\n } catch (error) {\n out.warn(`toon: closing the client failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n // And the daemon this run started, if it started one: leaving an `anon`\n // process behind would hold the terminal and outlive the command.\n context?.stopManagedAnon();\n }\n}\n\n/**\n * Run only when this file *is* the program.\n *\n * The ESM entry check, and the reason `runCli` can be imported by a test\n * without the test becoming a CLI invocation.\n *\n * Both sides are resolved through their symlinks before they are compared, and\n * that is the whole point rather than a nicety. `package.json` points `bin` at\n * this file, so npm links `node_modules/.bin/toon` at it; Node then reports\n * `import.meta.url` as the *realpath* while `process.argv[1]` is the path as\n * invoked — the link. Comparing those two strings answers \"no\" for every\n * documented way to run the command (`npx toon`, a global install, the project\n * `.bin`), and the failure is silent: nothing runs and the process exits 0, so\n * a script checking `$?` sees green (#640).\n *\n * A path that cannot be resolved is compared as it stands rather than\n * disqualifying the invocation, so a filesystem that will not answer\n * `realpath` can only leave this as good as the plain string compare, never\n * worse.\n */\nexport function isEntryPoint(moduleUrl: string, entry: string | undefined): boolean {\n if (entry === undefined) return false;\n try {\n const self = fileURLToPath(moduleUrl);\n const invoked = fileURLToPath(pathToFileURL(entry).href);\n return self === invoked || throughLinks(self) === throughLinks(invoked);\n } catch {\n return false;\n }\n}\n\n/** The real file behind a path, or the path itself if it has no answer. */\nfunction throughLinks(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nif (isEntryPoint(import.meta.url, process.argv[1])) {\n process.exitCode = await runCli(process.argv.slice(2));\n}\n","/**\n * The `toon` command line: what every command accepts, and how a mistake is\n * explained.\n *\n * Parsing is `node:util`'s {@link parseArgs} and nothing else — the package\n * targets Node ≥ 22, where that is a standard-library function, and a CLI whose\n * argument parser is a dependency is a CLI that can break on someone else's\n * release.\n *\n * Two decisions here are worth stating, because neither is the obvious one.\n *\n * **Every option is parsed against one union spec.** `parseArgs` is strict, so\n * it must be told about an option before it can see it; giving it only the\n * current command's options would make `toon balances --body x` fail as\n * \"unknown option\", which is true but unhelpful. Parsing against the union and\n * *then* checking the option against the command lets the error say the thing\n * that is actually wrong: `--body` is not an option of `balances`.\n *\n * **A mnemonic is never an option.** There is no `--mnemonic`, and there will\n * not be one: a flag value is written to shell history and is readable in `ps`\n * by every other user on the machine for as long as the process lives. The\n * phrase arrives on stdin (`toon init --import`), through `TOON_MNEMONIC`, or\n * out of an encrypted keystore — see {@link ./keystore.js}.\n */\nimport { parseArgs } from 'node:util';\n\n/**\n * The user asked for something that is not a command, or gave a command\n * arguments it cannot take. Always exit code 2, never a stack trace: a usage\n * mistake is a conversation, not a crash.\n */\nexport class UsageError extends Error {\n readonly code = 'USAGE';\n /** The command to print usage for alongside the message, when one is known. */\n readonly command: string | undefined;\n\n constructor(message: string, command?: string) {\n super(message);\n this.name = 'UsageError';\n this.command = command;\n }\n}\n\n/**\n * A setting could not be resolved: no connector, no keys, a keystore that is\n * not there, a password with nowhere to come from. Exit code 2, the same as a\n * usage mistake, because it is the same kind of problem — something the user\n * supplies is missing or wrong, and the message should say which.\n *\n * Lives beside {@link UsageError} rather than in `client/errors.ts` because it\n * is about *this program's* inputs — a library caller passes a config object and\n * never meets an environment variable.\n */\nexport class CliConfigError extends Error {\n readonly code = 'CONFIG';\n /** What to do about it, printed under the message. */\n readonly hint: string | undefined;\n\n constructor(message: string, hint?: string) {\n super(message);\n this.name = 'CliConfigError';\n this.hint = hint;\n }\n}\n\n/** One option as `parseArgs` wants it. */\ninterface OptionSpec {\n type: 'string' | 'boolean';\n short?: string;\n multiple?: boolean;\n /** One line of help. */\n help: string;\n /** Placeholder for a string option's value, e.g. `URL`. */\n arg?: string;\n}\n\n/**\n * Options every command accepts. These are the settings-resolution inputs —\n * each one is the highest-priority source for a setting that otherwise comes\n * from the environment or a default (see {@link ./context.js}).\n */\nexport const GLOBAL_OPTIONS: Record<string, OptionSpec> = {\n connector: {\n type: 'string',\n arg: 'URL',\n help: \"The connector's client-edge URL. Env TOON_CONNECTOR.\",\n },\n chain: {\n type: 'string',\n arg: 'evm|solana',\n help: 'Which settlement chain to pay on. Env TOON_CHAIN. Default: the first the node offers that you hold a key for.',\n },\n rpc: {\n type: 'string',\n arg: 'URL',\n help: 'Chain RPC endpoint. Env TOON_RPC_URL.',\n },\n store: {\n type: 'string',\n arg: 'PATH',\n help: 'Channel watermark file. Env TOON_CHANNEL_STORE. Default ~/.toon/channels.json.',\n },\n keystore: {\n type: 'string',\n arg: 'PATH',\n help: 'Encrypted mnemonic keystore. Env TOON_KEYSTORE. Default ~/.toon/keystore.json.',\n },\n 'password-file': {\n type: 'string',\n arg: 'PATH',\n help: 'Read the keystore password from this file instead of prompting.',\n },\n transport: {\n type: 'string',\n arg: 'auto|http|btp',\n help: 'Which carriage to pay over. Default auto.',\n },\n socks: {\n type: 'string',\n arg: 'URL',\n help:\n 'SOCKS5h proxy for a .anyone connector, e.g. socks5h://127.0.0.1:9050. ' +\n 'Env TOON_SOCKS. Default: start a managed anon daemon.',\n },\n json: { type: 'boolean', help: 'Print one JSON document on stdout and nothing else.' },\n quiet: { type: 'boolean', help: 'Suppress progress and warnings on stderr.' },\n help: { type: 'boolean', short: 'h', help: 'Show this help.' },\n version: { type: 'boolean', help: 'Print the client version.' },\n};\n\n/** Options that belong to individual commands. */\nexport const COMMAND_OPTIONS: Record<string, OptionSpec> = {\n import: { type: 'boolean', help: 'Import an existing BIP-39 phrase, read from stdin.' },\n 'legacy-derivation': {\n type: 'boolean',\n help: \"Derive the EVM key at Nostr's coin type, as this client did before 1.0.\",\n },\n 'all-derivations': {\n type: 'boolean',\n help: 'Show the addresses of every derivation scheme, not just the one in use.',\n },\n deposit: { type: 'string', arg: 'BASE_UNITS', help: 'Collateral to lock, in base units.' },\n 'settlement-timeout': {\n type: 'string',\n arg: 'SECONDS',\n help: 'Challenge period. Default 86400; EVM floors it at 3600.',\n },\n 'connector-view': {\n type: 'boolean',\n help: \"Also ask the connector for its own watermark, and show both.\",\n },\n method: { type: 'string', arg: 'VERB', help: 'HTTP method. Default POST.' },\n target: { type: 'string', arg: 'PATH', help: \"Path beneath the route's handler. Default ''.\" },\n header: {\n type: 'string',\n short: 'H',\n multiple: true,\n arg: 'NAME:VALUE',\n help: 'A request header. Repeat for more; order and duplicates are preserved.',\n },\n body: { type: 'string', arg: 'TEXT', help: 'Request body. `-` reads stdin to EOF.' },\n 'body-file': { type: 'string', arg: 'PATH', help: 'Read the request body from a file.' },\n 'json-body': {\n type: 'boolean',\n help: 'Check the body parses as JSON and send it as application/json.',\n },\n amount: {\n type: 'string',\n arg: 'BASE_UNITS',\n help: 'Amount in base units. On send, overrides the route price.',\n },\n to: { type: 'string', arg: 'ADDRESS', help: 'Destination address.' },\n asset: { type: 'string', arg: 'native|token', help: \"Which asset to move. Default 'token'.\" },\n};\n\n/** Everything `parseArgs` is allowed to see. */\nconst ALL_OPTIONS = { ...GLOBAL_OPTIONS, ...COMMAND_OPTIONS };\n\n/** What one command is, for dispatch and for help. */\nexport interface CommandSpec {\n summary: string;\n /** The argument line, without the leading `toon`. */\n usage: string;\n /** Long option names this command accepts on top of the globals. */\n options: string[];\n minPositionals: number;\n maxPositionals: number;\n /** Extra paragraphs for `toon help <command>`. */\n details?: string[];\n}\n\n/**\n * The command surface, in the order it is printed.\n *\n * `describe`, `price` and `identity` are the three that need no channel and no\n * money; `identity` needs no network at all. They are first because they are\n * what a newcomer runs before deciding to spend anything.\n */\nexport const COMMANDS: Record<string, CommandSpec> = {\n init: {\n summary: 'Create or import a keystore.',\n usage: 'init [--import] [--legacy-derivation]',\n options: ['import', 'legacy-derivation'],\n minPositionals: 0,\n maxPositionals: 0,\n details: [\n 'Writes an encrypted BIP-39 keystore to ~/.toon/keystore.json (mode 0600).',\n 'With --import the phrase is read from stdin — never from an argument, which',\n 'would be recorded in shell history and visible in `ps` to everyone on the box.',\n ],\n },\n identity: {\n summary: 'Show the addresses this keystore holds. Offline.',\n usage: 'identity [--all-derivations]',\n options: ['all-derivations'],\n minPositionals: 0,\n maxPositionals: 0,\n details: [\n 'Touches no network and no chain: the addresses are derived locally from the',\n 'phrase. --all-derivations also shows where a pre-1.0 keystore put the EVM key,',\n 'which is the address to look at when a channel opened before 1.0 seems to have',\n 'vanished.',\n ],\n },\n describe: {\n summary: 'Read a connector’s self-description. Free, needs no keys.',\n usage: 'describe [URL]',\n options: [],\n minPositionals: 0,\n maxPositionals: 1,\n details: [\n 'One unauthenticated GET returns everything needed to transact with a node:',\n 'its addresses, its endpoints, the key payloads are sealed to, what it settles',\n 'in, and what each route costs.',\n ],\n },\n price: {\n summary: 'What one route costs. Free, needs no keys.',\n usage: 'price <destination> [URL]',\n options: [],\n minPositionals: 1,\n maxPositionals: 2,\n },\n probe: {\n summary: \"Learn a path's cost without buying the work.\",\n usage: 'probe <destination>',\n options: [],\n minPositionals: 1,\n maxPositionals: 1,\n details: ['Needs an open channel: a probe carries a claim, it just does not spend it.'],\n },\n send: {\n summary: 'Pay for one HTTP request and print the answer.',\n usage: 'send [destination] [--method VERB] [--target PATH] [-H NAME:VALUE]... [--body TEXT | --body-file PATH | --body -] [--json-body] [--amount BASE_UNITS]',\n options: ['method', 'target', 'header', 'body', 'body-file', 'json-body', 'amount'],\n minPositionals: 0,\n maxPositionals: 1,\n details: [\n 'The destination is optional: with none, the request goes to the address the',\n 'node published for itself, so a connector URL is the whole of the config.',\n 'The status printed is the app’s own: a 404 from the app is a real answer, it',\n 'rides home fulfilled and costs exactly what a 200 costs. Only a refusal short',\n 'of the app exits 3.',\n ],\n },\n channel: {\n summary: 'Open, fund, inspect, close and settle the payment channel.',\n usage: 'channel open|deposit <amount>|close|settle|status [--deposit BASE_UNITS] [--connector-view]',\n options: ['deposit', 'settlement-timeout', 'connector-view'],\n minPositionals: 1,\n maxPositionals: 2,\n details: [\n 'Every one of these is your transaction, on your gas. `close` starts the',\n 'challenge period; `settle` pays out once it has elapsed.',\n ],\n },\n 'claim-state': {\n summary: \"The connector's own watermark for your channels.\",\n usage: 'claim-state',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n balances: {\n summary: 'Chain balances for this identity.',\n usage: 'balances',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n transfer: {\n summary: 'Move funds out of this wallet.',\n usage: 'transfer --to <address> --amount <base units> [--asset native|token]',\n options: ['to', 'amount', 'asset'],\n minPositionals: 0,\n maxPositionals: 0,\n },\n faucet: {\n summary: 'Ask the devnet faucet for test funds.',\n usage: 'faucet',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n help: {\n summary: 'Show help for a command.',\n usage: 'help [COMMAND]',\n options: [],\n minPositionals: 0,\n maxPositionals: 1,\n },\n};\n\n/** The `channel` subcommands, in the order a channel goes through them. */\nexport const CHANNEL_SUBCOMMANDS = ['open', 'deposit', 'status', 'close', 'settle'] as const;\n\n/** A parsed command line, before any setting is resolved. */\nexport interface ParsedCommandLine {\n /** `undefined` when the line was only `--help` or `--version`. */\n command: string | undefined;\n /** Positionals after the command word. */\n positionals: string[];\n values: ParsedValues;\n}\n\n/** Option values, typed the way `parseArgs` returns them. */\nexport type ParsedValues = Record<string, string | boolean | string[] | undefined>;\n\n/** Read a string option, or `undefined`. Throws if it was given more than once. */\nexport function stringOption(values: ParsedValues, name: string): string | undefined {\n const v = values[name];\n if (v === undefined) return undefined;\n if (typeof v === 'string') return v;\n if (Array.isArray(v)) {\n if (v.length > 1) throw new UsageError(`--${name} was given more than once`);\n return v[0];\n }\n return undefined;\n}\n\n/** Read a boolean option. Absent is `false`. */\nexport function boolOption(values: ParsedValues, name: string): boolean {\n return values[name] === true;\n}\n\n/** Read a repeatable string option as a list, in the order it was given. */\nexport function listOption(values: ParsedValues, name: string): string[] {\n const v = values[name];\n if (v === undefined) return [];\n if (typeof v === 'string') return [v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\n/**\n * Parse one command line.\n *\n * Throws {@link UsageError} — and only {@link UsageError} — for anything the\n * user can fix by typing something else.\n */\nexport function parseCommandLine(argv: string[]): ParsedCommandLine {\n let parsed;\n try {\n parsed = parseArgs({\n args: argv,\n options: ALL_OPTIONS,\n allowPositionals: true,\n strict: true,\n });\n } catch (err) {\n throw new UsageError(err instanceof Error ? err.message : String(err));\n }\n\n const values = parsed.values as ParsedValues;\n const positionals = parsed.positionals;\n const command = positionals[0];\n\n // `--help` and `--version` are answers in their own right, so they are read\n // before the command is validated: `toon --help` and `toon --version` must\n // work, and `toon nonsense --help` should print help rather than complain.\n if (command === undefined) {\n return { command: undefined, positionals: [], values };\n }\n\n const spec = COMMANDS[command];\n if (spec === undefined) {\n throw new UsageError(`unknown command '${command}'. Run 'toon help' for the list.`);\n }\n\n const rest = positionals.slice(1);\n if (!boolOption(values, 'help')) {\n for (const name of Object.keys(values)) {\n if (values[name] === undefined) continue;\n if (name in GLOBAL_OPTIONS) continue;\n if (spec.options.includes(name)) continue;\n throw new UsageError(`--${name} is not an option of '${command}'`, command);\n }\n if (rest.length < spec.minPositionals) {\n throw new UsageError(`'${command}' needs more arguments`, command);\n }\n if (rest.length > spec.maxPositionals) {\n throw new UsageError(\n `'${command}' takes at most ${String(spec.maxPositionals)} argument(s); got ${String(rest.length)}`,\n command\n );\n }\n }\n\n return { command, positionals: rest, values };\n}\n\n/** `--name ARG` or `-s, --name`, padded for a two-column layout. */\nfunction optionLine(name: string, spec: OptionSpec): [string, string] {\n const short = spec.short === undefined ? '' : `-${spec.short}, `;\n const arg = spec.arg === undefined ? '' : ` <${spec.arg}>`;\n return [` ${short}--${name}${arg}`, spec.help];\n}\n\n/** Render two-column rows with the left column padded to a common width. */\nfunction columns(rows: [string, string][]): string {\n const width = rows.reduce((w, [left]) => Math.max(w, left.length), 0);\n return rows.map(([left, right]) => `${left.padEnd(width)} ${right}`).join('\\n');\n}\n\n/**\n * The help text — for one command, or the whole surface.\n *\n * Kept here rather than in each command module so that adding a command that\n * nothing documents is impossible: the same table drives dispatch and help.\n */\nexport function usage(command?: string): string {\n if (command !== undefined && command in COMMANDS) {\n const spec = COMMANDS[command] as CommandSpec;\n const parts = [`toon ${spec.usage}`, '', spec.summary];\n if (spec.details) parts.push('', ...spec.details);\n const opts = spec.options.map((name) =>\n optionLine(name, COMMAND_OPTIONS[name] as OptionSpec)\n );\n if (opts.length > 0) parts.push('', 'Options:', columns(opts));\n parts.push(\n '',\n 'Global options:',\n columns(Object.entries(GLOBAL_OPTIONS).map(([n, s]) => optionLine(n, s)))\n );\n return parts.join('\\n');\n }\n\n return [\n 'toon — pay for an HTTP request, per request, over a payment channel.',\n '',\n 'Usage: toon <command> [options]',\n '',\n 'Commands:',\n columns(\n Object.entries(COMMANDS).map(([name, spec]) => [` ${name}`, spec.summary])\n ),\n '',\n 'Global options:',\n columns(Object.entries(GLOBAL_OPTIONS).map(([n, s]) => optionLine(n, s))),\n '',\n 'Environment: TOON_CONNECTOR, TOON_MNEMONIC, TOON_KEYSTORE,',\n ' TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE,',\n ' TOON_SOCKS.',\n '',\n \"Run 'toon help <command>' for one command in detail.\",\n ].join('\\n');\n}\n","/**\n * Turning a command line and an environment into a configured client.\n *\n * Every setting resolves the same way — **flag, then environment, then\n * default** — and the defaults are chosen so that a user who has run nothing but\n * `toon init` can still run `toon describe`. Where a default is a guess rather\n * than a fact, the guess is announced on stderr: falling back to the devnet\n * connector because none was named is exactly the kind of thing that should not\n * be silent, since the alternative is a user wondering why their production node\n * never saw the request.\n *\n * ## The one lazy import\n *\n * `ToonClient` is imported *here*, dynamically, and nowhere else. Every command\n * is written against {@link ToonClientLike} — the interface — so the whole CLI\n * can be unit-tested against a hand-written fake with no client, no network and\n * no chain anywhere in the test. The import stays a runtime lookup rather than a\n * static one for the same reason: a `toon --help` should not pay for loading\n * viem and the wire codec.\n *\n * ## Why a CLI never opens a channel by itself\n *\n * The library defaults `autoOpenChannel` to `true`, which is right for a\n * long-lived process configured once. It is wrong for a command: `toon send`\n * would submit chain transactions, spend gas and lock collateral as a side\n * effect of asking for one HTTP request. So the CLI turns it off and lets the\n * refusal explain itself — \"no channel yet, run `toon channel open`\" — which is\n * a sentence the user can act on, and reversible.\n */\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { generateRandomIdentity, type KeyDerivationScheme } from '../keys/KeyDerivation.js';\nimport type { ChainKind } from '../channel/types.js';\nimport type {\n ToonClientConfig,\n ToonClientLike,\n TransportPreference,\n} from '../client/types.js';\nimport { DEVNET } from '../presets.js';\nimport { CliConfigError, UsageError, boolOption, stringOption, type ParsedValues } from './args.js';\nimport {\n MNEMONIC_ENV,\n readKeystore,\n resolveKeystorePath,\n resolvePassword,\n keystoreExists,\n type Env,\n} from './keystore.js';\nimport type { Output } from './output.js';\nimport { isHiddenServiceUrl } from '../transport/hs-hostname.js';\nimport type { ManagedAnon } from './anon-daemon.js';\n\nexport type { Env };\n\n/** Environment variables that name a setting. */\nexport const CONNECTOR_ENV = 'TOON_CONNECTOR';\nexport const CHAIN_ENV = 'TOON_CHAIN';\nexport const RPC_ENV = 'TOON_RPC_URL';\nexport const CHANNEL_STORE_ENV = 'TOON_CHANNEL_STORE';\nexport const SOCKS_ENV = 'TOON_SOCKS';\n\n/** Where a setting's value came from. Reported so a surprising run can be explained. */\nexport type SettingSource = 'flag' | 'env' | 'default';\n\n/** Everything resolved from the command line and the environment. */\nexport interface CliSettings {\n connector: string;\n connectorSource: SettingSource;\n /** Unset means \"let the connector's settlements decide\". */\n chain?: ChainKind;\n /** Unset means \"the package's preset for whichever chain is chosen\". */\n rpcUrl?: string;\n /** Always a path: an in-memory watermark is never the right default for a CLI. */\n channelStore: string;\n transport: TransportPreference;\n /**\n * The SOCKS5h proxy for a hidden-service connector. Unset means \"start one\":\n * unlike the library, the CLI may run an `anon` daemon itself (ADR 0001).\n */\n socksProxy?: string;\n keystorePath: string;\n passwordFile?: string;\n json: boolean;\n quiet: boolean;\n}\n\n/** `~/.toon/channels.json`. */\nexport function defaultChannelStorePath(home: string = homedir()): string {\n return join(home, '.toon', 'channels.json');\n}\n\nfunction parseChain(value: string | undefined, from: string): ChainKind | undefined {\n if (value === undefined || value.length === 0) return undefined;\n if (value === 'evm' || value === 'solana') return value;\n throw new UsageError(`${from} must be 'evm' or 'solana'; got '${value}'`);\n}\n\nfunction parseTransport(value: string | undefined, from: string): TransportPreference {\n if (value === undefined || value.length === 0) return 'auto';\n if (value === 'auto' || value === 'http' || value === 'btp') return value;\n throw new UsageError(`${from} must be 'auto', 'http' or 'btp'; got '${value}'`);\n}\n\n/**\n * Resolve every setting, and collect the notes worth printing.\n *\n * Pure apart from `homedir()`: no file is read and no network is touched, which\n * is what makes the precedence rules testable one at a time.\n */\nexport function resolveSettings(\n values: ParsedValues,\n env: Env,\n options: { home?: string } = {}\n): { settings: CliSettings; warnings: string[] } {\n const home = options.home ?? homedir();\n const warnings: string[] = [];\n\n const connectorFlag = stringOption(values, 'connector');\n const connectorEnv = env[CONNECTOR_ENV];\n let connector: string;\n let connectorSource: SettingSource;\n if (connectorFlag !== undefined && connectorFlag.length > 0) {\n connector = connectorFlag;\n connectorSource = 'flag';\n } else if (connectorEnv !== undefined && connectorEnv.length > 0) {\n connector = connectorEnv;\n connectorSource = 'env';\n } else {\n connector = DEVNET.store.url;\n connectorSource = 'default';\n warnings.push(\n `toon: no connector given, using the devnet store node ${DEVNET.store.url}.\\n` +\n ` Set --connector or ${CONNECTOR_ENV} to talk to another node.`\n );\n }\n\n const chain =\n parseChain(stringOption(values, 'chain'), '--chain') ??\n parseChain(env[CHAIN_ENV], CHAIN_ENV);\n\n const rpcUrl = stringOption(values, 'rpc') ?? env[RPC_ENV];\n\n const channelStore =\n stringOption(values, 'store') ??\n (env[CHANNEL_STORE_ENV] !== undefined && env[CHANNEL_STORE_ENV].length > 0\n ? env[CHANNEL_STORE_ENV]\n : defaultChannelStorePath(home));\n\n const transport = parseTransport(stringOption(values, 'transport'), '--transport');\n\n const socksFlag = stringOption(values, 'socks');\n const socksEnv = env[SOCKS_ENV];\n const socksProxy =\n socksFlag !== undefined && socksFlag.length > 0\n ? socksFlag\n : socksEnv !== undefined && socksEnv.length > 0\n ? socksEnv\n : undefined;\n\n const settings: CliSettings = {\n connector,\n connectorSource,\n ...(chain !== undefined ? { chain } : {}),\n ...(rpcUrl !== undefined && rpcUrl.length > 0 ? { rpcUrl } : {}),\n channelStore,\n transport,\n ...(socksProxy !== undefined ? { socksProxy } : {}),\n keystorePath: resolveKeystorePath({\n flag: stringOption(values, 'keystore'),\n env,\n home,\n }),\n ...(stringOption(values, 'password-file') !== undefined\n ? { passwordFile: stringOption(values, 'password-file') }\n : {}),\n json: boolOption(values, 'json'),\n quiet: boolOption(values, 'quiet'),\n };\n\n return { settings, warnings };\n}\n\n/**\n * The key material a command will run with.\n *\n * `ephemeral` exists for the two commands that pay for nothing —\n * {@link ../cli/commands/describe.js} and {@link ../cli/commands/price.js} read\n * a connector's free, unauthenticated endpoints. Rather than making the client\n * cope with having no identity at all, they run with a throwaway one: nothing is\n * signed with it, no chain is touched, and it is discarded when the process\n * exits. That is what lets `toon describe` work on a machine that has never run\n * `toon init`.\n */\nexport type KeyMaterial =\n | { kind: 'mnemonic'; mnemonic: string; derivation: KeyDerivationScheme; from: 'env' | 'keystore' }\n | { kind: 'ephemeral' };\n\n/** Dependencies a command may need, all injectable so the CLI is testable end to end. */\nexport interface CliDependencies {\n env: Env;\n home: string;\n /** Read a whole file as UTF-8. */\n readFile?: (path: string) => string;\n /** The hidden password prompt, or `undefined` when stdin is not a terminal. */\n prompt?: ((message: string) => Promise<string>) | undefined;\n /** Read stdin to EOF — `send --body -`, and `init --import`. */\n readStdin?: () => Promise<Uint8Array>;\n /** Read a whole file as bytes — `send --body-file`, whose content may be binary. */\n readFileBytes?: (path: string) => Uint8Array;\n /** Build the client. Overridden in tests with a fake. */\n createClient?: (config: ToonClientConfig) => Promise<ToonClientLike>;\n /**\n * Start the managed `anon` daemon. Overridden in tests, which must never\n * download a binary.\n */\n startAnon?: (log: (message: string) => void) => Promise<ManagedAnon>;\n}\n\n/**\n * Find the keys.\n *\n * `TOON_MNEMONIC` wins because a phrase in the environment is an explicit\n * instruction from whoever set it, and because it is how a container without a\n * writable home directory is expected to run. It is read as the **standard**\n * derivation: a bare phrase carries no record of which addresses it means, and\n * standard is the one every other wallet agrees on. A phrase whose channels were\n * opened before 1.0 belongs in a keystore, where the file itself records that.\n */\nexport async function resolveKeyMaterial(\n settings: CliSettings,\n deps: CliDependencies,\n options: { keyless?: boolean } = {}\n): Promise<KeyMaterial> {\n const fromEnv = deps.env[MNEMONIC_ENV];\n if (fromEnv !== undefined && fromEnv.trim().length > 0) {\n return {\n kind: 'mnemonic',\n mnemonic: fromEnv.trim(),\n derivation: 'standard',\n from: 'env',\n };\n }\n\n if (keystoreExists(settings.keystorePath)) {\n const { password } = await resolvePassword({\n message: `Password for ${settings.keystorePath}: `,\n passwordFile: settings.passwordFile,\n env: deps.env,\n ...(deps.readFile !== undefined ? { readFile: deps.readFile } : {}),\n prompt: deps.prompt,\n });\n const opened = readKeystore(settings.keystorePath, password);\n return {\n kind: 'mnemonic',\n mnemonic: opened.mnemonic,\n derivation: opened.derivation,\n from: 'keystore',\n };\n }\n\n if (options.keyless === true) return { kind: 'ephemeral' };\n\n throw new CliConfigError(\n `no keys: ${MNEMONIC_ENV} is unset and there is no keystore at ${settings.keystorePath}`,\n \"Run 'toon init' to create one, or set TOON_MNEMONIC.\"\n );\n}\n\n/** Turn resolved settings and key material into the library's own config object. */\nexport function buildClientConfig(\n settings: CliSettings,\n keys: KeyMaterial\n): ToonClientConfig {\n const base: ToonClientConfig = {\n connector: settings.connector,\n channelStore: settings.channelStore,\n transport: settings.transport,\n ...(settings.socksProxy !== undefined ? { socksProxy: settings.socksProxy } : {}),\n // See this module's docs: a command never opens a channel as a side effect.\n autoOpenChannel: false,\n ...(settings.chain !== undefined ? { chain: settings.chain } : {}),\n ...(settings.rpcUrl !== undefined ? { rpcUrl: settings.rpcUrl } : {}),\n };\n\n if (keys.kind === 'mnemonic') {\n return { ...base, mnemonic: keys.mnemonic, keyDerivation: keys.derivation };\n }\n\n const identity = generateRandomIdentity();\n return {\n ...base,\n evmPrivateKey: identity.evm.privateKey,\n solanaSecretKey: identity.solana.secretKey,\n };\n}\n\n/**\n * The concrete client's factory, as this module needs to see it.\n *\n * Deliberately structural, and deliberately optional on the module namespace:\n * the CLI depends on the *shape* `create(config) => ToonClientLike`, so it type\n * checks and unit-tests without the class, and reports a comprehensible error\n * rather than a `TypeError` if a build ever ships without it.\n */\ninterface ToonClientModule {\n ToonClient?: { create(config: ToonClientConfig): Promise<ToonClientLike> };\n}\n\n/** Load `ToonClient` and construct one. The only place the class is named. */\nexport async function defaultCreateClient(config: ToonClientConfig): Promise<ToonClientLike> {\n const module = (await import('../client/index.js')) as ToonClientModule;\n const factory = module.ToonClient;\n if (factory === undefined) {\n throw new Error(\n 'this build of @toon-protocol/client exports no ToonClient; the CLI cannot run against it'\n );\n }\n return factory.create(config);\n}\n\n/** What a command is handed. */\nexport interface CommandContext {\n readonly command: string;\n readonly positionals: string[];\n readonly values: ParsedValues;\n readonly settings: CliSettings;\n readonly out: Output;\n readonly deps: CliDependencies;\n /**\n * The client, created on first use and reused after that.\n *\n * `keyless` lets the two free commands run with a throwaway identity instead\n * of failing on a machine with no keystore. `connector` is how `describe` and\n * `price` honour the URL given as their own argument, which outranks every\n * other source precisely because it was typed for this one invocation.\n */\n client(options?: { keyless?: boolean; connector?: string }): Promise<ToonClientLike>;\n /** The client, if one was ever created — so the caller can close it. */\n readonly openClient: ToonClientLike | undefined;\n}\n\n/** The live {@link CommandContext}. */\nexport class Context implements CommandContext {\n readonly command: string;\n readonly positionals: string[];\n readonly values: ParsedValues;\n readonly settings: CliSettings;\n readonly out: Output;\n readonly deps: CliDependencies;\n private instance: ToonClientLike | undefined;\n\n constructor(init: {\n command: string;\n positionals: string[];\n values: ParsedValues;\n settings: CliSettings;\n out: Output;\n deps: CliDependencies;\n }) {\n this.command = init.command;\n this.positionals = init.positionals;\n this.values = init.values;\n this.settings = init.settings;\n this.out = init.out;\n this.deps = init.deps;\n }\n\n private managedAnon: ManagedAnon | undefined;\n\n get openClient(): ToonClientLike | undefined {\n return this.instance;\n }\n\n async client(options: { keyless?: boolean; connector?: string } = {}): Promise<ToonClientLike> {\n if (this.instance !== undefined) return this.instance;\n const base =\n options.connector === undefined\n ? this.settings\n : { ...this.settings, connector: options.connector, connectorSource: 'flag' as const };\n const settings = await this.withProxy(base);\n const keys = await resolveKeyMaterial(settings, this.deps, options);\n const config = buildClientConfig(settings, keys);\n const create = this.deps.createClient ?? defaultCreateClient;\n this.instance = await create(config);\n return this.instance;\n }\n\n /**\n * Ensure a hidden-service connector has a proxy to be reached through.\n *\n * The library refuses to start a daemon (ADR 0001); the CLI starts one, and\n * says so. A silent twenty-second pause while a binary downloads and circuits\n * build is indistinguishable from a hang, so every step is announced on\n * stderr — where it cannot corrupt `--json` output.\n */\n private async withProxy(settings: CliSettings): Promise<CliSettings> {\n if (settings.socksProxy !== undefined) return settings;\n if (!isHiddenServiceUrl(settings.connector)) return settings;\n\n const log = (message: string): void => this.out.warn(`toon: ${message}`);\n log(`${settings.connector} is a hidden service; starting a local anon daemon`);\n const start = this.deps.startAnon ?? defaultStartAnon;\n this.managedAnon = await start(log);\n log(`proxying through ${this.managedAnon.socksProxy}`);\n return { ...settings, socksProxy: this.managedAnon.socksProxy };\n }\n\n /** Stop the daemon this context started, if it started one. */\n stopManagedAnon(): void {\n this.managedAnon?.stop();\n this.managedAnon = undefined;\n }\n}\n\n/**\n * The real daemon starter, imported only when one is actually needed — the\n * module reaches for `node:child_process` and `node:https`, and no command that\n * talks to a clearnet node should pay to load it.\n */\nasync function defaultStartAnon(log: (message: string) => void): Promise<ManagedAnon> {\n const { startManagedAnon } = await import('./anon-daemon.js');\n return startManagedAnon({ log });\n}\n","/**\n * Where the keys are, and how the password to open them is obtained.\n *\n * The keystore itself — scrypt, AES-256-GCM, the `version`/`derivation` fields\n * and the rule that a pre-1.0 file is read as `legacy` — belongs to\n * {@link ../keys/keystore-node.js}. This module is only the CLI's half: which\n * file, whose password, and what to say when neither can be worked out.\n *\n * ## The order a password is looked for, and why it is this order\n *\n * 1. `--password-file` — an explicit instruction, so it wins. A user who names\n * a file and is then prompted anyway has been ignored.\n * 2. `TOON_KEYSTORE_PASSWORD` — how CI supplies it. Deliberately ahead of the\n * prompt so a scripted run never blocks on a terminal that will never answer.\n * 3. A hidden prompt, when stdin is a TTY.\n * 4. Otherwise a clear error naming both non-interactive options. A CLI that\n * hangs forever on a pipe waiting for a password nobody can type is the\n * failure this ordering exists to prevent.\n *\n * There is no `--password`. A flag value lands in shell history and is visible\n * in `ps` to every user on the machine — the same reason there is no\n * `--mnemonic`.\n */\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { openKeystore, type OpenedKeystore } from '../keys/keystore-node.js';\nimport { CliConfigError } from './args.js';\n\n/** The environment, as a plain map — injected so resolution is testable. */\nexport type Env = Record<string, string | undefined>;\n\n/** Environment variable names this CLI reads for keys. */\nexport const KEYSTORE_ENV = 'TOON_KEYSTORE';\nexport const KEYSTORE_PASSWORD_ENV = 'TOON_KEYSTORE_PASSWORD';\nexport const MNEMONIC_ENV = 'TOON_MNEMONIC';\n\n/** `~/.toon/keystore.json`. */\nexport function defaultKeystorePath(home: string = homedir()): string {\n return join(home, '.toon', 'keystore.json');\n}\n\n/** Flag, then `TOON_KEYSTORE`, then the default path. */\nexport function resolveKeystorePath(options: {\n flag?: string | undefined;\n env?: Env;\n home?: string;\n}): string {\n const flag = options.flag;\n if (flag !== undefined && flag.length > 0) return flag;\n const fromEnv = options.env?.[KEYSTORE_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n return defaultKeystorePath(options.home ?? homedir());\n}\n\n/** How a password was obtained. Reported so a confusing run can be explained. */\nexport type PasswordSource = 'password-file' | 'env' | 'prompt';\n\nexport interface PasswordOptions {\n /** What the prompt says, e.g. `'Keystore password: '`. */\n message: string;\n /** The `--password-file` value, when one was given. */\n passwordFile?: string | undefined;\n env?: Env;\n /** Injected file reader, for tests. */\n readFile?: (path: string) => string;\n /**\n * The hidden prompt, or `undefined` when stdin is not a terminal. Injected\n * rather than detected here so the resolution order can be tested without a\n * TTY.\n */\n prompt?: ((message: string) => Promise<string>) | undefined;\n}\n\n/**\n * Resolve the keystore password. See this module's own docs for the order.\n *\n * A password file's content is trimmed of one trailing newline and nothing\n * else: `echo secret > pw.txt` is the way people make these files, and a\n * password of `\"secret\\n\"` would then be a password nobody can retype.\n */\nexport async function resolvePassword(\n options: PasswordOptions\n): Promise<{ password: string; source: PasswordSource }> {\n const read = options.readFile ?? ((p: string) => readFileSync(p, 'utf8'));\n\n if (options.passwordFile !== undefined && options.passwordFile.length > 0) {\n let contents: string;\n try {\n contents = read(options.passwordFile);\n } catch (err) {\n throw new CliConfigError(\n `cannot read the password file ${options.passwordFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n const password = contents.replace(/\\r?\\n$/, '');\n if (password.length === 0) {\n throw new CliConfigError(`the password file ${options.passwordFile} is empty`);\n }\n return { password, source: 'password-file' };\n }\n\n const fromEnv = options.env?.[KEYSTORE_PASSWORD_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return { password: fromEnv, source: 'env' };\n }\n\n if (options.prompt !== undefined) {\n const password = await options.prompt(options.message);\n if (password.length === 0) throw new CliConfigError('no password was entered');\n return { password, source: 'prompt' };\n }\n\n throw new CliConfigError(\n 'a keystore password is needed and stdin is not a terminal to ask on',\n `Set ${KEYSTORE_PASSWORD_ENV}, or pass --password-file <path>.`\n );\n}\n\n/**\n * Open the keystore at `path`.\n *\n * Distinguishes \"there is no keystore\" from \"that password is wrong\", because\n * the two have completely different remedies and the underlying decrypt reports\n * the second one only.\n */\nexport function readKeystore(path: string, password: string): OpenedKeystore {\n if (!existsSync(path)) {\n throw new CliConfigError(`no keystore at ${path}`, \"Run 'toon init' to create one.\");\n }\n try {\n return openKeystore(path, password);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CliConfigError(`could not open the keystore at ${path}: ${message}`);\n }\n}\n\n/** Create the directory a keystore is about to be written into, if needed. */\nexport function ensureKeystoreDirectory(path: string): void {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n}\n\n/** Does a keystore already exist here? Used by `init` to refuse to overwrite one. */\nexport function keystoreExists(path: string): boolean {\n return existsSync(path);\n}\n","/**\n * How the CLI says things.\n *\n * Two audiences, one code path. A person gets aligned columns and amounts they\n * can read; a script gets `--json`, and the contract there is absolute:\n * **stdout carries exactly one JSON document and nothing else**. Every warning,\n * every prompt, every \"falling back to the devnet preset\" note goes to stderr,\n * so `toon send … --json | jq` never chokes on a line of prose. {@link\n * Output.render} enforces the \"exactly one\" half by refusing to be called twice.\n *\n * Amounts are the other thing worth being deliberate about. A payment channel\n * deals in **base units** — the integers the chain and the connector actually\n * agree on — and a CLI that printed only `0.001 USDC` would be hiding the number\n * every error message, every claim and every deposit is denominated in. So both\n * are printed, base units first: `1000 (0.001 USDC)`. The decimals come from the\n * connector's own settlement entry, never from a guess.\n */\nimport { formatUnits } from 'viem';\nimport { DEVNET } from '../presets.js';\nimport type { ChannelTerms } from '../channel/types.js';\nimport type { ConnectorChainSettlementTerms } from '../connector/self-description.js';\n\n/** Somewhere to write a line of text. Injected so tests never touch a real stream. */\nexport type Writer = (text: string) => void;\n\nexport interface OutputOptions {\n json?: boolean;\n quiet?: boolean;\n stdout?: Writer;\n stderr?: Writer;\n}\n\n/**\n * What is needed to render an amount for a person: how many base units make a\n * whole one, and what to call it.\n *\n * Both are optional, and their absence is honest rather than papered over. A\n * node that publishes no decimals gets `1000` and no parenthetical, because a\n * decimal point in the wrong place is worse than no decimal point.\n */\nexport interface AssetInfo {\n decimals?: number;\n symbol?: string;\n}\n\n/**\n * A display label for a token address.\n *\n * This is the one place a preset is consulted, and it is consulted for a\n * **caption**: the connector publishes an asset's decimals but never its\n * symbol, so the alternative is an amount with no name on it. Nothing is ever\n * paid, signed or opened against what this returns — a wrong answer here\n * misspells a word, it does not move money.\n */\nexport function assetSymbol(tokenAddress: string | undefined): string | undefined {\n if (tokenAddress === undefined) return undefined;\n const t = tokenAddress.toLowerCase();\n if (t === DEVNET.evm.tokenAddress.toLowerCase()) return 'USDC';\n if (t === DEVNET.solana.tokenAddress.toLowerCase()) return 'USDC';\n return undefined;\n}\n\n/** The asset facts in a connector's settlement entry, ready to format with. */\nexport function assetFromSettlement(\n settlement: Pick<ConnectorChainSettlementTerms, 'decimals' | 'tokenAddress'> | undefined\n): AssetInfo {\n if (settlement === undefined) return {};\n return { decimals: settlement.decimals, symbol: assetSymbol(settlement.tokenAddress) };\n}\n\n/** The asset facts in a channel's signing domain. */\nexport function assetFromTerms(terms: ChannelTerms | undefined): AssetInfo {\n if (terms === undefined) return {};\n return { decimals: terms.decimals, symbol: assetSymbol(terms.token) };\n}\n\n/**\n * `1000 (0.001 USDC)` — base units, then the human figure.\n *\n * Falls back gracefully: no decimals gives `1000`, decimals without a symbol\n * gives `1000 (0.001)`.\n */\nexport function formatAmount(\n amount: bigint | string | number,\n asset: AssetInfo = {}\n): string {\n const base = typeof amount === 'bigint' ? amount : BigInt(amount);\n const raw = base.toString();\n if (asset.decimals === undefined) return raw;\n const human = formatUnits(base, asset.decimals);\n return asset.symbol === undefined ? `${raw} (${human})` : `${raw} (${human} ${asset.symbol})`;\n}\n\n/**\n * Convert a value into something `JSON.stringify` can be trusted with.\n *\n * `bigint` becomes a **decimal string**, never a number: every amount this\n * client handles can exceed 2^53, and a JSON number would round it silently —\n * the same reason the connector's own wire spells prices as strings. Bytes\n * become base64. Functions disappear, so a `SendResult`'s `text()`/`json()`\n * helpers cannot leak into the document as `null`.\n */\nexport function toJsonValue(value: unknown): unknown {\n if (typeof value === 'bigint') return value.toString();\n if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'function') return undefined;\n if (Array.isArray(value)) return value.map(toJsonValue);\n if (typeof value === 'object' && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n const converted = toJsonValue(v);\n if (converted !== undefined) out[k] = converted;\n }\n return out;\n }\n return value;\n}\n\n/** Render aligned `label value` rows. */\nexport function columns(rows: [string, string][], indent = ''): string {\n const width = rows.reduce((w, [left]) => Math.max(w, left.length), 0);\n return rows\n .map(([left, right]) => `${indent}${left.padEnd(width)} ${right}`)\n .join('\\n');\n}\n\n/**\n * Is this byte string text?\n *\n * Strict UTF-8 decoding, deliberately: a body that *almost* decodes is a body\n * printed with replacement characters where its actual bytes were, which is a\n * lie about what the app returned. If it does not decode cleanly it is binary,\n * and the CLI says so and gives you its size instead.\n */\nexport function decodeUtf8(bytes: Uint8Array): string | undefined {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n return undefined;\n }\n}\n\nexport class Output {\n readonly json: boolean;\n readonly quiet: boolean;\n private readonly out: Writer;\n private readonly err: Writer;\n private rendered = false;\n\n constructor(options: OutputOptions = {}) {\n this.json = options.json ?? false;\n this.quiet = options.quiet ?? false;\n this.out = options.stdout ?? ((text) => process.stdout.write(`${text}\\n`));\n this.err = options.stderr ?? ((text) => process.stderr.write(`${text}\\n`));\n }\n\n /** A line of human output. Suppressed entirely under `--json`. */\n line(text = ''): void {\n if (!this.json) this.out(text);\n }\n\n /** Aligned rows of human output. */\n rows(rows: [string, string][], indent = ' '): void {\n if (rows.length > 0) this.line(columns(rows, indent));\n }\n\n /**\n * A diagnostic. Always stderr — under `--json` because stdout is spoken for,\n * and otherwise because a warning interleaved with results is a warning that\n * gets piped into the next program.\n */\n warn(text: string): void {\n if (!this.quiet) this.err(text);\n }\n\n /** An error explanation. Stderr, and never suppressed by `--quiet`. */\n error(text: string): void {\n this.err(text);\n }\n\n /**\n * The command's answer: the JSON document under `--json`, the human rendering\n * otherwise.\n *\n * Calling this twice is a bug in the command, not a formatting choice — two\n * documents on stdout is not JSON — so it throws rather than emitting them.\n */\n render(payload: unknown, human: () => void): void {\n if (this.rendered) {\n throw new Error('Output.render was called twice: --json must emit exactly one document');\n }\n this.rendered = true;\n if (this.json) {\n this.out(JSON.stringify(toJsonValue(payload), null, 2));\n } else {\n human();\n }\n }\n}\n","/**\n * `toon balances` — what this identity holds on chain.\n *\n * Nothing here concerns the connector. It answers the two questions that come up\n * when a channel operation fails: is there gas to pay for the transaction, and\n * is there token to put in the channel.\n *\n * A chain whose RPC could not be reached is reported as unreadable rather than\n * as zero. \"I could not look\" and \"there is nothing there\" lead to opposite next\n * steps, and conflating them is how someone concludes their funds are gone.\n */\nimport type { CommandContext } from '../context.js';\nimport { formatAmount } from '../output.js';\nimport type { WalletTokenAmount } from '../../wallet/balances.js';\n\nfunction amountRow(token: WalletTokenAmount): [string, string] {\n const label = token.symbol ?? token.address ?? 'token';\n return [\n label,\n formatAmount(token.amount, {\n ...(token.decimals !== undefined ? { decimals: token.decimals } : {}),\n ...(token.symbol !== undefined ? { symbol: token.symbol } : {}),\n }),\n ];\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const chains = await client.wallet.balances();\n\n ctx.out.render({ identity: client.identity, chains }, () => {\n for (const chain of chains) {\n ctx.out.line(`${chain.chainKey} ${chain.address}`);\n if (chain.unreadable === true) {\n ctx.out.rows([['unreadable', chain.error ?? 'the RPC could not be reached']], ' ');\n ctx.out.line();\n continue;\n }\n const rows: [string, string][] = [];\n if (chain.native !== undefined) rows.push(amountRow(chain.native));\n for (const token of chain.tokens) rows.push(amountRow(token));\n ctx.out.rows(rows, ' ');\n ctx.out.line();\n }\n });\n\n return 0;\n}\n","/**\n * `toon channel open|deposit|status|close|settle` — the payment channel's\n * lifecycle, which is the only part of this CLI that spends gas.\n *\n * Every subcommand here is *your* transaction on *your* chain account. Nothing\n * about it goes through the connector: a connector has no endpoint that opens a\n * channel, it discovers yours by reading the chain (connector ADR 0052). That is\n * also why `status` reports two watermarks when asked to — the local one is what\n * this client has signed, the connector's is what it has banked, and they differ\n * exactly when a claim was signed and never accepted.\n */\nimport { UsageError, boolOption, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { CHANNEL_SUBCOMMANDS } from '../args.js';\nimport { assetFromTerms, formatAmount, type AssetInfo } from '../output.js';\nimport type { ChannelState, ClaimStateResult } from '../../client/types.js';\n\n/** The rows that describe a channel to a person. */\nfunction stateRows(state: ChannelState, asset: AssetInfo): [string, string][] {\n const rows: [string, string][] = [\n ['channel', state.channelId],\n ['chain', state.domain.chain],\n ['counterparty', state.counterparty],\n ['status', state.status],\n ['deposit', formatAmount(state.depositTotal, asset)],\n ['spent', formatAmount(state.spent, asset)],\n ['available', formatAmount(state.available, asset)],\n ['nonce', String(state.nonce)],\n ];\n if (state.onChain?.closedAt !== undefined) {\n rows.push(['closed at', `${state.onChain.closedAt.toString()} (unix seconds)`]);\n }\n if (state.onChain?.settleableAt !== undefined) {\n rows.push(['settleable at', `${state.onChain.settleableAt.toString()} (unix seconds)`]);\n }\n return rows;\n}\n\n/** The connector's own view of one channel, rendered beside ours. */\nfunction connectorRows(entry: ClaimStateResult, asset: AssetInfo): [string, string][] {\n if (!entry.ok) {\n return [['connector', `cannot report this channel (${entry.error})`]];\n }\n return [\n ['connector nonce', String(entry.nonce)],\n ['connector claimed', formatAmount(entry.cumulativeClaimed, asset)],\n [\n 'connector deposit',\n entry.depositTotal === null ? 'declared only' : formatAmount(entry.depositTotal, asset),\n ],\n [\n 'connector available',\n entry.available === null ? 'unknown' : formatAmount(entry.available, asset),\n ],\n ];\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const sub = ctx.positionals[0];\n if (sub === undefined || !(CHANNEL_SUBCOMMANDS as readonly string[]).includes(sub)) {\n throw new UsageError(\n `channel needs one of: ${CHANNEL_SUBCOMMANDS.join(', ')}`,\n 'channel'\n );\n }\n\n const client = await ctx.client();\n const channel = client.channel;\n\n if (sub === 'open') {\n const deposit = stringOption(ctx.values, 'deposit');\n const timeout = stringOption(ctx.values, 'settlement-timeout');\n const state = await channel.open({\n ...(deposit !== undefined ? { deposit } : {}),\n ...(timeout !== undefined ? { settlementTimeout: Number(timeout) } : {}),\n });\n const asset = assetFromTerms(state.domain);\n ctx.out.render(state, () => {\n ctx.out.line('Channel open.');\n ctx.out.rows(stateRows(state, asset));\n });\n return 0;\n }\n\n if (sub === 'deposit') {\n const amount = ctx.positionals[1] ?? stringOption(ctx.values, 'amount');\n if (amount === undefined) {\n throw new UsageError('channel deposit needs an amount in base units', 'channel');\n }\n const state = await channel.deposit(amount);\n const asset = assetFromTerms(state.domain);\n ctx.out.render(state, () => {\n ctx.out.line('Deposit confirmed.');\n ctx.out.rows(stateRows(state, asset));\n });\n return 0;\n }\n\n if (sub === 'close') {\n const result = await channel.close();\n ctx.out.render(result, () => {\n ctx.out.line('Challenge period started. Settle once it has elapsed.');\n const rows: [string, string][] = [];\n if (result.txHash !== undefined) rows.push(['tx', result.txHash]);\n if (result.closedAt !== undefined) rows.push(['closed at', result.closedAt.toString()]);\n if (result.settleableAt !== undefined) {\n rows.push(['settleable at', result.settleableAt.toString()]);\n }\n ctx.out.rows(rows);\n });\n return 0;\n }\n\n if (sub === 'settle') {\n const result = await channel.settle();\n ctx.out.render(result, () => {\n ctx.out.line('Channel settled; the collateral is released.');\n if (result.txHash !== undefined) ctx.out.rows([['tx', result.txHash]]);\n });\n return 0;\n }\n\n // status\n const state = await channel.state({ onChain: true });\n const asset = assetFromTerms(state.domain);\n let connectorView: ClaimStateResult | undefined;\n if (boolOption(ctx.values, 'connector-view')) {\n const entries = await client.claimState([state.channelId]);\n connectorView = entries[0];\n }\n\n ctx.out.render({ ...state, ...(connectorView !== undefined ? { connectorView } : {}) }, () => {\n ctx.out.rows(stateRows(state, asset));\n if (connectorView !== undefined) {\n ctx.out.line();\n ctx.out.rows(connectorRows(connectorView, asset));\n }\n });\n return 0;\n}\n","/**\n * `toon claim-state` — the connector's own watermark for the channels this\n * identity controls.\n *\n * The authoritative half of the picture. `toon channel status` shows what this\n * client has *signed*; this shows what the connector has *banked*, which is the\n * figure every future claim has to advance past. When the two disagree, a claim\n * was signed and never accepted, and the connector's number is the one to\n * believe.\n */\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const entries = await client.claimState();\n const description = await client.describe();\n const asset = assetFromSettlement(description.settlements[0]);\n\n ctx.out.render({ connector: client.connector, channels: entries }, () => {\n if (entries.length === 0) {\n ctx.out.line('This connector reports no channels for your account.');\n ctx.out.line(\"Open one with 'toon channel open --deposit 100000'.\");\n return;\n }\n for (const entry of entries) {\n const id = entry.channelId ?? entry.channelAccount ?? '(unnamed)';\n if (!entry.ok) {\n ctx.out.rows([\n ['channel', id],\n ['chain', entry.blockchain],\n ['state', `unreadable (${entry.error})`],\n ]);\n ctx.out.line();\n continue;\n }\n ctx.out.rows([\n ['channel', id],\n ['chain', entry.blockchain],\n ['nonce', String(entry.nonce)],\n ['claimed', formatAmount(entry.cumulativeClaimed, asset)],\n [\n 'deposit',\n entry.depositTotal === null ? 'declared only' : formatAmount(entry.depositTotal, asset),\n ],\n ['available', entry.available === null ? 'unknown' : formatAmount(entry.available, asset)],\n [\n // Printed as the connector gave it, unconverted: the field is\n // best-effort and non-durable, and `null` means \"unknown\", never\n // \"never claimed\" (client-edge-spec.md §1.10).\n 'last claim',\n entry.lastClaimTime === null ? 'unknown — not \"never\"' : String(entry.lastClaimTime),\n ],\n ]);\n ctx.out.line();\n }\n });\n\n return 0;\n}\n","/**\n * `toon describe [URL]` — read a connector's self-description.\n *\n * The first command anyone should run against an unfamiliar node, and the only\n * one that costs nothing and proves nothing: one unauthenticated `GET` returns\n * every fact needed to transact — the addresses it answers to, the endpoints and\n * carriages it offers, the key a payload is sealed to, what it settles in, and\n * what each route costs. There is no discovery to do beyond this.\n *\n * Runs with no keystore and no channel. A URL given here outranks `--connector`\n * and the environment, because it was typed for this one invocation.\n */\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const url = ctx.positionals[0];\n const client = await ctx.client({\n keyless: true,\n ...(url !== undefined ? { connector: url } : {}),\n });\n const description = await client.describe();\n const asset = assetFromSettlement(description.settlements[0]);\n\n const payload = {\n connector: client.connector,\n ilpAddresses: description.ilpAddresses,\n httpEndpoint: description.httpEndpoint,\n btpEndpoint: description.btpEndpoint,\n peerCarriages: description.peerCarriages,\n edgeIdentity: description.edgeIdentity,\n settlements: description.settlements,\n routes: description.routes,\n requiredTransport: description.requiredTransport,\n supportedVersions: description.supportedVersions,\n defaultVersion: description.defaultVersion,\n };\n\n ctx.out.render(payload, () => {\n const head: [string, string][] = [['connector', client.connector]];\n if (description.ilpAddresses.length > 0) {\n head.push(['addresses', description.ilpAddresses.join(', ')]);\n }\n if (description.httpEndpoint !== undefined) head.push(['http', description.httpEndpoint]);\n if (description.btpEndpoint !== undefined) head.push(['btp', description.btpEndpoint]);\n if (description.requiredTransport !== undefined) {\n head.push(['requires', `${description.requiredTransport} carriage`]);\n }\n if (description.edgeIdentity !== undefined) {\n head.push([\n 'seals to',\n `${description.edgeIdentity.publicKey}${\n description.edgeIdentity.keyId === '' ? '' : ` (key ${description.edgeIdentity.keyId})`\n }`,\n ]);\n }\n head.push([\n 'versions',\n `${description.supportedVersions.join(', ')} (default ${String(description.defaultVersion)})`,\n ]);\n ctx.out.rows(head);\n\n ctx.out.line();\n if (description.settlements.length === 0) {\n ctx.out.line('Settlements: none — this node cannot be paid.');\n } else {\n ctx.out.line('Settlements:');\n ctx.out.rows(\n description.settlements.map((s): [string, string] => [\n s.chain,\n [\n `counterparty ${s.settlementAddress}`,\n `token ${s.tokenAddress} (${String(s.decimals)}dp)`,\n s.kind === 'evm' ? `tokenNetwork ${s.tokenNetwork}` : `program ${s.programId}`,\n ].join(' '),\n ])\n );\n }\n\n ctx.out.line();\n if (description.routes.length === 0) {\n ctx.out.line('Routes: none published.');\n } else {\n ctx.out.line('Routes:');\n ctx.out.rows(\n description.routes.map((r): [string, string] => [\n r.prefix,\n // A route's own carriage pin, where it has one (TOON_Network#111).\n // Beside the price, because a route priced and not qualified reads as\n // one you can simply pay for — which is how the devnet relay read for\n // as long as it pinned BTP and said nothing.\n r.requiredTransport === undefined\n ? formatAmount(r.price, asset)\n : `${formatAmount(r.price, asset)} (${r.requiredTransport} carriage)`,\n ])\n );\n }\n });\n\n return 0;\n}\n","/**\n * `toon faucet` — ask the devnet faucet for test funds.\n *\n * Devnet only, and deliberately unglamorous: it drips the settlement token (and,\n * on Base Sepolia, the gas to move it) onto the address this keystore derives,\n * so that `toon channel open` has something to lock. On a real network this\n * command has nothing to do.\n */\nimport type { CommandContext } from '../context.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const result = await client.wallet.faucet();\n\n ctx.out.render(result, () => {\n ctx.out.line('Faucet request accepted.');\n ctx.out.rows([\n ['chain', result.chain],\n ['address', result.address],\n ]);\n ctx.out.line();\n ctx.out.line(\"Check it landed with 'toon balances'.\");\n });\n\n return 0;\n}\n","/**\n * `toon identity [--all-derivations]` — the addresses this keystore holds.\n *\n * Entirely offline: no connector, no chain, no channel. The addresses are a\n * property of the phrase and the derivation path, so answering needs nothing but\n * the keystore — which is exactly when you want an answer, since the usual\n * reason to run this is that something else could not reach the network.\n *\n * `--all-derivations` exists for one specific, confusing morning: a channel\n * opened before 1.0 appears to have vanished, because the EVM key moved from\n * Nostr's coin type to BIP-44's standard `m/44'/60'/0'/0/i`. The old address is\n * still derivable from the same phrase, and this is how you see it. (The Solana\n * key never moved, so it is the same under both.)\n */\nimport { boolOption } from '../args.js';\nimport { resolveKeyMaterial, type CommandContext } from '../context.js';\nimport {\n deriveFullIdentity,\n evmDerivationPath,\n type KeyDerivationScheme,\n} from '../../keys/KeyDerivation.js';\nimport { MNEMONIC_ENV } from '../keystore.js';\n\n/** SLIP-0010 path for the Solana key. The same under either scheme. */\nconst SOLANA_PATH = \"m/44'/501'/0'/0'\";\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const keys = await resolveKeyMaterial(ctx.settings, ctx.deps);\n if (keys.kind !== 'mnemonic') {\n // `resolveKeyMaterial` only returns `ephemeral` when asked to, and identity\n // never asks: showing a randomly generated address would be a lie.\n throw new Error('identity requires real keys');\n }\n\n const showAll = boolOption(ctx.values, 'all-derivations');\n const identity = deriveFullIdentity(keys.mnemonic, { scheme: keys.derivation });\n const source = keys.from === 'env' ? MNEMONIC_ENV : ctx.settings.keystorePath;\n\n const derivations: { scheme: KeyDerivationScheme; path: string; evmAddress: string }[] = (\n ['standard', 'legacy'] as const\n ).map((scheme) => ({\n scheme,\n path: evmDerivationPath(scheme),\n evmAddress: deriveFullIdentity(keys.mnemonic, { scheme }).evm.address,\n }));\n\n ctx.out.render(\n {\n source,\n derivation: keys.derivation,\n evmAddress: identity.evm.address,\n evmPath: evmDerivationPath(keys.derivation),\n solanaPublicKey: identity.solana.publicKey,\n solanaPath: SOLANA_PATH,\n ...(showAll ? { derivations } : {}),\n },\n () => {\n ctx.out.rows([\n ['evm', `${identity.evm.address} ${evmDerivationPath(keys.derivation)}`],\n ['solana', `${identity.solana.publicKey} ${SOLANA_PATH}`],\n ['derivation', keys.derivation],\n ['keys from', source],\n ]);\n if (showAll) {\n ctx.out.line();\n ctx.out.line('EVM address under each derivation:');\n ctx.out.rows(\n derivations.map((d): [string, string] => [\n d.scheme === keys.derivation ? `${d.scheme} (in use)` : d.scheme,\n `${d.evmAddress} ${d.path}`,\n ])\n );\n }\n }\n );\n\n return 0;\n}\n","/**\n * `toon init [--import] [--legacy-derivation]` — create or import a keystore.\n *\n * The first command a new user runs, and the only one that writes a secret. Two\n * refusals here are deliberate:\n *\n * - **It never overwrites an existing keystore.** The file it would replace may\n * be the only copy of a phrase holding an open channel's collateral, and there\n * is no undo for that.\n * - **A phrase is only ever read from stdin.** Not from an argument, which shell\n * history records and `ps` shows to every user on the machine.\n *\n * `--legacy-derivation` records that this phrase's EVM key lives at Nostr's coin\n * type — what to use when importing a phrase whose channels were opened before\n * 1.0, so the addresses come back where the money is.\n */\nimport { boolOption } from '../args.js';\nimport { CliConfigError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport {\n ensureKeystoreDirectory,\n keystoreExists,\n resolvePassword,\n} from '../keystore.js';\nimport { deriveFullIdentity, evmDerivationPath } from '../../keys/KeyDerivation.js';\nimport { generateKeystore, importKeystore } from '../../keys/keystore-node.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const path = ctx.settings.keystorePath;\n const derivation = boolOption(ctx.values, 'legacy-derivation') ? 'legacy' : 'standard';\n const importing = boolOption(ctx.values, 'import');\n\n if (keystoreExists(path)) {\n throw new CliConfigError(\n `a keystore already exists at ${path}`,\n 'Move it aside first — overwriting it would destroy the only copy of its phrase, ' +\n 'and any channel collateral that phrase controls.'\n );\n }\n\n // The phrase is read before the password so that a piped run consumes stdin\n // in a predictable order.\n let imported: string | undefined;\n if (importing) {\n const readStdin = ctx.deps.readStdin;\n if (readStdin === undefined) {\n throw new CliConfigError('--import reads the phrase from stdin, and stdin is unavailable');\n }\n ctx.out.warn('Reading the BIP-39 recovery phrase from stdin.');\n const bytes = await readStdin();\n imported = Buffer.from(bytes).toString('utf8').trim();\n if (imported.length === 0) throw new CliConfigError('no phrase arrived on stdin');\n }\n\n const { password, source } = await resolvePassword({\n message: `Choose a password for ${path}: `,\n passwordFile: ctx.settings.passwordFile,\n env: ctx.deps.env,\n ...(ctx.deps.readFile !== undefined ? { readFile: ctx.deps.readFile } : {}),\n prompt: ctx.deps.prompt,\n });\n // A typo in a password chosen at a prompt is unrecoverable — nothing else\n // knows what was meant — so it is asked for twice. A password supplied by file\n // or environment can be re-read, so it is not.\n if (source === 'prompt' && ctx.deps.prompt !== undefined) {\n const again = await ctx.deps.prompt('Confirm the password: ');\n if (again !== password) throw new CliConfigError('the two passwords did not match');\n }\n\n ensureKeystoreDirectory(path);\n\n let mnemonic: string;\n let generated: boolean;\n if (imported !== undefined) {\n try {\n importKeystore(path, imported, password, { derivation });\n } catch (err) {\n throw new CliConfigError(err instanceof Error ? err.message : String(err));\n }\n mnemonic = imported;\n generated = false;\n } else {\n mnemonic = generateKeystore(path, password, { derivation }).mnemonic;\n generated = true;\n }\n\n const identity = deriveFullIdentity(mnemonic, { scheme: derivation });\n\n ctx.out.render(\n {\n keystore: path,\n derivation,\n evmAddress: identity.evm.address,\n evmPath: evmDerivationPath(derivation),\n solanaPublicKey: identity.solana.publicKey,\n // Only ever present for a phrase this command just invented: there is one\n // chance to copy it down, and after that only the keystore has it.\n ...(generated ? { mnemonic } : {}),\n },\n () => {\n if (generated) {\n ctx.out.line('Write this recovery phrase down. It is shown once, and it is the only');\n ctx.out.line('way back to these addresses if the keystore file is lost.');\n ctx.out.line();\n ctx.out.line(` ${mnemonic}`);\n ctx.out.line();\n }\n ctx.out.rows([\n ['keystore', path],\n ['derivation', derivation],\n ['evm', `${identity.evm.address} ${evmDerivationPath(derivation)}`],\n ['solana', identity.solana.publicKey],\n ]);\n ctx.out.line();\n ctx.out.line('Next: fund it, then open a channel.');\n ctx.out.line(' toon faucet');\n ctx.out.line(' toon channel open --deposit 100000');\n }\n );\n\n return 0;\n}\n","/**\n * `toon price <destination> [URL]` — what one route costs.\n *\n * Free, keyless and channel-less, like `describe`. `null` back from the\n * connector is a real answer — \"no route I serve matches this destination\" —\n * and is printed as such rather than turned into an error, because asking about\n * a destination a node does not carry is a normal thing to do while finding out\n * which node does.\n */\nimport { UsageError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const destination = ctx.positionals[0];\n if (destination === undefined) throw new UsageError('price needs a destination', 'price');\n const url = ctx.positionals[1];\n\n const client = await ctx.client({\n keyless: true,\n ...(url !== undefined ? { connector: url } : {}),\n });\n const terms = await client.routePrice(destination);\n // The decimals a price is denominated in are the settlement's, so the\n // self-description is read even here — it is cached and already fetched.\n const description = await client.describe();\n const asset = assetFromSettlement(description.settlements[0]);\n const perKib = terms?.pricePerKib;\n\n ctx.out.render(\n {\n connector: client.connector,\n destination,\n price: terms?.price ?? null,\n ...(perKib !== undefined ? { pricePerKib: perKib } : {}),\n decimals: asset.decimals,\n asset: asset.symbol,\n },\n () => {\n if (terms === null) {\n ctx.out.line(`${destination} no route — this node prices nothing that covers it`);\n } else if (perKib === undefined) {\n ctx.out.line(`${destination} ${formatAmount(terms.price, asset)}`);\n } else {\n // A metered route's base price is never what a packet costs, so the\n // rate is printed beside it rather than left for a refusal to reveal.\n ctx.out.line(\n `${destination} ${formatAmount(terms.price, asset)}` +\n ` + ${formatAmount(perKib, asset)}/KiB of sealed payload`\n );\n }\n }\n );\n\n return 0;\n}\n","/**\n * `toon probe <destination>` — learn what a path costs without buying the work.\n *\n * A probe carries a real claim but never spends it: the connector prices the\n * path, reports the figure, and refuses the packet. So the refusal printed here\n * is the *successful* outcome, and the command exits 0 — the failure mode of a\n * probe is not getting an answer, not being told no.\n */\nimport { UsageError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const destination = ctx.positionals[0];\n if (destination === undefined) throw new UsageError('probe needs a destination', 'probe');\n\n const client = await ctx.client();\n const result = await client.probe(destination);\n const description = await client.describe();\n const asset = assetFromSettlement(description.settlements[0]);\n\n ctx.out.render({ destination, ...result }, () => {\n ctx.out.rows([\n ['destination', destination],\n ['cost', formatAmount(result.accumulatedCost, asset)],\n ['code', result.code],\n ['message', result.message],\n ]);\n });\n\n return 0;\n}\n","/**\n * `toon send [destination] …` — pay for one HTTP request and print the answer.\n *\n * The destination is optional: omitted, the request goes to the address the node\n * published for itself, so `TOON_CONNECTOR` alone is enough to buy something.\n *\n * This is what the whole client is for, and its output is shaped around one\n * distinction that is easy to get wrong.\n *\n * **A refusal is an outcome, not a crash.** The connector saying \"you underpaid\"\n * or \"this route wants the other carriage\" is a normal, informative answer: it\n * is printed in full, with what to do about it, and the process exits **3**. An\n * exception — a network that is not there, a keystore that will not open — is a\n * different kind of event and exits somewhere else entirely.\n *\n * **The status printed is the *app's*.** A `404` from the app behind the route\n * rides home on a FULFILL and costs exactly what a `200` costs, because the\n * connector charged for putting the request through, and it did. Only a refusal\n * short of the app is a refusal.\n */\nimport { UsageError, listOption, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, decodeUtf8, formatAmount, type AssetInfo } from '../output.js';\nimport type { SendRefused, SendRequest, SendResult } from '../../client/types.js';\n\n/** Split one `-H name:value` into its two halves. */\nexport function parseHeaderSpec(spec: string): [string, string] {\n const colon = spec.indexOf(':');\n if (colon <= 0) {\n throw new UsageError(`-H expects 'name:value'; got '${spec}'`, 'send');\n }\n return [spec.slice(0, colon).trim(), spec.slice(colon + 1).trim()];\n}\n\n/** Is a header with this name already present? Header names are case-insensitive. */\nfunction hasHeader(headers: [string, string][], name: string): boolean {\n const wanted = name.toLowerCase();\n return headers.some(([key]) => key.toLowerCase() === wanted);\n}\n\n/**\n * Assemble the request from the flags.\n *\n * The three body forms are mutually exclusive and each one exists for a\n * different shape of caller: `--body TEXT` for a person typing, `--body-file`\n * for content that is already a file (and may be binary, which is why it is read\n * as bytes), and `--body -` for a pipeline. Exported so the parsing is tested\n * without a client.\n */\nexport async function buildRequest(ctx: CommandContext): Promise<SendRequest> {\n const bodyFlag = stringOption(ctx.values, 'body');\n const bodyFile = stringOption(ctx.values, 'body-file');\n if (bodyFlag !== undefined && bodyFile !== undefined) {\n throw new UsageError('give --body or --body-file, not both', 'send');\n }\n\n const headers = listOption(ctx.values, 'header').map(parseHeaderSpec);\n\n let body: string | Uint8Array | undefined;\n if (bodyFlag === '-') {\n const readStdin = ctx.deps.readStdin;\n if (readStdin === undefined) {\n throw new UsageError('--body - reads stdin, and stdin is unavailable', 'send');\n }\n body = await readStdin();\n } else if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n const readFileBytes = ctx.deps.readFileBytes;\n if (readFileBytes === undefined) {\n throw new UsageError('--body-file cannot be read in this environment', 'send');\n }\n try {\n body = readFileBytes(bodyFile);\n } catch (err) {\n throw new UsageError(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`,\n 'send'\n );\n }\n }\n\n if (ctx.values['json-body'] === true) {\n if (body === undefined) throw new UsageError('--json-body needs a body', 'send');\n const text = typeof body === 'string' ? body : decodeUtf8(body);\n if (text === undefined) throw new UsageError('--json-body was given bytes that are not UTF-8', 'send');\n try {\n JSON.parse(text);\n } catch (err) {\n throw new UsageError(\n `--json-body was given something that is not JSON: ${err instanceof Error ? err.message : String(err)}`,\n 'send'\n );\n }\n // The body is forwarded as the exact bytes the user supplied rather than\n // re-serialized from the parse: `--json-body` is a check and a content type,\n // not a reformatter, and an app that signs or hashes its request body would\n // not survive being helpfully re-indented.\n if (!hasHeader(headers, 'content-type')) headers.push(['content-type', 'application/json']);\n }\n\n const method = stringOption(ctx.values, 'method');\n const target = stringOption(ctx.values, 'target');\n return {\n ...(method !== undefined ? { method } : {}),\n ...(target !== undefined ? { target } : {}),\n ...(headers.length > 0 ? { headers } : {}),\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * What to try next, given a refusal.\n *\n * The point of this CLI's error handling: a refusal that only says `F03` has\n * told a newcomer nothing. Each hint names the command that addresses the cause.\n */\nexport function refusalHint(result: SendRefused, asset: AssetInfo): string[] {\n const cost =\n result.accumulatedCost === undefined ? undefined : formatAmount(result.accumulatedCost, asset);\n\n switch (result.code) {\n case 'PAYMENT_REQUIRED':\n case 'TRANSPORT_REQUIRED': {\n const required = result.terms?.requiredTransport;\n if (required !== undefined) {\n return [`This route only accepts the ${required} carriage. Retry with --transport ${required}.`];\n }\n return [\n 'The connector answered with terms instead of doing the work, which means it saw no',\n \"usable claim. Check the channel with 'toon channel status --connector-view'.\",\n ];\n }\n case 'F03':\n return cost === undefined\n ? ['The claim did not advance far enough to cover the route.']\n : [\n `The route costs ${cost}. Either the claim did not advance by that much, or the`,\n 'channel has no room left for it — add collateral with',\n \"'toon channel deposit <base units>', then send again.\",\n ];\n case 'F01':\n return [\n 'The connector would not take the claim: it names a channel it cannot see, or a nonce',\n \"it has already banked. Compare the two watermarks with 'toon channel status --connector-view'.\",\n ];\n case 'F02':\n return [\n 'No route to that destination over this carriage. Check what this node actually serves',\n \"with 'toon describe', and which carriage it wants.\",\n ];\n case 'F00':\n return [\n \"The target path was refused before the app saw it: --target is resolved strictly beneath\",\n 'the route handler, so it cannot be absolute, contain `..`, or name a host.',\n ];\n case 'F06':\n return [\"No claim was attached. Open a channel with 'toon channel open --deposit 100000'.\"];\n default:\n if (result.code.startsWith('T')) {\n return ['A temporary refusal — the path asked you to try again shortly.'];\n }\n return [];\n }\n}\n\n/** The `--json` document for one result. `raw` is dropped: it repeats what is above it. */\nfunction payloadFor(result: SendResult): unknown {\n if (result.fulfilled) {\n const text = decodeUtf8(result.body);\n return {\n fulfilled: true,\n transport: result.transport,\n status: result.status,\n headers: result.headers,\n body: result.body,\n ...(text !== undefined ? { text } : {}),\n fulfillment: result.fulfillment,\n claim: result.claim,\n };\n }\n const { terms, ...rest } = result;\n return {\n ...rest,\n ...(terms !== undefined\n ? {\n terms: {\n destination: terms.destination,\n price: terms.price,\n httpEndpoint: terms.httpEndpoint,\n btpEndpoint: terms.btpEndpoint,\n requiredTransport: terms.requiredTransport,\n settlements: terms.settlements,\n sessionLeaseTtlMs: terms.sessionLeaseTtlMs,\n },\n }\n : {}),\n };\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const request = await buildRequest(ctx);\n const amountFlag = stringOption(ctx.values, 'amount');\n\n const client = await ctx.client();\n // The destination is optional: with none, the packet goes to the address the\n // node published for itself, so a connector URL is the whole of the config.\n const destination = ctx.positionals[0] ?? client.defaultDestination;\n if (destination === undefined) {\n throw new UsageError(\n 'send needs a destination, and this node published no address to default to',\n 'send'\n );\n }\n\n const result = await client.send(\n destination,\n request,\n amountFlag === undefined ? undefined : { amount: BigInt(amountFlag) }\n );\n\n const description = await client.describe();\n const asset = assetFromSettlement(description.settlements[0]);\n\n ctx.out.render(payloadFor(result), () => {\n if (result.fulfilled) {\n ctx.out.line(`FULFILL ${String(result.status)} (${result.transport})`);\n const claim = result.claim;\n ctx.out.rows(\n claim === undefined\n ? // A route priced at zero takes no claim, so there is no channel,\n // nonce or amount to show. Saying so beats printing zeroes.\n [['paid', 'nothing — this route is free']]\n : [\n [\n 'paid',\n `${formatAmount(claim.amount, asset)} channel ${claim.channelId} nonce ${String(claim.nonce)}`,\n ],\n ['cumulative', formatAmount(claim.cumulative, asset)],\n ]\n );\n if (result.headers.length > 0) {\n ctx.out.line();\n ctx.out.rows(result.headers.map(([k, v]): [string, string] => [`${k}:`, v]));\n }\n ctx.out.line();\n const text = decodeUtf8(result.body);\n if (text === undefined) {\n ctx.out.line(`<${String(result.body.length)} bytes of binary; use --json for base64>`);\n } else if (text.length > 0) {\n ctx.out.line(text.replace(/\\n$/, ''));\n }\n return;\n }\n\n ctx.out.line(\n `REFUSED ${result.code} (${result.transport}, refused by ${result.refusedBy})`\n );\n const rows: [string, string][] = [['message', result.message]];\n if (result.accumulatedCost !== undefined) {\n rows.push(['cost', formatAmount(result.accumulatedCost, asset)]);\n }\n if (result.claimAck !== undefined) {\n rows.push([\n 'claim',\n result.claimAck.result === 'accepted'\n ? 'accepted'\n : `rejected (${result.claimAck.reason ?? 'no reason given'})`,\n ]);\n }\n if (result.terms !== undefined) {\n rows.push(['route price', formatAmount(result.terms.price, asset)]);\n }\n ctx.out.rows(rows);\n const hint = refusalHint(result, asset);\n if (hint.length > 0) {\n ctx.out.line();\n for (const line of hint) ctx.out.line(line);\n }\n });\n\n return result.fulfilled ? 0 : 3;\n}\n","/**\n * `toon transfer --to <address> --amount <base units> [--asset native|token]`\n *\n * An ordinary on-chain send, out of the wallet this client derives. It exists\n * because the channel wallet is a real account that accumulates change — gas\n * left over, token recovered from a settled channel — and getting it out should\n * not require importing the phrase somewhere else.\n *\n * `--amount` is in **base units**, like every other amount this CLI takes: the\n * chain and the connector agree on integers, and a CLI that quietly accepted\n * `0.1` where a contract expects `100000` is a CLI that will one day send a\n * hundred thousand times too much.\n */\nimport { UsageError, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { formatAmount } from '../output.js';\nimport type { TransferAssetKind } from '../../wallet/transfer.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const to = stringOption(ctx.values, 'to');\n const amount = stringOption(ctx.values, 'amount');\n const assetFlag = stringOption(ctx.values, 'asset') ?? 'token';\n if (to === undefined) throw new UsageError('transfer needs --to <address>', 'transfer');\n if (amount === undefined) {\n throw new UsageError('transfer needs --amount <base units>', 'transfer');\n }\n if (assetFlag !== 'native' && assetFlag !== 'token') {\n throw new UsageError(`--asset must be 'native' or 'token'; got '${assetFlag}'`, 'transfer');\n }\n const asset: TransferAssetKind = assetFlag;\n\n const client = await ctx.client();\n const result = await client.wallet.transfer({ chain: client.chain, asset, to, amount });\n\n ctx.out.render(result, () => {\n ctx.out.line('Transfer delivered.');\n ctx.out.rows([\n ['chain', result.chain],\n ['asset', result.asset],\n ['to', result.to],\n ['amount', formatAmount(result.amount)],\n ['tx', result.txHash],\n ['balance before', formatAmount(result.balanceBefore)],\n ['balance after', formatAmount(result.balanceAfter)],\n ]);\n });\n\n return 0;\n}\n","/**\n * The command table: the one place a name becomes code.\n *\n * Kept beside {@link ../args.js!COMMANDS} — which is the one place a name\n * becomes *help* — and checked against it by this package's own tests, so a\n * command can never be dispatchable without being documented or documented\n * without being dispatchable.\n */\nimport type { CommandContext } from '../context.js';\nimport * as balances from './balances.js';\nimport * as channel from './channel.js';\nimport * as claimState from './claim-state.js';\nimport * as describe from './describe.js';\nimport * as faucet from './faucet.js';\nimport * as identity from './identity.js';\nimport * as init from './init.js';\nimport * as price from './price.js';\nimport * as probe from './probe.js';\nimport * as send from './send.js';\nimport * as transfer from './transfer.js';\n\n/** A command: do the work, return the process exit code. */\nexport type CommandRunner = (ctx: CommandContext) => Promise<number>;\n\nexport const RUNNERS: Record<string, CommandRunner> = {\n init: init.run,\n identity: identity.run,\n describe: describe.run,\n price: price.run,\n probe: probe.run,\n send: send.run,\n channel: channel.run,\n 'claim-state': claimState.run,\n balances: balances.run,\n transfer: transfer.run,\n faucet: faucet.run,\n};\n","/**\n * Talking to the terminal: reading a body from a pipe, and reading a secret\n * without putting it on screen.\n *\n * All of it is isolated here for one reason — every function below touches a\n * real file descriptor, which is exactly what a unit test cannot do. The\n * commands take these as injected dependencies, so what gets exercised in tests\n * is the *decision* (which source a password came from, whether the body came\n * from stdin) rather than the plumbing.\n *\n * Prompts are written to **stderr**, not stdout. Under `--json` stdout carries\n * one JSON document and nothing else, and a prompt is not part of the answer.\n */\n\n/** Read stdin to EOF as bytes. Used for `--body -` and for `init --import`. */\nexport async function readStdin(\n stream: NodeJS.ReadableStream = process.stdin\n): Promise<Uint8Array> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/** Read stdin to EOF and take its first line, newline stripped. */\nexport async function readStdinLine(\n stream: NodeJS.ReadableStream = process.stdin\n): Promise<string> {\n const bytes = await readStdin(stream);\n const first = Buffer.from(bytes).toString('utf8').split('\\n')[0];\n return first === undefined ? '' : first.replace(/\\r$/, '');\n}\n\n/** Is this process attached to a terminal that can prompt? */\nexport function isInteractive(input: NodeJS.ReadStream = process.stdin): boolean {\n return input.isTTY === true && typeof input.setRawMode === 'function';\n}\n\n/**\n * Control characters the raw-mode prompt has to interpret itself, written as\n * code points rather than literals so they survive every editor and diff.\n */\nconst CTRL_C = String.fromCharCode(3);\nconst CTRL_D = String.fromCharCode(4);\nconst BACKSPACE = String.fromCharCode(8);\nconst DELETE = String.fromCharCode(127);\n\n/**\n * Prompt for a secret with the terminal's echo turned off.\n *\n * Raw mode rather than `readline`: `readline` echoes as it reads and there is no\n * supported way to stop it, so the password would appear on the operator's\n * screen and in whatever is recording that screen. In raw mode the characters\n * arrive here and nowhere else, and nothing is written back.\n *\n * Ctrl-C is handled explicitly because raw mode means the terminal no longer\n * turns it into SIGINT: a prompt that ignored it would be a prompt you could not\n * escape.\n */\nexport function promptHidden(\n message: string,\n input: NodeJS.ReadStream = process.stdin,\n output: NodeJS.WritableStream = process.stderr\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n output.write(message);\n const wasRaw = input.isRaw;\n input.setRawMode(true);\n input.resume();\n input.setEncoding('utf8');\n\n let buffer = '';\n const finish = (fn: () => void): void => {\n input.removeListener('data', onData);\n input.setRawMode(wasRaw);\n input.pause();\n output.write('\\n');\n fn();\n };\n\n const onData = (chunk: string): void => {\n for (const char of chunk) {\n if (char === '\\r' || char === '\\n' || char === CTRL_D) {\n finish(() => {\n resolve(buffer);\n });\n return;\n }\n if (char === CTRL_C) {\n finish(() => {\n reject(new Error('cancelled'));\n });\n return;\n }\n if (char === DELETE || char === BACKSPACE) {\n buffer = buffer.slice(0, -1);\n continue;\n }\n buffer += char;\n }\n };\n\n input.on('data', onData);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAS,WAAAA,gBAAe;AACxB,SAAS,gBAAAC,eAAc,oBAAoB;AAC3C,SAAS,eAAe,qBAAqB;;;ACH7C,SAAS,iBAAiB;AAOnB,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B,OAAO;AAAA;AAAA,EAEP;AAAA,EAET,YAAY,SAAiB,SAAkB;AAC7C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAYO,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B,OAAO;AAAA;AAAA,EAEP;AAAA,EAET,YAAY,SAAiB,MAAe;AAC1C,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,OAAO;AAAA,EACd;AACF;AAkBO,IAAM,iBAA6C;AAAA,EACxD,WAAW;AAAA,IACT,MAAM;AAAA,IACN,KAAK;AAAA,IACL,MAAM;AAAA,EACR;AAAA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OAAO;AACd,WAAO,YAAY,OAAO,MAAM;AAAA,EAClC,UAAE;AAIA,UAAM,SAAS,SAAS;AACxB,QAAI,WAAW,QAAW;AACxB,UAAI;AACF,cAAM,OAAO,MAAM;AAAA,MACrB,SAAS,OAAO;AACd,YAAI,KAAK,oCAAoC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAAA,MACvG;AAAA,IACF;AAGA,aAAS,gBAAgB;AAAA,EAC3B;AACF;AAsBO,SAAS,aAAa,WAAmB,OAAoC;AAClF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI;AACF,UAAM,OAAO,cAAc,SAAS;AACpC,UAAM,UAAU,cAAc,cAAc,KAAK,EAAE,IAAI;AACvD,WAAO,SAAS,WAAW,aAAa,IAAI,MAAM,aAAa,OAAO;AAAA,EACxE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,aAAa,MAAsB;AAC1C,MAAI;AACF,WAAO,aAAa,IAAI;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,aAAa,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AAClD,UAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;AACvD;","names":["homedir","readFileSync","homedir","join","homedir","join","columns","run","state","asset","run","run","run","run","run","readStdin","run","run","readStdin","run","run","run","readFileSync","homedir"]}
1
+ {"version":3,"sources":["../../src/cli/main.ts","../../src/cli/args.ts","../../src/cli/context.ts","../../src/cli/keystore.ts","../../src/cli/output.ts","../../src/cli/commands/balances.ts","../../src/cli/commands/channel.ts","../../src/cli/commands/claim-state.ts","../../src/cli/commands/describe.ts","../../src/cli/commands/faucet.ts","../../src/cli/commands/identity.ts","../../src/cli/commands/init.ts","../../src/cli/commands/price.ts","../../src/cli/commands/probe.ts","../../src/cli/commands/send.ts","../../src/cli/commands/transfer.ts","../../src/cli/commands/index.ts","../../src/cli/stdin.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * The `toon` command.\n *\n * Dispatch, and the translation of everything that can go wrong into an exit\n * code a script can branch on:\n *\n * | code | meaning |\n * |------|---------|\n * | 0 | it worked — including a FULFILL whose app answered `404` |\n * | 1 | an unexpected error; this is the bug bucket |\n * | 2 | usage or configuration: something you typed or did not set |\n * | 3 | the packet was **refused** — a normal outcome, printed in full |\n * | 4 | funding or channel: no channel, no collateral, no gas |\n * | 5 | the connector or a chain RPC could not be reached |\n * | 6 | payment or a particular carriage is required |\n *\n * The mapping reads each error's `code` string rather than testing `instanceof`,\n * and that is deliberate: the error taxonomy lives in `client/errors.ts` and\n * grows there, so a CLI that imported every class by name would have to be\n * edited every time one was added — and would fail to *compile* against a build\n * that had not added it yet. Matching on the documented code string means a new\n * error lands with the right exit code the moment it carries the right code, and\n * an unrecognised one falls into 1, which is exactly what \"unexpected\" means.\n */\nimport { homedir } from 'node:os';\nimport { readFileSync, realpathSync } from 'node:fs';\nimport { fileURLToPath, pathToFileURL } from 'node:url';\nimport {\n CliConfigError,\n UsageError,\n boolOption,\n parseCommandLine,\n usage,\n} from './args.js';\nimport { Context, resolveSettings, type CliDependencies } from './context.js';\nimport { Output, type Writer } from './output.js';\nimport { RUNNERS } from './commands/index.js';\nimport { isInteractive, promptHidden, readStdin } from './stdin.js';\n\n/** Exit codes, named. */\nexport const EXIT = {\n ok: 0,\n unexpected: 1,\n usage: 2,\n refused: 3,\n funding: 4,\n network: 5,\n paymentRequired: 6,\n} as const;\n\n/** Error `code` strings that mean \"you typed or configured something wrong\". */\nconst USAGE_CODES = new Set([\n 'USAGE',\n 'CONFIG',\n 'VALIDATION_ERROR',\n 'UNKNOWN_CHAIN',\n 'INVALID_ADDRESS',\n 'INVALID_DESTINATION',\n 'CHAIN_UNAVAILABLE',\n 'ROUTE_NOT_PRICED',\n 'TRANSFER_UNSUPPORTED',\n]);\n\n/** …\"there is no channel, or nothing in it\". */\nconst FUNDING_CODES = new Set([\n 'CHANNEL_FUNDING',\n 'CHANNEL_RESUME',\n 'CHANNEL_NOT_OPEN',\n 'INSUFFICIENT_BALANCE',\n 'TRANSFER_NOT_DELIVERED',\n 'FACILITATOR',\n 'SPONSOR_REFUSED',\n]);\n\n/** …\"the far end could not be reached, or would not answer sensibly\". */\nconst NETWORK_CODES = new Set(['NETWORK_ERROR', 'CONNECTOR_ERROR', 'STALE_RPC_READ']);\n\n/** …\"pay, or come back over the other carriage\". */\nconst PAYMENT_CODES = new Set([\n 'PAYMENT_REQUIRED',\n 'TRANSPORT_REQUIRED',\n 'HTTP_402_REQUIRES_BTP',\n 'HTTP_401_REQUIRES_BTP',\n]);\n\n/** Socket-level failures, which arrive as a `cause` rather than as a `code`. */\nconst SYSCALL_CODES = new Set([\n 'ECONNREFUSED',\n 'ECONNRESET',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'ETIMEDOUT',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n 'UND_ERR_CONNECT_TIMEOUT',\n 'UND_ERR_SOCKET',\n]);\n\n/** The `code` an error carries, if it carries a string one. */\nfunction errorCode(error: unknown): string | undefined {\n if (typeof error !== 'object' || error === null) return undefined;\n const code = (error as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\n/**\n * Is this a socket failure in disguise?\n *\n * `fetch` reports a refused connection as a bare `TypeError: fetch failed` whose\n * real cause is nested one or two levels down, so the chain is walked rather\n * than the top-level error inspected. Getting this right is what separates\n * \"your connector is not running\" (5) from \"this is a bug\" (1).\n */\nfunction isTransportFailure(error: unknown): boolean {\n let current: unknown = error;\n for (let depth = 0; depth < 8 && current != null; depth += 1) {\n const code = errorCode(current);\n if (code !== undefined && SYSCALL_CODES.has(code)) return true;\n if (current instanceof TypeError && /fetch failed|network|socket/i.test(current.message)) {\n return true;\n }\n current = current instanceof Error ? (current as { cause?: unknown }).cause : undefined;\n }\n return false;\n}\n\n/** Which exit code an error deserves. See this module's own table. */\nexport function exitCodeFor(error: unknown): number {\n const code = errorCode(error);\n if (code !== undefined) {\n if (USAGE_CODES.has(code)) return EXIT.usage;\n if (FUNDING_CODES.has(code)) return EXIT.funding;\n if (NETWORK_CODES.has(code)) return EXIT.network;\n if (PAYMENT_CODES.has(code)) return EXIT.paymentRequired;\n // The connector-edge taxonomy names one cause per code; every one of them\n // is \"the connector answered something unusable\", which is a network-side\n // problem from here.\n if (code.endsWith('_HTTP_STATUS') || code.endsWith('_MALFORMED')) return EXIT.network;\n }\n if (isTransportFailure(error)) return EXIT.network;\n return EXIT.unexpected;\n}\n\n/**\n * Print an error the way a person can act on, and return its exit code.\n *\n * Always writes, `--quiet` notwithstanding: quiet suppresses progress, not the\n * reason a command produced nothing.\n */\nexport function reportError(error: unknown, stderr: Writer): number {\n if (error instanceof UsageError) {\n stderr(`toon: ${error.message}`);\n stderr('');\n stderr(usage(error.command));\n return EXIT.usage;\n }\n if (error instanceof CliConfigError) {\n stderr(`toon: ${error.message}`);\n if (error.hint !== undefined) stderr(` ${error.hint}`);\n return EXIT.usage;\n }\n\n const code = exitCodeFor(error);\n const message = error instanceof Error ? error.message : String(error);\n stderr(`toon: ${message}`);\n if (code === EXIT.network) {\n stderr(' The connector or the chain RPC could not be reached. Check the URL and try again.');\n }\n if (code === EXIT.unexpected && error instanceof Error && error.stack !== undefined) {\n // Nothing recognised this, so the stack is the only useful thing left.\n stderr(error.stack);\n }\n return code;\n}\n\n/** This package's version, read at runtime so nothing has to be generated. */\nexport function packageVersion(): string {\n try {\n const url = new URL('../../package.json', import.meta.url);\n const parsed: unknown = JSON.parse(readFileSync(url, 'utf8'));\n const version = (parsed as { version?: unknown }).version;\n return typeof version === 'string' ? version : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/**\n * Commands that never reach a connector at all.\n *\n * `init` writes a keystore and `identity` derives addresses from a phrase;\n * both are pure local key work. Telling someone which node we would have\n * defaulted to is noise on those, and worse than noise — it implies a network\n * call that is not about to happen.\n */\nconst OFFLINE_COMMANDS = new Set(['init', 'identity']);\n\n/**\n * Should the connector-resolution note be suppressed for this invocation?\n *\n * Two cases. The command takes no connector at all ({@link OFFLINE_COMMANDS}),\n * or its own argument names one: `describe <url>` and `price <dest> <url>` do,\n * and when they do the \"no connector given, using the devnet node\" note is not\n * merely noise — it is wrong. Either way it is suppressed rather than printed\n * and then contradicted.\n */\nfunction overridesConnector(command: string, positionals: string[]): boolean {\n if (OFFLINE_COMMANDS.has(command)) return true;\n if (command === 'describe') return positionals[0] !== undefined;\n if (command === 'price') return positionals[1] !== undefined;\n return false;\n}\n\nexport interface RunOptions {\n stdout?: Writer;\n stderr?: Writer;\n /** Overrides for anything that touches the outside world. Tests supply all of it. */\n deps?: Partial<CliDependencies>;\n}\n\n/** Everything the CLI needs from the world, with the real implementations. */\nfunction defaultDependencies(overrides: Partial<CliDependencies> = {}): CliDependencies {\n const interactive = overrides.prompt === undefined && isInteractive();\n return {\n env: process.env,\n home: homedir(),\n readFile: (path: string) => readFileSync(path, 'utf8'),\n readFileBytes: (path: string) => new Uint8Array(readFileSync(path)),\n readStdin: () => readStdin(),\n // A prompt is offered only when there is a terminal to prompt on; otherwise\n // it stays `undefined` and the password resolution says so plainly instead\n // of hanging on a pipe that will never answer.\n ...(interactive ? { prompt: (message: string) => promptHidden(message) } : {}),\n ...overrides,\n };\n}\n\n/**\n * Run one command line and return its exit code.\n *\n * Never throws, never calls `process.exit`: everything is a return value, which\n * is what makes the whole surface testable.\n */\nexport async function runCli(argv: string[], options: RunOptions = {}): Promise<number> {\n const stdout = options.stdout ?? ((text: string) => process.stdout.write(`${text}\\n`));\n const stderr = options.stderr ?? ((text: string) => process.stderr.write(`${text}\\n`));\n let out = new Output({ stdout, stderr });\n let context: Context | undefined;\n\n try {\n const line = parseCommandLine(argv);\n out = new Output({\n json: boolOption(line.values, 'json'),\n quiet: boolOption(line.values, 'quiet'),\n stdout,\n stderr,\n });\n\n if (boolOption(line.values, 'version')) {\n const version = packageVersion();\n out.render({ version }, () => {\n out.line(version);\n });\n return EXIT.ok;\n }\n\n // Help is an answer, so it goes to stdout — and it goes there directly,\n // bypassing `--json`, because help is prose and `--json` promises a\n // document about a connector, not about this program.\n if (line.command === undefined) {\n stdout(usage());\n return EXIT.ok;\n }\n if (line.command === 'help') {\n stdout(usage(line.positionals[0]));\n return EXIT.ok;\n }\n if (boolOption(line.values, 'help')) {\n stdout(usage(line.command));\n return EXIT.ok;\n }\n\n const deps = defaultDependencies(options.deps);\n const { settings, warnings } = resolveSettings(line.values, deps.env, { home: deps.home });\n if (!overridesConnector(line.command, line.positionals)) {\n for (const warning of warnings) out.warn(warning);\n }\n\n const runner = RUNNERS[line.command];\n if (runner === undefined) {\n throw new UsageError(`'${line.command}' has no implementation`, line.command);\n }\n\n context = new Context({\n command: line.command,\n positionals: line.positionals,\n values: line.values,\n settings,\n out,\n deps,\n });\n\n return await runner(context);\n } catch (error) {\n return reportError(error, stderr);\n } finally {\n // Release the BTP socket and flush the watermark, whatever happened. A\n // failure to close is reported and then dropped: it must never replace the\n // outcome the command already produced.\n const client = context?.openClient;\n if (client !== undefined) {\n try {\n await client.close();\n } catch (error) {\n out.warn(`toon: closing the client failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n // And the daemon this run started, if it started one: leaving an `anon`\n // process behind would hold the terminal and outlive the command.\n context?.stopManagedAnon();\n }\n}\n\n/**\n * Run only when this file *is* the program.\n *\n * The ESM entry check, and the reason `runCli` can be imported by a test\n * without the test becoming a CLI invocation.\n *\n * Both sides are resolved through their symlinks before they are compared, and\n * that is the whole point rather than a nicety. `package.json` points `bin` at\n * this file, so npm links `node_modules/.bin/toon` at it; Node then reports\n * `import.meta.url` as the *realpath* while `process.argv[1]` is the path as\n * invoked — the link. Comparing those two strings answers \"no\" for every\n * documented way to run the command (`npx toon`, a global install, the project\n * `.bin`), and the failure is silent: nothing runs and the process exits 0, so\n * a script checking `$?` sees green (#640).\n *\n * A path that cannot be resolved is compared as it stands rather than\n * disqualifying the invocation, so a filesystem that will not answer\n * `realpath` can only leave this as good as the plain string compare, never\n * worse.\n */\nexport function isEntryPoint(moduleUrl: string, entry: string | undefined): boolean {\n if (entry === undefined) return false;\n try {\n const self = fileURLToPath(moduleUrl);\n const invoked = fileURLToPath(pathToFileURL(entry).href);\n return self === invoked || throughLinks(self) === throughLinks(invoked);\n } catch {\n return false;\n }\n}\n\n/** The real file behind a path, or the path itself if it has no answer. */\nfunction throughLinks(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return path;\n }\n}\n\nif (isEntryPoint(import.meta.url, process.argv[1])) {\n process.exitCode = await runCli(process.argv.slice(2));\n}\n","/**\n * The `toon` command line: what every command accepts, and how a mistake is\n * explained.\n *\n * Parsing is `node:util`'s {@link parseArgs} and nothing else — the package\n * targets Node ≥ 22, where that is a standard-library function, and a CLI whose\n * argument parser is a dependency is a CLI that can break on someone else's\n * release.\n *\n * Two decisions here are worth stating, because neither is the obvious one.\n *\n * **Every option is parsed against one union spec.** `parseArgs` is strict, so\n * it must be told about an option before it can see it; giving it only the\n * current command's options would make `toon balances --body x` fail as\n * \"unknown option\", which is true but unhelpful. Parsing against the union and\n * *then* checking the option against the command lets the error say the thing\n * that is actually wrong: `--body` is not an option of `balances`.\n *\n * **A mnemonic is never an option.** There is no `--mnemonic`, and there will\n * not be one: a flag value is written to shell history and is readable in `ps`\n * by every other user on the machine for as long as the process lives. The\n * phrase arrives on stdin (`toon init --import`), through `TOON_MNEMONIC`, or\n * out of an encrypted keystore — see {@link ./keystore.js}.\n */\nimport { parseArgs } from 'node:util';\n\n/**\n * The user asked for something that is not a command, or gave a command\n * arguments it cannot take. Always exit code 2, never a stack trace: a usage\n * mistake is a conversation, not a crash.\n */\nexport class UsageError extends Error {\n readonly code = 'USAGE';\n /** The command to print usage for alongside the message, when one is known. */\n readonly command: string | undefined;\n\n constructor(message: string, command?: string) {\n super(message);\n this.name = 'UsageError';\n this.command = command;\n }\n}\n\n/**\n * A setting could not be resolved: no connector, no keys, a keystore that is\n * not there, a password with nowhere to come from. Exit code 2, the same as a\n * usage mistake, because it is the same kind of problem — something the user\n * supplies is missing or wrong, and the message should say which.\n *\n * Lives beside {@link UsageError} rather than in `client/errors.ts` because it\n * is about *this program's* inputs — a library caller passes a config object and\n * never meets an environment variable.\n */\nexport class CliConfigError extends Error {\n readonly code = 'CONFIG';\n /** What to do about it, printed under the message. */\n readonly hint: string | undefined;\n\n constructor(message: string, hint?: string) {\n super(message);\n this.name = 'CliConfigError';\n this.hint = hint;\n }\n}\n\n/** One option as `parseArgs` wants it. */\ninterface OptionSpec {\n type: 'string' | 'boolean';\n short?: string;\n multiple?: boolean;\n /** One line of help. */\n help: string;\n /** Placeholder for a string option's value, e.g. `URL`. */\n arg?: string;\n}\n\n/**\n * Options every command accepts. These are the settings-resolution inputs —\n * each one is the highest-priority source for a setting that otherwise comes\n * from the environment or a default (see {@link ./context.js}).\n */\nexport const GLOBAL_OPTIONS: Record<string, OptionSpec> = {\n connector: {\n type: 'string',\n arg: 'URL',\n help: \"The connector's client-edge URL. Env TOON_CONNECTOR.\",\n },\n chain: {\n type: 'string',\n arg: 'evm|solana',\n help: 'Which settlement chain to pay on. Env TOON_CHAIN. Default: the first the node offers that you hold a key for.',\n },\n rpc: {\n type: 'string',\n arg: 'URL',\n help: 'Chain RPC endpoint. Env TOON_RPC_URL.',\n },\n store: {\n type: 'string',\n arg: 'PATH',\n help: 'Channel watermark file. Env TOON_CHANNEL_STORE. Default ~/.toon/channels.json.',\n },\n keystore: {\n type: 'string',\n arg: 'PATH',\n help: 'Encrypted mnemonic keystore. Env TOON_KEYSTORE. Default ~/.toon/keystore.json.',\n },\n 'password-file': {\n type: 'string',\n arg: 'PATH',\n help: 'Read the keystore password from this file instead of prompting.',\n },\n transport: {\n type: 'string',\n arg: 'auto|http|btp',\n help: 'Which carriage to pay over. Default auto.',\n },\n socks: {\n type: 'string',\n arg: 'URL',\n help:\n 'SOCKS5h proxy for a .anyone connector, e.g. socks5h://127.0.0.1:9050. ' +\n 'Env TOON_SOCKS. Default: start a managed anon daemon.',\n },\n facilitator: {\n type: 'string',\n arg: 'URL',\n help:\n 'The x402 facilitator that relays a Base channel deposit and pays its gas. ' +\n 'Env TOON_FACILITATOR. Default: the devnet Onboarder on Base Sepolia.',\n },\n json: { type: 'boolean', help: 'Print one JSON document on stdout and nothing else.' },\n quiet: { type: 'boolean', help: 'Suppress progress and warnings on stderr.' },\n help: { type: 'boolean', short: 'h', help: 'Show this help.' },\n version: { type: 'boolean', help: 'Print the client version.' },\n};\n\n/** Options that belong to individual commands. */\nexport const COMMAND_OPTIONS: Record<string, OptionSpec> = {\n import: { type: 'boolean', help: 'Import an existing BIP-39 phrase, read from stdin.' },\n 'legacy-derivation': {\n type: 'boolean',\n help: \"Derive the EVM key at Nostr's coin type, as this client did before 1.0.\",\n },\n 'all-derivations': {\n type: 'boolean',\n help: 'Show the addresses of every derivation scheme, not just the one in use.',\n },\n deposit: {\n type: 'string',\n arg: 'BASE_UNITS',\n help: 'What a channel is opened with, in base units. Default 100000 (0.10 USDC).',\n },\n 'connector-view': {\n type: 'boolean',\n help: \"Also ask the connector for its own watermark, and show both.\",\n },\n method: { type: 'string', arg: 'VERB', help: 'HTTP method. Default POST.' },\n target: { type: 'string', arg: 'PATH', help: \"Path beneath the route's handler. Default ''.\" },\n header: {\n type: 'string',\n short: 'H',\n multiple: true,\n arg: 'NAME:VALUE',\n help: 'A request header. Repeat for more; order and duplicates are preserved.',\n },\n body: { type: 'string', arg: 'TEXT', help: 'Request body. `-` reads stdin to EOF.' },\n 'body-file': { type: 'string', arg: 'PATH', help: 'Read the request body from a file.' },\n 'json-body': {\n type: 'boolean',\n help: 'Check the body parses as JSON and send it as application/json.',\n },\n amount: {\n type: 'string',\n arg: 'BASE_UNITS',\n help: 'Amount in base units. On send, overrides the route price.',\n },\n to: { type: 'string', arg: 'ADDRESS', help: 'Destination address.' },\n asset: { type: 'string', arg: 'native|token', help: \"Which asset to move. Default 'token'.\" },\n};\n\n/** Everything `parseArgs` is allowed to see. */\nconst ALL_OPTIONS = { ...GLOBAL_OPTIONS, ...COMMAND_OPTIONS };\n\n/** What one command is, for dispatch and for help. */\nexport interface CommandSpec {\n summary: string;\n /** The argument line, without the leading `toon`. */\n usage: string;\n /** Long option names this command accepts on top of the globals. */\n options: string[];\n minPositionals: number;\n maxPositionals: number;\n /** Extra paragraphs for `toon help <command>`. */\n details?: string[];\n}\n\n/**\n * The command surface, in the order it is printed.\n *\n * `describe`, `price` and `identity` are the three that need no channel and no\n * money; `identity` needs no network at all. They are first because they are\n * what a newcomer runs before deciding to spend anything.\n */\nexport const COMMANDS: Record<string, CommandSpec> = {\n init: {\n summary: 'Create or import a keystore.',\n usage: 'init [--import] [--legacy-derivation]',\n options: ['import', 'legacy-derivation'],\n minPositionals: 0,\n maxPositionals: 0,\n details: [\n 'Writes an encrypted BIP-39 keystore to ~/.toon/keystore.json (mode 0600).',\n 'With --import the phrase is read from stdin — never from an argument, which',\n 'would be recorded in shell history and visible in `ps` to everyone on the box.',\n ],\n },\n identity: {\n summary: 'Show the addresses this keystore holds. Offline.',\n usage: 'identity [--all-derivations]',\n options: ['all-derivations'],\n minPositionals: 0,\n maxPositionals: 0,\n details: [\n 'Touches no network and no chain: the addresses are derived locally from the',\n 'phrase. --all-derivations also shows where a pre-1.0 keystore put the EVM key,',\n 'which is the address to look at when a channel opened before 1.0 seems to have',\n 'vanished.',\n ],\n },\n describe: {\n summary: 'Read a connector’s self-description. Free, needs no keys.',\n usage: 'describe [URL]',\n options: [],\n minPositionals: 0,\n maxPositionals: 1,\n details: [\n 'One unauthenticated GET returns everything needed to transact with a node:',\n 'its addresses, its endpoints, the key payloads are sealed to, what it settles',\n 'in, and what each route costs.',\n ],\n },\n price: {\n summary: 'What one route costs. Free, needs no keys.',\n usage: 'price <destination> [URL]',\n options: [],\n minPositionals: 1,\n maxPositionals: 2,\n },\n probe: {\n summary: \"Learn a path's cost without buying the work.\",\n usage: 'probe <destination>',\n options: [],\n minPositionals: 1,\n maxPositionals: 1,\n details: ['Needs a channel already paid on: a probe resends the last voucher, which spends nothing.'],\n },\n send: {\n summary: 'Pay for one HTTP request and print the answer.',\n usage: 'send [destination] [--method VERB] [--target PATH] [-H NAME:VALUE]... [--body TEXT | --body-file PATH | --body -] [--json-body] [--amount BASE_UNITS]',\n options: ['method', 'target', 'header', 'body', 'body-file', 'json-body', 'amount'],\n minPositionals: 0,\n maxPositionals: 1,\n details: [\n 'The destination is optional: with none, the request goes to the address the',\n 'node published for itself, so a connector URL is the whole of the config.',\n 'The status printed is the app’s own: a 404 from the app is a real answer, it',\n 'rides home fulfilled and costs exactly what a 200 costs. Only a refusal short',\n 'of the app exits 3.',\n ],\n },\n channel: {\n summary: 'Open, fund, inspect, close and settle the payment channel.',\n usage: 'channel open|deposit <amount>|close|settle|status [--deposit BASE_UNITS] [--connector-view]',\n options: ['deposit', 'connector-view'],\n minPositionals: 1,\n maxPositionals: 2,\n details: [\n 'Opening and depositing cost no gas: a facilitator relays the deposit on Base,',\n 'the connector sponsors the open on Solana. `close` and `settle` are your own',\n 'transactions, on your gas: `close` starts the exit window, and `settle` takes',\n 'the unspent deposit back once it has elapsed.',\n ],\n },\n 'claim-state': {\n summary: \"The connector's own watermark for your channels.\",\n usage: 'claim-state',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n balances: {\n summary: 'Chain balances for this identity.',\n usage: 'balances',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n transfer: {\n summary: 'Move funds out of this wallet.',\n usage: 'transfer --to <address> --amount <base units> [--asset native|token]',\n options: ['to', 'amount', 'asset'],\n minPositionals: 0,\n maxPositionals: 0,\n },\n faucet: {\n summary: 'Ask the devnet faucet for test funds.',\n usage: 'faucet',\n options: [],\n minPositionals: 0,\n maxPositionals: 0,\n },\n help: {\n summary: 'Show help for a command.',\n usage: 'help [COMMAND]',\n options: [],\n minPositionals: 0,\n maxPositionals: 1,\n },\n};\n\n/** The `channel` subcommands, in the order a channel goes through them. */\nexport const CHANNEL_SUBCOMMANDS = ['open', 'deposit', 'status', 'close', 'settle'] as const;\n\n/** A parsed command line, before any setting is resolved. */\nexport interface ParsedCommandLine {\n /** `undefined` when the line was only `--help` or `--version`. */\n command: string | undefined;\n /** Positionals after the command word. */\n positionals: string[];\n values: ParsedValues;\n}\n\n/** Option values, typed the way `parseArgs` returns them. */\nexport type ParsedValues = Record<string, string | boolean | string[] | undefined>;\n\n/** Read a string option, or `undefined`. Throws if it was given more than once. */\nexport function stringOption(values: ParsedValues, name: string): string | undefined {\n const v = values[name];\n if (v === undefined) return undefined;\n if (typeof v === 'string') return v;\n if (Array.isArray(v)) {\n if (v.length > 1) throw new UsageError(`--${name} was given more than once`);\n return v[0];\n }\n return undefined;\n}\n\n/** Read a boolean option. Absent is `false`. */\nexport function boolOption(values: ParsedValues, name: string): boolean {\n return values[name] === true;\n}\n\n/** Read a repeatable string option as a list, in the order it was given. */\nexport function listOption(values: ParsedValues, name: string): string[] {\n const v = values[name];\n if (v === undefined) return [];\n if (typeof v === 'string') return [v];\n if (Array.isArray(v)) return v;\n return [];\n}\n\n/**\n * Parse one command line.\n *\n * Throws {@link UsageError} — and only {@link UsageError} — for anything the\n * user can fix by typing something else.\n */\nexport function parseCommandLine(argv: string[]): ParsedCommandLine {\n let parsed;\n try {\n parsed = parseArgs({\n args: argv,\n options: ALL_OPTIONS,\n allowPositionals: true,\n strict: true,\n });\n } catch (err) {\n throw new UsageError(err instanceof Error ? err.message : String(err));\n }\n\n const values = parsed.values as ParsedValues;\n const positionals = parsed.positionals;\n const command = positionals[0];\n\n // `--help` and `--version` are answers in their own right, so they are read\n // before the command is validated: `toon --help` and `toon --version` must\n // work, and `toon nonsense --help` should print help rather than complain.\n if (command === undefined) {\n return { command: undefined, positionals: [], values };\n }\n\n const spec = COMMANDS[command];\n if (spec === undefined) {\n throw new UsageError(`unknown command '${command}'. Run 'toon help' for the list.`);\n }\n\n const rest = positionals.slice(1);\n if (!boolOption(values, 'help')) {\n for (const name of Object.keys(values)) {\n if (values[name] === undefined) continue;\n if (name in GLOBAL_OPTIONS) continue;\n if (spec.options.includes(name)) continue;\n throw new UsageError(`--${name} is not an option of '${command}'`, command);\n }\n if (rest.length < spec.minPositionals) {\n throw new UsageError(`'${command}' needs more arguments`, command);\n }\n if (rest.length > spec.maxPositionals) {\n throw new UsageError(\n `'${command}' takes at most ${String(spec.maxPositionals)} argument(s); got ${String(rest.length)}`,\n command\n );\n }\n }\n\n return { command, positionals: rest, values };\n}\n\n/** `--name ARG` or `-s, --name`, padded for a two-column layout. */\nfunction optionLine(name: string, spec: OptionSpec): [string, string] {\n const short = spec.short === undefined ? '' : `-${spec.short}, `;\n const arg = spec.arg === undefined ? '' : ` <${spec.arg}>`;\n return [` ${short}--${name}${arg}`, spec.help];\n}\n\n/** Render two-column rows with the left column padded to a common width. */\nfunction columns(rows: [string, string][]): string {\n const width = rows.reduce((w, [left]) => Math.max(w, left.length), 0);\n return rows.map(([left, right]) => `${left.padEnd(width)} ${right}`).join('\\n');\n}\n\n/**\n * The help text — for one command, or the whole surface.\n *\n * Kept here rather than in each command module so that adding a command that\n * nothing documents is impossible: the same table drives dispatch and help.\n */\nexport function usage(command?: string): string {\n if (command !== undefined && command in COMMANDS) {\n const spec = COMMANDS[command] as CommandSpec;\n const parts = [`toon ${spec.usage}`, '', spec.summary];\n if (spec.details) parts.push('', ...spec.details);\n const opts = spec.options.map((name) =>\n optionLine(name, COMMAND_OPTIONS[name] as OptionSpec)\n );\n if (opts.length > 0) parts.push('', 'Options:', columns(opts));\n parts.push(\n '',\n 'Global options:',\n columns(Object.entries(GLOBAL_OPTIONS).map(([n, s]) => optionLine(n, s)))\n );\n return parts.join('\\n');\n }\n\n return [\n 'toon — pay for an HTTP request, per request, over a payment channel.',\n '',\n 'Usage: toon <command> [options]',\n '',\n 'Commands:',\n columns(\n Object.entries(COMMANDS).map(([name, spec]) => [` ${name}`, spec.summary])\n ),\n '',\n 'Global options:',\n columns(Object.entries(GLOBAL_OPTIONS).map(([n, s]) => optionLine(n, s))),\n '',\n 'Environment: TOON_CONNECTOR, TOON_MNEMONIC, TOON_KEYSTORE,',\n ' TOON_KEYSTORE_PASSWORD, TOON_CHAIN, TOON_RPC_URL, TOON_CHANNEL_STORE,',\n ' TOON_SOCKS.',\n '',\n \"Run 'toon help <command>' for one command in detail.\",\n ].join('\\n');\n}\n","/**\n * Turning a command line and an environment into a configured client.\n *\n * Every setting resolves the same way — **flag, then environment, then\n * default** — and the defaults are chosen so that a user who has run nothing but\n * `toon init` can still run `toon describe`. Where a default is a guess rather\n * than a fact, the guess is announced on stderr: falling back to the devnet\n * connector because none was named is exactly the kind of thing that should not\n * be silent, since the alternative is a user wondering why their production node\n * never saw the request.\n *\n * ## The one lazy import\n *\n * `ToonClient` is imported *here*, dynamically, and nowhere else. Every command\n * is written against {@link ToonClientLike} — the interface — so the whole CLI\n * can be unit-tested against a hand-written fake with no client, no network and\n * no chain anywhere in the test. The import stays a runtime lookup rather than a\n * static one for the same reason: a `toon --help` should not pay for loading\n * viem and the wire codec.\n *\n * ## Why a CLI never opens a channel by itself\n *\n * The library defaults `autoOpenChannel` to `true`, which is right for a\n * long-lived process configured once. It is wrong for a command: `toon send`\n * would submit chain transactions, spend gas and lock collateral as a side\n * effect of asking for one HTTP request. So the CLI turns it off and lets the\n * refusal explain itself — \"no channel yet, run `toon channel open`\" — which is\n * a sentence the user can act on, and reversible.\n */\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { generateRandomIdentity, type KeyDerivationScheme } from '../keys/KeyDerivation.js';\nimport type { ChainKind } from '../channel/types.js';\nimport type {\n ToonClientConfig,\n ToonClientLike,\n TransportPreference,\n} from '../client/types.js';\nimport { DEVNET } from '../presets.js';\nimport { CliConfigError, UsageError, boolOption, stringOption, type ParsedValues } from './args.js';\nimport {\n MNEMONIC_ENV,\n readKeystore,\n resolveKeystorePath,\n resolvePassword,\n keystoreExists,\n type Env,\n} from './keystore.js';\nimport type { Output } from './output.js';\nimport { isHiddenServiceUrl } from '../transport/hs-hostname.js';\nimport type { ManagedAnon } from './anon-daemon.js';\n\nexport type { Env };\n\n/** Environment variables that name a setting. */\nexport const CONNECTOR_ENV = 'TOON_CONNECTOR';\nexport const CHAIN_ENV = 'TOON_CHAIN';\nexport const RPC_ENV = 'TOON_RPC_URL';\nexport const CHANNEL_STORE_ENV = 'TOON_CHANNEL_STORE';\nexport const SOCKS_ENV = 'TOON_SOCKS';\nexport const FACILITATOR_ENV = 'TOON_FACILITATOR';\n\n/** Where a setting's value came from. Reported so a surprising run can be explained. */\nexport type SettingSource = 'flag' | 'env' | 'default';\n\n/** Everything resolved from the command line and the environment. */\nexport interface CliSettings {\n connector: string;\n connectorSource: SettingSource;\n /** Unset means \"let the connector's settlements decide\". */\n chain?: ChainKind;\n /** Unset means \"the package's preset for whichever chain is chosen\". */\n rpcUrl?: string;\n /** Always a path: an in-memory watermark is never the right default for a CLI. */\n channelStore: string;\n transport: TransportPreference;\n /**\n * The SOCKS5h proxy for a hidden-service connector. Unset means \"start one\":\n * unlike the library, the CLI may run an `anon` daemon itself (ADR 0001).\n */\n socksProxy?: string;\n /** The x402 facilitator that relays Base deposits; unset means the network's default. */\n facilitatorUrl?: string;\n /** What a channel is opened with, base units, from `--deposit`. */\n deposit?: string;\n keystorePath: string;\n passwordFile?: string;\n json: boolean;\n quiet: boolean;\n}\n\n/** `~/.toon/channels.json`. */\nexport function defaultChannelStorePath(home: string = homedir()): string {\n return join(home, '.toon', 'channels.json');\n}\n\nfunction parseChain(value: string | undefined, from: string): ChainKind | undefined {\n if (value === undefined || value.length === 0) return undefined;\n if (value === 'evm' || value === 'solana') return value;\n throw new UsageError(`${from} must be 'evm' or 'solana'; got '${value}'`);\n}\n\nfunction parseTransport(value: string | undefined, from: string): TransportPreference {\n if (value === undefined || value.length === 0) return 'auto';\n if (value === 'auto' || value === 'http' || value === 'btp') return value;\n throw new UsageError(`${from} must be 'auto', 'http' or 'btp'; got '${value}'`);\n}\n\n/**\n * Resolve every setting, and collect the notes worth printing.\n *\n * Pure apart from `homedir()`: no file is read and no network is touched, which\n * is what makes the precedence rules testable one at a time.\n */\nexport function resolveSettings(\n values: ParsedValues,\n env: Env,\n options: { home?: string } = {}\n): { settings: CliSettings; warnings: string[] } {\n const home = options.home ?? homedir();\n const warnings: string[] = [];\n\n const connectorFlag = stringOption(values, 'connector');\n const connectorEnv = env[CONNECTOR_ENV];\n let connector: string;\n let connectorSource: SettingSource;\n if (connectorFlag !== undefined && connectorFlag.length > 0) {\n connector = connectorFlag;\n connectorSource = 'flag';\n } else if (connectorEnv !== undefined && connectorEnv.length > 0) {\n connector = connectorEnv;\n connectorSource = 'env';\n } else {\n connector = DEVNET.store.url;\n connectorSource = 'default';\n warnings.push(\n `toon: no connector given, using the devnet store node ${DEVNET.store.url}.\\n` +\n ` Set --connector or ${CONNECTOR_ENV} to talk to another node.`\n );\n }\n\n const chain =\n parseChain(stringOption(values, 'chain'), '--chain') ??\n parseChain(env[CHAIN_ENV], CHAIN_ENV);\n\n const rpcUrl = stringOption(values, 'rpc') ?? env[RPC_ENV];\n\n const channelStore =\n stringOption(values, 'store') ??\n (env[CHANNEL_STORE_ENV] !== undefined && env[CHANNEL_STORE_ENV].length > 0\n ? env[CHANNEL_STORE_ENV]\n : defaultChannelStorePath(home));\n\n const transport = parseTransport(stringOption(values, 'transport'), '--transport');\n\n const socksFlag = stringOption(values, 'socks');\n const socksEnv = env[SOCKS_ENV];\n const socksProxy =\n socksFlag !== undefined && socksFlag.length > 0\n ? socksFlag\n : socksEnv !== undefined && socksEnv.length > 0\n ? socksEnv\n : undefined;\n\n const facilitator = stringOption(values, 'facilitator') ?? env[FACILITATOR_ENV];\n const deposit = stringOption(values, 'deposit');\n\n const settings: CliSettings = {\n connector,\n connectorSource,\n ...(facilitator !== undefined && facilitator.length > 0 ? { facilitatorUrl: facilitator } : {}),\n ...(deposit !== undefined ? { deposit } : {}),\n ...(chain !== undefined ? { chain } : {}),\n ...(rpcUrl !== undefined && rpcUrl.length > 0 ? { rpcUrl } : {}),\n channelStore,\n transport,\n ...(socksProxy !== undefined ? { socksProxy } : {}),\n keystorePath: resolveKeystorePath({\n flag: stringOption(values, 'keystore'),\n env,\n home,\n }),\n ...(stringOption(values, 'password-file') !== undefined\n ? { passwordFile: stringOption(values, 'password-file') }\n : {}),\n json: boolOption(values, 'json'),\n quiet: boolOption(values, 'quiet'),\n };\n\n return { settings, warnings };\n}\n\n/**\n * The key material a command will run with.\n *\n * `ephemeral` exists for the two commands that pay for nothing —\n * {@link ../cli/commands/describe.js} and {@link ../cli/commands/price.js} read\n * a connector's free, unauthenticated endpoints. Rather than making the client\n * cope with having no identity at all, they run with a throwaway one: nothing is\n * signed with it, no chain is touched, and it is discarded when the process\n * exits. That is what lets `toon describe` work on a machine that has never run\n * `toon init`.\n */\nexport type KeyMaterial =\n | { kind: 'mnemonic'; mnemonic: string; derivation: KeyDerivationScheme; from: 'env' | 'keystore' }\n | { kind: 'ephemeral' };\n\n/** Dependencies a command may need, all injectable so the CLI is testable end to end. */\nexport interface CliDependencies {\n env: Env;\n home: string;\n /** Read a whole file as UTF-8. */\n readFile?: (path: string) => string;\n /** The hidden password prompt, or `undefined` when stdin is not a terminal. */\n prompt?: ((message: string) => Promise<string>) | undefined;\n /** Read stdin to EOF — `send --body -`, and `init --import`. */\n readStdin?: () => Promise<Uint8Array>;\n /** Read a whole file as bytes — `send --body-file`, whose content may be binary. */\n readFileBytes?: (path: string) => Uint8Array;\n /** Build the client. Overridden in tests with a fake. */\n createClient?: (config: ToonClientConfig) => Promise<ToonClientLike>;\n /**\n * Start the managed `anon` daemon. Overridden in tests, which must never\n * download a binary.\n */\n startAnon?: (log: (message: string) => void) => Promise<ManagedAnon>;\n}\n\n/**\n * Find the keys.\n *\n * `TOON_MNEMONIC` wins because a phrase in the environment is an explicit\n * instruction from whoever set it, and because it is how a container without a\n * writable home directory is expected to run. It is read as the **standard**\n * derivation: a bare phrase carries no record of which addresses it means, and\n * standard is the one every other wallet agrees on. A phrase whose channels were\n * opened before 1.0 belongs in a keystore, where the file itself records that.\n */\nexport async function resolveKeyMaterial(\n settings: CliSettings,\n deps: CliDependencies,\n options: { keyless?: boolean } = {}\n): Promise<KeyMaterial> {\n const fromEnv = deps.env[MNEMONIC_ENV];\n if (fromEnv !== undefined && fromEnv.trim().length > 0) {\n return {\n kind: 'mnemonic',\n mnemonic: fromEnv.trim(),\n derivation: 'standard',\n from: 'env',\n };\n }\n\n if (keystoreExists(settings.keystorePath)) {\n const { password } = await resolvePassword({\n message: `Password for ${settings.keystorePath}: `,\n passwordFile: settings.passwordFile,\n env: deps.env,\n ...(deps.readFile !== undefined ? { readFile: deps.readFile } : {}),\n prompt: deps.prompt,\n });\n const opened = readKeystore(settings.keystorePath, password);\n return {\n kind: 'mnemonic',\n mnemonic: opened.mnemonic,\n derivation: opened.derivation,\n from: 'keystore',\n };\n }\n\n if (options.keyless === true) return { kind: 'ephemeral' };\n\n throw new CliConfigError(\n `no keys: ${MNEMONIC_ENV} is unset and there is no keystore at ${settings.keystorePath}`,\n \"Run 'toon init' to create one, or set TOON_MNEMONIC.\"\n );\n}\n\n/** Turn resolved settings and key material into the library's own config object. */\nexport function buildClientConfig(\n settings: CliSettings,\n keys: KeyMaterial\n): ToonClientConfig {\n const base: ToonClientConfig = {\n connector: settings.connector,\n channelStore: settings.channelStore,\n transport: settings.transport,\n ...(settings.socksProxy !== undefined ? { socksProxy: settings.socksProxy } : {}),\n // See this module's docs: a command never opens a channel as a side effect.\n autoOpenChannel: false,\n ...(settings.chain !== undefined ? { chain: settings.chain } : {}),\n ...(settings.rpcUrl !== undefined ? { rpcUrl: settings.rpcUrl } : {}),\n ...(settings.facilitatorUrl !== undefined ? { facilitatorUrl: settings.facilitatorUrl } : {}),\n ...(settings.deposit !== undefined ? { deposit: settings.deposit } : {}),\n };\n\n if (keys.kind === 'mnemonic') {\n return { ...base, mnemonic: keys.mnemonic, keyDerivation: keys.derivation };\n }\n\n const identity = generateRandomIdentity();\n return {\n ...base,\n evmPrivateKey: identity.evm.privateKey,\n solanaSecretKey: identity.solana.secretKey,\n };\n}\n\n/**\n * The concrete client's factory, as this module needs to see it.\n *\n * Deliberately structural, and deliberately optional on the module namespace:\n * the CLI depends on the *shape* `create(config) => ToonClientLike`, so it type\n * checks and unit-tests without the class, and reports a comprehensible error\n * rather than a `TypeError` if a build ever ships without it.\n */\ninterface ToonClientModule {\n ToonClient?: { create(config: ToonClientConfig): Promise<ToonClientLike> };\n}\n\n/** Load `ToonClient` and construct one. The only place the class is named. */\nexport async function defaultCreateClient(config: ToonClientConfig): Promise<ToonClientLike> {\n const module = (await import('../client/index.js')) as ToonClientModule;\n const factory = module.ToonClient;\n if (factory === undefined) {\n throw new Error(\n 'this build of @toon-protocol/client exports no ToonClient; the CLI cannot run against it'\n );\n }\n return factory.create(config);\n}\n\n/** What a command is handed. */\nexport interface CommandContext {\n readonly command: string;\n readonly positionals: string[];\n readonly values: ParsedValues;\n readonly settings: CliSettings;\n readonly out: Output;\n readonly deps: CliDependencies;\n /**\n * The client, created on first use and reused after that.\n *\n * `keyless` lets the two free commands run with a throwaway identity instead\n * of failing on a machine with no keystore. `connector` is how `describe` and\n * `price` honour the URL given as their own argument, which outranks every\n * other source precisely because it was typed for this one invocation.\n */\n client(options?: { keyless?: boolean; connector?: string }): Promise<ToonClientLike>;\n /** The client, if one was ever created — so the caller can close it. */\n readonly openClient: ToonClientLike | undefined;\n}\n\n/** The live {@link CommandContext}. */\nexport class Context implements CommandContext {\n readonly command: string;\n readonly positionals: string[];\n readonly values: ParsedValues;\n readonly settings: CliSettings;\n readonly out: Output;\n readonly deps: CliDependencies;\n private instance: ToonClientLike | undefined;\n\n constructor(init: {\n command: string;\n positionals: string[];\n values: ParsedValues;\n settings: CliSettings;\n out: Output;\n deps: CliDependencies;\n }) {\n this.command = init.command;\n this.positionals = init.positionals;\n this.values = init.values;\n this.settings = init.settings;\n this.out = init.out;\n this.deps = init.deps;\n }\n\n private managedAnon: ManagedAnon | undefined;\n\n get openClient(): ToonClientLike | undefined {\n return this.instance;\n }\n\n async client(options: { keyless?: boolean; connector?: string } = {}): Promise<ToonClientLike> {\n if (this.instance !== undefined) return this.instance;\n const base =\n options.connector === undefined\n ? this.settings\n : { ...this.settings, connector: options.connector, connectorSource: 'flag' as const };\n const settings = await this.withProxy(base);\n const keys = await resolveKeyMaterial(settings, this.deps, options);\n const config = buildClientConfig(settings, keys);\n const create = this.deps.createClient ?? defaultCreateClient;\n this.instance = await create(config);\n return this.instance;\n }\n\n /**\n * Ensure a hidden-service connector has a proxy to be reached through.\n *\n * The library refuses to start a daemon (ADR 0001); the CLI starts one, and\n * says so. A silent twenty-second pause while a binary downloads and circuits\n * build is indistinguishable from a hang, so every step is announced on\n * stderr — where it cannot corrupt `--json` output.\n */\n private async withProxy(settings: CliSettings): Promise<CliSettings> {\n if (settings.socksProxy !== undefined) return settings;\n if (!isHiddenServiceUrl(settings.connector)) return settings;\n\n const log = (message: string): void => this.out.warn(`toon: ${message}`);\n log(`${settings.connector} is a hidden service; starting a local anon daemon`);\n const start = this.deps.startAnon ?? defaultStartAnon;\n this.managedAnon = await start(log);\n log(`proxying through ${this.managedAnon.socksProxy}`);\n return { ...settings, socksProxy: this.managedAnon.socksProxy };\n }\n\n /** Stop the daemon this context started, if it started one. */\n stopManagedAnon(): void {\n this.managedAnon?.stop();\n this.managedAnon = undefined;\n }\n}\n\n/**\n * The real daemon starter, imported only when one is actually needed — the\n * module reaches for `node:child_process` and `node:https`, and no command that\n * talks to a clearnet node should pay to load it.\n */\nasync function defaultStartAnon(log: (message: string) => void): Promise<ManagedAnon> {\n const { startManagedAnon } = await import('./anon-daemon.js');\n return startManagedAnon({ log });\n}\n","/**\n * Where the keys are, and how the password to open them is obtained.\n *\n * The keystore itself — scrypt, AES-256-GCM, the `version`/`derivation` fields\n * and the rule that a pre-1.0 file is read as `legacy` — belongs to\n * {@link ../keys/keystore-node.js}. This module is only the CLI's half: which\n * file, whose password, and what to say when neither can be worked out.\n *\n * ## The order a password is looked for, and why it is this order\n *\n * 1. `--password-file` — an explicit instruction, so it wins. A user who names\n * a file and is then prompted anyway has been ignored.\n * 2. `TOON_KEYSTORE_PASSWORD` — how CI supplies it. Deliberately ahead of the\n * prompt so a scripted run never blocks on a terminal that will never answer.\n * 3. A hidden prompt, when stdin is a TTY.\n * 4. Otherwise a clear error naming both non-interactive options. A CLI that\n * hangs forever on a pipe waiting for a password nobody can type is the\n * failure this ordering exists to prevent.\n *\n * There is no `--password`. A flag value lands in shell history and is visible\n * in `ps` to every user on the machine — the same reason there is no\n * `--mnemonic`.\n */\nimport { existsSync, mkdirSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { homedir } from 'node:os';\nimport { openKeystore, type OpenedKeystore } from '../keys/keystore-node.js';\nimport { CliConfigError } from './args.js';\n\n/** The environment, as a plain map — injected so resolution is testable. */\nexport type Env = Record<string, string | undefined>;\n\n/** Environment variable names this CLI reads for keys. */\nexport const KEYSTORE_ENV = 'TOON_KEYSTORE';\nexport const KEYSTORE_PASSWORD_ENV = 'TOON_KEYSTORE_PASSWORD';\nexport const MNEMONIC_ENV = 'TOON_MNEMONIC';\n\n/** `~/.toon/keystore.json`. */\nexport function defaultKeystorePath(home: string = homedir()): string {\n return join(home, '.toon', 'keystore.json');\n}\n\n/** Flag, then `TOON_KEYSTORE`, then the default path. */\nexport function resolveKeystorePath(options: {\n flag?: string | undefined;\n env?: Env;\n home?: string;\n}): string {\n const flag = options.flag;\n if (flag !== undefined && flag.length > 0) return flag;\n const fromEnv = options.env?.[KEYSTORE_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) return fromEnv;\n return defaultKeystorePath(options.home ?? homedir());\n}\n\n/** How a password was obtained. Reported so a confusing run can be explained. */\nexport type PasswordSource = 'password-file' | 'env' | 'prompt';\n\nexport interface PasswordOptions {\n /** What the prompt says, e.g. `'Keystore password: '`. */\n message: string;\n /** The `--password-file` value, when one was given. */\n passwordFile?: string | undefined;\n env?: Env;\n /** Injected file reader, for tests. */\n readFile?: (path: string) => string;\n /**\n * The hidden prompt, or `undefined` when stdin is not a terminal. Injected\n * rather than detected here so the resolution order can be tested without a\n * TTY.\n */\n prompt?: ((message: string) => Promise<string>) | undefined;\n}\n\n/**\n * Resolve the keystore password. See this module's own docs for the order.\n *\n * A password file's content is trimmed of one trailing newline and nothing\n * else: `echo secret > pw.txt` is the way people make these files, and a\n * password of `\"secret\\n\"` would then be a password nobody can retype.\n */\nexport async function resolvePassword(\n options: PasswordOptions\n): Promise<{ password: string; source: PasswordSource }> {\n const read = options.readFile ?? ((p: string) => readFileSync(p, 'utf8'));\n\n if (options.passwordFile !== undefined && options.passwordFile.length > 0) {\n let contents: string;\n try {\n contents = read(options.passwordFile);\n } catch (err) {\n throw new CliConfigError(\n `cannot read the password file ${options.passwordFile}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n const password = contents.replace(/\\r?\\n$/, '');\n if (password.length === 0) {\n throw new CliConfigError(`the password file ${options.passwordFile} is empty`);\n }\n return { password, source: 'password-file' };\n }\n\n const fromEnv = options.env?.[KEYSTORE_PASSWORD_ENV];\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return { password: fromEnv, source: 'env' };\n }\n\n if (options.prompt !== undefined) {\n const password = await options.prompt(options.message);\n if (password.length === 0) throw new CliConfigError('no password was entered');\n return { password, source: 'prompt' };\n }\n\n throw new CliConfigError(\n 'a keystore password is needed and stdin is not a terminal to ask on',\n `Set ${KEYSTORE_PASSWORD_ENV}, or pass --password-file <path>.`\n );\n}\n\n/**\n * Open the keystore at `path`.\n *\n * Distinguishes \"there is no keystore\" from \"that password is wrong\", because\n * the two have completely different remedies and the underlying decrypt reports\n * the second one only.\n */\nexport function readKeystore(path: string, password: string): OpenedKeystore {\n if (!existsSync(path)) {\n throw new CliConfigError(`no keystore at ${path}`, \"Run 'toon init' to create one.\");\n }\n try {\n return openKeystore(path, password);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new CliConfigError(`could not open the keystore at ${path}: ${message}`);\n }\n}\n\n/** Create the directory a keystore is about to be written into, if needed. */\nexport function ensureKeystoreDirectory(path: string): void {\n mkdirSync(dirname(path), { recursive: true, mode: 0o700 });\n}\n\n/** Does a keystore already exist here? Used by `init` to refuse to overwrite one. */\nexport function keystoreExists(path: string): boolean {\n return existsSync(path);\n}\n","/**\n * How the CLI says things.\n *\n * Two audiences, one code path. A person gets aligned columns and amounts they\n * can read; a script gets `--json`, and the contract there is absolute:\n * **stdout carries exactly one JSON document and nothing else**. Every warning,\n * every prompt, every \"falling back to the devnet preset\" note goes to stderr,\n * so `toon send … --json | jq` never chokes on a line of prose. {@link\n * Output.render} enforces the \"exactly one\" half by refusing to be called twice.\n *\n * Amounts are the other thing worth being deliberate about. A payment channel\n * deals in **base units** — the integers the chain and the connector actually\n * agree on — and a CLI that printed only `0.001 USDC` would be hiding the number\n * every error message, every claim and every deposit is denominated in. So both\n * are printed, base units first: `1000 (0.001 USDC)`. The human figure is only\n * given for an asset this client recognises: the connector's x402 terms name\n * an asset but not its decimals, and a decimal point in the wrong place is\n * worse than none.\n */\nimport { formatUnits } from 'viem';\nimport { DEVNET } from '../presets.js';\nimport type { BatchSettlementTerms } from '../channel/batch-settlement/offers.js';\n\n/** Somewhere to write a line of text. Injected so tests never touch a real stream. */\nexport type Writer = (text: string) => void;\n\nexport interface OutputOptions {\n json?: boolean;\n quiet?: boolean;\n stdout?: Writer;\n stderr?: Writer;\n}\n\n/**\n * What is needed to render an amount for a person: how many base units make a\n * whole one, and what to call it.\n *\n * Both are optional, and their absence is honest rather than papered over. A\n * node that publishes no decimals gets `1000` and no parenthetical, because a\n * decimal point in the wrong place is worse than no decimal point.\n */\nexport interface AssetInfo {\n decimals?: number;\n symbol?: string;\n}\n\n/** USDC by address: the devnet's, and Circle's on Base and Solana mainnet. All 6 decimals. */\nconst KNOWN_USDC = new Set(\n [\n DEVNET.evm.tokenAddress,\n DEVNET.solana.tokenAddress,\n '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',\n ].map((a) => (a.startsWith('0x') ? a.toLowerCase() : a))\n);\n\nfunction known(asset: string | undefined): boolean {\n if (asset === undefined) return false;\n return KNOWN_USDC.has(asset.startsWith('0x') ? asset.toLowerCase() : asset);\n}\n\n/**\n * A display label for a token address.\n *\n * This is one of the two places a preset is consulted, and it is consulted for\n * a **caption**: nothing is ever paid, signed or opened against what this\n * returns — a wrong answer here misspells a word, it does not move money.\n */\nexport function assetSymbol(tokenAddress: string | undefined): string | undefined {\n return known(tokenAddress) ? 'USDC' : undefined;\n}\n\n/** The asset facts for a token address this client recognises, ready to format with. */\nexport function assetInfo(asset: string | undefined): AssetInfo {\n return known(asset) ? { decimals: 6, symbol: 'USDC' } : {};\n}\n\n/** The asset a connector's x402 terms name, ready to format with. */\nexport function assetFromSettlement(terms: Pick<BatchSettlementTerms, 'asset'> | undefined): AssetInfo {\n return assetInfo(terms?.asset);\n}\n\n/**\n * `1000 (0.001 USDC)` — base units, then the human figure.\n *\n * Falls back gracefully: no decimals gives `1000`, decimals without a symbol\n * gives `1000 (0.001)`.\n */\nexport function formatAmount(\n amount: bigint | string | number,\n asset: AssetInfo = {}\n): string {\n const base = typeof amount === 'bigint' ? amount : BigInt(amount);\n const raw = base.toString();\n if (asset.decimals === undefined) return raw;\n const human = formatUnits(base, asset.decimals);\n return asset.symbol === undefined ? `${raw} (${human})` : `${raw} (${human} ${asset.symbol})`;\n}\n\n/**\n * Convert a value into something `JSON.stringify` can be trusted with.\n *\n * `bigint` becomes a **decimal string**, never a number: every amount this\n * client handles can exceed 2^53, and a JSON number would round it silently —\n * the same reason the connector's own wire spells prices as strings. Bytes\n * become base64. Functions disappear, so a `SendResult`'s `text()`/`json()`\n * helpers cannot leak into the document as `null`.\n */\nexport function toJsonValue(value: unknown): unknown {\n if (typeof value === 'bigint') return value.toString();\n if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');\n if (value instanceof Date) return value.toISOString();\n if (typeof value === 'function') return undefined;\n if (Array.isArray(value)) return value.map(toJsonValue);\n if (typeof value === 'object' && value !== null) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) {\n const converted = toJsonValue(v);\n if (converted !== undefined) out[k] = converted;\n }\n return out;\n }\n return value;\n}\n\n/** Render aligned `label value` rows. */\nexport function columns(rows: [string, string][], indent = ''): string {\n const width = rows.reduce((w, [left]) => Math.max(w, left.length), 0);\n return rows\n .map(([left, right]) => `${indent}${left.padEnd(width)} ${right}`)\n .join('\\n');\n}\n\n/**\n * Is this byte string text?\n *\n * Strict UTF-8 decoding, deliberately: a body that *almost* decodes is a body\n * printed with replacement characters where its actual bytes were, which is a\n * lie about what the app returned. If it does not decode cleanly it is binary,\n * and the CLI says so and gives you its size instead.\n */\nexport function decodeUtf8(bytes: Uint8Array): string | undefined {\n try {\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n return undefined;\n }\n}\n\nexport class Output {\n readonly json: boolean;\n readonly quiet: boolean;\n private readonly out: Writer;\n private readonly err: Writer;\n private rendered = false;\n\n constructor(options: OutputOptions = {}) {\n this.json = options.json ?? false;\n this.quiet = options.quiet ?? false;\n this.out = options.stdout ?? ((text) => process.stdout.write(`${text}\\n`));\n this.err = options.stderr ?? ((text) => process.stderr.write(`${text}\\n`));\n }\n\n /** A line of human output. Suppressed entirely under `--json`. */\n line(text = ''): void {\n if (!this.json) this.out(text);\n }\n\n /** Aligned rows of human output. */\n rows(rows: [string, string][], indent = ' '): void {\n if (rows.length > 0) this.line(columns(rows, indent));\n }\n\n /**\n * A diagnostic. Always stderr — under `--json` because stdout is spoken for,\n * and otherwise because a warning interleaved with results is a warning that\n * gets piped into the next program.\n */\n warn(text: string): void {\n if (!this.quiet) this.err(text);\n }\n\n /** An error explanation. Stderr, and never suppressed by `--quiet`. */\n error(text: string): void {\n this.err(text);\n }\n\n /**\n * The command's answer: the JSON document under `--json`, the human rendering\n * otherwise.\n *\n * Calling this twice is a bug in the command, not a formatting choice — two\n * documents on stdout is not JSON — so it throws rather than emitting them.\n */\n render(payload: unknown, human: () => void): void {\n if (this.rendered) {\n throw new Error('Output.render was called twice: --json must emit exactly one document');\n }\n this.rendered = true;\n if (this.json) {\n this.out(JSON.stringify(toJsonValue(payload), null, 2));\n } else {\n human();\n }\n }\n}\n","/**\n * `toon balances` — what this identity holds on chain.\n *\n * Nothing here concerns the connector. It answers the two questions that come up\n * when a channel operation fails: is there gas to pay for the transaction, and\n * is there token to put in the channel.\n *\n * A chain whose RPC could not be reached is reported as unreadable rather than\n * as zero. \"I could not look\" and \"there is nothing there\" lead to opposite next\n * steps, and conflating them is how someone concludes their funds are gone.\n */\nimport type { CommandContext } from '../context.js';\nimport { formatAmount } from '../output.js';\nimport type { WalletTokenAmount } from '../../wallet/balances.js';\n\nfunction amountRow(token: WalletTokenAmount): [string, string] {\n const label = token.symbol ?? token.address ?? 'token';\n return [\n label,\n formatAmount(token.amount, {\n ...(token.decimals !== undefined ? { decimals: token.decimals } : {}),\n ...(token.symbol !== undefined ? { symbol: token.symbol } : {}),\n }),\n ];\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const chains = await client.wallet.balances();\n\n ctx.out.render({ identity: client.identity, chains }, () => {\n for (const chain of chains) {\n ctx.out.line(`${chain.chainKey} ${chain.address}`);\n if (chain.unreadable === true) {\n ctx.out.rows([['unreadable', chain.error ?? 'the RPC could not be reached']], ' ');\n ctx.out.line();\n continue;\n }\n const rows: [string, string][] = [];\n if (chain.native !== undefined) rows.push(amountRow(chain.native));\n for (const token of chain.tokens) rows.push(amountRow(token));\n ctx.out.rows(rows, ' ');\n ctx.out.line();\n }\n });\n\n return 0;\n}\n","/**\n * `toon channel open|deposit|status|close|settle` — the x402 `batch-settlement`\n * channels this client pays the connector from (connector ADRs 0074, 0075).\n *\n * Opening costs no native gas: on Base a facilitator relays the deposit, on\n * Solana the connector sponsors the open. Leaving is the payer's own\n * transaction on its own chain account, and is the one step that costs gas.\n * `status` reports two watermarks when asked to — the local one is what this\n * client has signed, the connector's is what it has banked, and they differ\n * exactly when a voucher was signed and never accepted.\n */\nimport { UsageError, boolOption, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { CHANNEL_SUBCOMMANDS } from '../args.js';\nimport { assetInfo, formatAmount, type AssetInfo } from '../output.js';\nimport type { ClaimStateResult, ChannelState, BatchExitResult } from '../../client/types.js';\n\n/** The rows that describe one channel to a person. */\nfunction stateRows(state: ChannelState, asset: AssetInfo): [string, string][] {\n const rows: [string, string][] = [\n ['channel', state.channel.channelId],\n ['network', state.channel.network],\n ['deposit', formatAmount(state.depositTotal, asset)],\n ['signed', formatAmount(state.signed, asset)],\n [\n 'available',\n formatAmount(\n state.depositTotal > state.signed ? state.depositTotal - state.signed : 0n,\n asset\n ),\n ],\n ];\n if (state.closedAt !== undefined) rows.push(['closed at', `${state.closedAt.toString()} (unix seconds)`]);\n if (state.settleableAt !== undefined) {\n rows.push(['settleable at', `${state.settleableAt.toString()} (unix seconds)`]);\n }\n if (state.settledAt !== undefined) rows.push(['settled at', `${state.settledAt.toString()} (unix seconds)`]);\n return rows;\n}\n\n/** The connector's own view of one channel, rendered beside ours. */\nfunction connectorRows(entry: ClaimStateResult, asset: AssetInfo): [string, string][] {\n if (!entry.ok) {\n return [['connector', `cannot report this channel (${entry.error})`]];\n }\n return [\n ['connector claimed', formatAmount(entry.cumulativeClaimed, asset)],\n ['connector max', formatAmount(entry.maxCumulative, asset)],\n ['connector available', formatAmount(entry.available, asset)],\n ];\n}\n\n/** One channel's exit step, for a person. */\nfunction exitRows(result: BatchExitResult): [string, string][] {\n const rows: [string, string][] = [['channel', result.channelId]];\n if (result.transaction !== undefined) rows.push(['tx', result.transaction]);\n if (result.settleableAt !== undefined) rows.push(['settleable at', result.settleableAt.toString()]);\n if (result.error !== undefined) rows.push(['error', result.error]);\n if (\n result.transaction === undefined &&\n result.error === undefined &&\n result.settleableAt === undefined\n ) {\n rows.push(['status', 'nothing left to take back']);\n }\n return rows;\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const sub = ctx.positionals[0];\n if (sub === undefined || !(CHANNEL_SUBCOMMANDS as readonly string[]).includes(sub)) {\n throw new UsageError(`channel needs one of: ${CHANNEL_SUBCOMMANDS.join(', ')}`, 'channel');\n }\n\n const client = await ctx.client();\n const channel = client.channel;\n\n if (sub === 'open') {\n const state = await channel.open();\n const asset = assetInfo(state.channel.config.token);\n ctx.out.render(state, () => {\n ctx.out.line('Channel open.');\n ctx.out.rows(stateRows(state, asset));\n });\n return 0;\n }\n\n if (sub === 'deposit') {\n const amount = ctx.positionals[1] ?? stringOption(ctx.values, 'amount');\n if (amount === undefined) {\n throw new UsageError('channel deposit needs an amount in base units', 'channel');\n }\n let value: bigint;\n try {\n value = BigInt(amount);\n } catch {\n throw new UsageError(`'${amount}' is not a whole number of base units`, 'channel');\n }\n const state = await channel.deposit(value);\n const asset = assetInfo(state.channel.config.token);\n ctx.out.render(state, () => {\n ctx.out.line('Deposit confirmed.');\n ctx.out.rows(stateRows(state, asset));\n });\n return 0;\n }\n\n if (sub === 'close' || sub === 'settle') {\n const results = sub === 'close' ? await channel.close() : await channel.settle();\n ctx.out.render(results, () => {\n if (results.length === 0) {\n ctx.out.line('No channel is ready to settle yet.');\n return;\n }\n ctx.out.line(\n sub === 'close'\n ? 'Leaving every open channel. Settle each once its window has elapsed.'\n : 'Unspent deposits returned where each window had elapsed.'\n );\n for (const r of results) ctx.out.rows(exitRows(r));\n });\n return results.some((r) => r.error !== undefined) ? 1 : 0;\n }\n\n // status\n const channels = channel.channels();\n let connectorView: ClaimStateResult[] | undefined;\n if (boolOption(ctx.values, 'connector-view') && channels.length > 0) {\n connectorView = await client.claimState(channels.map((c) => c.channel.channelId));\n }\n ctx.out.render(connectorView === undefined ? channels : { channels, connector: connectorView }, () => {\n if (channels.length === 0) {\n ctx.out.line(\"No channel with this node yet. Open one with 'toon channel open', or pay for a request.\");\n return;\n }\n for (const state of channels) {\n const asset = assetInfo(state.channel.config.token);\n const rows = stateRows(state, asset);\n const theirs = connectorView?.find((e) => e.channelId === state.channel.channelId);\n if (theirs !== undefined) rows.push(...connectorRows(theirs, asset));\n ctx.out.rows(rows);\n ctx.out.line();\n }\n });\n return 0;\n}\n","/**\n * `toon claim-state` — the connector's own watermark for the channels this\n * identity controls.\n *\n * The authoritative half of the picture. `toon channel status` shows what this\n * client has *signed*; this shows what the connector has *banked*, which is the\n * figure every future claim has to advance past. When the two disagree, a claim\n * was signed and never accepted, and the connector's number is the one to\n * believe.\n */\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const entries = await client.claimState();\n const description = await client.describe();\n const asset = assetFromSettlement(description.batchSettlements[0]);\n\n ctx.out.render({ connector: client.connector, channels: entries }, () => {\n if (entries.length === 0) {\n ctx.out.line('This connector reports no channels for your account.');\n ctx.out.line(\"Open one with 'toon channel open', or pay for a request.\");\n return;\n }\n for (const entry of entries) {\n const id = entry.channelId ?? '(unnamed)';\n if (!entry.ok) {\n ctx.out.rows([\n ['channel', id],\n ['chain', entry.blockchain],\n ['state', `unreadable (${entry.error})`],\n ]);\n ctx.out.line();\n continue;\n }\n ctx.out.rows([\n ['channel', id],\n ['chain', entry.blockchain],\n ['claimed', formatAmount(entry.cumulativeClaimed, asset)],\n ['max cumulative', formatAmount(entry.maxCumulative, asset)],\n ['available', formatAmount(entry.available, asset)],\n [\n // Printed as the connector gave it, unconverted: the field is\n // best-effort and non-durable, and `null` means \"unknown\", never\n // \"never claimed\" (client-edge-spec.md §1.10).\n 'last claim',\n entry.lastClaimTime === null ? 'unknown — not \"never\"' : String(entry.lastClaimTime),\n ],\n ]);\n ctx.out.line();\n }\n });\n\n return 0;\n}\n","/**\n * `toon describe [URL]` — read a connector's self-description.\n *\n * The first command anyone should run against an unfamiliar node, and the only\n * one that costs nothing and proves nothing: one unauthenticated `GET` returns\n * every fact needed to transact — the addresses it answers to, the endpoints and\n * carriages it offers, the key a payload is sealed to, what it settles in, and\n * what each route costs. There is no discovery to do beyond this.\n *\n * Runs with no keystore and no channel. A URL given here outranks `--connector`\n * and the environment, because it was typed for this one invocation.\n */\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const url = ctx.positionals[0];\n const client = await ctx.client({\n keyless: true,\n ...(url !== undefined ? { connector: url } : {}),\n });\n const description = await client.describe();\n const asset = assetFromSettlement(description.batchSettlements[0]);\n\n const payload = {\n connector: client.connector,\n ilpAddresses: description.ilpAddresses,\n httpEndpoint: description.httpEndpoint,\n btpEndpoint: description.btpEndpoint,\n peerCarriages: description.peerCarriages,\n edgeIdentity: description.edgeIdentity,\n batchSettlements: description.batchSettlements,\n voucherSigners: description.voucherSigners,\n routes: description.routes,\n requiredTransport: description.requiredTransport,\n supportedVersions: description.supportedVersions,\n defaultVersion: description.defaultVersion,\n };\n\n ctx.out.render(payload, () => {\n const head: [string, string][] = [['connector', client.connector]];\n if (description.ilpAddresses.length > 0) {\n head.push(['addresses', description.ilpAddresses.join(', ')]);\n }\n if (description.httpEndpoint !== undefined) head.push(['http', description.httpEndpoint]);\n if (description.btpEndpoint !== undefined) head.push(['btp', description.btpEndpoint]);\n if (description.requiredTransport !== undefined) {\n head.push(['requires', `${description.requiredTransport} carriage`]);\n }\n if (description.edgeIdentity !== undefined) {\n head.push([\n 'seals to',\n `${description.edgeIdentity.publicKey}${\n description.edgeIdentity.keyId === '' ? '' : ` (key ${description.edgeIdentity.keyId})`\n }`,\n ]);\n }\n head.push([\n 'versions',\n `${description.supportedVersions.join(', ')} (default ${String(description.defaultVersion)})`,\n ]);\n ctx.out.rows(head);\n\n ctx.out.line();\n if (description.batchSettlements.length === 0) {\n ctx.out.line('Channels: none offered — this node cannot be paid.');\n } else {\n ctx.out.line('Channels (x402 batch-settlement):');\n ctx.out.rows(\n description.batchSettlements.map((t): [string, string] => [\n t.network,\n [\n `payTo ${t.payTo}`,\n `token ${t.asset}`,\n `min delay ${String(t.extra.withdrawDelay)}s`,\n t.chain === 'solana' ? `sponsor ${t.extra.feePayer}` : '',\n ]\n .filter((x) => x !== '')\n .join(' '),\n ])\n );\n }\n\n ctx.out.line();\n if (description.routes.length === 0) {\n ctx.out.line('Routes: none published.');\n } else {\n ctx.out.line('Routes:');\n ctx.out.rows(\n description.routes.map((r): [string, string] => [\n r.prefix,\n // A route's own carriage pin, where it has one (TOON_Network#111).\n // Beside the price, because a route priced and not qualified reads as\n // one you can simply pay for — which is how the devnet relay read for\n // as long as it pinned BTP and said nothing.\n r.requiredTransport === undefined\n ? formatAmount(r.price, asset)\n : `${formatAmount(r.price, asset)} (${r.requiredTransport} carriage)`,\n ])\n );\n }\n });\n\n return 0;\n}\n","/**\n * `toon faucet` — ask the devnet faucet for test funds.\n *\n * Devnet only, and deliberately unglamorous: it drips the settlement token (and,\n * on Base Sepolia, the gas to move it) onto the address this keystore derives,\n * so that `toon channel open` has something to lock. On a real network this\n * command has nothing to do.\n */\nimport type { CommandContext } from '../context.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const client = await ctx.client();\n const result = await client.wallet.faucet();\n\n ctx.out.render(result, () => {\n ctx.out.line('Faucet request accepted.');\n ctx.out.rows([\n ['chain', result.chain],\n ['address', result.address],\n ]);\n ctx.out.line();\n ctx.out.line(\"Check it landed with 'toon balances'.\");\n });\n\n return 0;\n}\n","/**\n * `toon identity [--all-derivations]` — the addresses this keystore holds.\n *\n * Entirely offline: no connector, no chain, no channel. The addresses are a\n * property of the phrase and the derivation path, so answering needs nothing but\n * the keystore — which is exactly when you want an answer, since the usual\n * reason to run this is that something else could not reach the network.\n *\n * `--all-derivations` exists for one specific, confusing morning: a channel\n * opened before 1.0 appears to have vanished, because the EVM key moved from\n * Nostr's coin type to BIP-44's standard `m/44'/60'/0'/0/i`. The old address is\n * still derivable from the same phrase, and this is how you see it. (The Solana\n * key never moved, so it is the same under both.)\n */\nimport { boolOption } from '../args.js';\nimport { resolveKeyMaterial, type CommandContext } from '../context.js';\nimport {\n deriveFullIdentity,\n evmDerivationPath,\n type KeyDerivationScheme,\n} from '../../keys/KeyDerivation.js';\nimport { MNEMONIC_ENV } from '../keystore.js';\n\n/** SLIP-0010 path for the Solana key. The same under either scheme. */\nconst SOLANA_PATH = \"m/44'/501'/0'/0'\";\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const keys = await resolveKeyMaterial(ctx.settings, ctx.deps);\n if (keys.kind !== 'mnemonic') {\n // `resolveKeyMaterial` only returns `ephemeral` when asked to, and identity\n // never asks: showing a randomly generated address would be a lie.\n throw new Error('identity requires real keys');\n }\n\n const showAll = boolOption(ctx.values, 'all-derivations');\n const identity = deriveFullIdentity(keys.mnemonic, { scheme: keys.derivation });\n const source = keys.from === 'env' ? MNEMONIC_ENV : ctx.settings.keystorePath;\n\n const derivations: { scheme: KeyDerivationScheme; path: string; evmAddress: string }[] = (\n ['standard', 'legacy'] as const\n ).map((scheme) => ({\n scheme,\n path: evmDerivationPath(scheme),\n evmAddress: deriveFullIdentity(keys.mnemonic, { scheme }).evm.address,\n }));\n\n ctx.out.render(\n {\n source,\n derivation: keys.derivation,\n evmAddress: identity.evm.address,\n evmPath: evmDerivationPath(keys.derivation),\n solanaPublicKey: identity.solana.publicKey,\n solanaPath: SOLANA_PATH,\n ...(showAll ? { derivations } : {}),\n },\n () => {\n ctx.out.rows([\n ['evm', `${identity.evm.address} ${evmDerivationPath(keys.derivation)}`],\n ['solana', `${identity.solana.publicKey} ${SOLANA_PATH}`],\n ['derivation', keys.derivation],\n ['keys from', source],\n ]);\n if (showAll) {\n ctx.out.line();\n ctx.out.line('EVM address under each derivation:');\n ctx.out.rows(\n derivations.map((d): [string, string] => [\n d.scheme === keys.derivation ? `${d.scheme} (in use)` : d.scheme,\n `${d.evmAddress} ${d.path}`,\n ])\n );\n }\n }\n );\n\n return 0;\n}\n","/**\n * `toon init [--import] [--legacy-derivation]` — create or import a keystore.\n *\n * The first command a new user runs, and the only one that writes a secret. Two\n * refusals here are deliberate:\n *\n * - **It never overwrites an existing keystore.** The file it would replace may\n * be the only copy of a phrase holding an open channel's collateral, and there\n * is no undo for that.\n * - **A phrase is only ever read from stdin.** Not from an argument, which shell\n * history records and `ps` shows to every user on the machine.\n *\n * `--legacy-derivation` records that this phrase's EVM key lives at Nostr's coin\n * type — what to use when importing a phrase whose channels were opened before\n * 1.0, so the addresses come back where the money is.\n */\nimport { boolOption } from '../args.js';\nimport { CliConfigError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport {\n ensureKeystoreDirectory,\n keystoreExists,\n resolvePassword,\n} from '../keystore.js';\nimport { deriveFullIdentity, evmDerivationPath } from '../../keys/KeyDerivation.js';\nimport { generateKeystore, importKeystore } from '../../keys/keystore-node.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const path = ctx.settings.keystorePath;\n const derivation = boolOption(ctx.values, 'legacy-derivation') ? 'legacy' : 'standard';\n const importing = boolOption(ctx.values, 'import');\n\n if (keystoreExists(path)) {\n throw new CliConfigError(\n `a keystore already exists at ${path}`,\n 'Move it aside first — overwriting it would destroy the only copy of its phrase, ' +\n 'and any channel collateral that phrase controls.'\n );\n }\n\n // The phrase is read before the password so that a piped run consumes stdin\n // in a predictable order.\n let imported: string | undefined;\n if (importing) {\n const readStdin = ctx.deps.readStdin;\n if (readStdin === undefined) {\n throw new CliConfigError('--import reads the phrase from stdin, and stdin is unavailable');\n }\n ctx.out.warn('Reading the BIP-39 recovery phrase from stdin.');\n const bytes = await readStdin();\n imported = Buffer.from(bytes).toString('utf8').trim();\n if (imported.length === 0) throw new CliConfigError('no phrase arrived on stdin');\n }\n\n const { password, source } = await resolvePassword({\n message: `Choose a password for ${path}: `,\n passwordFile: ctx.settings.passwordFile,\n env: ctx.deps.env,\n ...(ctx.deps.readFile !== undefined ? { readFile: ctx.deps.readFile } : {}),\n prompt: ctx.deps.prompt,\n });\n // A typo in a password chosen at a prompt is unrecoverable — nothing else\n // knows what was meant — so it is asked for twice. A password supplied by file\n // or environment can be re-read, so it is not.\n if (source === 'prompt' && ctx.deps.prompt !== undefined) {\n const again = await ctx.deps.prompt('Confirm the password: ');\n if (again !== password) throw new CliConfigError('the two passwords did not match');\n }\n\n ensureKeystoreDirectory(path);\n\n let mnemonic: string;\n let generated: boolean;\n if (imported !== undefined) {\n try {\n importKeystore(path, imported, password, { derivation });\n } catch (err) {\n throw new CliConfigError(err instanceof Error ? err.message : String(err));\n }\n mnemonic = imported;\n generated = false;\n } else {\n mnemonic = generateKeystore(path, password, { derivation }).mnemonic;\n generated = true;\n }\n\n const identity = deriveFullIdentity(mnemonic, { scheme: derivation });\n\n ctx.out.render(\n {\n keystore: path,\n derivation,\n evmAddress: identity.evm.address,\n evmPath: evmDerivationPath(derivation),\n solanaPublicKey: identity.solana.publicKey,\n // Only ever present for a phrase this command just invented: there is one\n // chance to copy it down, and after that only the keystore has it.\n ...(generated ? { mnemonic } : {}),\n },\n () => {\n if (generated) {\n ctx.out.line('Write this recovery phrase down. It is shown once, and it is the only');\n ctx.out.line('way back to these addresses if the keystore file is lost.');\n ctx.out.line();\n ctx.out.line(` ${mnemonic}`);\n ctx.out.line();\n }\n ctx.out.rows([\n ['keystore', path],\n ['derivation', derivation],\n ['evm', `${identity.evm.address} ${evmDerivationPath(derivation)}`],\n ['solana', identity.solana.publicKey],\n ]);\n ctx.out.line();\n ctx.out.line('Next: fund it, then open a channel.');\n ctx.out.line(' toon faucet');\n ctx.out.line(' toon channel open --deposit 100000');\n }\n );\n\n return 0;\n}\n","/**\n * `toon price <destination> [URL]` — what one route costs.\n *\n * Free, keyless and channel-less, like `describe`. `null` back from the\n * connector is a real answer — \"no route I serve matches this destination\" —\n * and is printed as such rather than turned into an error, because asking about\n * a destination a node does not carry is a normal thing to do while finding out\n * which node does.\n */\nimport { UsageError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const destination = ctx.positionals[0];\n if (destination === undefined) throw new UsageError('price needs a destination', 'price');\n const url = ctx.positionals[1];\n\n const client = await ctx.client({\n keyless: true,\n ...(url !== undefined ? { connector: url } : {}),\n });\n const terms = await client.routePrice(destination);\n // The decimals a price is denominated in are the settlement's, so the\n // self-description is read even here — it is cached and already fetched.\n const description = await client.describe();\n const asset = assetFromSettlement(description.batchSettlements[0]);\n const perKib = terms?.pricePerKib;\n\n ctx.out.render(\n {\n connector: client.connector,\n destination,\n price: terms?.price ?? null,\n ...(perKib !== undefined ? { pricePerKib: perKib } : {}),\n decimals: asset.decimals,\n asset: asset.symbol,\n },\n () => {\n if (terms === null) {\n ctx.out.line(`${destination} no route — this node prices nothing that covers it`);\n } else if (perKib === undefined) {\n ctx.out.line(`${destination} ${formatAmount(terms.price, asset)}`);\n } else {\n // A metered route's base price is never what a packet costs, so the\n // rate is printed beside it rather than left for a refusal to reveal.\n ctx.out.line(\n `${destination} ${formatAmount(terms.price, asset)}` +\n ` + ${formatAmount(perKib, asset)}/KiB of sealed payload`\n );\n }\n }\n );\n\n return 0;\n}\n","/**\n * `toon probe <destination>` — learn what a path costs without buying the work.\n *\n * A probe carries a real claim but never spends it: the connector prices the\n * path, reports the figure, and refuses the packet. So the refusal printed here\n * is the *successful* outcome, and the command exits 0 — the failure mode of a\n * probe is not getting an answer, not being told no.\n */\nimport { UsageError } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, formatAmount } from '../output.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const destination = ctx.positionals[0];\n if (destination === undefined) throw new UsageError('probe needs a destination', 'probe');\n\n const client = await ctx.client();\n const result = await client.probe(destination);\n const description = await client.describe();\n const asset = assetFromSettlement(description.batchSettlements[0]);\n\n ctx.out.render({ destination, ...result }, () => {\n ctx.out.rows([\n ['destination', destination],\n ['cost', formatAmount(result.accumulatedCost, asset)],\n ['code', result.code],\n ['message', result.message],\n ]);\n });\n\n return 0;\n}\n","/**\n * `toon send [destination] …` — pay for one HTTP request and print the answer.\n *\n * The destination is optional: omitted, the request goes to the address the node\n * published for itself, so `TOON_CONNECTOR` alone is enough to buy something.\n *\n * This is what the whole client is for, and its output is shaped around one\n * distinction that is easy to get wrong.\n *\n * **A refusal is an outcome, not a crash.** The connector saying \"you underpaid\"\n * or \"this route wants the other carriage\" is a normal, informative answer: it\n * is printed in full, with what to do about it, and the process exits **3**. An\n * exception — a network that is not there, a keystore that will not open — is a\n * different kind of event and exits somewhere else entirely.\n *\n * **The status printed is the *app's*.** A `404` from the app behind the route\n * rides home on a FULFILL and costs exactly what a `200` costs, because the\n * connector charged for putting the request through, and it did. Only a refusal\n * short of the app is a refusal.\n */\nimport { UsageError, listOption, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { assetFromSettlement, decodeUtf8, formatAmount, type AssetInfo } from '../output.js';\nimport type { SendRefused, SendRequest, SendResult } from '../../client/types.js';\n\n/** Split one `-H name:value` into its two halves. */\nexport function parseHeaderSpec(spec: string): [string, string] {\n const colon = spec.indexOf(':');\n if (colon <= 0) {\n throw new UsageError(`-H expects 'name:value'; got '${spec}'`, 'send');\n }\n return [spec.slice(0, colon).trim(), spec.slice(colon + 1).trim()];\n}\n\n/** Is a header with this name already present? Header names are case-insensitive. */\nfunction hasHeader(headers: [string, string][], name: string): boolean {\n const wanted = name.toLowerCase();\n return headers.some(([key]) => key.toLowerCase() === wanted);\n}\n\n/**\n * Assemble the request from the flags.\n *\n * The three body forms are mutually exclusive and each one exists for a\n * different shape of caller: `--body TEXT` for a person typing, `--body-file`\n * for content that is already a file (and may be binary, which is why it is read\n * as bytes), and `--body -` for a pipeline. Exported so the parsing is tested\n * without a client.\n */\nexport async function buildRequest(ctx: CommandContext): Promise<SendRequest> {\n const bodyFlag = stringOption(ctx.values, 'body');\n const bodyFile = stringOption(ctx.values, 'body-file');\n if (bodyFlag !== undefined && bodyFile !== undefined) {\n throw new UsageError('give --body or --body-file, not both', 'send');\n }\n\n const headers = listOption(ctx.values, 'header').map(parseHeaderSpec);\n\n let body: string | Uint8Array | undefined;\n if (bodyFlag === '-') {\n const readStdin = ctx.deps.readStdin;\n if (readStdin === undefined) {\n throw new UsageError('--body - reads stdin, and stdin is unavailable', 'send');\n }\n body = await readStdin();\n } else if (bodyFlag !== undefined) {\n body = bodyFlag;\n } else if (bodyFile !== undefined) {\n const readFileBytes = ctx.deps.readFileBytes;\n if (readFileBytes === undefined) {\n throw new UsageError('--body-file cannot be read in this environment', 'send');\n }\n try {\n body = readFileBytes(bodyFile);\n } catch (err) {\n throw new UsageError(\n `cannot read --body-file ${bodyFile}: ${err instanceof Error ? err.message : String(err)}`,\n 'send'\n );\n }\n }\n\n if (ctx.values['json-body'] === true) {\n if (body === undefined) throw new UsageError('--json-body needs a body', 'send');\n const text = typeof body === 'string' ? body : decodeUtf8(body);\n if (text === undefined) throw new UsageError('--json-body was given bytes that are not UTF-8', 'send');\n try {\n JSON.parse(text);\n } catch (err) {\n throw new UsageError(\n `--json-body was given something that is not JSON: ${err instanceof Error ? err.message : String(err)}`,\n 'send'\n );\n }\n // The body is forwarded as the exact bytes the user supplied rather than\n // re-serialized from the parse: `--json-body` is a check and a content type,\n // not a reformatter, and an app that signs or hashes its request body would\n // not survive being helpfully re-indented.\n if (!hasHeader(headers, 'content-type')) headers.push(['content-type', 'application/json']);\n }\n\n const method = stringOption(ctx.values, 'method');\n const target = stringOption(ctx.values, 'target');\n return {\n ...(method !== undefined ? { method } : {}),\n ...(target !== undefined ? { target } : {}),\n ...(headers.length > 0 ? { headers } : {}),\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * What to try next, given a refusal.\n *\n * The point of this CLI's error handling: a refusal that only says `F03` has\n * told a newcomer nothing. Each hint names the command that addresses the cause.\n */\nexport function refusalHint(result: SendRefused, asset: AssetInfo): string[] {\n const cost =\n result.accumulatedCost === undefined ? undefined : formatAmount(result.accumulatedCost, asset);\n\n switch (result.code) {\n case 'PAYMENT_REQUIRED':\n case 'TRANSPORT_REQUIRED': {\n const required = result.terms?.requiredTransport;\n if (required !== undefined) {\n return [`This route only accepts the ${required} carriage. Retry with --transport ${required}.`];\n }\n return [\n 'The connector answered with terms instead of doing the work, which means it saw no',\n \"usable claim. Check the channel with 'toon channel status --connector-view'.\",\n ];\n }\n case 'F03':\n return cost === undefined\n ? ['The claim did not advance far enough to cover the route.']\n : [\n `The route costs ${cost}. Either the claim did not advance by that much, or the`,\n 'channel has no room left for it — add collateral with',\n \"'toon channel deposit <base units>', then send again.\",\n ];\n case 'F01':\n return [\n 'The connector would not take the claim: it names a channel it cannot see, or a nonce',\n \"it has already banked. Compare the two watermarks with 'toon channel status --connector-view'.\",\n ];\n case 'F02':\n return [\n 'No route to that destination over this carriage. Check what this node actually serves',\n \"with 'toon describe', and which carriage it wants.\",\n ];\n case 'F00':\n return [\n \"The target path was refused before the app saw it: --target is resolved strictly beneath\",\n 'the route handler, so it cannot be absolute, contain `..`, or name a host.',\n ];\n case 'F06':\n return [\"No claim was attached. Open a channel with 'toon channel open --deposit 100000'.\"];\n default:\n if (result.code.startsWith('T')) {\n return ['A temporary refusal — the path asked you to try again shortly.'];\n }\n return [];\n }\n}\n\n/** The `--json` document for one result. `raw` is dropped: it repeats what is above it. */\nfunction payloadFor(result: SendResult): unknown {\n if (result.fulfilled) {\n const text = decodeUtf8(result.body);\n return {\n fulfilled: true,\n transport: result.transport,\n status: result.status,\n headers: result.headers,\n body: result.body,\n ...(text !== undefined ? { text } : {}),\n fulfillment: result.fulfillment,\n claim: result.claim,\n };\n }\n const { terms, ...rest } = result;\n return {\n ...rest,\n ...(terms !== undefined\n ? {\n terms: {\n destination: terms.destination,\n price: terms.price,\n httpEndpoint: terms.httpEndpoint,\n btpEndpoint: terms.btpEndpoint,\n requiredTransport: terms.requiredTransport,\n batchSettlements: terms.batchSettlements,\n sessionLeaseTtlMs: terms.sessionLeaseTtlMs,\n },\n }\n : {}),\n };\n}\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const request = await buildRequest(ctx);\n const amountFlag = stringOption(ctx.values, 'amount');\n\n const client = await ctx.client();\n // The destination is optional: with none, the packet goes to the address the\n // node published for itself, so a connector URL is the whole of the config.\n const destination = ctx.positionals[0] ?? client.defaultDestination;\n if (destination === undefined) {\n throw new UsageError(\n 'send needs a destination, and this node published no address to default to',\n 'send'\n );\n }\n\n const result = await client.send(\n destination,\n request,\n amountFlag === undefined ? undefined : { amount: BigInt(amountFlag) }\n );\n\n const description = await client.describe();\n const asset = assetFromSettlement(description.batchSettlements[0]);\n\n ctx.out.render(payloadFor(result), () => {\n if (result.fulfilled) {\n ctx.out.line(`FULFILL ${String(result.status)} (${result.transport})`);\n const claim = result.claim;\n ctx.out.rows(\n claim === undefined\n ? // A route priced at zero takes no voucher, so there is no channel\n // or amount to show. Saying so beats printing zeroes.\n [['paid', 'nothing — this route is free']]\n : [\n [\n 'paid',\n `${formatAmount(claim.amount, asset)} channel ${claim.channelId}`,\n ],\n ['cumulative', formatAmount(claim.cumulative, asset)],\n ]\n );\n if (result.headers.length > 0) {\n ctx.out.line();\n ctx.out.rows(result.headers.map(([k, v]): [string, string] => [`${k}:`, v]));\n }\n ctx.out.line();\n const text = decodeUtf8(result.body);\n if (text === undefined) {\n ctx.out.line(`<${String(result.body.length)} bytes of binary; use --json for base64>`);\n } else if (text.length > 0) {\n ctx.out.line(text.replace(/\\n$/, ''));\n }\n return;\n }\n\n ctx.out.line(\n `REFUSED ${result.code} (${result.transport}, refused by ${result.refusedBy})`\n );\n const rows: [string, string][] = [['message', result.message]];\n if (result.accumulatedCost !== undefined) {\n rows.push(['cost', formatAmount(result.accumulatedCost, asset)]);\n }\n if (result.claimAck !== undefined) {\n rows.push([\n 'claim',\n result.claimAck.result === 'accepted'\n ? 'accepted'\n : `rejected (${result.claimAck.reason ?? 'no reason given'})`,\n ]);\n }\n if (result.terms !== undefined) {\n rows.push(['route price', formatAmount(result.terms.price, asset)]);\n }\n ctx.out.rows(rows);\n const hint = refusalHint(result, asset);\n if (hint.length > 0) {\n ctx.out.line();\n for (const line of hint) ctx.out.line(line);\n }\n });\n\n return result.fulfilled ? 0 : 3;\n}\n","/**\n * `toon transfer --to <address> --amount <base units> [--asset native|token]`\n *\n * An ordinary on-chain send, out of the wallet this client derives. It exists\n * because the channel wallet is a real account that accumulates change — gas\n * left over, token recovered from a settled channel — and getting it out should\n * not require importing the phrase somewhere else.\n *\n * `--amount` is in **base units**, like every other amount this CLI takes: the\n * chain and the connector agree on integers, and a CLI that quietly accepted\n * `0.1` where a contract expects `100000` is a CLI that will one day send a\n * hundred thousand times too much.\n */\nimport { UsageError, stringOption } from '../args.js';\nimport type { CommandContext } from '../context.js';\nimport { formatAmount } from '../output.js';\nimport type { TransferAssetKind } from '../../wallet/transfer.js';\n\nexport async function run(ctx: CommandContext): Promise<number> {\n const to = stringOption(ctx.values, 'to');\n const amount = stringOption(ctx.values, 'amount');\n const assetFlag = stringOption(ctx.values, 'asset') ?? 'token';\n if (to === undefined) throw new UsageError('transfer needs --to <address>', 'transfer');\n if (amount === undefined) {\n throw new UsageError('transfer needs --amount <base units>', 'transfer');\n }\n if (assetFlag !== 'native' && assetFlag !== 'token') {\n throw new UsageError(`--asset must be 'native' or 'token'; got '${assetFlag}'`, 'transfer');\n }\n const asset: TransferAssetKind = assetFlag;\n\n const client = await ctx.client();\n const result = await client.wallet.transfer({ chain: client.chain, asset, to, amount });\n\n ctx.out.render(result, () => {\n ctx.out.line('Transfer delivered.');\n ctx.out.rows([\n ['chain', result.chain],\n ['asset', result.asset],\n ['to', result.to],\n ['amount', formatAmount(result.amount)],\n ['tx', result.txHash],\n ['balance before', formatAmount(result.balanceBefore)],\n ['balance after', formatAmount(result.balanceAfter)],\n ]);\n });\n\n return 0;\n}\n","/**\n * The command table: the one place a name becomes code.\n *\n * Kept beside {@link ../args.js!COMMANDS} — which is the one place a name\n * becomes *help* — and checked against it by this package's own tests, so a\n * command can never be dispatchable without being documented or documented\n * without being dispatchable.\n */\nimport type { CommandContext } from '../context.js';\nimport * as balances from './balances.js';\nimport * as channel from './channel.js';\nimport * as claimState from './claim-state.js';\nimport * as describe from './describe.js';\nimport * as faucet from './faucet.js';\nimport * as identity from './identity.js';\nimport * as init from './init.js';\nimport * as price from './price.js';\nimport * as probe from './probe.js';\nimport * as send from './send.js';\nimport * as transfer from './transfer.js';\n\n/** A command: do the work, return the process exit code. */\nexport type CommandRunner = (ctx: CommandContext) => Promise<number>;\n\nexport const RUNNERS: Record<string, CommandRunner> = {\n init: init.run,\n identity: identity.run,\n describe: describe.run,\n price: price.run,\n probe: probe.run,\n send: send.run,\n channel: channel.run,\n 'claim-state': claimState.run,\n balances: balances.run,\n transfer: transfer.run,\n faucet: faucet.run,\n};\n","/**\n * Talking to the terminal: reading a body from a pipe, and reading a secret\n * without putting it on screen.\n *\n * All of it is isolated here for one reason — every function below touches a\n * real file descriptor, which is exactly what a unit test cannot do. The\n * commands take these as injected dependencies, so what gets exercised in tests\n * is the *decision* (which source a password came from, whether the body came\n * from stdin) rather than the plumbing.\n *\n * Prompts are written to **stderr**, not stdout. Under `--json` stdout carries\n * one JSON document and nothing else, and a prompt is not part of the answer.\n */\n\n/** Read stdin to EOF as bytes. Used for `--body -` and for `init --import`. */\nexport async function readStdin(\n stream: NodeJS.ReadableStream = process.stdin\n): Promise<Uint8Array> {\n const chunks: Buffer[] = [];\n for await (const chunk of stream) {\n chunks.push(typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk);\n }\n return new Uint8Array(Buffer.concat(chunks));\n}\n\n/** Read stdin to EOF and take its first line, newline stripped. */\nexport async function readStdinLine(\n stream: NodeJS.ReadableStream = process.stdin\n): Promise<string> {\n const bytes = await readStdin(stream);\n const first = Buffer.from(bytes).toString('utf8').split('\\n')[0];\n return first === undefined ? '' : first.replace(/\\r$/, '');\n}\n\n/** Is this process attached to a terminal that can prompt? */\nexport function isInteractive(input: NodeJS.ReadStream = process.stdin): boolean {\n return input.isTTY === true && typeof input.setRawMode === 'function';\n}\n\n/**\n * Control characters the raw-mode prompt has to interpret itself, written as\n * code points rather than literals so they survive every editor and diff.\n */\nconst CTRL_C = String.fromCharCode(3);\nconst CTRL_D = String.fromCharCode(4);\nconst BACKSPACE = String.fromCharCode(8);\nconst DELETE = String.fromCharCode(127);\n\n/**\n * Prompt for a secret with the terminal's echo turned off.\n *\n * Raw mode rather than `readline`: `readline` echoes as it reads and there is no\n * supported way to stop it, so the password would appear on the operator's\n * screen and in whatever is recording that screen. In raw mode the characters\n * arrive here and nowhere else, and nothing is written back.\n *\n * Ctrl-C is handled explicitly because raw mode means the terminal no longer\n * turns it into SIGINT: a prompt that ignored it would be a prompt you could not\n * escape.\n */\nexport function promptHidden(\n message: string,\n input: NodeJS.ReadStream = process.stdin,\n output: NodeJS.WritableStream = process.stderr\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n output.write(message);\n const wasRaw = input.isRaw;\n input.setRawMode(true);\n input.resume();\n input.setEncoding('utf8');\n\n let buffer = '';\n const finish = (fn: () => void): void => {\n input.removeListener('data', onData);\n input.setRawMode(wasRaw);\n input.pause();\n output.write('\\n');\n fn();\n };\n\n const onData = (chunk: string): void => {\n for (const char of chunk) {\n if (char === '\\r' || char === '\\n' || char === CTRL_D) {\n finish(() => {\n resolve(buffer);\n });\n return;\n }\n if (char === CTRL_C) {\n finish(() => {\n reject(new Error('cancelled'));\n });\n return;\n }\n if (char === DELETE || char === BACKSPACE) {\n buffer = buffer.slice(0, -1);\n continue;\n }\n buffer += char;\n }\n };\n\n input.on('data', onData);\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyBA,SAAS,WAAAA,gBAAe;AACxB,SAAS,gBAAAC,eAAc,oBAAoB;AAC3C,SAAS,eAAe,qBAAqB;;;ACH7C,SAAS,iBAAiB;AAOnB,IAAM,aAAN,cAAyB,MAAM;AAAA,EAC3B,O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AAO;AAChC,MAAI;AACF,UAAM,OAAO,cAAc,SAAS;AACpC,UAAM,UAAU,cAAc,cAAc,KAAK,EAAE,IAAI;AACvD,WAAO,SAAS,WAAW,aAAa,IAAI,MAAM,aAAa,OAAO;AAAA,EACxE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,SAAS,aAAa,MAAsB;AAC1C,MAAI;AACF,WAAO,aAAa,IAAI;AAAA,EAC1B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,IAAI,aAAa,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AAClD,UAAQ,WAAW,MAAM,OAAO,QAAQ,KAAK,MAAM,CAAC,CAAC;AACvD;","names":["homedir","readFileSync","homedir","join","homedir","join","columns","run","run","run","run","run","run","readStdin","run","run","readStdin","run","run","run","readFileSync","homedir"]}