@toon-protocol/rig 2.9.0 → 2.10.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.
package/README.md CHANGED
@@ -290,10 +290,36 @@ rig push && rig site publish && rig name set my-app <manifestTxId>
290
290
  > **Real funds, a different rail from ILP.** `rig name buy`/`set` spend **mARIO on
291
291
  > Solana via the ar.io registry program** — *not* through TOON's ILP payment channels
292
292
  > (the rail behind `rig push` / `rig site publish` fees). `rig name` needs the
293
- > optional [`@ar.io/sdk`](https://docs.ar.io) dependency; install it if the command
294
- > reports it missing. As with every paid verb, these are estimate → confirm →
293
+ > optional [`@ar.io/sdk`](https://docs.ar.io) dependency (>= 4.0.3, the
294
+ > Solana-native release); install it if the command reports it missing.
295
+ > `rig name status` is a free, signerless read. As with every paid verb, these are estimate → confirm →
295
296
  > execute, and a `--json` run *without* `--yes` is a free estimate — nothing is spent.
296
297
 
298
+ #### Network program ids (`--network` / `RIG_ARIO_NETWORK`)
299
+
300
+ `--network` selects which cluster's **ar.io registry programs** every `rig name`
301
+ verb targets. The ids come from the installed `@ar.io/sdk` (>= 4.0.3) at runtime
302
+ (`ARIO_*_PROGRAM_ID` for mainnet, `DEVNET_PROGRAM_IDS` off it) — this table is
303
+ the human-readable snapshot (verified live 2026-07-17), useful when auditing
304
+ `--process-id` overrides or block-explorer output:
305
+
306
+ | Program | `--network mainnet` (default) | `--network devnet` |
307
+ |---|---|---|
308
+ | ario-core | `73YoECm6NKXpVRoe5f1Q9BcP5DJGPFUjnFy6AxBE5Nvh` | `8Njx9wPkXiNzDCgjwVsJFRjpAEV34gGW3n8DzX3V23m1` |
309
+ | ario-gar | `89fNiiwgpFSPHKuqfNUkgYTYjtAJAhyqHjXmgXeppGpf` | `7WsDTrtZBsfKtnP33XkjuqXCY69JE7n4QVYpynqJCFxz` |
310
+ | ario-arns (name registry) | `2yCUx5edFvUrkibYaUa2ZXWyx9kuJkS8CwyzsgHPWdZZ` | `6EZNezcg4rc5hnh8HG34vGquT3WpW5xXypzPb24uyEpp` |
311
+ | ario-ant (ANT state) | `2MWexMHfMhGJwMHv9Qm9YAVCqjUFUJwDJAysW4oCUGk5` | `DbHbRwUD1oAn1mrDSqtWtvwGcNrmhWdD2g8L4xmeQ7NX` |
312
+
313
+ - **There is no `--network testnet`**: ar.io deploys nothing on Solana's testnet
314
+ cluster (#376/#381) — the flag rejects it up front.
315
+ - Every spawned ANT is an **MPL Core** asset (`CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d`,
316
+ same id on every cluster); the asset pubkey is the SDK's `processId`.
317
+ - Free devnet test loop (#381): ARIO faucet `https://faucet.services.ar-io.dev/` →
318
+ `rig name buy --network devnet` → `rig name set` → resolves at the
319
+ devnet-connected gateway `https://<name>.ar-io.dev/`.
320
+ - `--process-id <id>` overrides the arns registry program outright (wins over
321
+ `--network`) — for pointing at a fresh/staging registry deployment.
322
+
297
323
  ---
298
324
 
299
325
  ## Strict `--json` stdout (machine consumers)
@@ -346,6 +372,13 @@ The mnemonic is resolved along one precedence chain — highest first:
346
372
  keystore (`keystorePath` + `TOON_CLIENT_KEYSTORE_PASSWORD`), then the `mnemonic`
347
373
  config field
348
374
 
375
+ The BIP-44 account index follows the same env-over-config rule: the
376
+ `RIG_ACCOUNT_INDEX` environment variable always wins; the shared config's
377
+ `mnemonicAccountIndex` applies ONLY when the phrase itself came from the shared
378
+ state dir (tier 4); otherwise account 0. An explicit `RIG_MNEMONIC` therefore
379
+ derives the same identity no matter which `TOON_CLIENT_HOME` is active — a
380
+ per-home config never silently shifts an explicitly provided identity.
381
+
349
382
  Every paid command reports which source is active and the derived pubkey
350
383
  (`Identity: <pubkey> (from …)`, and an `identity` object in `--json` output) — the
351
384
  phrase itself is never printed and never written to git config or any repo file.
@@ -91,6 +91,25 @@ function findDotenvMnemonic(startDir, stopDir) {
91
91
  dir = parent;
92
92
  }
93
93
  }
94
+ var HOME_INDEPENDENT_SOURCES = /* @__PURE__ */ new Set([
95
+ "env",
96
+ "env-alias",
97
+ "dotenv"
98
+ ]);
99
+ function resolveAccountIndex(env, source, file) {
100
+ const raw = env["RIG_ACCOUNT_INDEX"]?.trim();
101
+ if (raw) {
102
+ const parsed = Number(raw);
103
+ if (!Number.isInteger(parsed) || parsed < 0) {
104
+ throw new Error(
105
+ `RIG_ACCOUNT_INDEX must be a non-negative integer, got ${JSON.stringify(raw)}`
106
+ );
107
+ }
108
+ return parsed;
109
+ }
110
+ if (HOME_INDEPENDENT_SOURCES.has(source)) return 0;
111
+ return typeof file.mnemonicAccountIndex === "number" ? file.mnemonicAccountIndex : 0;
112
+ }
94
113
  function resolveMnemonicSource(options, file, configPath) {
95
114
  const { env } = options;
96
115
  const rigEnv = env["RIG_MNEMONIC"]?.trim();
@@ -152,7 +171,7 @@ async function resolveIdentity(options) {
152
171
  } else {
153
172
  source = picked;
154
173
  }
155
- const accountIndex = typeof file.mnemonicAccountIndex === "number" ? file.mnemonicAccountIndex : 0;
174
+ const accountIndex = resolveAccountIndex(options.env, source.source, file);
156
175
  const { pubkey } = keys.deriveNostrKeyFromMnemonic(source.mnemonic, accountIndex);
157
176
  return { ...source, accountIndex, pubkey };
158
177
  }
@@ -164,6 +183,7 @@ export {
164
183
  clientKeystorePath,
165
184
  readClientConfigFile,
166
185
  linkKeystoreInClientConfig,
186
+ resolveAccountIndex,
167
187
  resolveIdentity
168
188
  };
169
- //# sourceMappingURL=chunk-XGFBDUQX.js.map
189
+ //# sourceMappingURL=chunk-GZUDRNOK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/identity.ts"],"sourcesContent":["/**\n * Identity resolution for the standalone-only `rig` CLI (#248).\n *\n * One precedence chain, used by every command that signs or pays:\n *\n * 1. `RIG_MNEMONIC` environment variable\n * 2. `TOON_CLIENT_MNEMONIC` environment variable — DEPRECATED alias of the\n * env tier (a one-line stderr warning fires when it is the source)\n * 3. project-local `.env` — walked up from the working directory (through\n * the repo root to the filesystem root); ONLY the `RIG_MNEMONIC` line is\n * parsed out of it (never loaded into the process env, never required\n * to exist)\n * 4. the shared `~/.toon-client` state dir (`TOON_CLIENT_HOME` override):\n * encrypted keystore (`keystorePath` + `TOON_CLIENT_KEYSTORE_PASSWORD`,\n * auto-password fallback for daemon-provisioned keystores), then the\n * plain `mnemonic` config field — the pre-#248 standalone-context logic\n *\n * The BIP-44 account index follows the same env-over-config precedence:\n *\n * 1. `RIG_ACCOUNT_INDEX` environment variable (applies to every source)\n * 2. `mnemonicAccountIndex` from the shared config file — but ONLY when the\n * phrase itself came from that shared state dir (keystore/config tiers).\n * An env- or `.env`-sourced phrase derives at index 0 unless\n * `RIG_ACCOUNT_INDEX` says otherwise, so an explicit `RIG_MNEMONIC`\n * pins the same identity no matter which `TOON_CLIENT_HOME` is active\n * (#384 — a per-home config must never silently shift an explicitly\n * provided identity).\n * 3. account 0\n *\n * The phrase itself is never written anywhere by rig (not to git config, not\n * to any repo file) and never printed — callers report only the SOURCE and\n * the derived pubkey.\n *\n * Key derivation and keystore decryption live in the `@toon-protocol/client`\n * dependency, loaded via dynamic import so this module can be statically\n * imported by every command without dragging the client into runs that fail\n * earlier (usage errors, missing git repo, …).\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join } from 'node:path';\n\n/** Where the mnemonic came from (reported in output; the phrase never is). */\nexport type IdentitySourceKind =\n /** `RIG_MNEMONIC` environment variable. */\n | 'env'\n /** `TOON_CLIENT_MNEMONIC` environment variable (deprecated alias). */\n | 'env-alias'\n /** `RIG_MNEMONIC` parsed out of a project-local `.env` file. */\n | 'dotenv'\n /** Encrypted keystore referenced by the shared client config. */\n | 'keystore'\n /** Plain `mnemonic` field of the shared client config file. */\n | 'config';\n\n/** A resolved signing identity: source + derived pubkey (never the phrase). */\nexport interface ResolvedIdentity {\n /** The BIP-39 phrase. Handle with care; never log or persist it. */\n mnemonic: string;\n /** BIP-44 account index used for derivation — `RIG_ACCOUNT_INDEX` env,\n * else `mnemonicAccountIndex` from the shared config (home-sourced phrases\n * only), else 0. */\n accountIndex: number;\n source: IdentitySourceKind;\n /** Human-facing source label, e.g. `RIG_MNEMONIC env` or a file path. */\n sourceLabel: string;\n /** Derived Nostr pubkey (hex) — the repo owner / `toon.owner` value. */\n pubkey: string;\n}\n\n/** No mnemonic could be resolved anywhere on the chain. */\nexport class MissingIdentityError extends Error {\n constructor(configPath: string) {\n super(\n 'no identity found — rig needs a BIP-39 seed phrase to sign and pay.\\n' +\n 'Generate one now (no BIP-39 tooling needed):\\n' +\n ' • `rig identity create` — mint a fresh identity into the encrypted ' +\n 'keystore (shows the phrase once to back up)\\n' +\n 'Or point rig at an existing phrase (highest precedence first):\\n' +\n ' • RIG_MNEMONIC environment variable\\n' +\n ' • RIG_MNEMONIC=<phrase> in a project-local .env file (gitignore it!)\\n' +\n ` • the shared client config at ${configPath} (mnemonic or ` +\n 'keystorePath + TOON_CLIENT_KEYSTORE_PASSWORD)'\n );\n this.name = 'MissingIdentityError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Shared client config conventions (duplicated from client-mcp — the same\n// note as standalone/nonce-guard.ts: no @toon-protocol/client-mcp import)\n// ---------------------------------------------------------------------------\n\n/**\n * Duplicated daemon convention (client-mcp `daemon/config.ts`): the password\n * used to encrypt a keystore rig auto-provisions (`rig identity create`\n * with no `TOON_CLIENT_KEYSTORE_PASSWORD` set) so the identity reloads across\n * runs with no env var. At-rest obfuscation only.\n */\nexport const DEFAULT_KEYSTORE_PASSWORD = 'toon-client-default';\n\n/** Shared client state dir: `TOON_CLIENT_HOME`, else `~/.toon-client`. */\nexport function clientStateDir(env: NodeJS.ProcessEnv): string {\n return env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n}\n\n/** Shared client config file path (`<state-dir>/config.json`). */\nexport function clientConfigPath(env: NodeJS.ProcessEnv): string {\n return join(clientStateDir(env), 'config.json');\n}\n\n/** Default encrypted-keystore path (`<state-dir>/keystore.json`) — the same\n * convention the daemon's first-run provisioning uses. */\nexport function clientKeystorePath(env: NodeJS.ProcessEnv): string {\n return join(clientStateDir(env), 'keystore.json');\n}\n\n/** The subset of the shared client config file identity resolution reads. */\nexport interface ClientConfigIdentityFields {\n mnemonic?: unknown;\n mnemonicAccountIndex?: unknown;\n keystorePath?: unknown;\n keystoreAutoPassword?: unknown;\n}\n\nexport function readClientConfigFile(path: string): ClientConfigIdentityFields {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as ClientConfigIdentityFields;\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') return {};\n throw new Error(\n `failed to read client config at ${path}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n}\n\n/**\n * Link a freshly written keystore into the shared client config so the\n * keystore tier of {@link resolveIdentity} (and the daemon) picks it up on the\n * next run — merging into any existing config, preserving every other field,\n * and writing owner-only (mode 0o600). `keystoreAutoPassword` records whether\n * rig chose the default password (so a user-set password still requires the\n * env var to decrypt, exactly like the daemon's first-run convention).\n */\nexport function linkKeystoreInClientConfig(\n env: NodeJS.ProcessEnv,\n keystorePath: string,\n autoPassword: boolean\n): string {\n const configPath = clientConfigPath(env);\n mkdirSync(dirname(configPath), { recursive: true });\n const existing = readClientConfigFile(configPath) as Record<string, unknown>;\n const merged: Record<string, unknown> = {\n ...existing,\n keystorePath,\n ...(autoPassword\n ? { keystoreAutoPassword: true }\n : // A user-set password: drop any stale auto flag so decryption\n // requires TOON_CLIENT_KEYSTORE_PASSWORD.\n { keystoreAutoPassword: false }),\n };\n writeFileSync(configPath, JSON.stringify(merged, null, 2) + '\\n', {\n encoding: 'utf8',\n mode: 0o600,\n });\n return configPath;\n}\n\n// ---------------------------------------------------------------------------\n// .env parsing (RIG_MNEMONIC only — never arbitrary env loading)\n// ---------------------------------------------------------------------------\n\nconst DOTENV_LINE_RE = /^\\s*(?:export\\s+)?RIG_MNEMONIC\\s*=\\s*(.*)\\s*$/;\n\n/**\n * Extract ONLY the `RIG_MNEMONIC` value from `.env` file content. Supports\n * `export ` prefixes, single/double quotes, full-line `#` comments, and\n * inline ` #` comments on unquoted values. Multiple assignments: the last\n * one wins (shell-sourcing semantics). An empty value counts as unset.\n * Nothing is ever loaded into `process.env`.\n */\nexport function parseDotenvMnemonic(content: string): string | undefined {\n let found: string | undefined;\n for (const line of content.split(/\\r?\\n/)) {\n const match = DOTENV_LINE_RE.exec(line);\n if (!match) continue;\n let value = (match[1] ?? '').trim();\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote)) {\n value = value.slice(1, -1);\n } else {\n // Unquoted: an inline comment starts at the first whitespace-preceded #.\n const hash = value.search(/\\s#/);\n if (hash !== -1) value = value.slice(0, hash);\n value = value.trim();\n }\n if (value !== '') found = value;\n }\n return found;\n}\n\n/**\n * Walk up from `startDir` (the working directory — the walk passes through\n * the repo root) to the filesystem root, returning the first `.env` file\n * that defines `RIG_MNEMONIC`. `stopDir` bounds the walk (tests).\n */\nexport function findDotenvMnemonic(\n startDir: string,\n stopDir?: string\n): { path: string; mnemonic: string } | undefined {\n let dir = startDir;\n for (;;) {\n const candidate = join(dir, '.env');\n if (existsSync(candidate)) {\n try {\n const mnemonic = parseDotenvMnemonic(readFileSync(candidate, 'utf8'));\n if (mnemonic !== undefined) return { path: candidate, mnemonic };\n } catch {\n // Unreadable .env → keep walking; the file is never required.\n }\n }\n if (stopDir !== undefined && dir === stopDir) return undefined;\n const parent = dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Account index (env > per-home config for home-sourced phrases > 0)\n// ---------------------------------------------------------------------------\n\n/** Sources whose phrase lives OUTSIDE the shared state dir. For these the\n * per-home `mnemonicAccountIndex` must not apply — an explicit\n * `RIG_MNEMONIC` derives the same identity across every\n * `TOON_CLIENT_HOME` (#384). */\nconst HOME_INDEPENDENT_SOURCES: ReadonlySet<IdentitySourceKind> = new Set([\n 'env',\n 'env-alias',\n 'dotenv',\n]);\n\n/**\n * Resolve the BIP-44 account index for a phrase from `source`:\n * `RIG_ACCOUNT_INDEX` env always wins; the shared config's\n * `mnemonicAccountIndex` applies only when the phrase itself came from the\n * shared state dir (keystore/config tiers); default 0. Throws on a\n * malformed `RIG_ACCOUNT_INDEX` — silently deriving a different identity\n * is exactly the surprise this precedence exists to prevent.\n */\nexport function resolveAccountIndex(\n env: NodeJS.ProcessEnv,\n source: IdentitySourceKind,\n file: ClientConfigIdentityFields\n): number {\n const raw = env['RIG_ACCOUNT_INDEX']?.trim();\n if (raw) {\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new Error(\n `RIG_ACCOUNT_INDEX must be a non-negative integer, got ${JSON.stringify(raw)}`\n );\n }\n return parsed;\n }\n if (HOME_INDEPENDENT_SOURCES.has(source)) return 0;\n return typeof file.mnemonicAccountIndex === 'number' ? file.mnemonicAccountIndex : 0;\n}\n\n// ---------------------------------------------------------------------------\n// Resolution\n// ---------------------------------------------------------------------------\n\nexport interface ResolveIdentityOptions {\n env: NodeJS.ProcessEnv;\n /** Working directory the `.env` walk starts from. */\n cwd: string;\n /** Stderr line sink for the deprecated-alias warning. */\n warn(line: string): void;\n /** Bound the `.env` walk-up (tests only). */\n dotenvStopDir?: string;\n}\n\n/** The resolved source before any derivation (dependency-free). */\ninterface MnemonicSource {\n mnemonic: string;\n source: IdentitySourceKind;\n sourceLabel: string;\n}\n\nfunction resolveMnemonicSource(\n options: ResolveIdentityOptions,\n file: ClientConfigIdentityFields,\n configPath: string\n): MnemonicSource | { keystorePath: string } {\n const { env } = options;\n\n const rigEnv = env['RIG_MNEMONIC']?.trim();\n if (rigEnv) {\n return { mnemonic: rigEnv, source: 'env', sourceLabel: 'RIG_MNEMONIC env' };\n }\n\n const aliasEnv = env['TOON_CLIENT_MNEMONIC']?.trim();\n if (aliasEnv) {\n options.warn(\n 'rig: TOON_CLIENT_MNEMONIC is deprecated — rename the variable to RIG_MNEMONIC'\n );\n return {\n mnemonic: aliasEnv,\n source: 'env-alias',\n sourceLabel: 'TOON_CLIENT_MNEMONIC env (deprecated alias)',\n };\n }\n\n const dotenv = findDotenvMnemonic(options.cwd, options.dotenvStopDir);\n if (dotenv) {\n return {\n mnemonic: dotenv.mnemonic,\n source: 'dotenv',\n sourceLabel: dotenv.path,\n };\n }\n\n if (typeof file.keystorePath === 'string' && file.keystorePath !== '') {\n return { keystorePath: file.keystorePath };\n }\n if (typeof file.mnemonic === 'string' && file.mnemonic.trim() !== '') {\n return {\n mnemonic: file.mnemonic.trim(),\n source: 'config',\n sourceLabel: configPath,\n };\n }\n throw new MissingIdentityError(configPath);\n}\n\n/**\n * Load the client key helpers. `@toon-protocol/client` is a regular runtime\n * dependency (#259); the import stays dynamic purely so commands that fail\n * earlier never pay its startup cost.\n */\nasync function loadClientKeys(): Promise<{\n loadKeystore(path: string, password: string): string;\n deriveNostrKeyFromMnemonic(\n mnemonic: string,\n accountIndex?: number\n ): { secretKey: Uint8Array; pubkey: string };\n}> {\n return await import('@toon-protocol/client');\n}\n\n/**\n * Resolve the CLI signing identity along the precedence chain and derive its\n * Nostr pubkey. Throws {@link MissingIdentityError} (with the full\n * three-option remediation) when nothing on the chain yields a phrase.\n */\nexport async function resolveIdentity(\n options: ResolveIdentityOptions\n): Promise<ResolvedIdentity> {\n const configPath = clientConfigPath(options.env);\n const file = readClientConfigFile(configPath);\n const picked = resolveMnemonicSource(options, file, configPath);\n\n const keys = await loadClientKeys();\n let source: MnemonicSource;\n if ('keystorePath' in picked) {\n const password =\n options.env['TOON_CLIENT_KEYSTORE_PASSWORD'] ??\n (file.keystoreAutoPassword === true ? DEFAULT_KEYSTORE_PASSWORD : undefined);\n if (!password) {\n throw new Error(\n `keystorePath is set in ${configPath} but TOON_CLIENT_KEYSTORE_PASSWORD is not provided`\n );\n }\n source = {\n mnemonic: keys.loadKeystore(picked.keystorePath, password),\n source: 'keystore',\n sourceLabel: picked.keystorePath,\n };\n } else {\n source = picked;\n }\n\n const accountIndex = resolveAccountIndex(options.env, source.source, file);\n const { pubkey } = keys.deriveNostrKeyFromMnemonic(source.mnemonic, accountIndex);\n return { ...source, accountIndex, pubkey };\n}\n"],"mappings":";AAuCA,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,SAAS,YAAY;AA+BvB,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,YAAoB;AAC9B;AAAA,MACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uCAOqC,UAAU;AAAA,IAEjD;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAaO,IAAM,4BAA4B;AAGlC,SAAS,eAAe,KAAgC;AAC7D,SAAO,IAAI,kBAAkB,KAAK,KAAK,QAAQ,GAAG,cAAc;AAClE;AAGO,SAAS,iBAAiB,KAAgC;AAC/D,SAAO,KAAK,eAAe,GAAG,GAAG,aAAa;AAChD;AAIO,SAAS,mBAAmB,KAAgC;AACjE,SAAO,KAAK,eAAe,GAAG,GAAG,eAAe;AAClD;AAUO,SAAS,qBAAqB,MAA0C;AAC7E,MAAI;AACF,WAAO,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;AAAA,EAC9C,SAAS,KAAK;AACZ,QAAK,IAA8B,SAAS,SAAU,QAAO,CAAC;AAC9D,UAAM,IAAI;AAAA,MACR,mCAAmC,IAAI,KAAK,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAC9F;AAAA,EACF;AACF;AAUO,SAAS,2BACd,KACA,cACA,cACQ;AACR,QAAM,aAAa,iBAAiB,GAAG;AACvC,YAAU,QAAQ,UAAU,GAAG,EAAE,WAAW,KAAK,CAAC;AAClD,QAAM,WAAW,qBAAqB,UAAU;AAChD,QAAM,SAAkC;AAAA,IACtC,GAAG;AAAA,IACH;AAAA,IACA,GAAI,eACA,EAAE,sBAAsB,KAAK;AAAA;AAAA;AAAA,MAG7B,EAAE,sBAAsB,MAAM;AAAA;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AAOA,eAAe,iBAMZ;AACD,SAAO,MAAM,OAAO,uBAAuB;AAC7C;AAOA,eAAsB,gBACpB,SAC2B;AAC3B,QAAM,aAAa,iBAAiB,QAAQ,GAAG;AAC/C,QAAM,OAAO,qBAAqB,UAAU;AAC5C,QAAM,SAAS,sBAAsB,SAAS,MAAM,UAAU;AAE9D,QAAM,OAAO,MAAM,eAAe;AAClC,MAAI;AACJ,MAAI,kBAAkB,QAAQ;AAC5B,UAAM,WACJ,QAAQ,IAAI,+BAA+B,MAC1C,KAAK,yBAAyB,OAAO,4BAA4B;AACpE,QAAI,CAAC,UAAU;AACb,YAAM,IAAI;AAAA,QACR,0BAA0B,UAAU;AAAA,MACtC;AAAA,IACF;AACA,aAAS;AAAA,MACP,UAAU,KAAK,aAAa,OAAO,cAAc,QAAQ;AAAA,MACzD,QAAQ;AAAA,MACR,aAAa,OAAO;AAAA,IACtB;AAAA,EACF,OAAO;AACL,aAAS;AAAA,EACX;AAEA,QAAM,eAAe,oBAAoB,QAAQ,KAAK,OAAO,QAAQ,IAAI;AACzE,QAAM,EAAE,OAAO,IAAI,KAAK,2BAA2B,OAAO,UAAU,YAAY;AAChF,SAAO,EAAE,GAAG,QAAQ,cAAc,OAAO;AAC3C;","names":[]}
@@ -95,6 +95,16 @@ var DEVNET_CHAIN_RPC_URLS = {
95
95
  "evm:31337": "https://evm-rpc.devnet.toonprotocol.dev",
96
96
  "solana:devnet": "https://solana-rpc.devnet.toonprotocol.dev"
97
97
  };
98
+ function devnetChainRpcUrl(chain) {
99
+ const exact = DEVNET_CHAIN_RPC_URLS[chain];
100
+ if (exact) return exact;
101
+ const chainId = evmChainIdOf(chain);
102
+ if (chainId === void 0) return void 0;
103
+ for (const [key, url] of Object.entries(DEVNET_CHAIN_RPC_URLS)) {
104
+ if (evmChainIdOf(key) === chainId) return url;
105
+ }
106
+ return void 0;
107
+ }
98
108
  function hostOf(url) {
99
109
  if (!url) return void 0;
100
110
  try {
@@ -151,10 +161,10 @@ function solanaPresetForChain(chain) {
151
161
  function resolveChainSettlement(chain, explicit, announce) {
152
162
  const family = chain.split(":")[0] ?? chain;
153
163
  const evmPreset = family === "evm" ? evmPresetForChain(chain) : void 0;
154
- const devnetRpc = isDevnetZonePeer(announce) ? DEVNET_CHAIN_RPC_URLS[chain] : void 0;
164
+ const devnetRpc = isDevnetZonePeer(announce) ? devnetChainRpcUrl(chain) : void 0;
155
165
  const explicitOrZoneRpc = explicit.chainRpcUrls?.[chain] ?? devnetRpc;
156
166
  const rpcHost = hostOf(explicitOrZoneRpc);
157
- const zoneSelfHosted = isDevnetZonePeer(announce) && DEVNET_CHAIN_RPC_URLS[chain] !== void 0 || rpcHost !== void 0 && (rpcHost === DEVNET_ZONE || rpcHost.endsWith(`.${DEVNET_ZONE}`));
167
+ const zoneSelfHosted = isDevnetZonePeer(announce) && devnetChainRpcUrl(chain) !== void 0 || rpcHost !== void 0 && (rpcHost === DEVNET_ZONE || rpcHost.endsWith(`.${DEVNET_ZONE}`));
158
168
  const solPreset = family === "solana" && !zoneSelfHosted ? solanaPresetForChain(chain) : void 0;
159
169
  const rpcUrl = explicitOrZoneRpc ?? evmPreset?.rpcUrl ?? solPreset?.rpcUrl;
160
170
  const tokenAddress = explicit.preferredTokens?.[chain] ?? announce?.info.preferredTokens?.[chain] ?? (evmPreset?.usdcAddress || void 0) ?? solPreset?.tokenMint;
@@ -350,6 +360,7 @@ export {
350
360
  pickPaymentPeer,
351
361
  DEVNET_ZONE,
352
362
  DEVNET_CHAIN_RPC_URLS,
363
+ devnetChainRpcUrl,
353
364
  isDevnetZonePeer,
354
365
  evmChainIdOf,
355
366
  evmPresetForChain,
@@ -363,4 +374,4 @@ export {
363
374
  loadGenesisSeed,
364
375
  genesisSeedPubkeys
365
376
  };
366
- //# sourceMappingURL=chunk-LTQPBBHA.js.map
377
+ //# sourceMappingURL=chunk-RALCZLP6.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/standalone/network-bootstrap.ts"],"sourcesContent":["/**\n * Network bootstrap for the standalone (embedded-client) rig path (#264):\n * resolve the payment topology — uplink, ILP destinations/routes, settlement\n * chain and its on-chain parameters — from the network itself instead of\n * hand-fed constants.\n *\n * Sources, in strict precedence order (first hit wins, per field):\n *\n * 1. EXPLICIT USER CONFIG — env vars / shared client-config file fields.\n * 2. LIVE kind:10032 ANNOUNCE — the payment peer's `IlpPeerInfo` event\n * discovered on the relay-origin (the relay the paid command resolved\n * via `rig remote`, i.e. what the user pointed rig at). The announce\n * carries `btpEndpoint`/`httpEndpoint` (uplink), `ilpAddress` (channel\n * anchor), `supportedChains` + `settlementAddresses` (settlement), and\n * the out-of-band `routes` map (`{publish, store}` ILP destinations).\n * 3. GENESIS SEED — `@toon-protocol/core`'s committed genesis peer seed\n * (core >= 2.0.1 ships the live devnet apex), the offline fallback when\n * the relay is unreachable or serves no valid announce.\n *\n * Chain-level parameters the announce does NOT carry (EVM TokenNetwork\n * contract, token address, RPC URL) are derived per selected chain:\n * explicit config > announce (`tokenNetworks`/`preferredTokens`, when a peer\n * announces them) > the deployed-devnet endpoint table (canonical\n * `*.devnet.toonprotocol.dev` hosts, keyed off the announce's own hostnames)\n * > core's deterministic chain presets (`CHAIN_PRESETS`, matched by chain\n * id — e.g. `evm:31337` is the Foundry/anvil deploy whose TOON contract\n * addresses are deterministic).\n *\n * Settlement-chain selection (#260 root cause 4) — simple and predictable:\n *\n * 1. EXPLICIT — `TOON_CLIENT_CHAIN` env / `chain` config field (family or\n * full chain id), or the first entry of an explicit `supportedChains`.\n * 2. PERSISTED CHANNEL — the chain of the most recently used live channel\n * recorded for this identity in the #262 channel map (a channel there\n * means collateral is already locked on that chain).\n * 3. FUNDED — the first announced chain (EVM or Solana, in announce\n * order) where the identity's token balance is > 0 (one `eth_call` /\n * `getTokenAccountsByOwner` per candidate).\n * 4. DEFAULT — the first EVM chain the peer announces (else the first\n * announced chain), with a printed rationale.\n *\n * This module is pure Node + `@toon-protocol/core` (rig's own core 2.x —\n * distinct from the embedded client's internal core; see\n * `../cli/standalone-mode.ts` for the coexistence note).\n */\n\nimport {\n CHAIN_PRESETS,\n GenesisPeerLoader,\n isEventExpired,\n parseIlpPeerInfo,\n resolveClientNetwork,\n type GenesisPeer,\n type IlpPeerInfo,\n} from '@toon-protocol/core';\nimport {\n queryRelay,\n type NostrEvent,\n type WebSocketFactory,\n} from '../remote-state.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** kind:10032 — ILP peer info announcement (mirrors core's constant). */\nexport const ILP_PEER_INFO_KIND = 10032;\n\n/** Publish/store ILP route hints riding out-of-band in announce content. */\nexport interface AnnouncedRoutes {\n publish?: string;\n store?: string;\n}\n\n/** One schema-valid, unexpired kind:10032 announce seen on the relay. */\nexport interface AnnouncedPeer {\n /** Announcing identity (event author, hex). */\n pubkey: string;\n /** Parsed + validated `IlpPeerInfo` (rig's core 2.x parser). */\n info: IlpPeerInfo;\n /** Out-of-band `routes` content field, when present and well-formed. */\n routes?: AnnouncedRoutes;\n /** Announce timestamp (freshness tiebreaker). */\n createdAt: number;\n}\n\n/** Per-chain settlement parameters resolved for the embedded client. */\nexport interface ChainSettlement {\n /** Chain id as announced/configured, e.g. `evm:31337`. */\n chain: string;\n /** `evm` | `solana` | `mina` | … (first chain-id segment). */\n family: string;\n /** JSON-RPC / GraphQL endpoint, when derivable. */\n rpcUrl?: string;\n /** Preferred token (USDC / SPL mint) address, when derivable. */\n tokenAddress?: string;\n /** EVM TokenNetwork contract, when derivable (EVM only). */\n tokenNetwork?: string;\n /** Solana payment-channel program id, when derivable (Solana only). */\n programId?: string;\n}\n\n/** Why a settlement chain was selected (documented rule, in order). */\nexport type ChainSelectionReason =\n | 'explicit'\n | 'persisted-channel'\n | 'funded'\n | 'default';\n\n/** The selected settlement chain plus its rationale. */\nexport interface ChainSelection {\n chain: string;\n reason: ChainSelectionReason;\n /** One human-readable line explaining the pick. */\n detail: string;\n}\n\n// ---------------------------------------------------------------------------\n// Announce discovery\n// ---------------------------------------------------------------------------\n\n/** Default bounded wait for the kind:10032 relay query. */\nexport const DISCOVERY_TIMEOUT_MS = 5000;\n\nfunction parseRoutes(content: string): AnnouncedRoutes | undefined {\n try {\n const parsed = JSON.parse(content) as { routes?: unknown };\n const routes = parsed.routes;\n if (typeof routes !== 'object' || routes === null) return undefined;\n const { publish, store } = routes as Record<string, unknown>;\n const out: AnnouncedRoutes = {\n ...(typeof publish === 'string' && publish.length > 0 ? { publish } : {}),\n ...(typeof store === 'string' && store.length > 0 ? { store } : {}),\n };\n return out.publish || out.store ? out : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Query `relayUrl` for kind:10032 announces and return the latest\n * schema-valid, unexpired announce per author. Invalid/expired events are\n * skipped silently (the relay serves plenty of non-peer 10032 experiments).\n */\nexport async function discoverAnnouncedPeers(\n relayUrl: string,\n options: {\n timeoutMs?: number;\n webSocketFactory?: WebSocketFactory;\n } = {}\n): Promise<AnnouncedPeer[]> {\n const factory =\n options.webSocketFactory ?? defaultDiscoveryWebSocketFactory();\n const events = await queryRelay(\n relayUrl,\n { kinds: [ILP_PEER_INFO_KIND], limit: 100 },\n options.timeoutMs ?? DISCOVERY_TIMEOUT_MS,\n factory\n );\n\n const latestByAuthor = new Map<string, NostrEvent>();\n for (const event of events) {\n if (event.kind !== ILP_PEER_INFO_KIND) continue;\n const prev = latestByAuthor.get(event.pubkey);\n if (!prev || event.created_at > prev.created_at) {\n latestByAuthor.set(event.pubkey, event);\n }\n }\n\n const peers: AnnouncedPeer[] = [];\n for (const event of latestByAuthor.values()) {\n if (isEventExpired(event as Parameters<typeof isEventExpired>[0])) {\n continue;\n }\n let info: IlpPeerInfo;\n try {\n info = parseIlpPeerInfo(event as Parameters<typeof parseIlpPeerInfo>[0]);\n } catch {\n continue; // not a schema-valid IlpPeerInfo announce\n }\n const routes = parseRoutes(event.content);\n peers.push({\n pubkey: event.pubkey,\n info,\n ...(routes ? { routes } : {}),\n createdAt: event.created_at,\n });\n }\n return peers;\n}\n\nfunction defaultDiscoveryWebSocketFactory(): WebSocketFactory {\n return (url) => {\n const ctor = (\n globalThis as {\n WebSocket?: new (url: string) => ReturnType<WebSocketFactory>;\n }\n ).WebSocket;\n if (!ctor) {\n throw new Error(\n 'No global WebSocket constructor (Node >= 22 required) for announce discovery'\n );\n }\n return new ctor(url);\n };\n}\n\n/**\n * Pick THE payment peer among discovered announces:\n *\n * 1. the announce authored by a genesis-seed pubkey (the committed apex\n * identity — the strongest signal),\n * 2. else an announce that can actually take paid writes: has an uplink\n * endpoint AND `settlementAddresses`, preferring one whose own\n * `ilpAddress` is its `routes.publish` (the publish edge — that is\n * where rig pays first),\n * 3. freshest `created_at` breaks remaining ties.\n */\nexport function pickPaymentPeer(\n peers: AnnouncedPeer[],\n seedPubkeys: readonly string[]\n): AnnouncedPeer | undefined {\n const seeded = peers.filter((p) => seedPubkeys.includes(p.pubkey));\n if (seeded.length > 0) {\n return seeded.sort((a, b) => b.createdAt - a.createdAt)[0];\n }\n\n const payable = peers.filter(\n (p) =>\n (p.info.httpEndpoint || p.info.btpEndpoint) &&\n p.info.settlementAddresses &&\n Object.keys(p.info.settlementAddresses).length > 0\n );\n if (payable.length === 0) return undefined;\n const publishEdges = payable.filter(\n (p) => p.routes?.publish !== undefined && p.routes.publish === p.info.ilpAddress\n );\n const pool = publishEdges.length > 0 ? publishEdges : payable;\n return pool.sort((a, b) => b.createdAt - a.createdAt)[0];\n}\n\n// ---------------------------------------------------------------------------\n// Per-chain settlement derivation\n// ---------------------------------------------------------------------------\n\n/**\n * The one deployed-network endpoint table rig ships: the canonical TOON\n * devnet (`*.devnet.toonprotocol.dev`, see toon-meta docs/deployment.md).\n * Chain RPC endpoints are deployment infrastructure the kind:10032 announce\n * does not carry (yet), so when the discovered peer's own endpoints live\n * under this zone, its self-hosted chains resolve to the canonical hosts.\n * Same status as `DEVNET_FAUCET_URL` in `../cli/fund.ts`. Everything here\n * is overridable by explicit `chainRpcUrls` config.\n */\nexport const DEVNET_ZONE = 'devnet.toonprotocol.dev';\n\n/** Canonical devnet chain RPC endpoints (self-hosted chains only). */\nexport const DEVNET_CHAIN_RPC_URLS: Readonly<Record<string, string>> = {\n 'evm:31337': 'https://evm-rpc.devnet.toonprotocol.dev',\n 'solana:devnet': 'https://solana-rpc.devnet.toonprotocol.dev',\n};\n\n/**\n * Devnet endpoint-table lookup. EVM entries match by NUMERIC CHAIN ID, not\n * exact key: announces spell the same chain both `evm:31337` and\n * `evm:anvil:31337` (`evm:{network}:{chainId}` — the network label is\n * cosmetic), and an exact-key miss here left the announced EVM chain\n * without a reachable RPC, so zero-config devnet negotiation could not\n * balance-probe it and fell through to an unusable chain (#384).\n */\nexport function devnetChainRpcUrl(chain: string): string | undefined {\n const exact = DEVNET_CHAIN_RPC_URLS[chain];\n if (exact) return exact;\n const chainId = evmChainIdOf(chain);\n if (chainId === undefined) return undefined;\n for (const [key, url] of Object.entries(DEVNET_CHAIN_RPC_URLS)) {\n if (evmChainIdOf(key) === chainId) return url;\n }\n return undefined;\n}\n\n/** Hostname of a ws(s)/http(s) URL, or undefined when unparsable. */\nfunction hostOf(url: string | undefined): string | undefined {\n if (!url) return undefined;\n try {\n return new URL(url).hostname;\n } catch {\n return undefined;\n }\n}\n\n/** True when the announce's own endpoints live under the TOON devnet zone. */\nexport function isDevnetZonePeer(\n peer: Pick<AnnouncedPeer, 'info'> | undefined\n): boolean {\n if (!peer) return false;\n return [\n hostOf(peer.info.httpEndpoint),\n hostOf(peer.info.btpEndpoint),\n hostOf(peer.info.relayUrl),\n ].some((h) => h !== undefined && (h === DEVNET_ZONE || h.endsWith(`.${DEVNET_ZONE}`)));\n}\n\n/** Numeric chain id of an `evm:<id>` / `evm:<name>:<id>` chain key. */\nexport function evmChainIdOf(chain: string): number | undefined {\n const parts = chain.split(':');\n if (parts[0] !== 'evm') return undefined;\n const raw = parts.length >= 3 ? parts[2] : parts[1];\n const id = Number.parseInt(raw ?? '', 10);\n return Number.isNaN(id) ? undefined : id;\n}\n\n/**\n * Core chain preset matching an EVM chain key by numeric chain id. Presets\n * carry the DETERMINISTIC TOON contract addresses per chain (e.g. the\n * `anvil` 31337 Foundry deploy), which is what makes `tokenNetwork`\n * derivable without the announce carrying it.\n */\nexport function evmPresetForChain(chain: string):\n | { rpcUrl: string; usdcAddress: string; tokenNetworkAddress: string }\n | undefined {\n const id = evmChainIdOf(chain);\n if (id === undefined) return undefined;\n for (const preset of Object.values(CHAIN_PRESETS)) {\n if (preset.chainId === id) {\n return {\n rpcUrl: preset.rpcUrl,\n usdcAddress: preset.usdcAddress,\n tokenNetworkAddress: preset.tokenNetworkAddress,\n };\n }\n }\n return undefined;\n}\n\n/**\n * Public-cluster Solana preset matching a `solana:<cluster>` chain key. Draws\n * from core's client network presets (`resolveClientNetwork`) — the same\n * tables the daemon and townhouse resolve — so the deployed public-devnet\n * program/mint and the mainnet-beta RPC + Circle USDC mint come from ONE\n * source. `programId` is present only where the TOON payment-channel program\n * is actually deployed (public devnet today; mainnet-beta once deployed).\n * Self-hosted validators (e.g. the TOON devnet's own `solana-rpc.*` box) have\n * their own regenerated program ids — those must come from the announce or\n * explicit config, never a preset.\n */\nexport function solanaPresetForChain(chain: string):\n | { rpcUrl?: string; tokenMint?: string; programId?: string }\n | undefined {\n const [family, cluster] = chain.split(':');\n if (family !== 'solana' || !cluster) return undefined;\n const tier =\n cluster === 'mainnet-beta'\n ? 'mainnet'\n : cluster === 'devnet'\n ? 'devnet'\n : cluster === 'testnet'\n ? 'testnet'\n : undefined;\n if (!tier) return undefined;\n const presets = resolveClientNetwork(tier);\n // Look up by the exact chain key: the `testnet` tier resolves to the\n // deployed `solana:devnet` cluster, so `solana:testnet` correctly finds\n // nothing (TOON has no deployment on Solana's testnet cluster).\n const rpcUrl = presets.chainRpcUrls[chain];\n const tokenMint = presets.preferredTokens[chain];\n const programId =\n presets.solanaChannel && presets.supportedChains.includes(chain)\n ? presets.solanaChannel.programId\n : undefined;\n if (!rpcUrl && !tokenMint && !programId) return undefined;\n return {\n ...(rpcUrl ? { rpcUrl } : {}),\n ...(tokenMint ? { tokenMint } : {}),\n ...(programId ? { programId } : {}),\n };\n}\n\n/** Explicit per-chain maps from the shared client-config file. */\nexport interface ExplicitChainConfig {\n chainRpcUrls?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n}\n\n/**\n * Resolve one chain's settlement parameters: explicit config > announce >\n * devnet endpoint table (RPC only, devnet-zone peers) > core chain preset.\n * Fields stay undefined when no source covers them — callers decide whether\n * that is fatal (see {@link TokenNetworkUnderivableError} /\n * {@link SolanaChannelUnderivableError}).\n *\n * For `solana:*` chains the chain-keyed maps carry the SPL analogues: the\n * `preferredTokens` entry is the token mint, and the `tokenNetworks` entry is\n * the payment-channel PROGRAM id (the map is chain-keyed settlement-contract\n * addressing — TokenNetwork contract on EVM, channel program on Solana),\n * surfaced as {@link ChainSettlement.programId}.\n */\nexport function resolveChainSettlement(\n chain: string,\n explicit: ExplicitChainConfig,\n announce?: AnnouncedPeer\n): ChainSettlement {\n const family = chain.split(':')[0] ?? chain;\n const evmPreset = family === 'evm' ? evmPresetForChain(chain) : undefined;\n const devnetRpc = isDevnetZonePeer(announce)\n ? devnetChainRpcUrl(chain)\n : undefined;\n // The devnet zone SELF-HOSTS this chain (its own validator): the\n // public-cluster preset addresses do not exist there (the devnet's Solana\n // program id is regenerated per redeploy), so presets must not fill gaps —\n // only the announce or explicit config can (else the caller fails fast\n // with an actionable error instead of an on-chain \"program not found\").\n // Detected via the announcing peer's zone OR the resolved RPC host, so an\n // explicit zone RPC is protected even when discovery was skipped/failed.\n const explicitOrZoneRpc = explicit.chainRpcUrls?.[chain] ?? devnetRpc;\n const rpcHost = hostOf(explicitOrZoneRpc);\n const zoneSelfHosted =\n (isDevnetZonePeer(announce) && devnetChainRpcUrl(chain) !== undefined) ||\n (rpcHost !== undefined &&\n (rpcHost === DEVNET_ZONE || rpcHost.endsWith(`.${DEVNET_ZONE}`)));\n const solPreset =\n family === 'solana' && !zoneSelfHosted\n ? solanaPresetForChain(chain)\n : undefined;\n\n const rpcUrl = explicitOrZoneRpc ?? evmPreset?.rpcUrl ?? solPreset?.rpcUrl;\n const tokenAddress =\n explicit.preferredTokens?.[chain] ??\n announce?.info.preferredTokens?.[chain] ??\n (evmPreset?.usdcAddress || undefined) ??\n solPreset?.tokenMint;\n const tokenNetwork =\n family === 'evm'\n ? (explicit.tokenNetworks?.[chain] ??\n announce?.info.tokenNetworks?.[chain] ??\n (evmPreset?.tokenNetworkAddress || undefined))\n : undefined;\n const programId =\n family === 'solana'\n ? (explicit.tokenNetworks?.[chain] ??\n announce?.info.tokenNetworks?.[chain] ??\n solPreset?.programId)\n : undefined;\n\n return {\n chain,\n family,\n ...(rpcUrl ? { rpcUrl } : {}),\n ...(tokenAddress ? { tokenAddress } : {}),\n ...(tokenNetwork ? { tokenNetwork } : {}),\n ...(programId ? { programId } : {}),\n };\n}\n\n/** An EVM chain was selected but its TokenNetwork cannot be derived. */\nexport class TokenNetworkUnderivableError extends Error {\n constructor(chain: string, announce: AnnouncedPeer | undefined, relayUrl: string) {\n const announceRef = announce\n ? `the kind:10032 announce from ${announce.pubkey.slice(0, 16)}… on ${relayUrl}`\n : `no kind:10032 announce was found on ${relayUrl}`;\n super(\n `cannot derive the TokenNetwork contract for settlement chain ` +\n `\"${chain}\": ${announceRef} carries no tokenNetworks[\"${chain}\"], ` +\n `and no built-in chain preset matches its chain id — add ` +\n `tokenNetworks[\"${chain}\"] to the client config (or pick another ` +\n `chain via TOON_CLIENT_CHAIN / the chain config field)`\n );\n this.name = 'TokenNetworkUnderivableError';\n }\n}\n\n/**\n * A Solana chain was selected but its channel parameters cannot be derived.\n * The missing pieces are named so the error is directly actionable: a\n * `solanaChannel` config object always works; the chain-keyed maps\n * (`tokenNetworks` = program id, `preferredTokens` = mint,\n * `chainRpcUrls` = RPC) work per-chain.\n */\nexport class SolanaChannelUnderivableError extends Error {\n constructor(\n chain: string,\n missing: string[],\n announce: AnnouncedPeer | undefined,\n relayUrl: string\n ) {\n const announceRef = announce\n ? `the kind:10032 announce from ${announce.pubkey.slice(0, 16)}… on ${relayUrl} does not carry them`\n : `no kind:10032 announce was found on ${relayUrl}`;\n super(\n `cannot derive the Solana channel parameters for settlement chain ` +\n `\"${chain}\" (missing: ${missing.join(', ')}): ${announceRef}, and ` +\n `no built-in preset covers this cluster — add a solanaChannel ` +\n `{ rpcUrl, programId, tokenMint } object to the client config (or ` +\n `set tokenNetworks[\"${chain}\"] = <program id>, ` +\n `preferredTokens[\"${chain}\"] = <mint>, chainRpcUrls[\"${chain}\"]), ` +\n `or pick another chain via TOON_CLIENT_CHAIN / the chain config field`\n );\n this.name = 'SolanaChannelUnderivableError';\n }\n}\n\n// ---------------------------------------------------------------------------\n// Settlement-chain selection (#260 root cause 4)\n// ---------------------------------------------------------------------------\n\n/** The slice of a #262 channel-map record chain selection consumes. */\nexport interface ChannelRecordLike {\n chain: string;\n lastUsedAt: string;\n /** True when the withdraw flow closed/settled the channel. */\n closed: boolean;\n}\n\n/** Async token-balance probe (injectable; default is a raw `eth_call`). */\nexport type EvmBalanceProbe = (args: {\n rpcUrl: string;\n tokenAddress: string;\n owner: string;\n}) => Promise<bigint>;\n\n/**\n * Async SPL token-balance probe (injectable; default is a raw\n * `getTokenAccountsByOwner`). `tokenAddress` is the SPL mint and `owner`\n * the identity's base58 Solana address — the same argument shape as\n * {@link EvmBalanceProbe} so both feed the one funded-chain loop.\n */\nexport type SolanaBalanceProbe = (args: {\n rpcUrl: string;\n tokenAddress: string;\n owner: string;\n}) => Promise<bigint>;\n\nexport interface SelectChainOptions {\n /**\n * Explicit chain choice: full chain id (`evm:31337`), a family\n * (`evm` | `solana` | `mina`) matched against announced chains, or the\n * first entry of an explicit `supportedChains` config.\n */\n explicitChain?: string;\n /** Chains the payment peer announces (announce order preserved). */\n announcedChains: readonly string[];\n /** #262 channel-map records for this identity (any anchor). */\n records?: readonly ChannelRecordLike[];\n /** Identity's EVM address (funded-chain probe, `evm:*` candidates). */\n evmAddress?: string;\n /**\n * Identity's base58 Solana address (funded-chain probe, `solana:*`\n * candidates). Absent (e.g. the identity's Ed25519 key could not be\n * derived) means Solana chains are simply not probed.\n */\n solanaAddress?: string;\n /** Per-chain settlement resolver (for RPC/token of probe candidates). */\n resolveSettlement: (chain: string) => ChainSettlement;\n /** EVM balance probe; probe errors just skip the candidate. */\n probeBalance?: EvmBalanceProbe;\n /** Solana balance probe; probe errors just skip the candidate. */\n probeSolanaBalance?: SolanaBalanceProbe;\n}\n\n/**\n * Select the settlement chain per the documented rule: explicit >\n * persisted channel > funded chain (EVM + Solana, in announce order) >\n * first announced EVM chain.\n */\nexport async function selectSettlementChain(\n options: SelectChainOptions\n): Promise<ChainSelection> {\n const { explicitChain, announcedChains } = options;\n\n // 1 — explicit config always wins (even when the peer does not announce\n // it: the user may know better than a stale announce).\n if (explicitChain) {\n if (explicitChain.includes(':')) {\n return {\n chain: explicitChain,\n reason: 'explicit',\n detail: `chain ${explicitChain} set by config`,\n };\n }\n const familyMatch = announcedChains.find(\n (c) => (c.split(':')[0] ?? c) === explicitChain\n );\n if (!familyMatch) {\n throw new Error(\n `configured chain family \"${explicitChain}\" is not announced by the ` +\n `payment peer (announced: ${announcedChains.join(', ') || 'none'}) — ` +\n 'set a full chain id (e.g. \"evm:31337\") to force it'\n );\n }\n return {\n chain: familyMatch,\n reason: 'explicit',\n detail: `chain family \"${explicitChain}\" set by config → ${familyMatch}`,\n };\n }\n\n // 2 — a live persisted channel means collateral is already locked there.\n const live = (options.records ?? [])\n .filter((r) => !r.closed && announcedChains.includes(r.chain))\n .sort((a, b) => b.lastUsedAt.localeCompare(a.lastUsedAt));\n const persisted = live[0];\n if (persisted) {\n return {\n chain: persisted.chain,\n reason: 'persisted-channel',\n detail: `existing payment channel on ${persisted.chain} (rig channel map)`,\n };\n }\n\n // 3 — first announced chain where the identity holds tokens, probing\n // EVM and Solana candidates in ANNOUNCE ORDER (the peer's stated\n // preference breaks a both-funded tie). Families without an address or\n // probe are skipped, as are candidates whose RPC/token are underivable.\n const evmChains = announcedChains.filter((c) => c.startsWith('evm:'));\n for (const chain of announcedChains) {\n const family = chain.split(':')[0];\n let probe: EvmBalanceProbe | SolanaBalanceProbe | undefined;\n let owner: string | undefined;\n if (family === 'evm') {\n probe = options.probeBalance;\n owner = options.evmAddress;\n } else if (family === 'solana') {\n probe = options.probeSolanaBalance;\n owner = options.solanaAddress;\n }\n if (!probe || !owner) continue;\n const settlement = options.resolveSettlement(chain);\n if (!settlement.rpcUrl || !settlement.tokenAddress) continue;\n try {\n const balance = await probe({\n rpcUrl: settlement.rpcUrl,\n tokenAddress: settlement.tokenAddress,\n owner,\n });\n if (balance > 0n) {\n return {\n chain,\n reason: 'funded',\n detail: `wallet holds ${balance} token base units on ${chain}`,\n };\n }\n } catch {\n // Unreachable RPC / bad token — not a candidate; fall through.\n }\n }\n\n // 4 — predictable default: the first EVM chain the peer announces.\n const fallback = evmChains[0] ?? announcedChains[0];\n if (!fallback) {\n throw new Error(\n 'the payment peer announces no settlement chains — cannot select a ' +\n 'chain for paid writes (set supportedChains/chain in the client config)'\n );\n }\n return {\n chain: fallback,\n reason: 'default',\n detail: evmChains[0]\n ? `first EVM chain announced by the payment peer`\n : `first chain announced by the payment peer (no EVM chain announced)`,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Default balance probes (raw JSON-RPC, no extra deps)\n// ---------------------------------------------------------------------------\n\n/** ERC-20 `balanceOf(address)` selector. */\nconst BALANCE_OF_SELECTOR = '0x70a08231';\n\n/**\n * Read an ERC-20 balance with one raw `eth_call` (keeps the probe free of\n * viem — the embedded client is not started yet when selection runs).\n */\nexport async function evmTokenBalance(args: {\n rpcUrl: string;\n tokenAddress: string;\n owner: string;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}): Promise<bigint> {\n const fetchImpl = args.fetchImpl ?? fetch;\n const owner = args.owner.replace(/^0x/, '').toLowerCase().padStart(64, '0');\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), args.timeoutMs ?? 5000);\n try {\n const res = await fetchImpl(args.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'eth_call',\n params: [\n { to: args.tokenAddress, data: `${BALANCE_OF_SELECTOR}${owner}` },\n 'latest',\n ],\n }),\n signal: controller.signal,\n });\n if (!res.ok) {\n throw new Error(`eth_call failed: HTTP ${res.status}`);\n }\n const body = (await res.json()) as { result?: unknown; error?: { message?: string } };\n if (typeof body.result !== 'string') {\n throw new Error(`eth_call failed: ${body.error?.message ?? 'no result'}`);\n }\n return BigInt(body.result === '0x' ? '0x0' : body.result);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Read an SPL token balance with one raw `getTokenAccountsByOwner` call\n * (keeps the probe free of @solana/web3.js — the embedded client is not\n * started yet when selection runs). `tokenAddress` is the mint; balances\n * are summed across all of the owner's token accounts for that mint (an\n * owner can hold the mint in more than one account).\n */\nexport async function solanaTokenBalance(args: {\n rpcUrl: string;\n tokenAddress: string;\n owner: string;\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n}): Promise<bigint> {\n const fetchImpl = args.fetchImpl ?? fetch;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), args.timeoutMs ?? 5000);\n try {\n const res = await fetchImpl(args.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [\n args.owner,\n { mint: args.tokenAddress },\n { encoding: 'jsonParsed' },\n ],\n }),\n signal: controller.signal,\n });\n if (!res.ok) {\n throw new Error(`getTokenAccountsByOwner failed: HTTP ${res.status}`);\n }\n const body = (await res.json()) as {\n result?: { value?: unknown };\n error?: { message?: string };\n };\n const accounts = body.result?.value;\n if (!Array.isArray(accounts)) {\n throw new Error(\n `getTokenAccountsByOwner failed: ${body.error?.message ?? 'no result'}`\n );\n }\n let total = 0n;\n for (const account of accounts) {\n const amount = (\n account as {\n account?: {\n data?: {\n parsed?: { info?: { tokenAmount?: { amount?: unknown } } };\n };\n };\n }\n )?.account?.data?.parsed?.info?.tokenAmount?.amount;\n if (typeof amount === 'string') total += BigInt(amount);\n }\n return total;\n } finally {\n clearTimeout(timer);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Genesis seed access (rig's own core 2.x — live devnet apex since 2.0.1)\n// ---------------------------------------------------------------------------\n\n/** The committed genesis peer seed (first entry), if any. */\nexport function loadGenesisSeed(): GenesisPeer | undefined {\n return GenesisPeerLoader.loadGenesisPeers()[0];\n}\n\n/** All committed genesis-seed pubkeys (announce-selection preference). */\nexport function genesisSeedPubkeys(): string[] {\n return GenesisPeerLoader.loadGenesisPeers().map((p) => p.pubkey);\n}\n"],"mappings":";;;;;AA8CA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAYA,IAAM,qBAAqB;AAwD3B,IAAM,uBAAuB;AAEpC,SAAS,YAAY,SAA8C;AACjE,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,OAAO;AACjC,UAAM,SAAS,OAAO;AACtB,QAAI,OAAO,WAAW,YAAY,WAAW,KAAM,QAAO;AAC1D,UAAM,EAAE,SAAS,MAAM,IAAI;AAC3B,UAAM,MAAuB;AAAA,MAC3B,GAAI,OAAO,YAAY,YAAY,QAAQ,SAAS,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA,MACvE,GAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,EAAE,MAAM,IAAI,CAAC;AAAA,IACnE;AACA,WAAO,IAAI,WAAW,IAAI,QAAQ,MAAM;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOA,eAAsB,uBACpB,UACA,UAGI,CAAC,GACqB;AAC1B,QAAM,UACJ,QAAQ,oBAAoB,iCAAiC;AAC/D,QAAM,SAAS,MAAM;AAAA,I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