@toon-protocol/rig 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/rig.js CHANGED
@@ -1098,7 +1098,7 @@ function loadPaidSession(deps, relayUrl) {
1098
1098
  });
1099
1099
  }
1100
1100
  var defaultLoadStandalone = async (options) => {
1101
- const mod = await import("../standalone-mode-AA2UWRGQ.js");
1101
+ const mod = await import("../standalone-mode-LBWGU7NV.js");
1102
1102
  return mod.createStandaloneContext(options);
1103
1103
  };
1104
1104
  function identityReport(ctx) {
@@ -51,6 +51,8 @@ import {
51
51
  encodeEventToToon,
52
52
  resolveClientNetwork
53
53
  } from "@toon-protocol/core";
54
+ var OFFICIAL_PROXY_URL = "https://proxy.devnet.toonprotocol.dev/rust/ilp";
55
+ var OFFICIAL_PUBLISH_DESTINATION = "g.toon.relay";
54
56
  var MissingUplinkError = class extends Error {
55
57
  constructor(configPath, relayUrl) {
56
58
  const discovered = relayUrl ? `no announce with a btp/http endpoint was found on ${relayUrl} and the genesis seed has none; ` : "";
@@ -73,9 +75,6 @@ function readClientConfig(path) {
73
75
  );
74
76
  }
75
77
  }
76
- function proxyBaseOf(httpEndpoint) {
77
- return httpEndpoint.replace(/\/+$/, "").replace(/\/ilp$/i, "");
78
- }
79
78
  function buildMinaAutoDeploy(dir, identityPubkey, chain, warn) {
80
79
  const store = MinaZkAppStore.forHome(dir);
81
80
  let existing;
@@ -182,20 +181,12 @@ async function resolveNetworkTopology(inputs) {
182
181
  ...file.tokenNetworks ? { tokenNetworks: file.tokenNetworks } : {}
183
182
  };
184
183
  let proxyUrl = explicitProxyUrl;
185
- let btpUrl = explicitBtpUrl;
184
+ const btpUrl = explicitBtpUrl;
186
185
  if (!proxyUrl && !btpUrl) {
187
- if (announce?.info.httpEndpoint) {
188
- proxyUrl = proxyBaseOf(announce.info.httpEndpoint);
189
- } else if (announce?.info.btpEndpoint) {
190
- btpUrl = announce.info.btpEndpoint;
191
- } else if (genesisSeed?.btpEndpoint) {
192
- btpUrl = genesisSeed.btpEndpoint;
193
- } else if (inputs.requireUplink !== false) {
194
- throw new MissingUplinkError(configPath, relayUrl);
195
- }
186
+ proxyUrl = OFFICIAL_PROXY_URL;
196
187
  }
197
188
  const destination = explicitDestination ?? announce?.info.ilpAddress ?? genesisSeed?.ilpAddress ?? "g.proxy";
198
- const publishDestination = explicitPublish ?? announce?.routes?.publish;
189
+ const publishDestination = explicitPublish ?? announce?.routes?.publish ?? (proxyUrl === OFFICIAL_PROXY_URL ? OFFICIAL_PUBLISH_DESTINATION : void 0);
199
190
  const storeDestination = explicitStore ?? announce?.routes?.store;
200
191
  let routePrices;
201
192
  const capabilities = announce?.capabilities;
@@ -724,8 +715,10 @@ async function createStandaloneContext(options) {
724
715
  }
725
716
  export {
726
717
  MissingUplinkError,
718
+ OFFICIAL_PROXY_URL,
719
+ OFFICIAL_PUBLISH_DESTINATION,
727
720
  buildMinaAutoDeploy,
728
721
  createStandaloneContext,
729
722
  resolveNetworkTopology
730
723
  };
731
- //# sourceMappingURL=standalone-mode-AA2UWRGQ.js.map
724
+ //# sourceMappingURL=standalone-mode-LBWGU7NV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli/standalone-mode.ts"],"sourcesContent":["/**\n * The embedded-client (standalone) publisher backing every paid `rig`\n * command: build a nonce-guarded {@link StandalonePublisher} from the\n * caller's own identity and config.\n *\n * Identity comes from the #248 precedence chain (`./identity.ts`:\n * RIG_MNEMONIC env → TOON_CLIENT_MNEMONIC env alias → project `.env` →\n * `~/.toon-client` keystore/config). The remaining config resolution\n * DUPLICATES the toon-clientd conventions\n * (`packages/client-mcp/src/daemon/config.ts`) the same way\n * `../standalone/nonce-guard.ts` does — this package must not import\n * `@toon-protocol/client-mcp` (circular; see that module's doc). Keep in sync:\n *\n * - state dir: `TOON_CLIENT_HOME`, else `~/.toon-client`; config `config.json`\n * - env overrides: `TOON_CLIENT_PROXY_URL`, `TOON_CLIENT_BTP_URL`,\n * `TOON_CLIENT_RELAY_URL`, `TOON_CLIENT_DESTINATION`,\n * `TOON_CLIENT_PUBLISH_DESTINATION`, `TOON_CLIENT_STORE_DESTINATION`,\n * `TOON_CLIENT_CHAIN`\n *\n * NETWORK BOOTSTRAP (#264): what explicit config does not pin is resolved\n * from the network itself — the payment peer's live kind:10032 announce on\n * the relay-origin, falling back to `@toon-protocol/core`'s committed\n * genesis peer seed. Uplink, channel anchor, publish/store routes, the\n * settlement chain and its TokenNetwork/token/RPC parameters all follow the\n * `explicit config > live announce > genesis seed` order documented in\n * `../standalone/network-bootstrap.ts`. The pure resolution lives in\n * {@link resolveNetworkTopology} (unit-testable without any network).\n *\n * TOPOLOGY CACHE (#279): the resolved topology is persisted under\n * `TOON_CLIENT_HOME` (`../standalone/topology-cache.ts`) keyed by\n * relay-origin + identity + an explicit-config fingerprint, with a 15-min\n * TTL (`RIG_TOPOLOGY_TTL_MS` overrides; `0` disables). A cache hit skips\n * announce discovery and the funded-chain probes entirely; a cached\n * topology that then fails to BOOTSTRAP is invalidated and re-resolved\n * live in-process ({@link TopologyRecoveringPublisher}), so staleness costs\n * one failed attempt, never a broken run. Only paid-path resolutions\n * (`requireUplink !== false`) are written — a free-read topology may lack\n * an uplink and must not shadow the paid path's MissingUplinkError.\n *\n * CORE COEXISTENCE NOTE: rig performs discovery with ITS OWN\n * `@toon-protocol/core` (^2.0.x — live genesis seed), while the embedded\n * `@toon-protocol/client` keeps its internal core (^1.6.x) for its own\n * bootstrap/negotiation. The two never exchange class instances — rig feeds\n * the client plain config (`knownPeers`, settlement maps), so the version\n * split is safe by construction.\n *\n * This module statically imports `@toon-protocol/client` (heavy: viem,\n * noble, nostr-tools), so it must only ever be reached through the dynamic\n * import in `push.ts` (see `./standalone-context.ts`).\n */\n\nimport { readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ToonClientConfig } from '@toon-protocol/client';\nimport {\n EvmSigner,\n deriveFullIdentity,\n deriveNostrKeyFromMnemonic,\n} from '@toon-protocol/client';\nimport {\n decodeEventFromToon,\n encodeEventToToon,\n resolveClientNetwork,\n} from '@toon-protocol/core';\nimport type {\n BlobUpload,\n FeeRates,\n GitObjectUpload,\n Publisher,\n PublishReceipt,\n UploadReceipt,\n} from '../publisher.js';\nimport type { UnsignedEvent } from '../nip34-events.js';\nimport {\n ChannelMapStore,\n RIG_CHANNEL_MAP_FILENAME,\n type ChannelMapRecord,\n} from '../standalone/channel-map.js';\nimport {\n TOPOLOGY_CACHE_FILENAME,\n TOPOLOGY_TTL_ENV,\n TopologyCache,\n explicitConfigFingerprint,\n topologyCacheKey,\n topologyCacheTtlMs,\n} from '../standalone/topology-cache.js';\nimport {\n DISCOVERY_TIMEOUT_MS,\n MinaChannelUnderivableError,\n SolanaChannelUnderivableError,\n TokenNetworkUnderivableError,\n discoverAnnouncedPeers,\n evmChainIdOf,\n evmTokenBalance,\n genesisSeedPubkeys,\n loadGenesisSeed,\n pickPaymentPeer,\n resolveChainSettlement,\n selectSettlementChain,\n solanaTokenBalance,\n type AnnouncedPeer,\n type ChainSelection,\n type ChainSettlement,\n type ChannelRecordLike,\n type EvmBalanceProbe,\n type ExplicitChainConfig,\n type SolanaBalanceProbe,\n} from '../standalone/network-bootstrap.js';\nimport {\n StandalonePublisher,\n deriveRouteDestinations,\n type WalletViewFallback,\n} from '../standalone/standalone-publisher.js';\nimport { standaloneForced } from '../standalone/nonce-guard.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { MinaZkAppStore } from '../standalone/mina-zkapp-store.js';\nimport { resolveIdentity } from './identity.js';\nimport type {\n StandaloneContext,\n StandaloneLoadOptions,\n} from './standalone-context.js';\n\n/** The subset of the shared client config file standalone mode consumes. */\nexport interface ClientConfigFile {\n network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';\n mnemonicAccountIndex?: number;\n btpUrl?: string;\n proxyUrl?: string;\n relayUrl?: string;\n destination?: string;\n publishDestination?: string;\n storeDestination?: string;\n feePerEvent?: string;\n channelStorePath?: string;\n /** Settlement chain: family (`evm`) or full id (`evm:31337`). */\n chain?: string;\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n chainRpcUrls?: Record<string, string>;\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n}\n\n/** An identity was resolved, but there is no way to send paid writes. */\n/**\n * The official TOON relay implementation's client edge — the Rust connector\n * on the devnet apex (connector #616: the parallel-fleet comparison\n * concluded and the Rust fleet serves the protocol's own `g.toon`\n * namespace). This is rig's DEFAULT uplink: paid writes go here unless an\n * entry is explicitly configured (`rig entry <url>` / `rig entry sandbox` /\n * the TOON_CLIENT_* env overrides). The channel bootstrap needs no\n * announce: the edge's x402 greeting carries the channel-opening facts\n * (connector #617), which the embedded client synthesizes a negotiation\n * from.\n */\nexport const OFFICIAL_PROXY_URL =\n 'https://proxy.devnet.toonprotocol.dev/rust/ilp';\n/** The official relay-write route on that edge. */\nexport const OFFICIAL_PUBLISH_DESTINATION = 'g.toon.relay';\n\nexport class MissingUplinkError extends Error {\n constructor(configPath: string, relayUrl: string | undefined) {\n const discovered = relayUrl\n ? `no announce with a btp/http endpoint was found on ${relayUrl} and ` +\n 'the genesis seed has none; '\n : '';\n super(\n `no write uplink configured: ${discovered}set TOON_CLIENT_PROXY_URL ` +\n '(connector payment proxy) or TOON_CLIENT_BTP_URL, or add ' +\n `proxyUrl/btpUrl to ${configPath}`\n );\n this.name = 'MissingUplinkError';\n }\n}\n\nfunction configDir(env: NodeJS.ProcessEnv): string {\n return env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n}\n\nfunction readClientConfig(path: string): ClientConfigFile {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as ClientConfigFile;\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// Pure topology resolution (#264) — exported for tests\n// ---------------------------------------------------------------------------\n\n/** A genesis-seed peer as this module consumes it (rig's core 3.x shape). */\nexport interface GenesisSeedLike {\n pubkey: string;\n relayUrl: string;\n ilpAddress: string;\n btpEndpoint: string;\n}\n\n/** Inputs to {@link resolveNetworkTopology} (side-effect free). */\nexport interface NetworkTopologyInputs {\n env: NodeJS.ProcessEnv;\n file: ClientConfigFile;\n /** For error messages (\"add X to <configPath>\"). */\n configPath: string;\n /** Resolved relay-origin (already precedence-resolved). */\n relayUrl: string;\n /** The discovered payment-peer announce, if any. */\n announce: AnnouncedPeer | undefined;\n /** The committed genesis seed entry, if any. */\n genesisSeed: GenesisSeedLike | undefined;\n identity: { mnemonic: string; accountIndex: number; pubkey: string };\n /**\n * #262 channel-map records for this identity (chain selection input).\n * A thunk so the (possibly corrupt-throwing) map read only happens when\n * chain selection actually needs it.\n */\n channelRecords: () => ChannelRecordLike[];\n /** EVM balance probe override (tests); default: raw `eth_call`. */\n probeBalance?: EvmBalanceProbe;\n /**\n * Solana balance probe override (tests); default: raw\n * `getTokenAccountsByOwner`.\n */\n probeSolanaBalance?: SolanaBalanceProbe;\n /**\n * When false (#263 free reads, e.g. `rig balance`), a missing uplink is\n * tolerated instead of throwing {@link MissingUplinkError}.\n */\n requireUplink?: boolean;\n warn: (line: string) => void;\n}\n\n/** The resolved payment topology feeding the embedded client config. */\nexport interface NetworkTopology {\n proxyUrl?: string;\n btpUrl?: string;\n /** Channel anchor / default ILP destination. */\n destination: string;\n publishDestination?: string;\n storeDestination?: string;\n /** The peer the embedded client bootstraps + negotiates with. */\n knownPeers: { pubkey: string; relayUrl: string; btpEndpoint: string }[];\n /**\n * FLAT per-packet route prices the peer announces for the effective\n * publish/store destinations (kind:10032 `capabilities`; base-unit integer\n * strings — this document is JSON-cached). The connector rejects any\n * balance-proof claim advancing the channel by less than the destination\n * route's price (F06), so the publisher floors its per-packet fees here.\n */\n routePrices?: { publish?: string; store?: string };\n /** The selected settlement chain + rationale (absent: nothing known). */\n selection?: ChainSelection;\n supportedChains?: string[];\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n chainRpcUrls?: Record<string, string>;\n /**\n * Solana channel parameters derived for the (first) `solana:*` chain in\n * play — the config-ready `ToonClientConfig.solanaChannel` shape. Absent\n * when no Solana chain is supported or an explicit `solanaChannel` config\n * object already covers it (explicit rides through verbatim).\n */\n solanaChannel?: { rpcUrl: string; programId: string; tokenMint?: string };\n /**\n * Mina channel parameters derived for the (first) `mina:*` chain in play —\n * the config-ready `ToonClientConfig.minaChannel` shape. Absent when no Mina\n * chain is supported or an explicit `minaChannel` config object already\n * covers it (explicit rides through verbatim).\n */\n minaChannel?: {\n graphqlUrl: string;\n zkAppAddress: string;\n tokenId?: string;\n networkId?: 'devnet' | 'mainnet';\n };\n}\n\n/**\n * Build the embedded client's `minaChannel` from one resolved settlement — or\n * throw the actionable {@link MinaChannelUnderivableError} naming the missing\n * pieces. A Mina chain in play with no way to open its channel must fail HERE,\n * not later as the embedded client's generic \"Mina channel config not\n * provided\". The required pieces are `graphqlUrl` (from a core preset) and\n * `zkAppAddress` (from the live announce); `tokenId`/`networkId` ride through\n * when present (a Mina channel with no token id opens on native MINA).\n */\n/**\n * The `autoDeploy` block attached to a DERIVED `minaChannel` (an explicit\n * config object keeps the pin-a-zkApp semantics and never auto-deploys):\n * reuse the recorded per-pair zkApp when one exists, persist a fresh\n * deployment's key BEFORE the open proceeds (losing it strands the ~1.1 MINA\n * the deployment cost), and route the slow compile/deploy/inclusion progress\n * to the warn stream.\n */\nexport function buildMinaAutoDeploy(\n dir: string,\n identityPubkey: string,\n chain: string,\n warn: (line: string) => void\n): NonNullable<NonNullable<ToonClientConfig['minaChannel']>['autoDeploy']> {\n const store = MinaZkAppStore.forHome(dir);\n let existing: ReturnType<MinaZkAppStore['lookup']>;\n try {\n existing = store.lookup(identityPubkey, chain);\n } catch (err) {\n warn(\n `rig: unreadable Mina zkApp store at ${store.filePath} ` +\n `(${err instanceof Error ? err.message : String(err)}) — a fresh ` +\n 'zkApp may be deployed'\n );\n }\n return {\n ...(existing\n ? {\n deployed: {\n zkAppAddress: existing.zkAppAddress,\n zkAppPrivateKey: existing.zkAppPrivateKey,\n },\n }\n : {}),\n // Persist the zkApp key BEFORE the deploy tx is sent (bug #3): a crash or\n // failed cache-invalidation retry between send and confirmation then finds\n // this record next run and REDEPLOYS the same address, instead of paying\n // the ~1.1-MINA account-creation fee for a brand-new zkApp every attempt.\n onDeploying: (record) => {\n store.save({\n identity: identityPubkey,\n chain,\n zkAppAddress: record.zkAppAddress,\n zkAppPrivateKey: record.zkAppPrivateKey,\n feePayer: record.feePayer,\n deployedAt: new Date().toISOString(),\n source:\n 'rig auto-deploy (npm @toon-protocol/mina-zkapp build, pending)',\n });\n warn(\n `rig: recorded pending Mina zkApp ${record.zkAppAddress} before ` +\n `deploy — key saved to ${store.filePath} (reused on retry)`\n );\n },\n onDeployed: (record) => {\n store.save({\n identity: identityPubkey,\n chain,\n zkAppAddress: record.zkAppAddress,\n zkAppPrivateKey: record.zkAppPrivateKey,\n feePayer: record.feePayer,\n ...(record.deployTxHash !== undefined\n ? { deployTxHash: record.deployTxHash }\n : {}),\n ...(record.vkHash !== undefined ? { vkHash: record.vkHash } : {}),\n deployedAt: new Date().toISOString(),\n source: 'rig auto-deploy (npm @toon-protocol/mina-zkapp build)',\n });\n warn(\n `rig: deployed a dedicated Mina PaymentChannel zkApp ` +\n `${record.zkAppAddress} — key saved to ${store.filePath}`\n );\n },\n onProgress: (line) => warn(`rig: mina: ${line}`),\n };\n}\n\nfunction deriveMinaChannel(\n settlement: ChainSettlement,\n announce: AnnouncedPeer | undefined,\n relayUrl: string\n): NonNullable<NetworkTopology['minaChannel']> {\n const { rpcUrl, zkAppAddress, minaTokenId, networkId } = settlement;\n if (!rpcUrl || !zkAppAddress) {\n const missing = [\n ...(rpcUrl ? [] : ['graphqlUrl']),\n ...(zkAppAddress ? [] : ['zkAppAddress']),\n ];\n throw new MinaChannelUnderivableError(\n settlement.chain,\n missing,\n announce,\n relayUrl\n );\n }\n return {\n graphqlUrl: rpcUrl,\n zkAppAddress,\n ...(minaTokenId ? { tokenId: minaTokenId } : {}),\n ...(networkId ? { networkId } : {}),\n };\n}\n\n/**\n * Build the embedded client's `solanaChannel` from one resolved settlement —\n * or throw the actionable {@link SolanaChannelUnderivableError} naming the\n * missing pieces. A Solana chain in play with no way to open its channel must\n * fail HERE, not later as the embedded client's generic \"Solana channel\n * config not provided\".\n */\nfunction deriveSolanaChannel(\n settlement: ChainSettlement,\n announce: AnnouncedPeer | undefined,\n relayUrl: string\n): NonNullable<NetworkTopology['solanaChannel']> {\n const { rpcUrl, programId, tokenAddress } = settlement;\n if (!rpcUrl || !programId || !tokenAddress) {\n const missing = [\n ...(rpcUrl ? [] : ['rpcUrl']),\n ...(programId ? [] : ['programId']),\n ...(tokenAddress ? [] : ['tokenMint']),\n ];\n throw new SolanaChannelUnderivableError(\n settlement.chain,\n missing,\n announce,\n relayUrl\n );\n }\n return { rpcUrl, programId, tokenMint: tokenAddress };\n}\n\n/**\n * Resolve the payment topology per the #264 precedence order —\n * `explicit config > live announce > genesis seed` for every field, plus the\n * documented settlement-chain selection rule (see\n * `../standalone/network-bootstrap.ts`).\n *\n * @throws {MissingUplinkError} when no source yields an uplink.\n * @throws {TokenNetworkUnderivableError} when the selected EVM chain's\n * TokenNetwork cannot be derived from config, announce, or chain preset.\n */\nexport async function resolveNetworkTopology(\n inputs: NetworkTopologyInputs\n): Promise<NetworkTopology> {\n const { env, file, configPath, relayUrl, announce, genesisSeed, warn } =\n inputs;\n\n // ── Explicit config (always wins, per field) ─────────────────────────────\n const explicitProxyUrl = env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl;\n const explicitBtpUrl = env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl;\n const explicitDestination =\n env['TOON_CLIENT_DESTINATION'] ?? file.destination;\n const explicitPublish =\n env['TOON_CLIENT_PUBLISH_DESTINATION'] ?? file.publishDestination;\n const explicitStore =\n env['TOON_CLIENT_STORE_DESTINATION'] ?? file.storeDestination;\n const explicitChain = env['TOON_CLIENT_CHAIN'] ?? file.chain;\n const explicitMaps: ExplicitChainConfig = {\n ...(file.chainRpcUrls ? { chainRpcUrls: file.chainRpcUrls } : {}),\n ...(file.preferredTokens ? { preferredTokens: file.preferredTokens } : {}),\n ...(file.tokenNetworks ? { tokenNetworks: file.tokenNetworks } : {}),\n };\n\n // ── Uplink: explicit > THE OFFICIAL EDGE ─────────────────────────────────\n // The cutover (connector #616): the Rust connector is the official TOON\n // relay implementation, so with no explicit entry the uplink IS the\n // official edge — the live announce and the genesis seed no longer place\n // the uplink (they still inform the destination anchor, routes, prices\n // and bootstrap peers below). Opting onto another fleet is what\n // `rig entry <url>` / `rig entry sandbox` and the TOON_CLIENT_* env\n // overrides are for, and those are all EXPLICIT. `MissingUplinkError`\n // can no longer fire from here — an uplink always resolves.\n let proxyUrl = explicitProxyUrl;\n const btpUrl = explicitBtpUrl;\n if (!proxyUrl && !btpUrl) {\n proxyUrl = OFFICIAL_PROXY_URL;\n }\n\n // ── Destination anchor + publish/store routes ────────────────────────────\n // The channel anchors at the peer's announced ilpAddress; publish/store\n // routes come from the announce's `routes` map. Explicit values always\n // win; with neither, the publisher's `<base>.relay.store` anchor-derivation\n // convention remains as the last-resort fallback (explicit anchors only).\n const destination =\n explicitDestination ??\n announce?.info.ilpAddress ??\n genesisSeed?.ilpAddress ??\n 'g.proxy';\n const publishDestination =\n explicitPublish ??\n announce?.routes?.publish ??\n (proxyUrl === OFFICIAL_PROXY_URL\n ? OFFICIAL_PUBLISH_DESTINATION\n : undefined);\n const storeDestination = explicitStore ?? announce?.routes?.store;\n\n // ── Route-price floors ───────────────────────────────────────────────────\n // The announce's `capabilities` carry a FLAT price per destination route,\n // and the connector gates every paid packet at it (a claim advancing the\n // channel by less is rejected — F06). Match the announced prices against\n // the EFFECTIVE publish/store destinations — including the publisher's\n // `<base>.relay.store` anchor-derivation fallback, so the floor applies\n // exactly when a paid write would actually target the priced route. An\n // unmatched destination gets no floor (behavior unchanged).\n let routePrices: NetworkTopology['routePrices'];\n const capabilities = announce?.capabilities;\n if (capabilities && capabilities.length > 0) {\n const derived = deriveRouteDestinations(destination);\n const priceOf = (address: string): string | undefined =>\n capabilities.find((c) => c.address === address)?.price;\n const publishPrice = priceOf(publishDestination ?? derived.publish);\n const storePrice = priceOf(storeDestination ?? derived.store);\n if (publishPrice !== undefined || storePrice !== undefined) {\n routePrices = {\n ...(publishPrice !== undefined ? { publish: publishPrice } : {}),\n ...(storePrice !== undefined ? { store: storePrice } : {}),\n };\n }\n }\n\n // ── Known peer for the embedded client's own bootstrap ───────────────────\n // The client re-queries the peer's announce itself (its internal core) and\n // negotiates the settlement chain; rig just tells it WHO to bootstrap with.\n const knownPeers = announce\n ? [\n {\n pubkey: announce.pubkey,\n relayUrl,\n btpEndpoint: announce.info.btpEndpoint ?? '',\n },\n ]\n : genesisSeed\n ? [\n {\n pubkey: genesisSeed.pubkey,\n relayUrl: genesisSeed.relayUrl,\n btpEndpoint: genesisSeed.btpEndpoint,\n },\n ]\n : [];\n\n // ── Settlement chain + per-chain parameters ──────────────────────────────\n // NOTE: the `network` preset field is deliberately NOT forwarded to the\n // embedded client. `applyNetworkPresets` puts preset chains FIRST in\n // `supportedChains`, which is what steered devnet negotiation to the\n // unfunded public Solana preset (#260 root cause 4). The announce + the\n // rule below define the chain; presets only serve as per-chain parameter\n // fallbacks inside `resolveChainSettlement`.\n const announcedChains = announce?.info.supportedChains ?? [];\n const resolveSettlement = (chain: string) =>\n resolveChainSettlement(chain, explicitMaps, announce);\n\n let selection: ChainSelection | undefined;\n let supportedChains: string[] | undefined;\n let preferredTokens: Record<string, string> | undefined;\n let tokenNetworks: Record<string, string> | undefined;\n let chainRpcUrls: Record<string, string> | undefined;\n let solanaChannel: NetworkTopology['solanaChannel'];\n let minaChannel: NetworkTopology['minaChannel'];\n\n if (file.supportedChains?.length) {\n // Explicit chain list: pass through in order (its order IS the\n // negotiation preference), filling per-chain parameter gaps from\n // announce/presets.\n const listed = file.supportedChains;\n const kept: string[] = [];\n let firstDropError: unknown;\n preferredTokens = { ...file.preferredTokens };\n tokenNetworks = { ...file.tokenNetworks };\n chainRpcUrls = { ...file.chainRpcUrls };\n for (const chain of listed) {\n const s = resolveSettlement(chain);\n // Chain negotiation is an EXACT string intersection of the two chain\n // lists — a spelling difference for the same chain (config\n // `evm:base:31337` vs announced `evm:31337`) silently strands the\n // chain and negotiation falls through to whatever else matches. When\n // a listed EVM chain names the same numeric chain id as an announced\n // one, advertise the ANNOUNCED spelling (parameters resolved from the\n // configured spelling carry over).\n let key = chain;\n if (s.family === 'evm' && !announcedChains.includes(chain)) {\n const chainId = evmChainIdOf(chain);\n const equivalent =\n chainId !== undefined\n ? announcedChains.find((c) => evmChainIdOf(c) === chainId)\n : undefined;\n if (equivalent) {\n warn(\n `rig: aligning configured settlement chain \"${chain}\" to the ` +\n `announced spelling \"${equivalent}\" (same EVM chain id ` +\n `${chainId}) — chain negotiation matches identifiers exactly`\n );\n key = equivalent;\n }\n }\n if (kept.includes(key)) continue;\n if (s.tokenAddress && !preferredTokens[key]) {\n preferredTokens[key] = s.tokenAddress;\n }\n if (s.tokenNetwork && !tokenNetworks[key]) {\n tokenNetworks[key] = s.tokenNetwork;\n }\n if (s.rpcUrl && !chainRpcUrls[key]) {\n chainRpcUrls[key] = s.rpcUrl;\n }\n // Same fail-fast guarantee as the announce/selection path below: an\n // explicitly configured EVM chain whose TokenNetwork/RPC cannot be\n // derived must fail HERE with an actionable error, not later as the\n // embedded client's generic \"tokenNetwork address is required\".\n if (s.family === 'evm') {\n if (!tokenNetworks[key]) {\n throw new TokenNetworkUnderivableError(chain, announce, relayUrl);\n }\n if (!chainRpcUrls[key]) {\n throw new Error(\n `no RPC URL is derivable for settlement chain \"${chain}\"` +\n ` — add chainRpcUrls[\"${chain}\"] to ${configPath}`\n );\n }\n }\n // A listed Solana chain is advertised to negotiation, which may pick\n // it — so its channel parameters must be derivable NOW. An explicit\n // solanaChannel config object covers it (rides through to the embedded\n // client verbatim); otherwise the first derivable Solana chain\n // provides the channel params, and an UNDERIVABLE one is dropped from\n // the advertised list (warned, with the remedy) instead of leaving a\n // chain in play that the on-chain open is guaranteed to die on.\n if (s.family === 'solana' && !file.solanaChannel) {\n if (solanaChannel) {\n // The embedded client carries ONE solanaChannel — a second Solana\n // chain cannot be honored with distinct params.\n kept.push(key);\n continue;\n }\n try {\n solanaChannel = deriveSolanaChannel(s, announce, relayUrl);\n } catch (err) {\n firstDropError ??= err;\n warn(\n `rig: dropping settlement chain ${chain} from the configured ` +\n `supportedChains — ${err instanceof Error ? err.message : String(err)}`\n );\n continue;\n }\n }\n // A listed Mina chain: same fail-fast contract as Solana. An explicit\n // minaChannel config covers it (rides through verbatim); otherwise the\n // first derivable Mina chain provides the channel params, and an\n // UNDERIVABLE one is dropped from the advertised list (warned) instead of\n // leaving a chain in play the on-chain open is guaranteed to die on.\n if (s.family === 'mina' && !file.minaChannel) {\n if (minaChannel) {\n kept.push(key);\n continue;\n }\n try {\n minaChannel = deriveMinaChannel(s, announce, relayUrl);\n } catch (err) {\n firstDropError ??= err;\n warn(\n `rig: dropping settlement chain ${chain} from the configured ` +\n `supportedChains — ${err instanceof Error ? err.message : String(err)}`\n );\n continue;\n }\n }\n kept.push(key);\n }\n if (kept.length === 0) {\n // Every listed chain was dropped — surface the first underivable\n // error instead of negotiating with an empty chain list.\n throw firstDropError;\n }\n supportedChains = kept;\n // The embedded client validates chainRpcUrls keys ⊆ supportedChains, so\n // entries for dropped/re-spelled chains must not survive; prune all\n // three chain-keyed maps to the advertised list for coherence.\n const advertised = new Set(kept);\n const prune = (map: Record<string, string>): Record<string, string> =>\n Object.fromEntries(\n Object.entries(map).filter(([chain]) => advertised.has(chain))\n );\n preferredTokens = prune(preferredTokens);\n tokenNetworks = prune(tokenNetworks);\n chainRpcUrls = prune(chainRpcUrls);\n selection = {\n chain: supportedChains[0] as string,\n reason: 'explicit',\n detail: 'supportedChains set by config',\n };\n } else if (explicitChain || announcedChains.length > 0) {\n // Selection rule: explicit > persisted channel > funded > first EVM.\n const { secretKey } = deriveNostrKeyFromMnemonic(\n inputs.identity.mnemonic,\n inputs.identity.accountIndex\n );\n const evmAddress = new EvmSigner(secretKey).address;\n // The Solana funded-chain probe needs the identity's base58 Solana\n // address, derived pre-client-start via the client's own SLIP-0010\n // helper (same paths the embedded client uses, so the probed address IS\n // the one the client will settle with). Only derived when a `solana:*`\n // chain is actually announced and no explicit chain pins selection\n // anyway; `deriveFullIdentity` degrades to an empty publicKey when the\n // Ed25519 deps are unavailable — then Solana chains are not probed.\n let solanaAddress: string | undefined;\n if (\n !explicitChain &&\n announcedChains.some((c) => c.startsWith('solana:'))\n ) {\n const fullIdentity = await deriveFullIdentity(\n inputs.identity.mnemonic,\n inputs.identity.accountIndex\n );\n solanaAddress = fullIdentity.solana.publicKey || undefined;\n // Only the address is needed here — drop the derived key material.\n fullIdentity.nostr.secretKey.fill(0);\n fullIdentity.evm.privateKey.fill(0);\n fullIdentity.solana.secretKey.fill(0);\n }\n selection = await selectSettlementChain({\n ...(explicitChain ? { explicitChain } : {}),\n announcedChains,\n records: inputs.channelRecords(),\n evmAddress,\n ...(solanaAddress ? { solanaAddress } : {}),\n resolveSettlement,\n probeBalance: inputs.probeBalance ?? evmTokenBalance,\n probeSolanaBalance: inputs.probeSolanaBalance ?? solanaTokenBalance,\n });\n const settlement = resolveSettlement(selection.chain);\n if (settlement.family === 'evm') {\n if (!settlement.tokenNetwork) {\n throw new TokenNetworkUnderivableError(\n selection.chain,\n announce,\n relayUrl\n );\n }\n if (!settlement.rpcUrl) {\n throw new Error(\n `no RPC URL is derivable for settlement chain \"${selection.chain}\"` +\n ` — add chainRpcUrls[\"${selection.chain}\"] to ${configPath}`\n );\n }\n }\n // Same fail-fast for a selected Solana chain: its channel parameters\n // must be derivable now (an explicit solanaChannel config covers it).\n if (settlement.family === 'solana' && !file.solanaChannel) {\n solanaChannel = deriveSolanaChannel(settlement, announce, relayUrl);\n }\n // Same fail-fast for a selected Mina chain (an explicit minaChannel covers it).\n if (settlement.family === 'mina' && !file.minaChannel) {\n minaChannel = deriveMinaChannel(settlement, announce, relayUrl);\n }\n supportedChains = [selection.chain];\n preferredTokens = settlement.tokenAddress\n ? { [selection.chain]: settlement.tokenAddress }\n : undefined;\n tokenNetworks = settlement.tokenNetwork\n ? { [selection.chain]: settlement.tokenNetwork }\n : undefined;\n chainRpcUrls = settlement.rpcUrl\n ? { [selection.chain]: settlement.rpcUrl }\n : undefined;\n if (selection.reason !== 'explicit') {\n warn(\n `rig: settlement chain ${selection.chain} selected — ` +\n `${selection.detail}; set TOON_CLIENT_CHAIN (or supportedChains ` +\n 'in the client config) to override'\n );\n } else if (explicitChain && selection.chain !== explicitChain) {\n // The explicit pin was re-spelled to the announced chain id (chain\n // negotiation matches identifiers exactly) — say so, like the\n // configured-supportedChains path does.\n warn(\n `rig: aligning configured settlement chain \"${explicitChain}\" to ` +\n `the announced spelling \"${selection.chain}\" — ${selection.detail}`\n );\n }\n } else {\n warn(\n 'rig: no settlement chains are configured or announced — paid writes ' +\n 'will fail until a chain is configured (supportedChains) or the ' +\n `payment peer announces its chains on ${relayUrl}`\n );\n }\n\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n if (network && network !== 'custom' && !file.supportedChains?.length) {\n warn(\n `rig: ignoring the \"${network}\" network preset for settlement — the ` +\n \"settlement chain comes from the payment peer's announce and your \" +\n 'config, because preset chains can point at networks your wallet ' +\n 'has no funds on; set supportedChains explicitly to use preset chains'\n );\n }\n\n return {\n ...(proxyUrl ? { proxyUrl } : {}),\n ...(btpUrl ? { btpUrl } : {}),\n destination,\n ...(publishDestination ? { publishDestination } : {}),\n ...(storeDestination ? { storeDestination } : {}),\n ...(routePrices ? { routePrices } : {}),\n knownPeers,\n ...(selection ? { selection } : {}),\n ...(supportedChains ? { supportedChains } : {}),\n ...(preferredTokens && Object.keys(preferredTokens).length > 0\n ? { preferredTokens }\n : {}),\n ...(tokenNetworks && Object.keys(tokenNetworks).length > 0\n ? { tokenNetworks }\n : {}),\n ...(chainRpcUrls && Object.keys(chainRpcUrls).length > 0\n ? { chainRpcUrls }\n : {}),\n ...(solanaChannel ? { solanaChannel } : {}),\n ...(minaChannel ? { minaChannel } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cached-topology recovery (#279)\n// ---------------------------------------------------------------------------\n\n/** Structural check for a cached {@link NetworkTopology} document. */\nfunction isNetworkTopology(value: unknown): value is NetworkTopology {\n if (typeof value !== 'object' || value === null) return false;\n const t = value as Record<string, unknown>;\n return typeof t['destination'] === 'string' && Array.isArray(t['knownPeers']);\n}\n\n/**\n * Start failures that must NEVER trigger a cache-invalidation retry: they\n * are concurrency/state guards, not topology staleness — retrying would\n * bypass exactly what they protect.\n */\nconst NON_RECOVERABLE_START_ERRORS: ReadonlySet<string> = new Set([\n 'DaemonIdentityConflictError',\n 'StandaloneLockError',\n 'ChannelMapCorruptError',\n // An unfunded Mina fee payer is a wallet-funding problem, not topology\n // staleness — re-resolving the topology cannot fix it, so retrying would\n // just re-run the (already fail-fast) preflight for nothing.\n 'MinaFeePayerUnfundedError',\n]);\n\n/**\n * Publisher wrapper implementing the #279 cache-invalidation contract: when\n * the inner publisher was built from a CACHED topology and its bootstrap\n * (`start`/`startClientOnly`) fails, the cache entry is invalidated, the\n * topology is re-resolved LIVE, a fresh publisher replaces the inner one,\n * and the operation proceeds — one retry, never more. Bootstrap failures\n * are pre-payment by construction (start() completes before any claim is\n * signed), so the retry can never double-pay. Publishers built from a live\n * resolution get no recovery hook and fail through unchanged.\n */\nclass TopologyRecoveringPublisher implements Publisher {\n private inner: StandalonePublisher;\n private rebuild: (() => Promise<StandalonePublisher>) | undefined;\n private readonly warn: (line: string) => void;\n\n constructor(\n inner: StandalonePublisher,\n rebuild: (() => Promise<StandalonePublisher>) | undefined,\n warn: (line: string) => void\n ) {\n this.inner = inner;\n this.rebuild = rebuild;\n this.warn = warn;\n }\n\n getPublicKey(): string {\n return this.inner.getPublicKey();\n }\n\n getFeeRates(): Promise<FeeRates> {\n return this.inner.getFeeRates();\n }\n\n /**\n * Run the bootstrap step, recovering ONCE from a stale cached topology.\n * A rebuild failure surfaces the LIVE resolution's error — that is the\n * network's real state, strictly more actionable than the cached failure.\n */\n private async ensure(\n start: (p: StandalonePublisher) => Promise<void>\n ): Promise<StandalonePublisher> {\n try {\n await start(this.inner);\n return this.inner;\n } catch (err) {\n const rebuild = this.rebuild;\n this.rebuild = undefined;\n const name = err instanceof Error ? err.name : '';\n if (!rebuild || NON_RECOVERABLE_START_ERRORS.has(name)) throw err;\n this.warn(\n 'rig: bootstrap with the cached network topology failed ' +\n `(${err instanceof Error ? err.message : String(err)}) — ` +\n 'invalidating the cache and re-resolving live'\n );\n const fresh = await rebuild();\n try {\n // Failed starts release their own lock/state; stop() is idempotent.\n await this.inner.stop();\n } catch {\n // best-effort teardown of the abandoned publisher\n }\n this.inner = fresh;\n await start(this.inner);\n return this.inner;\n }\n }\n\n async publishEvent(\n event: UnsignedEvent,\n relayUrls: string[]\n ): Promise<PublishReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.publishEvent(event, relayUrls);\n }\n\n async uploadGitObject(upload: GitObjectUpload): Promise<UploadReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.uploadGitObject(upload);\n }\n\n async uploadBlob(upload: BlobUpload): Promise<UploadReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.uploadBlob(upload);\n }\n\n // ── money lifecycle passthroughs (#263) — same recovery contract ─────────\n\n async openChannelExplicit(\n opts?: Parameters<StandalonePublisher['openChannelExplicit']>[0]\n ): ReturnType<StandalonePublisher['openChannelExplicit']> {\n const p = await this.ensure((x) => x.start());\n return p.openChannelExplicit(opts);\n }\n\n async closeRecordedChannel(\n record: ChannelMapRecord\n ): ReturnType<StandalonePublisher['closeRecordedChannel']> {\n const p = await this.ensure((x) => x.startClientOnly());\n return p.closeRecordedChannel(record);\n }\n\n async settleRecordedChannel(\n record: ChannelMapRecord\n ): ReturnType<StandalonePublisher['settleRecordedChannel']> {\n const p = await this.ensure((x) => x.startClientOnly());\n return p.settleRecordedChannel(record);\n }\n\n /** Free read on the unstarted client — no bootstrap, no recovery needed. */\n readWalletChainBalances(\n ...args: Parameters<StandalonePublisher['readWalletChainBalances']>\n ): ReturnType<StandalonePublisher['readWalletChainBalances']> {\n return this.inner.readWalletChainBalances(...args);\n }\n\n async stop(): Promise<void> {\n await this.inner.stop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context factory\n// ---------------------------------------------------------------------------\n\n/**\n * #262 channel-map records for this identity, reduced to the slice chain\n * selection consumes (`closed` folds in the claim-watermark timers).\n */\nfunction chainRecordsFor(\n map: ChannelMapStore,\n identity: string\n): ChannelRecordLike[] {\n return map\n .list()\n .filter((r) => r.identity === identity)\n .map((r) => {\n const watermark = map.readWatermark(r.channelId);\n return {\n chain: r.chain,\n lastUsedAt: r.lastUsedAt,\n closed:\n watermark?.closedAt !== undefined ||\n watermark?.settledAt !== undefined,\n };\n });\n}\n\n/**\n * Assemble an embedded-client standalone context: resolved identity + config\n * → network bootstrap (announce discovery / genesis seed) → ToonClientConfig\n * → nonce-guarded StandalonePublisher (guard + client start + channel open\n * happen lazily on the first paid call, or eagerly via the publisher's own\n * `start`).\n */\nexport async function createStandaloneContext(\n options: StandaloneLoadOptions\n): Promise<StandaloneContext> {\n const { env } = options;\n const warn = (line: string) => options.warn(line);\n const dir = configDir(env);\n const configPath = join(dir, 'config.json');\n const file = readClientConfig(configPath);\n const identity = await resolveIdentity(options);\n\n // Force-standalone override (RIG_STANDALONE / `rig --standalone`): when set,\n // the embedded publisher skips the same-identity daemon refusal so a running\n // toon-clientd never blocks the standalone path. The per-identity NonceLock\n // still guards against two standalone processes racing the claim watermark.\n const skipDaemonCheck = standaloneForced(env);\n if (skipDaemonCheck) {\n warn(\n 'rig: force-standalone (RIG_STANDALONE) — bypassing any running ' +\n 'toon-clientd; this rig process signs its own claims (stop the daemon ' +\n 'if it is also writing on this identity)'\n );\n }\n\n const genesisSeed = loadGenesisSeed();\n\n // ── Relay-origin ──────────────────────────────────────────────────────────\n // The relay the paid command resolved via `rig remote` (passed by the\n // command) is the user's clearest network statement; env/file follow, and\n // the genesis seed's relay is the out-of-the-box fallback.\n const relayUrl =\n options.relayUrl ??\n env['TOON_CLIENT_RELAY_URL'] ??\n file.relayUrl ??\n genesisSeed?.relayUrl ??\n // Last resort: the genesis seed normally supplies the relay, so this is\n // only reached when no seed/config/env relay is present. Point at the\n // shared public devnet relay rather than a dead local default.\n 'wss://relay-ws.devnet.toonprotocol.dev';\n\n // ── Peer→channel persistence (#262) ──────────────────────────────────────\n const channelStorePath = file.channelStorePath ?? join(dir, 'channels.json');\n const channelMap = new ChannelMapStore({\n mapPath: join(dir, RIG_CHANNEL_MAP_FILENAME),\n watermarkPath: channelStorePath,\n });\n\n // ── Topology cache (#279): keyed by relay-origin + identity + explicit\n // config; a hit skips discovery AND the pure-but-probing resolution below.\n const cache = new TopologyCache<NetworkTopology>({\n path: join(dir, TOPOLOGY_CACHE_FILENAME),\n ttlMs: topologyCacheTtlMs(env),\n validate: isNetworkTopology,\n });\n const cacheKey = topologyCacheKey({\n relayUrl,\n identity: identity.pubkey,\n fingerprint: explicitConfigFingerprint(\n env,\n file as Record<string, unknown>\n ),\n });\n\n const resolveLiveTopology = async (): Promise<NetworkTopology> => {\n // ── Live announce discovery ────────────────────────────────────────────\n // Skipped when explicit config already pins the whole payment topology\n // (fully-configured setups keep their zero-roundtrip start and their\n // exact pre-#264 behavior). A listed `solana:*` chain WITHOUT explicit\n // channel parameters is not fully pinned: the announce is a needed\n // parameter source (program id / mint), and skipping discovery would\n // also skip the announced-spelling alignment that keeps the chain list\n // negotiable. Discovery failure is non-fatal: warn + genesis seed.\n const solanaExplicitlyComplete = (file.supportedChains ?? []).every(\n (chain) =>\n !chain.startsWith('solana:') ||\n Boolean(file.solanaChannel) ||\n Boolean(\n file.tokenNetworks?.[chain] &&\n file.preferredTokens?.[chain] &&\n file.chainRpcUrls?.[chain]\n )\n );\n // A listed `mina:*` chain WITHOUT an explicit `minaChannel` is not fully\n // pinned either: the announce is the authoritative source for the\n // deployment's zkApp (and token id), so discovery must run. Only an\n // explicit `minaChannel` config makes a Mina chain announce-independent.\n const minaExplicitlyComplete = (file.supportedChains ?? []).every(\n (chain) => !chain.startsWith('mina:') || Boolean(file.minaChannel)\n );\n const fullyExplicit =\n Boolean(\n (env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl) ||\n (env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl)\n ) &&\n Boolean(env['TOON_CLIENT_DESTINATION'] ?? file.destination) &&\n Boolean(file.supportedChains?.length) &&\n solanaExplicitlyComplete &&\n minaExplicitlyComplete;\n let announce: AnnouncedPeer | undefined;\n if (!fullyExplicit) {\n try {\n const peers = await discoverAnnouncedPeers(relayUrl, {\n timeoutMs: DISCOVERY_TIMEOUT_MS,\n });\n announce = pickPaymentPeer(peers, genesisSeedPubkeys());\n if (!announce) {\n warn(\n `rig: no payment-peer announce (kind:10032) found on ${relayUrl} — ` +\n 'falling back to the genesis peer seed'\n );\n }\n } catch (err) {\n warn(\n `rig: announce discovery on ${relayUrl} failed ` +\n `(${err instanceof Error ? err.message : String(err)}) — falling ` +\n 'back to the genesis peer seed'\n );\n }\n }\n\n // ── Topology resolution (pure; explicit > announce > genesis) ──────────\n const resolved = await resolveNetworkTopology({\n env,\n file,\n configPath,\n relayUrl,\n announce,\n genesisSeed,\n identity: {\n mnemonic: identity.mnemonic,\n accountIndex: identity.accountIndex,\n pubkey: identity.pubkey,\n },\n channelRecords: () => chainRecordsFor(channelMap, identity.pubkey),\n ...(options.requireUplink !== undefined\n ? { requireUplink: options.requireUplink }\n : {}),\n warn,\n });\n // Cache only paid-path resolutions: a `requireUplink: false` free read\n // may resolve WITHOUT an uplink, and caching that would let a later paid\n // command skip past MissingUplinkError with a broken topology.\n if (options.requireUplink !== false) cache.write(cacheKey, resolved);\n return resolved;\n };\n\n const cached = cache.read(cacheKey);\n if (cached) {\n warn(\n `rig: network topology from cache (${Math.round(cached.ageMs / 1000)}s ` +\n `old; ${TOPOLOGY_TTL_ENV}=0 disables) — skipping announce discovery`\n );\n }\n const topology = cached?.topology ?? (await resolveLiveTopology());\n\n const eventFee = BigInt(file.feePerEvent ?? '1');\n\n const buildPublisher = (topo: NetworkTopology): StandalonePublisher => {\n const clientConfig: ToonClientConfig = {\n // validateConfig requires connectorUrl OR proxyUrl; with BTP-only\n // config a dummy connectorUrl satisfies it (unused at runtime — same\n // convention as the daemon).\n ...(topo.proxyUrl\n ? { proxyUrl: topo.proxyUrl }\n : { connectorUrl: 'http://127.0.0.1:1' }),\n mnemonic: identity.mnemonic,\n mnemonicAccountIndex: identity.accountIndex,\n ilpInfo: {\n pubkey: '00'.repeat(32),\n ilpAddress: 'g.toon.client',\n btpEndpoint: topo.btpUrl ?? '',\n assetCode: 'USD',\n assetScale: 6,\n },\n toonEncoder: encodeEventToToon,\n toonDecoder: decodeEventFromToon,\n ...(topo.btpUrl ? { btpUrl: topo.btpUrl, btpAuthToken: '' } : {}),\n destinationAddress: topo.destination,\n // The embedded client bootstraps against the known peer above; its\n // `relayUrl` config only seeds ArDrive-merged peers, so it stays unset.\n relayUrl: '',\n knownPeers: topo.knownPeers,\n channelStorePath,\n ...(topo.supportedChains\n ? { supportedChains: topo.supportedChains }\n : {}),\n ...(file.settlementAddresses\n ? { settlementAddresses: file.settlementAddresses }\n : {}),\n ...(topo.preferredTokens\n ? { preferredTokens: topo.preferredTokens }\n : {}),\n ...(topo.tokenNetworks ? { tokenNetworks: topo.tokenNetworks } : {}),\n ...(topo.chainRpcUrls ? { chainRpcUrls: topo.chainRpcUrls } : {}),\n // Solana channel params: an explicit config object wins verbatim; else\n // the topology's derivation (announce/presets — see resolveNetworkTopology).\n ...(file.solanaChannel\n ? { solanaChannel: file.solanaChannel }\n : topo.solanaChannel\n ? { solanaChannel: topo.solanaChannel }\n : {}),\n // Mina channel params: an explicit config object wins verbatim; else the\n // topology's derivation (announce zkApp/tokenId + preset graphqlUrl —\n // see resolveNetworkTopology / deriveMinaChannel).\n // An explicit config object keeps today's pin-a-zkApp semantics\n // verbatim. The DERIVED path additionally gets `autoDeploy`: the\n // announce/preset zkApp is shared and single-pair, so a fresh identity\n // can never open on it — the client checks on-chain ownership and\n // deploys a dedicated per-pair zkApp when needed, persisting the key\n // through the rig zkApp store (losing it would strand ~1.1 MINA).\n ...(file.minaChannel\n ? { minaChannel: file.minaChannel }\n : topo.minaChannel\n ? {\n minaChannel: {\n ...topo.minaChannel,\n autoDeploy: buildMinaAutoDeploy(\n dir,\n identity.pubkey,\n `mina:${topo.minaChannel.networkId ?? 'devnet'}`,\n warn\n ),\n },\n }\n : {}),\n };\n\n return new StandalonePublisher({\n clientConfig,\n eventFee,\n channelMap,\n warn,\n ...(skipDaemonCheck ? { skipDaemonCheck: true } : {}),\n ...(topo.publishDestination\n ? { publishDestination: topo.publishDestination }\n : {}),\n ...(topo.storeDestination\n ? { storeDestination: topo.storeDestination }\n : {}),\n // Route-price floors (F06): every per-packet claim must advance the\n // channel by at least the destination route's announced price.\n ...(topo.routePrices\n ? {\n routePrices: {\n ...(topo.routePrices.publish !== undefined\n ? { publish: BigInt(topo.routePrices.publish) }\n : {}),\n ...(topo.routePrices.store !== undefined\n ? { store: BigInt(topo.routePrices.store) }\n : {}),\n },\n }\n : {}),\n // `rig channel open --peer` (#263): anchor the channel (and its map\n // key) to an explicit peer destination instead of the configured\n // default.\n ...(options.channelDestination\n ? { channelDestination: options.channelDestination }\n : {}),\n // The peer's announce does not carry TokenNetwork/token parameters, so\n // the client's negotiation leaves them empty (#260 root cause 3) — the\n // publisher back-fills them from the derived per-chain maps before the\n // channel opens.\n ...(topo.tokenNetworks || topo.preferredTokens\n ? {\n negotiationFallbacks: {\n ...(topo.tokenNetworks\n ? { tokenNetworks: topo.tokenNetworks }\n : {}),\n ...(topo.preferredTokens\n ? { preferredTokens: topo.preferredTokens }\n : {}),\n },\n }\n : {}),\n });\n };\n\n // Cache-sourced publishers get the #279 recovery hook: a failed bootstrap\n // invalidates the entry, re-resolves live (which re-writes the cache), and\n // retries once. Live-resolved publishers fail through unchanged.\n const publisher = new TopologyRecoveringPublisher(\n buildPublisher(topology),\n cached\n ? async () => {\n cache.invalidate(cacheKey);\n return buildPublisher(await resolveLiveTopology());\n }\n : undefined,\n warn\n );\n\n // Wallet-view preset defaults (#299): when the identity has no configured\n // Solana/Mina channel (the common single-EVM-chain case), `rig balance` still\n // shows those chains — 0 for an account not yet on-chain — by reading the\n // named network's public RPC/GraphQL. Resolved HERE and passed only to the\n // wallet-view read, NOT merged into the client's settlement config: setting\n // `network` there would expand `supportedChains` via applyNetworkPresets and\n // change chain negotiation, which this deliberately avoids.\n const walletViewNetwork = env['TOON_CLIENT_NETWORK'] ?? file.network;\n let walletViewFallback: WalletViewFallback | undefined;\n if (\n walletViewNetwork === 'devnet' ||\n walletViewNetwork === 'testnet' ||\n walletViewNetwork === 'mainnet'\n ) {\n const presets = resolveClientNetwork(walletViewNetwork);\n walletViewFallback = {\n ...(presets.solanaChannel\n ? { solanaChannel: presets.solanaChannel }\n : {}),\n ...(presets.minaChannel ? { minaChannel: presets.minaChannel } : {}),\n };\n }\n\n return {\n ownerPubkey: publisher.getPublicKey(),\n identitySource: identity.source,\n identitySourceLabel: identity.sourceLabel,\n publisher,\n defaultRelayUrls: [relayUrl],\n fetchRemote: (args) => fetchRemoteState(args),\n // Money lifecycle (#263): same guard/start/channel-map machinery as the\n // paid-write path, surfaced for fund/balance/channel open|close|settle.\n money: {\n openChannel: (opts) => publisher.openChannelExplicit(opts),\n closeChannel: (record) => publisher.closeRecordedChannel(record),\n settleChannel: (record) => publisher.settleRecordedChannel(record),\n walletChainBalances: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;AAKA,QAAM,YAAY,IAAI;AAAA,IACpB,eAAe,QAAQ;AAAA,IACvB,SACI,YAAY;AACV,YAAM,WAAW,QAAQ;AACzB,aAAO,eAAe,MAAM,oBAAoB,CAAC;AAAA,IACnD,IACA;AAAA,IACJ;AAAA,EACF;AASA,QAAM,oBAAoB,IAAI,qBAAqB,KAAK,KAAK;AAC7D,MAAI;AACJ,MACE,sBAAsB,YACtB,sBAAsB,aACtB,sBAAsB,WACtB;AACA,UAAM,UAAU,qBAAqB,iBAAiB;AACtD,yBAAqB;AAAA,MACnB,GAAI,QAAQ,gBACR,EAAE,eAAe,QAAQ,cAAc,IACvC,CAAC;AAAA,MACL,GAAI,QAAQ,cAAc,EAAE,aAAa,QAAQ,YAAY,IAAI,CAAC;AAAA,IACpE;AAAA,EACF;AAEA,SAAO;AAAA,IACL,aAAa,UAAU,aAAa;AAAA,IACpC,gBAAgB,SAAS;AAAA,IACzB,qBAAqB,SAAS;AAAA,IAC9B;AAAA,IACA,kBAAkB,CAAC,QAAQ;AAAA,IAC3B,aAAa,CAAC,SAAS,iBAAiB,IAAI;AAAA;AAAA;AAAA,IAG5C,OAAO;AAAA,MACL,aAAa,CAAC,SAAS,UAAU,oBAAoB,IAAI;AAAA,MACzD,cAAc,CAAC,WAAW,UAAU,qBAAqB,MAAM;AAAA,MAC/D,eAAe,CAAC,WAAW,UAAU,sBAAsB,MAAM;AAAA,MACjE,qBAAqB,MACnB,UAAU,wBAAwB,kBAAkB;AAAA,IACxD;AAAA,IACA,MAAM,MAAM,UAAU,KAAK;AAAA,EAC7B;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toon-protocol/rig",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "Git-to-TOON write path core — build git objects and NIP-34 events for the Rig control plane",
5
5
  "license": "MIT",
6
6
  "author": "Jonathan Green",
@@ -43,7 +43,7 @@
43
43
  ],
44
44
  "dependencies": {
45
45
  "@toon-format/toon": "^1.0.0",
46
- "@toon-protocol/client": "^0.22.0",
46
+ "@toon-protocol/client": "^0.24.0",
47
47
  "@toon-protocol/core": "^3.1.2",
48
48
  "nostr-tools": "^2.20.0"
49
49
  },
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/standalone-mode.ts"],"sourcesContent":["/**\n * The embedded-client (standalone) publisher backing every paid `rig`\n * command: build a nonce-guarded {@link StandalonePublisher} from the\n * caller's own identity and config.\n *\n * Identity comes from the #248 precedence chain (`./identity.ts`:\n * RIG_MNEMONIC env → TOON_CLIENT_MNEMONIC env alias → project `.env` →\n * `~/.toon-client` keystore/config). The remaining config resolution\n * DUPLICATES the toon-clientd conventions\n * (`packages/client-mcp/src/daemon/config.ts`) the same way\n * `../standalone/nonce-guard.ts` does — this package must not import\n * `@toon-protocol/client-mcp` (circular; see that module's doc). Keep in sync:\n *\n * - state dir: `TOON_CLIENT_HOME`, else `~/.toon-client`; config `config.json`\n * - env overrides: `TOON_CLIENT_PROXY_URL`, `TOON_CLIENT_BTP_URL`,\n * `TOON_CLIENT_RELAY_URL`, `TOON_CLIENT_DESTINATION`,\n * `TOON_CLIENT_PUBLISH_DESTINATION`, `TOON_CLIENT_STORE_DESTINATION`,\n * `TOON_CLIENT_CHAIN`\n *\n * NETWORK BOOTSTRAP (#264): what explicit config does not pin is resolved\n * from the network itself — the payment peer's live kind:10032 announce on\n * the relay-origin, falling back to `@toon-protocol/core`'s committed\n * genesis peer seed. Uplink, channel anchor, publish/store routes, the\n * settlement chain and its TokenNetwork/token/RPC parameters all follow the\n * `explicit config > live announce > genesis seed` order documented in\n * `../standalone/network-bootstrap.ts`. The pure resolution lives in\n * {@link resolveNetworkTopology} (unit-testable without any network).\n *\n * TOPOLOGY CACHE (#279): the resolved topology is persisted under\n * `TOON_CLIENT_HOME` (`../standalone/topology-cache.ts`) keyed by\n * relay-origin + identity + an explicit-config fingerprint, with a 15-min\n * TTL (`RIG_TOPOLOGY_TTL_MS` overrides; `0` disables). A cache hit skips\n * announce discovery and the funded-chain probes entirely; a cached\n * topology that then fails to BOOTSTRAP is invalidated and re-resolved\n * live in-process ({@link TopologyRecoveringPublisher}), so staleness costs\n * one failed attempt, never a broken run. Only paid-path resolutions\n * (`requireUplink !== false`) are written — a free-read topology may lack\n * an uplink and must not shadow the paid path's MissingUplinkError.\n *\n * CORE COEXISTENCE NOTE: rig performs discovery with ITS OWN\n * `@toon-protocol/core` (^2.0.x — live genesis seed), while the embedded\n * `@toon-protocol/client` keeps its internal core (^1.6.x) for its own\n * bootstrap/negotiation. The two never exchange class instances — rig feeds\n * the client plain config (`knownPeers`, settlement maps), so the version\n * split is safe by construction.\n *\n * This module statically imports `@toon-protocol/client` (heavy: viem,\n * noble, nostr-tools), so it must only ever be reached through the dynamic\n * import in `push.ts` (see `./standalone-context.ts`).\n */\n\nimport { readFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { ToonClientConfig } from '@toon-protocol/client';\nimport {\n EvmSigner,\n deriveFullIdentity,\n deriveNostrKeyFromMnemonic,\n} from '@toon-protocol/client';\nimport {\n decodeEventFromToon,\n encodeEventToToon,\n resolveClientNetwork,\n} from '@toon-protocol/core';\nimport type {\n BlobUpload,\n FeeRates,\n GitObjectUpload,\n Publisher,\n PublishReceipt,\n UploadReceipt,\n} from '../publisher.js';\nimport type { UnsignedEvent } from '../nip34-events.js';\nimport {\n ChannelMapStore,\n RIG_CHANNEL_MAP_FILENAME,\n type ChannelMapRecord,\n} from '../standalone/channel-map.js';\nimport {\n TOPOLOGY_CACHE_FILENAME,\n TOPOLOGY_TTL_ENV,\n TopologyCache,\n explicitConfigFingerprint,\n topologyCacheKey,\n topologyCacheTtlMs,\n} from '../standalone/topology-cache.js';\nimport {\n DISCOVERY_TIMEOUT_MS,\n MinaChannelUnderivableError,\n SolanaChannelUnderivableError,\n TokenNetworkUnderivableError,\n discoverAnnouncedPeers,\n evmChainIdOf,\n evmTokenBalance,\n genesisSeedPubkeys,\n loadGenesisSeed,\n pickPaymentPeer,\n resolveChainSettlement,\n selectSettlementChain,\n solanaTokenBalance,\n type AnnouncedPeer,\n type ChainSelection,\n type ChainSettlement,\n type ChannelRecordLike,\n type EvmBalanceProbe,\n type ExplicitChainConfig,\n type SolanaBalanceProbe,\n} from '../standalone/network-bootstrap.js';\nimport {\n StandalonePublisher,\n deriveRouteDestinations,\n type WalletViewFallback,\n} from '../standalone/standalone-publisher.js';\nimport { standaloneForced } from '../standalone/nonce-guard.js';\nimport { fetchRemoteState } from '../remote-state.js';\nimport { MinaZkAppStore } from '../standalone/mina-zkapp-store.js';\nimport { resolveIdentity } from './identity.js';\nimport type {\n StandaloneContext,\n StandaloneLoadOptions,\n} from './standalone-context.js';\n\n/** The subset of the shared client config file standalone mode consumes. */\nexport interface ClientConfigFile {\n network?: 'mainnet' | 'testnet' | 'devnet' | 'custom';\n mnemonicAccountIndex?: number;\n btpUrl?: string;\n proxyUrl?: string;\n relayUrl?: string;\n destination?: string;\n publishDestination?: string;\n storeDestination?: string;\n feePerEvent?: string;\n channelStorePath?: string;\n /** Settlement chain: family (`evm`) or full id (`evm:31337`). */\n chain?: string;\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n chainRpcUrls?: Record<string, string>;\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n}\n\n/** An identity was resolved, but there is no way to send paid writes. */\nexport class MissingUplinkError extends Error {\n constructor(configPath: string, relayUrl: string | undefined) {\n const discovered = relayUrl\n ? `no announce with a btp/http endpoint was found on ${relayUrl} and ` +\n 'the genesis seed has none; '\n : '';\n super(\n `no write uplink configured: ${discovered}set TOON_CLIENT_PROXY_URL ` +\n '(connector payment proxy) or TOON_CLIENT_BTP_URL, or add ' +\n `proxyUrl/btpUrl to ${configPath}`\n );\n this.name = 'MissingUplinkError';\n }\n}\n\nfunction configDir(env: NodeJS.ProcessEnv): string {\n return env['TOON_CLIENT_HOME'] ?? join(homedir(), '.toon-client');\n}\n\nfunction readClientConfig(path: string): ClientConfigFile {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as ClientConfigFile;\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/** `https://host/ilp` → `https://host` (the client re-derives `/ilp`). */\nfunction proxyBaseOf(httpEndpoint: string): string {\n return httpEndpoint.replace(/\\/+$/, '').replace(/\\/ilp$/i, '');\n}\n\n// ---------------------------------------------------------------------------\n// Pure topology resolution (#264) — exported for tests\n// ---------------------------------------------------------------------------\n\n/** A genesis-seed peer as this module consumes it (rig's core 3.x shape). */\nexport interface GenesisSeedLike {\n pubkey: string;\n relayUrl: string;\n ilpAddress: string;\n btpEndpoint: string;\n}\n\n/** Inputs to {@link resolveNetworkTopology} (side-effect free). */\nexport interface NetworkTopologyInputs {\n env: NodeJS.ProcessEnv;\n file: ClientConfigFile;\n /** For error messages (\"add X to <configPath>\"). */\n configPath: string;\n /** Resolved relay-origin (already precedence-resolved). */\n relayUrl: string;\n /** The discovered payment-peer announce, if any. */\n announce: AnnouncedPeer | undefined;\n /** The committed genesis seed entry, if any. */\n genesisSeed: GenesisSeedLike | undefined;\n identity: { mnemonic: string; accountIndex: number; pubkey: string };\n /**\n * #262 channel-map records for this identity (chain selection input).\n * A thunk so the (possibly corrupt-throwing) map read only happens when\n * chain selection actually needs it.\n */\n channelRecords: () => ChannelRecordLike[];\n /** EVM balance probe override (tests); default: raw `eth_call`. */\n probeBalance?: EvmBalanceProbe;\n /**\n * Solana balance probe override (tests); default: raw\n * `getTokenAccountsByOwner`.\n */\n probeSolanaBalance?: SolanaBalanceProbe;\n /**\n * When false (#263 free reads, e.g. `rig balance`), a missing uplink is\n * tolerated instead of throwing {@link MissingUplinkError}.\n */\n requireUplink?: boolean;\n warn: (line: string) => void;\n}\n\n/** The resolved payment topology feeding the embedded client config. */\nexport interface NetworkTopology {\n proxyUrl?: string;\n btpUrl?: string;\n /** Channel anchor / default ILP destination. */\n destination: string;\n publishDestination?: string;\n storeDestination?: string;\n /** The peer the embedded client bootstraps + negotiates with. */\n knownPeers: { pubkey: string; relayUrl: string; btpEndpoint: string }[];\n /**\n * FLAT per-packet route prices the peer announces for the effective\n * publish/store destinations (kind:10032 `capabilities`; base-unit integer\n * strings — this document is JSON-cached). The connector rejects any\n * balance-proof claim advancing the channel by less than the destination\n * route's price (F06), so the publisher floors its per-packet fees here.\n */\n routePrices?: { publish?: string; store?: string };\n /** The selected settlement chain + rationale (absent: nothing known). */\n selection?: ChainSelection;\n supportedChains?: string[];\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n chainRpcUrls?: Record<string, string>;\n /**\n * Solana channel parameters derived for the (first) `solana:*` chain in\n * play — the config-ready `ToonClientConfig.solanaChannel` shape. Absent\n * when no Solana chain is supported or an explicit `solanaChannel` config\n * object already covers it (explicit rides through verbatim).\n */\n solanaChannel?: { rpcUrl: string; programId: string; tokenMint?: string };\n /**\n * Mina channel parameters derived for the (first) `mina:*` chain in play —\n * the config-ready `ToonClientConfig.minaChannel` shape. Absent when no Mina\n * chain is supported or an explicit `minaChannel` config object already\n * covers it (explicit rides through verbatim).\n */\n minaChannel?: {\n graphqlUrl: string;\n zkAppAddress: string;\n tokenId?: string;\n networkId?: 'devnet' | 'mainnet';\n };\n}\n\n/**\n * Build the embedded client's `minaChannel` from one resolved settlement — or\n * throw the actionable {@link MinaChannelUnderivableError} naming the missing\n * pieces. A Mina chain in play with no way to open its channel must fail HERE,\n * not later as the embedded client's generic \"Mina channel config not\n * provided\". The required pieces are `graphqlUrl` (from a core preset) and\n * `zkAppAddress` (from the live announce); `tokenId`/`networkId` ride through\n * when present (a Mina channel with no token id opens on native MINA).\n */\n/**\n * The `autoDeploy` block attached to a DERIVED `minaChannel` (an explicit\n * config object keeps the pin-a-zkApp semantics and never auto-deploys):\n * reuse the recorded per-pair zkApp when one exists, persist a fresh\n * deployment's key BEFORE the open proceeds (losing it strands the ~1.1 MINA\n * the deployment cost), and route the slow compile/deploy/inclusion progress\n * to the warn stream.\n */\nexport function buildMinaAutoDeploy(\n dir: string,\n identityPubkey: string,\n chain: string,\n warn: (line: string) => void\n): NonNullable<NonNullable<ToonClientConfig['minaChannel']>['autoDeploy']> {\n const store = MinaZkAppStore.forHome(dir);\n let existing: ReturnType<MinaZkAppStore['lookup']>;\n try {\n existing = store.lookup(identityPubkey, chain);\n } catch (err) {\n warn(\n `rig: unreadable Mina zkApp store at ${store.filePath} ` +\n `(${err instanceof Error ? err.message : String(err)}) — a fresh ` +\n 'zkApp may be deployed'\n );\n }\n return {\n ...(existing\n ? {\n deployed: {\n zkAppAddress: existing.zkAppAddress,\n zkAppPrivateKey: existing.zkAppPrivateKey,\n },\n }\n : {}),\n // Persist the zkApp key BEFORE the deploy tx is sent (bug #3): a crash or\n // failed cache-invalidation retry between send and confirmation then finds\n // this record next run and REDEPLOYS the same address, instead of paying\n // the ~1.1-MINA account-creation fee for a brand-new zkApp every attempt.\n onDeploying: (record) => {\n store.save({\n identity: identityPubkey,\n chain,\n zkAppAddress: record.zkAppAddress,\n zkAppPrivateKey: record.zkAppPrivateKey,\n feePayer: record.feePayer,\n deployedAt: new Date().toISOString(),\n source:\n 'rig auto-deploy (npm @toon-protocol/mina-zkapp build, pending)',\n });\n warn(\n `rig: recorded pending Mina zkApp ${record.zkAppAddress} before ` +\n `deploy — key saved to ${store.filePath} (reused on retry)`\n );\n },\n onDeployed: (record) => {\n store.save({\n identity: identityPubkey,\n chain,\n zkAppAddress: record.zkAppAddress,\n zkAppPrivateKey: record.zkAppPrivateKey,\n feePayer: record.feePayer,\n ...(record.deployTxHash !== undefined\n ? { deployTxHash: record.deployTxHash }\n : {}),\n ...(record.vkHash !== undefined ? { vkHash: record.vkHash } : {}),\n deployedAt: new Date().toISOString(),\n source: 'rig auto-deploy (npm @toon-protocol/mina-zkapp build)',\n });\n warn(\n `rig: deployed a dedicated Mina PaymentChannel zkApp ` +\n `${record.zkAppAddress} — key saved to ${store.filePath}`\n );\n },\n onProgress: (line) => warn(`rig: mina: ${line}`),\n };\n}\n\nfunction deriveMinaChannel(\n settlement: ChainSettlement,\n announce: AnnouncedPeer | undefined,\n relayUrl: string\n): NonNullable<NetworkTopology['minaChannel']> {\n const { rpcUrl, zkAppAddress, minaTokenId, networkId } = settlement;\n if (!rpcUrl || !zkAppAddress) {\n const missing = [\n ...(rpcUrl ? [] : ['graphqlUrl']),\n ...(zkAppAddress ? [] : ['zkAppAddress']),\n ];\n throw new MinaChannelUnderivableError(\n settlement.chain,\n missing,\n announce,\n relayUrl\n );\n }\n return {\n graphqlUrl: rpcUrl,\n zkAppAddress,\n ...(minaTokenId ? { tokenId: minaTokenId } : {}),\n ...(networkId ? { networkId } : {}),\n };\n}\n\n/**\n * Build the embedded client's `solanaChannel` from one resolved settlement —\n * or throw the actionable {@link SolanaChannelUnderivableError} naming the\n * missing pieces. A Solana chain in play with no way to open its channel must\n * fail HERE, not later as the embedded client's generic \"Solana channel\n * config not provided\".\n */\nfunction deriveSolanaChannel(\n settlement: ChainSettlement,\n announce: AnnouncedPeer | undefined,\n relayUrl: string\n): NonNullable<NetworkTopology['solanaChannel']> {\n const { rpcUrl, programId, tokenAddress } = settlement;\n if (!rpcUrl || !programId || !tokenAddress) {\n const missing = [\n ...(rpcUrl ? [] : ['rpcUrl']),\n ...(programId ? [] : ['programId']),\n ...(tokenAddress ? [] : ['tokenMint']),\n ];\n throw new SolanaChannelUnderivableError(\n settlement.chain,\n missing,\n announce,\n relayUrl\n );\n }\n return { rpcUrl, programId, tokenMint: tokenAddress };\n}\n\n/**\n * Resolve the payment topology per the #264 precedence order —\n * `explicit config > live announce > genesis seed` for every field, plus the\n * documented settlement-chain selection rule (see\n * `../standalone/network-bootstrap.ts`).\n *\n * @throws {MissingUplinkError} when no source yields an uplink.\n * @throws {TokenNetworkUnderivableError} when the selected EVM chain's\n * TokenNetwork cannot be derived from config, announce, or chain preset.\n */\nexport async function resolveNetworkTopology(\n inputs: NetworkTopologyInputs\n): Promise<NetworkTopology> {\n const { env, file, configPath, relayUrl, announce, genesisSeed, warn } =\n inputs;\n\n // ── Explicit config (always wins, per field) ─────────────────────────────\n const explicitProxyUrl = env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl;\n const explicitBtpUrl = env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl;\n const explicitDestination =\n env['TOON_CLIENT_DESTINATION'] ?? file.destination;\n const explicitPublish =\n env['TOON_CLIENT_PUBLISH_DESTINATION'] ?? file.publishDestination;\n const explicitStore =\n env['TOON_CLIENT_STORE_DESTINATION'] ?? file.storeDestination;\n const explicitChain = env['TOON_CLIENT_CHAIN'] ?? file.chain;\n const explicitMaps: ExplicitChainConfig = {\n ...(file.chainRpcUrls ? { chainRpcUrls: file.chainRpcUrls } : {}),\n ...(file.preferredTokens ? { preferredTokens: file.preferredTokens } : {}),\n ...(file.tokenNetworks ? { tokenNetworks: file.tokenNetworks } : {}),\n };\n\n // ── Uplink: explicit > announce (http > btp) > genesis seed ──────────────\n let proxyUrl = explicitProxyUrl;\n let btpUrl = explicitBtpUrl;\n if (!proxyUrl && !btpUrl) {\n if (announce?.info.httpEndpoint) {\n proxyUrl = proxyBaseOf(announce.info.httpEndpoint);\n } else if (announce?.info.btpEndpoint) {\n btpUrl = announce.info.btpEndpoint;\n } else if (genesisSeed?.btpEndpoint) {\n btpUrl = genesisSeed.btpEndpoint;\n } else if (inputs.requireUplink !== false) {\n // Free reads (`rig balance`, #263) tolerate a missing uplink; paid\n // commands fail here, after every source has been tried.\n throw new MissingUplinkError(configPath, relayUrl);\n }\n }\n\n // ── Destination anchor + publish/store routes ────────────────────────────\n // The channel anchors at the peer's announced ilpAddress; publish/store\n // routes come from the announce's `routes` map. Explicit values always\n // win; with neither, the publisher's `<base>.relay.store` anchor-derivation\n // convention remains as the last-resort fallback (explicit anchors only).\n const destination =\n explicitDestination ??\n announce?.info.ilpAddress ??\n genesisSeed?.ilpAddress ??\n 'g.proxy';\n const publishDestination = explicitPublish ?? announce?.routes?.publish;\n const storeDestination = explicitStore ?? announce?.routes?.store;\n\n // ── Route-price floors ───────────────────────────────────────────────────\n // The announce's `capabilities` carry a FLAT price per destination route,\n // and the connector gates every paid packet at it (a claim advancing the\n // channel by less is rejected — F06). Match the announced prices against\n // the EFFECTIVE publish/store destinations — including the publisher's\n // `<base>.relay.store` anchor-derivation fallback, so the floor applies\n // exactly when a paid write would actually target the priced route. An\n // unmatched destination gets no floor (behavior unchanged).\n let routePrices: NetworkTopology['routePrices'];\n const capabilities = announce?.capabilities;\n if (capabilities && capabilities.length > 0) {\n const derived = deriveRouteDestinations(destination);\n const priceOf = (address: string): string | undefined =>\n capabilities.find((c) => c.address === address)?.price;\n const publishPrice = priceOf(publishDestination ?? derived.publish);\n const storePrice = priceOf(storeDestination ?? derived.store);\n if (publishPrice !== undefined || storePrice !== undefined) {\n routePrices = {\n ...(publishPrice !== undefined ? { publish: publishPrice } : {}),\n ...(storePrice !== undefined ? { store: storePrice } : {}),\n };\n }\n }\n\n // ── Known peer for the embedded client's own bootstrap ───────────────────\n // The client re-queries the peer's announce itself (its internal core) and\n // negotiates the settlement chain; rig just tells it WHO to bootstrap with.\n const knownPeers = announce\n ? [\n {\n pubkey: announce.pubkey,\n relayUrl,\n btpEndpoint: announce.info.btpEndpoint ?? '',\n },\n ]\n : genesisSeed\n ? [\n {\n pubkey: genesisSeed.pubkey,\n relayUrl: genesisSeed.relayUrl,\n btpEndpoint: genesisSeed.btpEndpoint,\n },\n ]\n : [];\n\n // ── Settlement chain + per-chain parameters ──────────────────────────────\n // NOTE: the `network` preset field is deliberately NOT forwarded to the\n // embedded client. `applyNetworkPresets` puts preset chains FIRST in\n // `supportedChains`, which is what steered devnet negotiation to the\n // unfunded public Solana preset (#260 root cause 4). The announce + the\n // rule below define the chain; presets only serve as per-chain parameter\n // fallbacks inside `resolveChainSettlement`.\n const announcedChains = announce?.info.supportedChains ?? [];\n const resolveSettlement = (chain: string) =>\n resolveChainSettlement(chain, explicitMaps, announce);\n\n let selection: ChainSelection | undefined;\n let supportedChains: string[] | undefined;\n let preferredTokens: Record<string, string> | undefined;\n let tokenNetworks: Record<string, string> | undefined;\n let chainRpcUrls: Record<string, string> | undefined;\n let solanaChannel: NetworkTopology['solanaChannel'];\n let minaChannel: NetworkTopology['minaChannel'];\n\n if (file.supportedChains?.length) {\n // Explicit chain list: pass through in order (its order IS the\n // negotiation preference), filling per-chain parameter gaps from\n // announce/presets.\n const listed = file.supportedChains;\n const kept: string[] = [];\n let firstDropError: unknown;\n preferredTokens = { ...file.preferredTokens };\n tokenNetworks = { ...file.tokenNetworks };\n chainRpcUrls = { ...file.chainRpcUrls };\n for (const chain of listed) {\n const s = resolveSettlement(chain);\n // Chain negotiation is an EXACT string intersection of the two chain\n // lists — a spelling difference for the same chain (config\n // `evm:base:31337` vs announced `evm:31337`) silently strands the\n // chain and negotiation falls through to whatever else matches. When\n // a listed EVM chain names the same numeric chain id as an announced\n // one, advertise the ANNOUNCED spelling (parameters resolved from the\n // configured spelling carry over).\n let key = chain;\n if (s.family === 'evm' && !announcedChains.includes(chain)) {\n const chainId = evmChainIdOf(chain);\n const equivalent =\n chainId !== undefined\n ? announcedChains.find((c) => evmChainIdOf(c) === chainId)\n : undefined;\n if (equivalent) {\n warn(\n `rig: aligning configured settlement chain \"${chain}\" to the ` +\n `announced spelling \"${equivalent}\" (same EVM chain id ` +\n `${chainId}) — chain negotiation matches identifiers exactly`\n );\n key = equivalent;\n }\n }\n if (kept.includes(key)) continue;\n if (s.tokenAddress && !preferredTokens[key]) {\n preferredTokens[key] = s.tokenAddress;\n }\n if (s.tokenNetwork && !tokenNetworks[key]) {\n tokenNetworks[key] = s.tokenNetwork;\n }\n if (s.rpcUrl && !chainRpcUrls[key]) {\n chainRpcUrls[key] = s.rpcUrl;\n }\n // Same fail-fast guarantee as the announce/selection path below: an\n // explicitly configured EVM chain whose TokenNetwork/RPC cannot be\n // derived must fail HERE with an actionable error, not later as the\n // embedded client's generic \"tokenNetwork address is required\".\n if (s.family === 'evm') {\n if (!tokenNetworks[key]) {\n throw new TokenNetworkUnderivableError(chain, announce, relayUrl);\n }\n if (!chainRpcUrls[key]) {\n throw new Error(\n `no RPC URL is derivable for settlement chain \"${chain}\"` +\n ` — add chainRpcUrls[\"${chain}\"] to ${configPath}`\n );\n }\n }\n // A listed Solana chain is advertised to negotiation, which may pick\n // it — so its channel parameters must be derivable NOW. An explicit\n // solanaChannel config object covers it (rides through to the embedded\n // client verbatim); otherwise the first derivable Solana chain\n // provides the channel params, and an UNDERIVABLE one is dropped from\n // the advertised list (warned, with the remedy) instead of leaving a\n // chain in play that the on-chain open is guaranteed to die on.\n if (s.family === 'solana' && !file.solanaChannel) {\n if (solanaChannel) {\n // The embedded client carries ONE solanaChannel — a second Solana\n // chain cannot be honored with distinct params.\n kept.push(key);\n continue;\n }\n try {\n solanaChannel = deriveSolanaChannel(s, announce, relayUrl);\n } catch (err) {\n firstDropError ??= err;\n warn(\n `rig: dropping settlement chain ${chain} from the configured ` +\n `supportedChains — ${err instanceof Error ? err.message : String(err)}`\n );\n continue;\n }\n }\n // A listed Mina chain: same fail-fast contract as Solana. An explicit\n // minaChannel config covers it (rides through verbatim); otherwise the\n // first derivable Mina chain provides the channel params, and an\n // UNDERIVABLE one is dropped from the advertised list (warned) instead of\n // leaving a chain in play the on-chain open is guaranteed to die on.\n if (s.family === 'mina' && !file.minaChannel) {\n if (minaChannel) {\n kept.push(key);\n continue;\n }\n try {\n minaChannel = deriveMinaChannel(s, announce, relayUrl);\n } catch (err) {\n firstDropError ??= err;\n warn(\n `rig: dropping settlement chain ${chain} from the configured ` +\n `supportedChains — ${err instanceof Error ? err.message : String(err)}`\n );\n continue;\n }\n }\n kept.push(key);\n }\n if (kept.length === 0) {\n // Every listed chain was dropped — surface the first underivable\n // error instead of negotiating with an empty chain list.\n throw firstDropError;\n }\n supportedChains = kept;\n // The embedded client validates chainRpcUrls keys ⊆ supportedChains, so\n // entries for dropped/re-spelled chains must not survive; prune all\n // three chain-keyed maps to the advertised list for coherence.\n const advertised = new Set(kept);\n const prune = (map: Record<string, string>): Record<string, string> =>\n Object.fromEntries(\n Object.entries(map).filter(([chain]) => advertised.has(chain))\n );\n preferredTokens = prune(preferredTokens);\n tokenNetworks = prune(tokenNetworks);\n chainRpcUrls = prune(chainRpcUrls);\n selection = {\n chain: supportedChains[0] as string,\n reason: 'explicit',\n detail: 'supportedChains set by config',\n };\n } else if (explicitChain || announcedChains.length > 0) {\n // Selection rule: explicit > persisted channel > funded > first EVM.\n const { secretKey } = deriveNostrKeyFromMnemonic(\n inputs.identity.mnemonic,\n inputs.identity.accountIndex\n );\n const evmAddress = new EvmSigner(secretKey).address;\n // The Solana funded-chain probe needs the identity's base58 Solana\n // address, derived pre-client-start via the client's own SLIP-0010\n // helper (same paths the embedded client uses, so the probed address IS\n // the one the client will settle with). Only derived when a `solana:*`\n // chain is actually announced and no explicit chain pins selection\n // anyway; `deriveFullIdentity` degrades to an empty publicKey when the\n // Ed25519 deps are unavailable — then Solana chains are not probed.\n let solanaAddress: string | undefined;\n if (\n !explicitChain &&\n announcedChains.some((c) => c.startsWith('solana:'))\n ) {\n const fullIdentity = await deriveFullIdentity(\n inputs.identity.mnemonic,\n inputs.identity.accountIndex\n );\n solanaAddress = fullIdentity.solana.publicKey || undefined;\n // Only the address is needed here — drop the derived key material.\n fullIdentity.nostr.secretKey.fill(0);\n fullIdentity.evm.privateKey.fill(0);\n fullIdentity.solana.secretKey.fill(0);\n }\n selection = await selectSettlementChain({\n ...(explicitChain ? { explicitChain } : {}),\n announcedChains,\n records: inputs.channelRecords(),\n evmAddress,\n ...(solanaAddress ? { solanaAddress } : {}),\n resolveSettlement,\n probeBalance: inputs.probeBalance ?? evmTokenBalance,\n probeSolanaBalance: inputs.probeSolanaBalance ?? solanaTokenBalance,\n });\n const settlement = resolveSettlement(selection.chain);\n if (settlement.family === 'evm') {\n if (!settlement.tokenNetwork) {\n throw new TokenNetworkUnderivableError(\n selection.chain,\n announce,\n relayUrl\n );\n }\n if (!settlement.rpcUrl) {\n throw new Error(\n `no RPC URL is derivable for settlement chain \"${selection.chain}\"` +\n ` — add chainRpcUrls[\"${selection.chain}\"] to ${configPath}`\n );\n }\n }\n // Same fail-fast for a selected Solana chain: its channel parameters\n // must be derivable now (an explicit solanaChannel config covers it).\n if (settlement.family === 'solana' && !file.solanaChannel) {\n solanaChannel = deriveSolanaChannel(settlement, announce, relayUrl);\n }\n // Same fail-fast for a selected Mina chain (an explicit minaChannel covers it).\n if (settlement.family === 'mina' && !file.minaChannel) {\n minaChannel = deriveMinaChannel(settlement, announce, relayUrl);\n }\n supportedChains = [selection.chain];\n preferredTokens = settlement.tokenAddress\n ? { [selection.chain]: settlement.tokenAddress }\n : undefined;\n tokenNetworks = settlement.tokenNetwork\n ? { [selection.chain]: settlement.tokenNetwork }\n : undefined;\n chainRpcUrls = settlement.rpcUrl\n ? { [selection.chain]: settlement.rpcUrl }\n : undefined;\n if (selection.reason !== 'explicit') {\n warn(\n `rig: settlement chain ${selection.chain} selected — ` +\n `${selection.detail}; set TOON_CLIENT_CHAIN (or supportedChains ` +\n 'in the client config) to override'\n );\n } else if (explicitChain && selection.chain !== explicitChain) {\n // The explicit pin was re-spelled to the announced chain id (chain\n // negotiation matches identifiers exactly) — say so, like the\n // configured-supportedChains path does.\n warn(\n `rig: aligning configured settlement chain \"${explicitChain}\" to ` +\n `the announced spelling \"${selection.chain}\" — ${selection.detail}`\n );\n }\n } else {\n warn(\n 'rig: no settlement chains are configured or announced — paid writes ' +\n 'will fail until a chain is configured (supportedChains) or the ' +\n `payment peer announces its chains on ${relayUrl}`\n );\n }\n\n const network = env['TOON_CLIENT_NETWORK'] ?? file.network;\n if (network && network !== 'custom' && !file.supportedChains?.length) {\n warn(\n `rig: ignoring the \"${network}\" network preset for settlement — the ` +\n \"settlement chain comes from the payment peer's announce and your \" +\n 'config, because preset chains can point at networks your wallet ' +\n 'has no funds on; set supportedChains explicitly to use preset chains'\n );\n }\n\n return {\n ...(proxyUrl ? { proxyUrl } : {}),\n ...(btpUrl ? { btpUrl } : {}),\n destination,\n ...(publishDestination ? { publishDestination } : {}),\n ...(storeDestination ? { storeDestination } : {}),\n ...(routePrices ? { routePrices } : {}),\n knownPeers,\n ...(selection ? { selection } : {}),\n ...(supportedChains ? { supportedChains } : {}),\n ...(preferredTokens && Object.keys(preferredTokens).length > 0\n ? { preferredTokens }\n : {}),\n ...(tokenNetworks && Object.keys(tokenNetworks).length > 0\n ? { tokenNetworks }\n : {}),\n ...(chainRpcUrls && Object.keys(chainRpcUrls).length > 0\n ? { chainRpcUrls }\n : {}),\n ...(solanaChannel ? { solanaChannel } : {}),\n ...(minaChannel ? { minaChannel } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cached-topology recovery (#279)\n// ---------------------------------------------------------------------------\n\n/** Structural check for a cached {@link NetworkTopology} document. */\nfunction isNetworkTopology(value: unknown): value is NetworkTopology {\n if (typeof value !== 'object' || value === null) return false;\n const t = value as Record<string, unknown>;\n return typeof t['destination'] === 'string' && Array.isArray(t['knownPeers']);\n}\n\n/**\n * Start failures that must NEVER trigger a cache-invalidation retry: they\n * are concurrency/state guards, not topology staleness — retrying would\n * bypass exactly what they protect.\n */\nconst NON_RECOVERABLE_START_ERRORS: ReadonlySet<string> = new Set([\n 'DaemonIdentityConflictError',\n 'StandaloneLockError',\n 'ChannelMapCorruptError',\n // An unfunded Mina fee payer is a wallet-funding problem, not topology\n // staleness — re-resolving the topology cannot fix it, so retrying would\n // just re-run the (already fail-fast) preflight for nothing.\n 'MinaFeePayerUnfundedError',\n]);\n\n/**\n * Publisher wrapper implementing the #279 cache-invalidation contract: when\n * the inner publisher was built from a CACHED topology and its bootstrap\n * (`start`/`startClientOnly`) fails, the cache entry is invalidated, the\n * topology is re-resolved LIVE, a fresh publisher replaces the inner one,\n * and the operation proceeds — one retry, never more. Bootstrap failures\n * are pre-payment by construction (start() completes before any claim is\n * signed), so the retry can never double-pay. Publishers built from a live\n * resolution get no recovery hook and fail through unchanged.\n */\nclass TopologyRecoveringPublisher implements Publisher {\n private inner: StandalonePublisher;\n private rebuild: (() => Promise<StandalonePublisher>) | undefined;\n private readonly warn: (line: string) => void;\n\n constructor(\n inner: StandalonePublisher,\n rebuild: (() => Promise<StandalonePublisher>) | undefined,\n warn: (line: string) => void\n ) {\n this.inner = inner;\n this.rebuild = rebuild;\n this.warn = warn;\n }\n\n getPublicKey(): string {\n return this.inner.getPublicKey();\n }\n\n getFeeRates(): Promise<FeeRates> {\n return this.inner.getFeeRates();\n }\n\n /**\n * Run the bootstrap step, recovering ONCE from a stale cached topology.\n * A rebuild failure surfaces the LIVE resolution's error — that is the\n * network's real state, strictly more actionable than the cached failure.\n */\n private async ensure(\n start: (p: StandalonePublisher) => Promise<void>\n ): Promise<StandalonePublisher> {\n try {\n await start(this.inner);\n return this.inner;\n } catch (err) {\n const rebuild = this.rebuild;\n this.rebuild = undefined;\n const name = err instanceof Error ? err.name : '';\n if (!rebuild || NON_RECOVERABLE_START_ERRORS.has(name)) throw err;\n this.warn(\n 'rig: bootstrap with the cached network topology failed ' +\n `(${err instanceof Error ? err.message : String(err)}) — ` +\n 'invalidating the cache and re-resolving live'\n );\n const fresh = await rebuild();\n try {\n // Failed starts release their own lock/state; stop() is idempotent.\n await this.inner.stop();\n } catch {\n // best-effort teardown of the abandoned publisher\n }\n this.inner = fresh;\n await start(this.inner);\n return this.inner;\n }\n }\n\n async publishEvent(\n event: UnsignedEvent,\n relayUrls: string[]\n ): Promise<PublishReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.publishEvent(event, relayUrls);\n }\n\n async uploadGitObject(upload: GitObjectUpload): Promise<UploadReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.uploadGitObject(upload);\n }\n\n async uploadBlob(upload: BlobUpload): Promise<UploadReceipt> {\n const p = await this.ensure((x) => x.start());\n return p.uploadBlob(upload);\n }\n\n // ── money lifecycle passthroughs (#263) — same recovery contract ─────────\n\n async openChannelExplicit(\n opts?: Parameters<StandalonePublisher['openChannelExplicit']>[0]\n ): ReturnType<StandalonePublisher['openChannelExplicit']> {\n const p = await this.ensure((x) => x.start());\n return p.openChannelExplicit(opts);\n }\n\n async closeRecordedChannel(\n record: ChannelMapRecord\n ): ReturnType<StandalonePublisher['closeRecordedChannel']> {\n const p = await this.ensure((x) => x.startClientOnly());\n return p.closeRecordedChannel(record);\n }\n\n async settleRecordedChannel(\n record: ChannelMapRecord\n ): ReturnType<StandalonePublisher['settleRecordedChannel']> {\n const p = await this.ensure((x) => x.startClientOnly());\n return p.settleRecordedChannel(record);\n }\n\n /** Free read on the unstarted client — no bootstrap, no recovery needed. */\n readWalletChainBalances(\n ...args: Parameters<StandalonePublisher['readWalletChainBalances']>\n ): ReturnType<StandalonePublisher['readWalletChainBalances']> {\n return this.inner.readWalletChainBalances(...args);\n }\n\n async stop(): Promise<void> {\n await this.inner.stop();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Context factory\n// ---------------------------------------------------------------------------\n\n/**\n * #262 channel-map records for this identity, reduced to the slice chain\n * selection consumes (`closed` folds in the claim-watermark timers).\n */\nfunction chainRecordsFor(\n map: ChannelMapStore,\n identity: string\n): ChannelRecordLike[] {\n return map\n .list()\n .filter((r) => r.identity === identity)\n .map((r) => {\n const watermark = map.readWatermark(r.channelId);\n return {\n chain: r.chain,\n lastUsedAt: r.lastUsedAt,\n closed:\n watermark?.closedAt !== undefined ||\n watermark?.settledAt !== undefined,\n };\n });\n}\n\n/**\n * Assemble an embedded-client standalone context: resolved identity + config\n * → network bootstrap (announce discovery / genesis seed) → ToonClientConfig\n * → nonce-guarded StandalonePublisher (guard + client start + channel open\n * happen lazily on the first paid call, or eagerly via the publisher's own\n * `start`).\n */\nexport async function createStandaloneContext(\n options: StandaloneLoadOptions\n): Promise<StandaloneContext> {\n const { env } = options;\n const warn = (line: string) => options.warn(line);\n const dir = configDir(env);\n const configPath = join(dir, 'config.json');\n const file = readClientConfig(configPath);\n const identity = await resolveIdentity(options);\n\n // Force-standalone override (RIG_STANDALONE / `rig --standalone`): when set,\n // the embedded publisher skips the same-identity daemon refusal so a running\n // toon-clientd never blocks the standalone path. The per-identity NonceLock\n // still guards against two standalone processes racing the claim watermark.\n const skipDaemonCheck = standaloneForced(env);\n if (skipDaemonCheck) {\n warn(\n 'rig: force-standalone (RIG_STANDALONE) — bypassing any running ' +\n 'toon-clientd; this rig process signs its own claims (stop the daemon ' +\n 'if it is also writing on this identity)'\n );\n }\n\n const genesisSeed = loadGenesisSeed();\n\n // ── Relay-origin ──────────────────────────────────────────────────────────\n // The relay the paid command resolved via `rig remote` (passed by the\n // command) is the user's clearest network statement; env/file follow, and\n // the genesis seed's relay is the out-of-the-box fallback.\n const relayUrl =\n options.relayUrl ??\n env['TOON_CLIENT_RELAY_URL'] ??\n file.relayUrl ??\n genesisSeed?.relayUrl ??\n // Last resort: the genesis seed normally supplies the relay, so this is\n // only reached when no seed/config/env relay is present. Point at the\n // shared public devnet relay rather than a dead local default.\n 'wss://relay-ws.devnet.toonprotocol.dev';\n\n // ── Peer→channel persistence (#262) ──────────────────────────────────────\n const channelStorePath = file.channelStorePath ?? join(dir, 'channels.json');\n const channelMap = new ChannelMapStore({\n mapPath: join(dir, RIG_CHANNEL_MAP_FILENAME),\n watermarkPath: channelStorePath,\n });\n\n // ── Topology cache (#279): keyed by relay-origin + identity + explicit\n // config; a hit skips discovery AND the pure-but-probing resolution below.\n const cache = new TopologyCache<NetworkTopology>({\n path: join(dir, TOPOLOGY_CACHE_FILENAME),\n ttlMs: topologyCacheTtlMs(env),\n validate: isNetworkTopology,\n });\n const cacheKey = topologyCacheKey({\n relayUrl,\n identity: identity.pubkey,\n fingerprint: explicitConfigFingerprint(\n env,\n file as Record<string, unknown>\n ),\n });\n\n const resolveLiveTopology = async (): Promise<NetworkTopology> => {\n // ── Live announce discovery ────────────────────────────────────────────\n // Skipped when explicit config already pins the whole payment topology\n // (fully-configured setups keep their zero-roundtrip start and their\n // exact pre-#264 behavior). A listed `solana:*` chain WITHOUT explicit\n // channel parameters is not fully pinned: the announce is a needed\n // parameter source (program id / mint), and skipping discovery would\n // also skip the announced-spelling alignment that keeps the chain list\n // negotiable. Discovery failure is non-fatal: warn + genesis seed.\n const solanaExplicitlyComplete = (file.supportedChains ?? []).every(\n (chain) =>\n !chain.startsWith('solana:') ||\n Boolean(file.solanaChannel) ||\n Boolean(\n file.tokenNetworks?.[chain] &&\n file.preferredTokens?.[chain] &&\n file.chainRpcUrls?.[chain]\n )\n );\n // A listed `mina:*` chain WITHOUT an explicit `minaChannel` is not fully\n // pinned either: the announce is the authoritative source for the\n // deployment's zkApp (and token id), so discovery must run. Only an\n // explicit `minaChannel` config makes a Mina chain announce-independent.\n const minaExplicitlyComplete = (file.supportedChains ?? []).every(\n (chain) => !chain.startsWith('mina:') || Boolean(file.minaChannel)\n );\n const fullyExplicit =\n Boolean(\n (env['TOON_CLIENT_PROXY_URL'] ?? file.proxyUrl) ||\n (env['TOON_CLIENT_BTP_URL'] ?? file.btpUrl)\n ) &&\n Boolean(env['TOON_CLIENT_DESTINATION'] ?? file.destination) &&\n Boolean(file.supportedChains?.length) &&\n solanaExplicitlyComplete &&\n minaExplicitlyComplete;\n let announce: AnnouncedPeer | undefined;\n if (!fullyExplicit) {\n try {\n const peers = await discoverAnnouncedPeers(relayUrl, {\n timeoutMs: DISCOVERY_TIMEOUT_MS,\n });\n announce = pickPaymentPeer(peers, genesisSeedPubkeys());\n if (!announce) {\n warn(\n `rig: no payment-peer announce (kind:10032) found on ${relayUrl} — ` +\n 'falling back to the genesis peer seed'\n );\n }\n } catch (err) {\n warn(\n `rig: announce discovery on ${relayUrl} failed ` +\n `(${err instanceof Error ? err.message : String(err)}) — falling ` +\n 'back to the genesis peer seed'\n );\n }\n }\n\n // ── Topology resolution (pure; explicit > announce > genesis) ──────────\n const resolved = await resolveNetworkTopology({\n env,\n file,\n configPath,\n relayUrl,\n announce,\n genesisSeed,\n identity: {\n mnemonic: identity.mnemonic,\n accountIndex: identity.accountIndex,\n pubkey: identity.pubkey,\n },\n channelRecords: () => chainRecordsFor(channelMap, identity.pubkey),\n ...(options.requireUplink !== undefined\n ? { requireUplink: options.requireUplink }\n : {}),\n warn,\n });\n // Cache only paid-path resolutions: a `requireUplink: false` free read\n // may resolve WITHOUT an uplink, and caching that would let a later paid\n // command skip past MissingUplinkError with a broken topology.\n if (options.requireUplink !== false) cache.write(cacheKey, resolved);\n return resolved;\n };\n\n const cached = cache.read(cacheKey);\n if (cached) {\n warn(\n `rig: network topology from cache (${Math.round(cached.ageMs / 1000)}s ` +\n `old; ${TOPOLOGY_TTL_ENV}=0 disables) — skipping announce discovery`\n );\n }\n const topology = cached?.topology ?? (await resolveLiveTopology());\n\n const eventFee = BigInt(file.feePerEvent ?? '1');\n\n const buildPublisher = (topo: NetworkTopology): StandalonePublisher => {\n const clientConfig: ToonClientConfig = {\n // validateConfig requires connectorUrl OR proxyUrl; with BTP-only\n // config a dummy connectorUrl satisfies it (unused at runtime — same\n // convention as the daemon).\n ...(topo.proxyUrl\n ? { proxyUrl: topo.proxyUrl }\n : { connectorUrl: 'http://127.0.0.1:1' }),\n mnemonic: identity.mnemonic,\n mnemonicAccountIndex: identity.accountIndex,\n ilpInfo: {\n pubkey: '00'.repeat(32),\n ilpAddress: 'g.toon.client',\n btpEndpoint: topo.btpUrl ?? '',\n assetCode: 'USD',\n assetScale: 6,\n },\n toonEncoder: encodeEventToToon,\n toonDecoder: decodeEventFromToon,\n ...(topo.btpUrl ? { btpUrl: topo.btpUrl, btpAuthToken: '' } : {}),\n destinationAddress: topo.destination,\n // The embedded client bootstraps against the known peer above; its\n // `relayUrl` config only seeds ArDrive-merged peers, so it stays unset.\n relayUrl: '',\n knownPeers: topo.knownPeers,\n channelStorePath,\n ...(topo.supportedChains\n ? { supportedChains: topo.supportedChains }\n : {}),\n ...(file.settlementAddresses\n ? { settlementAddresses: file.settlementAddresses }\n : {}),\n ...(topo.preferredTokens\n ? { preferredTokens: topo.preferredTokens }\n : {}),\n ...(topo.tokenNetworks ? { tokenNetworks: topo.tokenNetworks } : {}),\n ...(topo.chainRpcUrls ? { chainRpcUrls: topo.chainRpcUrls } : {}),\n // Solana channel params: an explicit config object wins verbatim; else\n // the topology's derivation (announce/presets — see resolveNetworkTopology).\n ...(file.solanaChannel\n ? { solanaChannel: file.solanaChannel }\n : topo.solanaChannel\n ? { solanaChannel: topo.solanaChannel }\n : {}),\n // Mina channel params: an explicit config object wins verbatim; else the\n // topology's derivation (announce zkApp/tokenId + preset graphqlUrl —\n // see resolveNetworkTopology / deriveMinaChannel).\n // An explicit config object keeps today's pin-a-zkApp semantics\n // verbatim. The DERIVED path additionally gets `autoDeploy`: the\n // announce/preset zkApp is shared and single-pair, so a fresh identity\n // can never open on it — the client checks on-chain ownership and\n // deploys a dedicated per-pair zkApp when needed, persisting the key\n // through the rig zkApp store (losing it would strand ~1.1 MINA).\n ...(file.minaChannel\n ? { minaChannel: file.minaChannel }\n : topo.minaChannel\n ? {\n minaChannel: {\n ...topo.minaChannel,\n autoDeploy: buildMinaAutoDeploy(\n dir,\n identity.pubkey,\n `mina:${topo.minaChannel.networkId ?? 'devnet'}`,\n warn\n ),\n },\n }\n : {}),\n };\n\n return new StandalonePublisher({\n clientConfig,\n eventFee,\n channelMap,\n warn,\n ...(skipDaemonCheck ? { skipDaemonCheck: true } : {}),\n ...(topo.publishDestination\n ? { publishDestination: topo.publishDestination }\n : {}),\n ...(topo.storeDestination\n ? { storeDestination: topo.storeDestination }\n : {}),\n // Route-price floors (F06): every per-packet claim must advance the\n // channel by at least the destination route's announced price.\n ...(topo.routePrices\n ? {\n routePrices: {\n ...(topo.routePrices.publish !== undefined\n ? { publish: BigInt(topo.routePrices.publish) }\n : {}),\n ...(topo.routePrices.store !== undefined\n ? { store: BigInt(topo.routePrices.store) }\n : {}),\n },\n }\n : {}),\n // `rig channel open --peer` (#263): anchor the channel (and its map\n // key) to an explicit peer destination instead of the configured\n // default.\n ...(options.channelDestination\n ? { channelDestination: options.channelDestination }\n : {}),\n // The peer's announce does not carry TokenNetwork/token parameters, so\n // the client's negotiation leaves them empty (#260 root cause 3) — the\n // publisher back-fills them from the derived per-chain maps before the\n // channel opens.\n ...(topo.tokenNetworks || topo.preferredTokens\n ? {\n negotiationFallbacks: {\n ...(topo.tokenNetworks\n ? { tokenNetworks: topo.tokenNetworks }\n : {}),\n ...(topo.preferredTokens\n ? { preferredTokens: topo.preferredTokens }\n : {}),\n },\n }\n : {}),\n });\n };\n\n // Cache-sourced publishers get the #279 recovery hook: a failed bootstrap\n // invalidates the entry, re-resolves live (which re-writes the cache), and\n // retries once. Live-resolved publishers fail through unchanged.\n const publisher = new TopologyRecoveringPublisher(\n buildPublisher(topology),\n cached\n ? async () => {\n cache.invalidate(cacheKey);\n return buildPublisher(await resolveLiveTopology());\n }\n : undefined,\n warn\n );\n\n // Wallet-view preset defaults (#299): when the identity has no configured\n // Solana/Mina channel (the common single-EVM-chain case), `rig balance` still\n // shows those chains — 0 for an account not yet on-chain — by reading the\n // named network's public RPC/GraphQL. Resolved HERE and passed only to the\n // wallet-view read, NOT merged into the client's settlement config: setting\n // `network` there would expand `supportedChains` via applyNetworkPresets and\n // change chain negotiation, which this deliberately avoids.\n const walletViewNetwork = env['TOON_CLIENT_NETWORK'] ?? file.network;\n let walletViewFallback: WalletViewFallback | undefined;\n if (\n walletViewNetwork === 'devnet' ||\n walletViewNetwork === 'testnet' ||\n walletViewNetwork === 'mainnet'\n ) {\n const presets = resolveClientNetwork(walletViewNetwork);\n walletViewFallback = {\n ...(presets.solanaChannel\n ? { solanaChannel: presets.solanaChannel }\n : {}),\n ...(presets.minaChannel ? { minaChannel: presets.minaChannel } : {}),\n };\n }\n\n return {\n ownerPubkey: publisher.getPublicKey(),\n identitySource: identity.source,\n identitySourceLabel: identity.sourceLabel,\n publisher,\n defaultRelayUrls: [relayUrl],\n fetchRemote: (args) => fetchRemoteState(args),\n // Money lifecycle (#263): same guard/start/channel-map machinery as the\n // paid-write path, surfaced for fund/balance/channel open|close|settle.\n money: {\n openChannel: (opts) => publisher.openChannelExplicit(opts),\n closeChannel: (record) => publisher.closeRecordedChannel(record),\n settleChannel: (record) => publisher.settleRecordedChannel(record),\n walletChainBalances: () =>\n publisher.readWalletChainBalances(walletViewFallback),\n },\n stop: () => publisher.stop(),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AACxB,SAAS,YAAY;AAErB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAmFA,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,YAAoB,UAA8B;AAC5D,UAAM,aAAa,WACf,qDAAqD,QAAQ,qCAE7D;AACJ;AAAA,MACE,+BAA+B,UAAU,yGAEjB,UAAU;AAAA,IACpC;AACA,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,UAAU,KAAgC;AACjD,SAAO,IAAI,kBAAkB,KAAK,KAAK,QAAQ,GAAG,cAAc;AAClE;AAEA,SAAS,iBAAiB,MAAgC;AACxD,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;AAGA,SAAS,YAAY,cAA8B;AACjD,SAAO,aAAa,QAAQ,QAAQ,EAAE,EAAE,QAAQ,WAAW,EAAE;AAC/D;AA8GO,SAAS,oBACd,KACA,g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