@toon-protocol/client 0.23.0 → 0.25.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/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ToonClient.ts","../src/config.ts","../src/errors.ts","../src/keys/KeyDerivation.ts","../src/utils/binary.ts","../src/adapters/ConnectorEdgeClient.ts","../src/wire/oer.ts","../src/wire/envelope.ts","../src/wire/giftwrap.ts","../src/wire/sealed-exchange.ts","../src/modes/http.ts","../src/utils/retry.ts","../src/adapters/HttpRuntimeClient.ts","../src/btp/protocol.ts","../src/btp/IsomorphicBtpClient.ts","../src/utils/condition.ts","../src/adapters/ilp-send.ts","../src/adapters/BtpRuntimeClient.ts","../src/adapters/HttpIlpClient.ts","../src/adapters/selectIlpTransport.ts","../src/channel/OnChainChannelClient.ts","../src/channel/solana-payment-channel.ts","../src/signing/evm-signer.ts","../src/signing/solana-signer.ts","../src/signing/mina-signer.ts","../src/channel/mina-payment-channel.ts","../src/channel/mina-deposit.ts","../src/channel/ChannelManager.ts","../src/channel/ChannelStore.ts","../src/balance/WalletBalanceReader.ts","../src/blob-storage.ts","../src/adapters/Http402Client.ts","../src/swap/settle-received-claims.ts","../src/swap/mina-settlement.ts","../src/adapters/HttpConnectorAdmin.ts","../src/channel/ReceivedClaimStore.ts","../src/swap/received-claims.ts","../src/swap/evm-claim-digest.ts","../src/swap/preimage-retention.ts","../src/swap/atomic-reveal.ts","../src/faucet.ts","../src/keys/KeyManager.ts","../src/keys/PasskeyAuth.ts","../src/keys/encoding.ts","../src/keys/KeyVault.ts","../src/keys/BackupService.ts","../src/keys/keystore-node.ts"],"sourcesContent":["import {\n generateSecretKey,\n getPublicKey,\n finalizeEvent,\n} from 'nostr-tools/pure';\nimport type { NostrEvent, EventTemplate } from 'nostr-tools/pure';\nimport type {\n BootstrapService,\n DiscoveryTracker,\n IlpSendResult,\n IlpClient,\n} from '@toon-protocol/core';\nimport type { NetworkFamilyStatus } from '@toon-protocol/core';\nimport { validateConfig, applyDefaults, getNetworkStatus } from './config.js';\nimport {\n toBase64,\n fromBase64,\n encodeUtf8,\n decodeUtf8,\n} from './utils/binary.js';\nimport {\n ConnectorEdgeClient,\n connectorEdgeBaseUrl,\n} from './adapters/ConnectorEdgeClient.js';\nimport { readExchangeOutcome, sealExchange } from './wire/sealed-exchange.js';\nimport type { ResolvedConfig } from './config.js';\nimport { initializeHttpMode } from './modes/http.js';\nimport { ToonClientError } from './errors.js';\nimport { EvmSigner } from './signing/evm-signer.js';\nimport { SolanaSigner } from './signing/solana-signer.js';\nimport { MinaSigner } from './signing/mina-signer.js';\nimport { deriveFullIdentity } from './keys/KeyDerivation.js';\nimport {\n ChannelManager,\n type PeerNegotiation,\n} from './channel/ChannelManager.js';\nimport { JsonFileChannelStore } from './channel/ChannelStore.js';\nimport type { OnChainChannelClient } from './channel/OnChainChannelClient.js';\nimport {\n readEvmTokenBalance,\n readSolanaTokenBalance,\n readMinaBalance,\n readWalletBalances,\n type WalletBalance,\n type WalletBalanceSources,\n type WalletChainBalances,\n} from './balance/WalletBalanceReader.js';\nimport {\n requestBlobStorage,\n type RequestBlobStorageResult,\n} from './blob-storage.js';\nimport type { BtpRuntimeClient } from './adapters/BtpRuntimeClient.js';\nimport type { IlpSendParams } from './adapters/ilp-send.js';\nimport {\n Http402Client,\n type H402FetchOptions,\n} from './adapters/Http402Client.js';\nimport type { SettlementBundle } from '@toon-protocol/sdk';\nimport {\n submitEvmSettlement,\n type SubmitEvmSettlementResult,\n} from './swap/settle-received-claims.js';\nimport {\n submitMinaSettlement,\n type MinaSignaturePair,\n} from './swap/mina-settlement.js';\nimport type {\n ToonClientConfig,\n ToonStartResult,\n PublishEventResult,\n SignedBalanceProof,\n} from './types.js';\n\n/**\n * Validate an operator-supplied maker Mina co-signature (`{ r, s }` decimal\n * Field strings). Returns undefined for an absent/malformed entry so the\n * settlement path fails closed with `MINA_MAKER_COSIGN_REQUIRED` rather than\n * forwarding garbage into o1js.\n */\nfunction parseMakerMinaSignature(\n raw: { r: string; s: string } | undefined\n): MinaSignaturePair | undefined {\n if (\n raw &&\n typeof raw.r === 'string' &&\n raw.r.length > 0 &&\n typeof raw.s === 'string' &&\n raw.s.length > 0\n ) {\n return { r: raw.r, s: raw.s };\n }\n return undefined;\n}\n\n/**\n * Internal state for ToonClient after initialization.\n */\ninterface ToonClientState {\n bootstrapService: BootstrapService;\n discoveryTracker: DiscoveryTracker;\n runtimeClient: IlpClient;\n peersDiscovered: number;\n btpClient?: BtpRuntimeClient;\n}\n\n/**\n * ToonClient - High-level client for interacting with TOON network.\n *\n * This story implements HTTP mode only. Embedded mode will be added in a future epic.\n *\n * @example HTTP Mode\n * ```typescript\n * import { ToonClient } from '@toon-protocol/client';\n * import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';\n * import { encodeEvent, decodeEvent } from '@toon-protocol/relay';\n *\n * const secretKey = generateSecretKey();\n * const pubkey = getPublicKey(secretKey);\n *\n * const client = new ToonClient({\n * connectorUrl: 'http://localhost:8080',\n * secretKey,\n * ilpInfo: {\n * pubkey,\n * ilpAddress: `g.toon.${pubkey.slice(0, 8)}`,\n * btpEndpoint: 'ws://localhost:3000',\n * },\n * toonEncoder: encodeEvent,\n * toonDecoder: decodeEvent,\n * });\n *\n * await client.start(); // Bootstrap peers, start monitoring\n *\n * // Publish to default destination (from config)\n * await client.publishEvent(signedEvent);\n *\n * // Publish to specific destination (multi-hop routing)\n * await client.publishEvent(signedEvent, { destination: 'g.toon.peer1' });\n *\n * await client.stop(); // Cleanup\n * ```\n */\nexport class ToonClient {\n private readonly config: ResolvedConfig;\n private state: ToonClientState | null = null;\n private readonly evmSigner?: EvmSigner;\n private solanaSigner?: SolanaSigner;\n /**\n * Ed25519 signing seed (32 bytes) derived from the mnemonic for the Solana\n * identity. Retained so `start()` can inject it into the on-chain channel\n * client's Solana config (same key as `solanaSigner`).\n */\n private solanaSeed?: Uint8Array;\n private minaSigner?: MinaSigner;\n /**\n * Mina private key (big-endian hex scalar, as `deriveFullIdentity` emits)\n * derived from the mnemonic. Retained so `start()` can inject it into the\n * on-chain channel client's Mina config (same key as `minaSigner`).\n */\n private minaPrivateKey?: string;\n private channelManager?: ChannelManager;\n /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */\n private onChainChannelClient?: OnChainChannelClient;\n private readonly peerNegotiations = new Map<string, PeerNegotiation>();\n /**\n * Asks terminating connectors for their identity key, caching one per\n * client edge. A packet cannot be formed without the key of the connector\n * that terminates it (ADR 0018), so this is reached on every paid write.\n */\n private readonly connectorEdge = new ConnectorEdgeClient({\n // Resolve `fetch` per call rather than binding it once: a host that\n // installs its own global (and a test that swaps one in) must be the one\n // this reaches, whenever it is reached.\n fetch: (input, init) => globalThis.fetch(input, init),\n });\n\n /**\n * Creates a new ToonClient instance.\n *\n * @param config - Client configuration\n * @throws {ValidationError} If configuration is invalid\n */\n constructor(config: ToonClientConfig) {\n // Validate config (will reject embedded mode, require connectorUrl)\n validateConfig(config);\n\n // Apply defaults to optional fields (auto-generates secretKey if needed)\n this.config = applyDefaults(config);\n\n // Create EVM signer if private key provided\n if (this.config.evmPrivateKey) {\n this.evmSigner = new EvmSigner(this.config.evmPrivateKey);\n }\n }\n\n /**\n * Generates a new Nostr keypair.\n *\n * @returns Object with secretKey (Uint8Array) and pubkey (hex string)\n */\n static generateKeypair(): { secretKey: Uint8Array; pubkey: string } {\n const secretKey = generateSecretKey();\n const pubkey = getPublicKey(secretKey);\n return { secretKey, pubkey };\n }\n\n /**\n * Gets the Nostr public key derived from the secret key.\n * Works before start() is called.\n */\n getPublicKey(): string {\n return getPublicKey(this.config.secretKey);\n }\n\n /**\n * Sign an unsigned Nostr event template with the client's Nostr secret key,\n * returning a fully-signed event (id + pubkey + sig).\n *\n * This is the key primitive behind the daemon's sign-and-publish path: a UI\n * or agent supplies only `{ kind, content, tags, created_at }` and never holds\n * the private key — signing happens here, inside the key owner.\n */\n signEvent(template: EventTemplate): NostrEvent {\n return finalizeEvent(template, this.config.secretKey);\n }\n\n /**\n * Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),\n * signing the request with this client's Nostr key and paying through its\n * existing channel. Returns the Arweave tx id on success.\n *\n * Backs the daemon's `upload-media` path: the key and claim/channel plumbing\n * stay inside the client; callers pass only the bytes.\n */\n async uploadBlob(params: {\n blobData: Uint8Array;\n contentType?: string;\n bid?: string;\n destination?: string;\n ilpAmount?: bigint;\n }): Promise<RequestBlobStorageResult> {\n return requestBlobStorage(this, this.config.secretKey, params);\n }\n\n /**\n * Per-chain settlement readiness for the configured `network` tier, mirroring\n * the relay node's status. Returns `undefined` when no named `network` is\n * set (or `network: 'custom'`), since there is no preset tier to report on.\n */\n getNetworkStatus(): NetworkFamilyStatus | undefined {\n return getNetworkStatus(this.config);\n }\n\n /**\n * Gets the EVM address derived from the Nostr secret key (or explicit evmPrivateKey override).\n */\n getEvmAddress(): string | undefined {\n return this.evmSigner?.address;\n }\n\n /**\n * Gets the Solana (base58) address, when the client was constructed from a\n * `mnemonic`. Available only AFTER `start()` (Solana keys are derived\n * asynchronously). Returns undefined otherwise.\n */\n getSolanaAddress(): string | undefined {\n return this.solanaSigner?.signerIdentifier;\n }\n\n /**\n * Gets the Mina (base58) address, when the client was constructed from a\n * `mnemonic` AND `mina-signer` is installed. Available only AFTER `start()`.\n * Returns undefined otherwise.\n */\n getMinaAddress(): string | undefined {\n return this.minaSigner?.signerIdentifier;\n }\n\n /**\n * Derive the Solana/Mina keys from the mnemonic and register their signers on\n * the ChannelManager. Mirrors how the EVM signer is wired, but for the\n * non-secp256k1 chains. Skips any chain whose optional dependency is missing.\n */\n private async registerMnemonicChainSigners(\n mnemonic: string,\n accountIndex = 0\n ): Promise<void> {\n if (!this.channelManager) return;\n const identity = await deriveFullIdentity(mnemonic, accountIndex);\n\n // Solana: @noble/curves Ed25519 expects a 32-byte seed; deriveFullIdentity\n // returns a 64-byte keypair (seed||pubkey).\n if (identity.solana.publicKey) {\n const seed = identity.solana.secretKey.slice(0, 32);\n this.solanaSeed = seed;\n this.solanaSigner = new SolanaSigner(seed, identity.solana.publicKey);\n this.channelManager.registerChainSigner('solana', this.solanaSigner);\n }\n\n // Mina: only present when mina-signer is installed (optional dep).\n if (identity.mina.publicKey) {\n this.minaPrivateKey = identity.mina.privateKey;\n // Pass the configured GraphQL URL so the signer can read the channel's\n // on-chain `depositTotal` and bind the conserved `balanceB = depositTotal\n // − balanceA` commitment that a funded zkApp requires (connector#133);\n // without it Mina claims use the legacy balanceB=0 form and a funded zkApp\n // rejects them (F06 - Invalid zk-SNARK proof on claim).\n this.minaSigner = new MinaSigner(\n identity.mina.privateKey,\n identity.mina.publicKey,\n this.config.minaChannel?.graphqlUrl\n ? { graphqlUrl: this.config.minaChannel.graphqlUrl }\n : undefined\n );\n this.channelManager.registerChainSigner('mina', this.minaSigner);\n }\n }\n\n /**\n * Starts the ToonClient.\n *\n * This will:\n * 1. Initialize HTTP mode components (runtime client, admin client, bootstrap, monitor)\n * 2. Bootstrap the network (discover peers, register, and open channels)\n * 3. Start monitoring relay for new peers (kind:10032 events)\n *\n * @returns Result with number of peers discovered and mode\n * @throws {ToonClientError} If client is already started\n * @throws {ToonClientError} If initialization fails\n */\n async start(): Promise<ToonStartResult> {\n if (this.state !== null) {\n throw new ToonClientError('Client already started', 'INVALID_STATE');\n }\n\n try {\n // Create channel manager FIRST (before bootstrap) so it can sign claims during settlement\n if (this.evmSigner) {\n const store = this.config.channelStorePath\n ? new JsonFileChannelStore(this.config.channelStorePath)\n : undefined;\n this.channelManager = new ChannelManager(this.evmSigner, store);\n\n // When constructed from a mnemonic, derive the non-secp256k1 keys\n // (Solana Ed25519, Mina Pallas) and register their signers so the\n // client can settle on those chains too. Derivation is async (dynamic\n // imports + optional deps), hence done here rather than in the\n // synchronous constructor. Gracefully skips a chain whose optional dep\n // is absent (e.g. mina-signer) — deriveFullIdentity leaves it empty.\n if (this.config.mnemonic) {\n await this.registerMnemonicChainSigners(\n this.config.mnemonic,\n this.config.mnemonicAccountIndex ?? 0\n );\n }\n }\n\n // Initialize HTTP mode components\n const initialization = await initializeHttpMode(this.config);\n\n const { bootstrapService, discoveryTracker, runtimeClient, btpClient } =\n initialization;\n\n // Wire claim signer to bootstrap service if we have channel manager\n if (this.channelManager) {\n const cm = this.channelManager;\n const nostrPubkey = this.getPublicKey();\n // Derive default chain context from config (first supported chain)\n const defaultChainCtx = this.getDefaultChainContext();\n bootstrapService.setClaimSigner(\n async (channelId: string, amount: bigint) => {\n // Track the channel if not already tracked\n if (!cm.isTracking(channelId)) {\n cm.trackChannel(channelId, defaultChainCtx);\n }\n // Sign balance proof and build full claim message with the\n // chain-appropriate signer (the channel is tracked above, so a\n // non-EVM channel yields its correct envelope, not an EVM claim).\n const proof = await cm.signBalanceProof(channelId, amount);\n const signer = cm.getSignerForChannel(channelId);\n return signer.buildClaimMessage(proof, nostrPubkey);\n }\n );\n }\n\n // Start bootstrap process (discover peers, register with settlement, announce)\n const bootstrapResults = await bootstrapService.bootstrap();\n\n // Store negotiation metadata from bootstrap results for lazy channel opening\n for (const result of bootstrapResults) {\n if (result.negotiatedChain && result.settlementAddress) {\n const chainType = result.negotiatedChain.split(':')[0] ?? 'evm';\n const parts = result.negotiatedChain.split(':');\n // Accept 3-part `evm:{network}:{chainId}` and 2-part `evm:{chainId}`.\n const chainId =\n parts.length >= 3\n ? parseInt(parts[2] ?? '0', 10)\n : parts.length >= 2\n ? parseInt(parts[1] ?? '0', 10)\n : 0;\n const r = result as typeof result & {\n tokenAddress?: string;\n tokenNetwork?: string;\n };\n this.peerNegotiations.set(result.registeredPeerId, {\n chain: result.negotiatedChain,\n chainType,\n chainId: isNaN(chainId) ? 0 : chainId,\n settlementAddress: result.settlementAddress,\n tokenAddress: r.tokenAddress,\n tokenNetwork: r.tokenNetwork,\n });\n } else if (\n result.registeredPeerId &&\n !this.peerNegotiations.has(result.registeredPeerId)\n ) {\n // Lightweight client fallback: bootstrap discovered the peer but didn't\n // negotiate a chain (no connector admin to register with). Extract the\n // peer's settlement info from their kind:10032 event data and match\n // against our supported chains.\n const peerInfo = result.peerInfo as typeof result.peerInfo & {\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n };\n const peerChains = peerInfo.supportedChains ?? [];\n const ourChains = this.config.supportedChains ?? [];\n // Find the first chain both sides support\n const matchedChain =\n ourChains.find((c) => peerChains.includes(c)) ?? ourChains[0];\n if (matchedChain) {\n const peerAddr = peerInfo.settlementAddresses?.[matchedChain];\n const parts = matchedChain.split(':');\n const chainId =\n parts.length >= 3\n ? parseInt(parts[2] ?? '0', 10)\n : parts.length >= 2\n ? parseInt(parts[1] ?? '0', 10)\n : 0;\n if (peerAddr) {\n this.peerNegotiations.set(result.registeredPeerId, {\n chain: matchedChain,\n chainType: parts[0] ?? 'evm',\n chainId: isNaN(chainId) ? 0 : chainId,\n settlementAddress: peerAddr,\n tokenAddress:\n peerInfo.preferredTokens?.[matchedChain] ??\n this.config.preferredTokens?.[matchedChain],\n tokenNetwork:\n peerInfo.tokenNetworks?.[matchedChain] ??\n this.config.tokenNetworks?.[matchedChain],\n });\n }\n }\n }\n // Track any pre-opened channels (backwards compat)\n if (\n this.channelManager &&\n result.channelId &&\n !this.channelManager.isTracking(result.channelId)\n ) {\n const chainCtx = this.getChainContext(result.negotiatedChain);\n this.channelManager.trackChannel(result.channelId, chainCtx);\n }\n }\n\n // Wire on-chain channel client into ChannelManager for lazy opens\n if (this.channelManager && initialization.onChainChannelClient) {\n this.onChainChannelClient = initialization.onChainChannelClient;\n this.channelManager.setChannelClient(\n initialization.onChainChannelClient\n );\n\n // Late-bind the Solana channel config: the program/RPC/token come from\n // config, the Ed25519 keypair from the mnemonic-derived Solana seed.\n // Requires both a Solana seed (mnemonic-derived) and explicit\n // solanaChannel config — otherwise the on-chain Solana opener has no\n // program/RPC and would throw at openChannel time.\n if (this.config.solanaChannel && this.solanaSeed) {\n initialization.onChainChannelClient.setSolanaConfig({\n rpcUrl: this.config.solanaChannel.rpcUrl,\n programId: this.config.solanaChannel.programId,\n tokenMint: this.config.solanaChannel.tokenMint,\n challengeDuration: this.config.solanaChannel.challengeDuration,\n deposit: this.config.solanaChannel.deposit,\n keypair: this.solanaSeed,\n });\n }\n\n // Late-bind the Mina channel config (parallel to Solana). The\n // graphqlUrl + zkAppAddress come from config; the Mina private key from\n // the mnemonic-derived Mina identity (same key as the registered Mina\n // signer). Requires both a Mina private key (mnemonic-derived, present\n // only when `mina-signer` is installed) and explicit minaChannel config.\n //\n // openMinaChannel now performs a REAL on-chain channel open\n // (initialize + optional deposit) on the deployed zkApp so the\n // connector's getChannelState reports `opened` and the claim verifies +\n // stores (parity with Solana). Full on-chain Mina SETTLE remains gated by\n // the connector-side settlement-executor (same blocker as Solana).\n if (this.config.minaChannel && this.minaPrivateKey) {\n initialization.onChainChannelClient.setMinaConfig({\n graphqlUrl: this.config.minaChannel.graphqlUrl,\n ...(this.config.minaChannel.zkAppAddress !== undefined\n ? { zkAppAddress: this.config.minaChannel.zkAppAddress }\n : {}),\n ...(this.config.minaChannel.autoDeploy !== undefined\n ? { autoDeploy: this.config.minaChannel.autoDeploy }\n : {}),\n privateKey: this.minaPrivateKey,\n ...(this.config.minaChannel.challengeDuration !== undefined\n ? { challengeDuration: this.config.minaChannel.challengeDuration }\n : {}),\n ...(this.config.minaChannel.tokenId !== undefined\n ? { tokenId: this.config.minaChannel.tokenId }\n : {}),\n ...(this.config.minaChannel.deposit !== undefined\n ? { deposit: this.config.minaChannel.deposit }\n : {}),\n ...(this.config.minaChannel.networkId !== undefined\n ? { networkId: this.config.minaChannel.networkId }\n : {}),\n });\n }\n }\n\n // Store state\n this.state = {\n bootstrapService,\n discoveryTracker,\n runtimeClient,\n peersDiscovered: bootstrapResults.length,\n btpClient: btpClient ?? undefined,\n };\n\n return {\n peersDiscovered: bootstrapResults.length,\n mode: 'http',\n };\n } catch (error) {\n throw new ToonClientError(\n 'Failed to start client',\n 'INITIALIZATION_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Publishes a Nostr event through the connector that terminates\n * `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).\n *\n * What crosses the wire, in order:\n *\n * 1. **The terminating connector's identity is fetched first.** `data` is\n * sealed to that key, so a packet cannot be formed without it — and\n * there is no default to fall back to, because sealing to the wrong key\n * is a confidentiality failure that merely presents as undeliverable.\n * 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat\n * per handler, so `GET /ilp/routes/price` — the same longest-prefix\n * lookup the claim gate charges against — is the only thing that can\n * state what this write costs. `options.ilpAmount` still overrides.\n * 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`\n * carrying `{\"event\": …}` — never HTTP text.\n * 4. **The PREPARE carries a real execution condition**, minted as\n * `sha256` of the fulfilment derived from the secret sealed inside the\n * wrap. The transport verifies the returned preimage against it, so a\n * FULFILL nobody could have earned is counted failed rather than\n * accepted.\n * 5. **The answer is opened with that same secret.** A FULFILL carries a\n * sealed response envelope; a REJECT sealed at the termination means the\n * destination refused, and a plaintext one means somebody on the path\n * did. `refusedBy` keeps those apart.\n *\n * An HTTP status inside the response envelope is envelope CONTENT, not a\n * packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.\n * This method still reports a non-2xx as `success: false` — the event did\n * not persist — but `response` is populated either way, so a caller can see\n * exactly what it paid for.\n *\n * @param event - Signed Nostr event to publish\n * @param options - Optional destination, claim, amount and request target\n * @throws {ToonClientError} If the client is not started, the terminating\n * connector's identity or route price cannot be obtained, or the send\n * fails outright.\n */\n async publishEvent(\n event: NostrEvent,\n options?: {\n destination?: string;\n claim?: SignedBalanceProof;\n ilpAmount?: bigint;\n /** Sub-path resolved strictly BENEATH the route's handler path (ADR\n * 0025). Default '' — the handler's own path, correct whenever the\n * destination terminates at exactly one endpoint. Never absolute:\n * a leading '/' is refused by the connector (F00). */\n proxyPath?: string;\n }\n ): Promise<PublishEventResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n try {\n const destination =\n options?.destination ?? this.config.destinationAddress;\n const edge = this.resolveClientEdgeEndpoint();\n\n // (1) The key first — no packet exists without it.\n const identity = await this.connectorEdge.getIdentity(edge);\n\n // (2) The price is ASKED for, not computed. ADR 0020 makes a price flat\n // per handler — the route table is the price list — so there is no\n // per-byte rate to multiply and nothing local that could disagree with\n // what the connector will actually charge. An explicit `ilpAmount`\n // still overrides, and never triggers the lookup.\n const amount =\n options?.ilpAmount !== undefined\n ? String(options.ilpAmount)\n : String(await this.routePriceFor(edge, destination));\n\n // (3)+(4) One call mints the envelope's seal and the condition that\n // matches it, so the two can never drift apart.\n const exchange = sealExchange(\n {\n method: 'POST',\n // ADR 0025 (connector #596): the envelope target is resolved\n // STRICTLY BENEATH the route's configured handler path — it can\n // extend that path, never replace it. '' means \"the handler's own\n // path\", which is the whole answer for a route that terminates at\n // exactly one endpoint (g.rust.relay → …/write, g.rust.store →\n // …/store): the DESTINATION picks the endpoint, not the target.\n // An absolute target like '/write' is refused as an escape\n // attempt (F00) before the app is ever reached.\n target: options?.proxyPath ?? '',\n headers: [['content-type', 'application/json']],\n body: encodeUtf8(JSON.stringify({ event })),\n },\n identity.publicKey\n );\n\n const transport = this.getClaimTransport();\n const claimMessage = await this.resolveClaimForDestination(\n destination,\n BigInt(amount),\n options?.claim\n );\n\n const response = await transport.sendIlpPacketWithClaim(\n {\n destination,\n amount,\n data: toBase64(exchange.data),\n executionCondition: exchange.condition,\n },\n claimMessage\n );\n\n // (5) Open the answer with the secret this packet sealed.\n const outcome = readExchangeOutcome(\n response,\n response.data === undefined ? undefined : fromBase64(response.data),\n exchange.sharedSecret\n );\n\n if (outcome.kind === 'destination-refused') {\n return {\n success: false,\n refusedBy: 'destination',\n code: outcome.code,\n error: `Destination refused the write: ${outcome.code} - ${outcome.message}`,\n };\n }\n if (outcome.kind === 'path-refused') {\n return {\n success: false,\n refusedBy: 'path',\n code: outcome.code,\n error: `A connector on the path refused the write: ${outcome.code} - ${outcome.message}`,\n };\n }\n\n const { response: answer } = outcome;\n if (answer.status < 200 || answer.status >= 300) {\n const detail =\n answer.body.length > 0 ? ` - ${decodeUtf8(answer.body)}` : '';\n return {\n success: false,\n response: answer,\n error: `Write failed: the destination answered HTTP ${answer.status}${detail}`,\n };\n }\n\n return { success: true, eventId: event.id, response: answer };\n } catch (error) {\n console.error(\n '[ToonClient.publishEvent] ROOT CAUSE:',\n String(error),\n error instanceof Error ? error.stack : ''\n );\n // Two conditions are raised by THIS method before any packet exists, and\n // name a thing the caller can fix: the destination is not terminated\n // here, or there is no client edge to ask at all. Wrapping either in\n // `PUBLISH_ERROR` would hide the one fact worth surfacing behind the\n // most generic code this method has. Everything else — including a\n // connector that will not answer for its identity — keeps the existing\n // wrapping, so `PUBLISH_ERROR` still means \"the publish itself failed\".\n if (\n error instanceof ToonClientError &&\n (error.code === 'NO_TERMINATED_ROUTE' ||\n error.code === 'NO_CONNECTOR_EDGE')\n ) {\n throw error;\n }\n throw new ToonClientError(\n 'Failed to publish event',\n 'PUBLISH_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * What a destination costs, asked of the connector that terminates it —\n * `null` when it terminates no route matching it.\n *\n * The public form of the lookup `publishEvent` makes, for callers that need\n * a price BEFORE they build a packet: a pre-push estimate that must equal\n * what the push will actually pay, a fee quote shown to a user for consent.\n * Since ADR 0020 a price is flat per handler, so the figure is the whole\n * fee for one packet to that destination — there is nothing to multiply it\n * by. Cached per destination, so this is cheap to call repeatedly.\n *\n * @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.\n * @throws {ConnectorEdgeError} when the connector cannot be asked.\n */\n async getRoutePrice(destination: string): Promise<bigint | null> {\n const price = await this.connectorEdge.getRoutePrice(\n this.resolveClientEdgeEndpoint(),\n destination\n );\n return price === null ? null : price.price;\n }\n\n /**\n * What this destination costs, from the connector that terminates it.\n *\n * ADR 0020 makes a price flat per handler: one handler, one price, and an\n * app that wants to charge differently exposes more handlers. There is\n * therefore nothing to compute — the route table IS the price list, and\n * `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate\n * charges against, so it can never state a price a real request would not\n * be charged.\n *\n * Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is\n * one round trip per destination rather than one per packet.\n *\n * @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers\n * `404` — it does not terminate this destination. That is a refusal to\n * guess, not a zero: pricing an unroutable write at 0 (or at some local\n * fallback rate) would send a packet certain to be rejected, and report\n * the wrong reason for it.\n */\n private async routePriceFor(\n edge: string,\n destination: string\n ): Promise<bigint> {\n const price = await this.connectorEdge.getRoutePrice(edge, destination);\n if (price === null) {\n throw new ToonClientError(\n `The connector at ${edge} terminates no route for \"${destination}\", so it ` +\n 'cannot say what a write there costs. Check the destination, or pass an ' +\n 'explicit `ilpAmount` to price it yourself.',\n 'NO_TERMINATED_ROUTE'\n );\n }\n return price.price;\n }\n\n /**\n * The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the\n * same origin paid writes already POST `/ilp` to.\n *\n * Preferring the live transport's own endpoint over config is deliberate:\n * transport selection may have followed a discovered `httpEndpoint`, and\n * the identity must come from the connector actually being paid, not from\n * whatever URL was configured before discovery ran.\n *\n * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.\n */\n private resolveClientEdgeEndpoint(): string {\n const runtime = this.state?.runtimeClient as\n | { clientEdgeEndpoint?: string }\n | undefined;\n const endpoint =\n runtime?.clientEdgeEndpoint ??\n this.config.proxyUrl ??\n this.config.connectorUrl;\n if (!endpoint) {\n throw new ToonClientError(\n 'No connector client edge to ask for an identity. Configure `proxyUrl` or ' +\n '`connectorUrl`; a payload cannot be sealed without the terminating ' +\n \"connector's key (ADR 0018).\",\n 'NO_CONNECTOR_EDGE'\n );\n }\n return connectorEdgeBaseUrl(endpoint);\n }\n\n /**\n * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that\n * makes paying for an HTTP resource transparent:\n *\n * 1. Issues the HTTP request to `url`.\n * 2. On `402`, parses the x402 `accepts` array and selects the\n * `toon-channel` entry (see {@link Http402Client} for the wire shape).\n * 3. Opens/reuses a payment channel for the entry's ILP destination (via\n * ChannelManager), signs a balance proof for the demanded price, and\n * re-sends the SAME HTTP request as a transparent HTTP-in-ILP packet to\n * the connector's `POST /ilp` (via {@link HttpIlpClient}), with the claim\n * in the `ILP-Payment-Channel-Claim` header.\n * 4. Reconstructs and returns a standard Web `Response` from the FULFILL\n * `data`. The caller never sees ILP.\n *\n * If the origin offers no `toon-channel` entry, the original `402` Response is\n * returned unchanged (the caller sees the vanilla x402 challenge).\n *\n * The channel/claim plumbing is wired to the live ChannelManager + per-chain\n * signer via `resolveClaimForDestination` — identical to `publishEvent`. The\n * `amount` paid comes from the selected x402 entry (the resource's price).\n *\n * @throws {ToonClientError} If the client is not started.\n * @throws {ConnectorError} If the connector rejects the payment or returns no\n * HTTP payload.\n */\n async h402Fetch(url: string, opts?: H402FetchOptions): Promise<Response> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n // Pay only when a channel manager is configured; otherwise the engine still\n // probes and transparently surfaces the vanilla 402 (no resolveClaim hook).\n const client = new Http402Client({\n // Share this client's identity cache rather than letting each per-call\n // engine fetch the same connector's key again: `h402Fetch` builds a\n // fresh Http402Client per call (below), and a paid request now needs a\n // terminating key.\n connectorEdge: this.connectorEdge,\n ...(this.channelManager\n ? {\n resolveClaim: (destination: string, amount: bigint) =>\n this.resolveClaimForDestination(destination, amount),\n }\n : {}),\n });\n\n return client.fetch(url, opts);\n }\n\n /**\n * Sends a raw swap ILP packet (Story 12.5) to a swap peer with an attached\n * balance-proof claim. This is a lower-level surface than `publishEvent`:\n * it forwards the raw `IlpSendResult` so the sender (`streamSwap()`) can\n * decode FULFILL metadata itself.\n *\n * Claim resolution mirrors `publishEvent`:\n * (a) explicit `params.claim` -> use it,\n * (b) `channelManager` present -> auto-open + auto-sign for the peer\n * matching `destination`,\n * (c) neither -> throw MISSING_CLAIM.\n *\n * A caller may supply a sender-chosen 32-byte `executionCondition`\n * (`C = sha256(P)`, one fresh preimage per packet — toon-client#350,\n * rolling-swap spec §3 R1/R2) and an explicit `expiresAt` (R7). Both are\n * set on the wire by either transport (HTTP `POST /ilp` and BTP), and on\n * FULFILL the transport verifies `sha256(fulfillment) == condition` —\n * a mismatch comes back as `accepted: false` (code F99), never a silent\n * accept. Omitting them keeps today's zero-condition legacy packet.\n *\n * @throws {ToonClientError} INVALID_STATE / NO_ILP_TRANSPORT / MISSING_CLAIM\n */\n async sendSwapPacket(params: {\n destination: string;\n amount: bigint;\n toonData: Uint8Array;\n timeout?: number;\n claim?: SignedBalanceProof;\n /** Sender-chosen 32-byte execution condition; absent/zero = legacy. */\n executionCondition?: Uint8Array;\n /** Explicit ILP expiry; defaults to `now + timeout` in the transport. */\n expiresAt?: Date;\n }): Promise<IlpSendResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n const transport = this.getClaimTransport();\n\n const claimMessage = await this.resolveClaimForDestination(\n params.destination,\n params.amount,\n params.claim\n );\n\n return transport.sendIlpPacketWithClaim(\n {\n destination: params.destination,\n amount: String(params.amount),\n data: toBase64(params.toonData),\n timeout: params.timeout ?? 30000,\n ...(params.executionCondition\n ? { executionCondition: params.executionCondition }\n : {}),\n ...(params.expiresAt ? { expiresAt: params.expiresAt } : {}),\n },\n claimMessage as unknown as Record<string, unknown>\n );\n }\n\n /**\n * Build a BTP claim message from a pre-signed balance proof using the\n * CHAIN-APPROPRIATE signer.\n *\n * The explicit-claim path (caller signs the balance proof, then passes\n * `{ claim }`) must wrap the proof with the signer matching the channel's\n * chain. Hardcoding `EvmSigner.buildClaimMessage` here produced an EVM\n * `BTPClaimMessage` for a Solana/Mina balance proof — no `blockchain`\n * discriminator and the base58 channel account placed in the EVM\n * `channelId` field — which the connector's inbound validator classifies\n * as EVM and rejects with F06 (`Invalid channelId format`).\n *\n * When the proof's `channelId` is tracked we use\n * `getSignerForChannel(channelId).buildClaimMessage`, which emits the\n * correct per-chain envelope (e.g. `blockchain:'solana'` + base58\n * `channelAccount`). When it is not tracked we fall back to the EVM signer\n * to preserve prior behavior for lightweight/EVM-only callers.\n *\n * EVM output is byte-identical to the previous hardcoded path (the EVM\n * adapter in `getSignerForChannel` delegates to the same\n * `EvmSigner.buildClaimMessage`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- claim message is opaque forwarded type\n private buildClaimMessageForProof(claim: SignedBalanceProof): any {\n if (this.channelManager?.isTracking(claim.channelId)) {\n const signer = this.channelManager.getSignerForChannel(claim.channelId);\n return signer.buildClaimMessage(claim, this.getPublicKey());\n }\n return EvmSigner.buildClaimMessage(claim, this.getPublicKey());\n }\n\n /**\n * Resolve the ILP transport for a paid (claim-bearing) write.\n *\n * The connector is a payment-proxy: paid writes carry an ILP PREPARE plus the\n * signed payment-channel claim. Either transport speaks the SAME claim\n * contract — the BTP `payment-channel-claim` protocolData entry and the\n * ILP-over-HTTP `ILP-Payment-Channel-Claim` header serialize the same claim\n * JSON — so we route through whichever transport is ACTIVE rather than\n * hard-requiring BTP.\n *\n * Selection (mirrors `modes/http.ts` runtime-client precedence):\n * 1. `runtimeClient` when it implements `sendIlpPacketWithClaim` — this is\n * the HttpIlpClient (proxy `POST /ilp`) when a `proxyUrl`/\n * `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.\n * 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).\n *\n * The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no\n * proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no\n * paid-write transport and we throw a clear, actionable error.\n *\n * @throws {ToonClientError} NO_ILP_TRANSPORT when no active transport can send\n * a packet+claim.\n */\n private getClaimTransport(): {\n // IlpSendParams: both built-in transports (HttpIlpClient / BtpRuntimeClient)\n // accept the sender-chosen `executionCondition` + explicit `expiresAt`\n // extensions (toon-client#350) and enforce FULFILL preimage verification.\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult>;\n } {\n const state = this.state;\n if (!state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n const candidates: (IlpClient | BtpRuntimeClient | undefined)[] = [\n state.runtimeClient,\n state.btpClient,\n ];\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof (candidate as IlpClient).sendIlpPacketWithClaim === 'function'\n ) {\n return candidate as ReturnType<ToonClient['getClaimTransport']>;\n }\n }\n throw new ToonClientError(\n 'No ILP transport for paid writes. Configure `proxyUrl`/`connectorHttpEndpoint` ' +\n '(route through the connector proxy over ILP-over-HTTP) or `btpUrl` (BTP socket).',\n 'NO_ILP_TRANSPORT'\n );\n }\n\n /**\n * Shared claim-resolution logic used by `publishEvent` and `sendSwapPacket`.\n */\n private async resolveClaimForDestination(\n destination: string,\n amount: bigint,\n explicitClaim?: SignedBalanceProof\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- claim message is opaque forwarded type\n ): Promise<any> {\n if (explicitClaim) {\n return this.buildClaimMessageForProof(explicitClaim);\n }\n if (this.channelManager) {\n const peerId = this.resolvePeerId(destination);\n const negotiation = this.peerNegotiations.get(peerId);\n if (!negotiation) {\n throw new ToonClientError(\n `No negotiation metadata for peer \"${peerId}\" — was bootstrap completed?`,\n 'PEER_NOT_NEGOTIATED'\n );\n }\n const channelId = await this.channelManager.ensureChannel(\n peerId,\n negotiation\n );\n const proof = await this.channelManager.signBalanceProof(\n channelId,\n amount\n );\n const signer = this.channelManager.getSignerForChannel(channelId);\n return signer.buildClaimMessage(proof, this.getPublicKey());\n }\n throw new ToonClientError(\n 'No claim provided and no channel manager configured',\n 'MISSING_CLAIM'\n );\n }\n\n /**\n * Signs a balance proof for the given channel with the specified amount.\n * Delegates to ChannelManager which auto-increments nonce and tracks cumulative amount.\n *\n * @param channelId - Payment channel identifier\n * @param amount - Additional amount to add to cumulative transferred amount\n * @returns Signed balance proof\n * @throws {ToonClientError} If no EVM signer configured or channel not tracked\n */\n async signBalanceProof(\n channelId: string,\n amount: bigint\n ): Promise<SignedBalanceProof> {\n if (!this.channelManager) {\n throw new ToonClientError(\n 'No EVM signer configured. Provide evmPrivateKey in config.',\n 'NO_EVM_SIGNER'\n );\n }\n return this.channelManager.signBalanceProof(channelId, amount);\n }\n\n /**\n * Eagerly open (or return existing) payment channel for the given destination.\n *\n * Channels are normally opened lazily on the first `publishEvent()` /\n * `sendSwapPacket()` call. This method exposes the lazy-open path so\n * callers (and E2E tests) that need a tracked `channelId` BEFORE publishing\n * can force the open. Idempotent — returns the existing channel ID for the\n * peer if one is already open.\n *\n * @param destination - Optional ILP destination address. Defaults to\n * `config.destinationAddress`.\n * @returns The channel ID of the (now) open channel.\n * @throws {ToonClientError} If client not started, no channel manager\n * configured, or peer negotiation metadata missing.\n */\n async openChannel(destination?: string): Promise<string> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n if (!this.channelManager) {\n throw new ToonClientError(\n 'No channel manager configured. Provide evmPrivateKey in config.',\n 'NO_EVM_SIGNER'\n );\n }\n const dest = destination ?? this.config.destinationAddress;\n if (!dest) {\n throw new ToonClientError(\n 'No destination provided and no default destinationAddress configured.',\n 'NO_DESTINATION'\n );\n }\n const peerId = this.resolvePeerId(dest);\n const negotiation = this.peerNegotiations.get(peerId);\n if (!negotiation) {\n throw new ToonClientError(\n `No negotiation metadata for peer \"${peerId}\" — was bootstrap completed?`,\n 'PEER_NOT_NEGOTIATED'\n );\n }\n return this.channelManager.ensureChannel(peerId, negotiation);\n }\n\n /**\n * Gets list of tracked payment channel IDs.\n */\n getTrackedChannels(): string[] {\n return this.channelManager?.getTrackedChannels() ?? [];\n }\n\n /**\n * Gets the current nonce for a tracked channel.\n */\n getChannelNonce(channelId: string): number {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getNonce(channelId);\n }\n\n /**\n * Gets the cumulative transferred amount for a tracked channel.\n */\n getChannelCumulativeAmount(channelId: string): bigint {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getCumulativeAmount(channelId);\n }\n\n /**\n * Gets the on-chain deposit total (locked collateral) for a tracked channel.\n * The available (spendable) balance is this minus the cumulative spent amount.\n */\n getChannelDepositTotal(channelId: string): bigint {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getDepositTotal(channelId);\n }\n\n /**\n * Deposit additional collateral into an open channel. `amount` is the delta to\n * add (base units, decimal string or bigint). The daemon signs its own tx; no\n * key material leaves the client. Reads the current tracked deposit, performs\n * the on-chain deposit, updates the tracked total, and returns the new total.\n * EVM is live; Solana/Mina deposit lands in a follow-up.\n */\n async depositToChannel(\n channelId: string,\n amount: string | bigint\n ): Promise<{ channelId: string; txHash?: string; depositTotal: string }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const delta = BigInt(amount);\n if (delta <= 0n) throw new Error('Deposit amount must be positive.');\n const currentDeposit = this.channelManager.getDepositTotal(channelId);\n const result = await this.onChainChannelClient.depositToChannel(\n channelId,\n delta,\n {\n currentDeposit,\n }\n );\n this.channelManager.setDepositTotal(channelId, result.depositTotal);\n return {\n channelId,\n ...(result.txHash ? { txHash: result.txHash } : {}),\n depositTotal: result.depositTotal.toString(),\n };\n }\n\n /**\n * Close a channel to begin the settlement grace period (first half of\n * withdraw). Records `closedAt`/`settleableAt` (unix seconds) on the tracked\n * channel — persisted, so the grace timer survives a daemon restart. Spends\n * on-chain. EVM today; Solana/Mina are follow-ups.\n */\n async closeChannel(\n channelId: string\n ): Promise<{\n channelId: string;\n txHash?: string;\n closedAt: string;\n settleableAt: string;\n }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const r = await this.onChainChannelClient.closeChannel(channelId);\n this.channelManager.setChannelClosed(channelId, r.closedAt, r.settleableAt);\n return {\n channelId,\n ...(r.txHash ? { txHash: r.txHash } : {}),\n closedAt: r.closedAt.toString(),\n settleableAt: r.settleableAt.toString(),\n };\n }\n\n /**\n * Settle a closed channel to release collateral (second half of withdraw).\n * THE time guard: never settle before `settleableAt`. A too-early call throws\n * a retryable error (carrying the remaining seconds) BEFORE spending gas — the\n * contract would revert anyway. Spends on-chain. EVM today.\n */\n async settleChannel(\n channelId: string\n ): Promise<{ channelId: string; txHash?: string }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const settleableAt = this.channelManager.getSettleableAt(channelId);\n if (settleableAt === undefined) {\n throw new Error(\n `Channel \"${channelId}\" is not closed; call closeChannel first.`\n );\n }\n const nowSec = BigInt(Math.floor(Date.now() / 1000));\n if (nowSec < settleableAt) {\n const remaining = settleableAt - nowSec;\n throw Object.assign(\n new Error(\n `Channel \"${channelId}\" is not settleable yet — ${remaining}s remain (settleable at ${settleableAt}).`\n ),\n {\n name: 'SettleTooEarlyError',\n retryable: true,\n settleableAt: settleableAt.toString(),\n }\n );\n }\n const r = await this.onChainChannelClient.settleChannel(channelId);\n this.channelManager.setChannelSettled(channelId, nowSec);\n return { channelId, ...(r.txHash ? { txHash: r.txHash } : {}) };\n }\n\n /**\n * Submit a receive-side swap settlement bundle on-chain (toon-client#352).\n * The bundle comes from the sdk's `buildSettlementTx` over persisted,\n * verified chain-B claims (`buildSwapSettlements`); this signs it with the\n * client's EVM account (the claim recipient) and broadcasts it.\n *\n * Env-gated seam: EVM only, and only when `chainRpcUrls[bundle.chain]` is\n * configured — otherwise this throws a clear config error and callers\n * surface a built-not-submitted result. Solana submission and the Mina\n * receive-side co-sign path are explicit follow-ups (see\n * swap/settle-received-claims.ts module doc).\n */\n async settleSwapBundle(\n bundle: SettlementBundle\n ): Promise<SubmitEvmSettlementResult> {\n if (bundle.chainKind === 'mina') {\n // Mina receive-side redemption (#357): reads the live channel state,\n // produces the recipient's co-signature, and drives the dual-party\n // `claimFromChannel` (o1js proving). Config-gated on minaChannel.graphqlUrl\n // + a derived Mina key; fails closed (never a silent pass) with a stable\n // MinaSettlementError code that the daemon surfaces.\n if (!this.minaPrivateKey) {\n throw new Error(\n 'Mina signer not configured (no mnemonic / mina-signer) — cannot co-sign the receive-side claim.'\n );\n }\n const makerSignature = parseMakerMinaSignature(\n this.config.swapMinaMakerSignatures?.[bundle.channelId]\n );\n const { txHash } = await submitMinaSettlement(bundle, {\n recipientPrivateKey: this.minaPrivateKey,\n ...(this.config.minaChannel?.graphqlUrl\n ? { graphqlUrl: this.config.minaChannel.graphqlUrl }\n : {}),\n ...(makerSignature ? { makerSignature } : {}),\n });\n return { txHash };\n }\n if (bundle.chainKind !== 'evm') {\n throw new Error(\n `Swap settlement submission for ${bundle.chainKind} (${bundle.chain}) is not wired yet — EVM only today.`\n );\n }\n const rpcUrl = this.config.chainRpcUrls?.[bundle.chain];\n if (!rpcUrl) {\n throw new Error(\n `No RPC URL configured for chain \"${bundle.chain}\" — add it to chainRpcUrls to enable swap settlement submission.`\n );\n }\n if (!this.evmSigner) {\n throw new Error('EVM signer not configured (no evmPrivateKey/mnemonic).');\n }\n return submitEvmSettlement(bundle, {\n rpcUrl,\n account: this.evmSigner.account,\n });\n }\n\n /** Where a tracked channel sits in the withdraw journey. */\n getChannelCloseState(\n channelId: string\n ): 'open' | 'closing' | 'settleable' | 'settled' {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getChannelCloseState(channelId);\n }\n\n getSettleableAt(channelId: string): bigint | undefined {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getSettleableAt(channelId);\n }\n\n /**\n * Re-hydrate a RESUMED channel's on-chain deposit. Persisted channel state\n * omits `depositTotal`, so after a daemon restart the tracked deposit is `0`\n * and the wallet shows 0 spendable even though real collateral is locked\n * on-chain. Read the participant's `deposit` from the `participants` mapping\n * and update the tracked total so `depositTotal - cumulativeAmount` is right.\n * Best-effort by caller (await + catch); returns the on-chain deposit, or\n * `undefined` when it can't be read (no channel manager / on-chain client /\n * EVM address).\n */\n async rehydrateChannelDeposit(\n channelId: string,\n opts: { chain: string; tokenNetworkAddress: string }\n ): Promise<bigint | undefined> {\n if (!this.channelManager || !this.onChainChannelClient) return undefined;\n const participant = this.getEvmAddress();\n if (!participant) return undefined;\n const { deposit } = await this.onChainChannelClient.readEvmParticipantState(\n {\n chain: opts.chain,\n tokenNetworkAddress: opts.tokenNetworkAddress,\n channelId,\n participant,\n }\n );\n this.channelManager.setDepositTotal(channelId, deposit);\n return deposit;\n }\n\n /**\n * Read the on-chain settlement-token balance of this client's OWN wallet on\n * each configured chain (EVM token, Solana SPL, native MINA). A free read — no\n * signing, no payment. Best-effort per chain: a chain whose config is absent or\n * whose RPC read fails is omitted rather than failing the whole result, so the\n * wallet view degrades gracefully. Available after `start()` (Solana/Mina keys\n * are derived there).\n */\n async getBalances(): Promise<WalletBalance[]> {\n const out: WalletBalance[] = [];\n\n // EVM: read the settlement token (preferredTokens) for the client's\n // settlement chain. `supportedChains` is a union with the network PRESET\n // first (see applyDefaults), so the preset's primary EVM chain (e.g.\n // base-sepolia on devnet) sorts ahead of an explicitly-configured chain\n // like `evm:anvil:31337`. Picking the FIRST evm key would read the preset\n // chain's token — a different contract with a 0 balance — even though the\n // faucet funds, and channels live on, the settlement chain. So prefer the\n // evm key that is the actual settlement chain (present in\n // `settlementAddresses`), falling back to the first usable evm chain.\n const evmAddress = this.getEvmAddress();\n const rpcUrls = this.config.chainRpcUrls;\n const tokens = this.config.preferredTokens;\n if (evmAddress && rpcUrls && tokens) {\n const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);\n const usableEvm = (c: string): boolean =>\n c.startsWith('evm') && Boolean(rpcUrls[c]) && Boolean(tokens[c]);\n const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});\n const chainKey =\n settlementKeys.find((c) => usableEvm(c)) ?? chainKeys.find(usableEvm);\n const rpcUrl = chainKey ? rpcUrls[chainKey] : undefined;\n const tokenAddress = chainKey ? tokens[chainKey] : undefined;\n if (chainKey && rpcUrl && tokenAddress) {\n try {\n out.push(\n await readEvmTokenBalance({\n rpcUrl,\n chainKey,\n tokenAddress,\n owner: evmAddress,\n })\n );\n } catch {\n /* best-effort: drop EVM on read failure */\n }\n }\n }\n\n // Solana: SPL balance of the negotiated token mint.\n const solAddress = this.getSolanaAddress();\n const sol = this.config.solanaChannel;\n if (solAddress && sol?.rpcUrl && sol.tokenMint) {\n try {\n out.push(\n await readSolanaTokenBalance({\n rpcUrl: sol.rpcUrl,\n mint: sol.tokenMint,\n owner: solAddress,\n })\n );\n } catch {\n /* best-effort */\n }\n }\n\n // Mina: native MINA balance via GraphQL.\n const minaAddress = this.getMinaAddress();\n const mina = this.config.minaChannel;\n if (minaAddress && mina?.graphqlUrl) {\n try {\n out.push(\n await readMinaBalance({\n graphqlUrl: mina.graphqlUrl,\n owner: minaAddress,\n })\n );\n } catch {\n /* best-effort */\n }\n }\n\n return out;\n }\n\n /**\n * The FULL multi-chain wallet view (#299): for every chain the identity is\n * configured for, the native coin (ETH / SOL / MINA) AND every configured\n * token (USDC), grouped per chain with the identity's address on that chain.\n * A superset of {@link getBalances} — which stays scoped to the channel's\n * settlement token — kept as a separate reader so channel-settlement callers\n * are unaffected.\n *\n * FREE: read-only RPC, no signing, no payment. Works on an UNSTARTED client:\n * the Solana/Mina addresses (which the signers only register during\n * `start()`) are derived on demand from the retained mnemonic — the SAME keys\n * `start()` would register and that `rig fund` prints — so all configured\n * chains appear even before a start. Best-effort per chain: an unreachable\n * RPC yields `{ unreadable: true }` for that chain, never failing the others.\n *\n * `fallback` supplies Solana/Mina channel params (RPC/GraphQL + token) to use\n * ONLY when `config.solanaChannel`/`config.minaChannel` are unset — a\n * wallet-view-only default (e.g. the network preset's public RPC) that lets a\n * caller show all three chains, reading 0 for a not-yet-on-chain account,\n * WITHOUT injecting those channels into the client's settlement config (which\n * would change chain negotiation). Explicit config wins.\n */\n async getWalletBalances(fallback?: {\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n }): Promise<WalletChainBalances[]> {\n const sources: WalletBalanceSources = {};\n\n // Solana/Mina keys are only registered as signers during start(); derive\n // them from the retained mnemonic on demand so an unstarted client (e.g.\n // `rig balance`) still reports every configured chain. Derived once, lazily.\n let derived: Awaited<ReturnType<typeof deriveFullIdentity>> | undefined;\n let derivedTried = false;\n const ensureDerived = async (): Promise<typeof derived> => {\n if (derivedTried) return derived;\n derivedTried = true;\n if (this.config.mnemonic) {\n derived = await deriveFullIdentity(\n this.config.mnemonic,\n this.config.mnemonicAccountIndex ?? 0\n );\n }\n return derived;\n };\n\n // EVM: native ETH + settlement USDC. Pick the settlement chain key the same\n // way getBalances does (settlement chain wins over the preset primary).\n const evmAddress = this.getEvmAddress();\n const rpcUrls = this.config.chainRpcUrls;\n const tokens = this.config.preferredTokens;\n if (evmAddress && rpcUrls) {\n const usableEvm = (c: string): boolean =>\n c.startsWith('evm') && Boolean(rpcUrls[c]);\n const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});\n const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);\n const chainKey =\n settlementKeys.find(usableEvm) ?? chainKeys.find(usableEvm);\n if (chainKey && rpcUrls[chainKey]) {\n sources.evm = {\n chainKey,\n rpcUrl: rpcUrls[chainKey],\n owner: evmAddress,\n ...(tokens?.[chainKey] ? { tokenAddress: tokens[chainKey] } : {}),\n };\n }\n }\n\n // Solana: native SOL + SPL USDC (the negotiated mint). Explicit config\n // wins; else the caller's wallet-view fallback (e.g. network preset RPC).\n const sol = this.config.solanaChannel ?? fallback?.solanaChannel;\n if (sol?.rpcUrl) {\n const solAddress =\n this.getSolanaAddress() ?? (await ensureDerived())?.solana.publicKey;\n if (solAddress) {\n sources.solana = {\n chainKey: 'solana',\n rpcUrl: sol.rpcUrl,\n owner: solAddress,\n ...(sol.tokenMint ? { tokenMint: sol.tokenMint } : {}),\n };\n }\n }\n\n // Mina: native MINA plus, when the deployment settles a custom token, that\n // token's balance (USDC) — read via the derived/explicit `minaChannel.tokenId`\n // (core preset or announce, see resolveNetworkTopology/deriveMinaChannel). A\n // fresh client with no explicit `config.minaChannel` still gets both.\n // Explicit config wins; else the caller's wallet-view fallback.\n const mina = this.config.minaChannel ?? fallback?.minaChannel;\n if (mina?.graphqlUrl) {\n const minaAddress =\n this.getMinaAddress() ?? (await ensureDerived())?.mina.publicKey;\n if (minaAddress) {\n sources.mina = {\n chainKey: 'mina',\n graphqlUrl: mina.graphqlUrl,\n owner: minaAddress,\n ...(mina.tokenId ? { tokenId: mina.tokenId } : {}),\n };\n }\n }\n\n return readWalletBalances(sources);\n }\n\n /**\n * Resolves an ILP destination address to a peer ID.\n * Convention: destination \"g.toon.peer1\" → peerId \"peer1\" (last segment).\n * Falls back to first known peer if no match.\n */\n private resolvePeerId(destination: string): string {\n // Check if destination matches a known peer's ILP address pattern\n const segments = destination.split('.');\n const lastSegment = segments[segments.length - 1] ?? '';\n\n // Direct match against peerNegotiations keys\n if (lastSegment && this.peerNegotiations.has(lastSegment)) {\n return lastSegment;\n }\n\n // Try \"nostr-\" prefixed peer IDs (convention: nostr-{pubkey_prefix})\n for (const peerId of this.peerNegotiations.keys()) {\n if (\n destination.endsWith(`.${peerId}`) ||\n destination.endsWith(`.${peerId.replace('nostr-', '')}`)\n ) {\n return peerId;\n }\n }\n\n // Fallback: return first peer\n const firstPeerResult = this.peerNegotiations.keys().next();\n if (!firstPeerResult.done && firstPeerResult.value)\n return firstPeerResult.value;\n\n throw new ToonClientError(\n `Cannot resolve peer for destination: ${destination}`,\n 'PEER_NOT_FOUND'\n );\n }\n\n /**\n * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.\n */\n private getChainContext(\n negotiatedChain?: string\n ):\n | { chainId: number; tokenNetworkAddress: string; tokenAddress?: string }\n | undefined {\n if (!negotiatedChain) return undefined;\n const parts = negotiatedChain.split(':');\n // Accept 3-part `evm:{network}:{chainId}` and 2-part `evm:{chainId}`.\n const chainIdPart =\n parts.length >= 3 ? parts[2] : parts.length >= 2 ? parts[1] : undefined;\n const numericChainId =\n chainIdPart !== undefined ? parseInt(chainIdPart, 10) : NaN;\n if (isNaN(numericChainId)) return undefined;\n const tokenNetworkAddress = this.config.tokenNetworks?.[negotiatedChain];\n if (!tokenNetworkAddress) return undefined;\n const tokenAddress = this.config.preferredTokens?.[negotiatedChain];\n return { chainId: numericChainId, tokenNetworkAddress, tokenAddress };\n }\n\n /**\n * Gets the default chain context from the first supported chain in config.\n */\n private getDefaultChainContext():\n | { chainId: number; tokenNetworkAddress: string; tokenAddress?: string }\n | undefined {\n const chains = this.config.supportedChains;\n if (!chains?.length) return undefined;\n return this.getChainContext(chains[0]);\n }\n\n /**\n * Sends an ILP payment, optionally with a balance proof claim via BTP.\n *\n * @param params - Payment parameters\n * @returns ILP send result\n * @throws {ToonClientError} If client is not started\n */\n async sendPayment(params: {\n destination: string;\n amount: string;\n data?: string;\n claim?: SignedBalanceProof;\n }): Promise<IlpSendResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n const ilpParams = {\n destination: params.destination,\n amount: params.amount,\n data: params.data ?? '',\n };\n\n // Require claim + BTP — plain sendIlpPacket is only valid for\n // node-to-node forwarding (relay.ts), not client-to-node.\n if (!params.claim) {\n throw new ToonClientError(\n 'Signed balance proof required. Call signBalanceProof() first.',\n 'MISSING_CLAIM'\n );\n }\n const transport = this.getClaimTransport();\n\n const claimMessage = this.buildClaimMessageForProof(params.claim);\n return transport.sendIlpPacketWithClaim(\n ilpParams,\n claimMessage as unknown as Record<string, unknown>\n );\n }\n\n /**\n * Stops the ToonClient and cleans up resources.\n *\n * This will:\n * 1. Disconnect BTP client if connected\n * 2. Clear internal state\n *\n * @throws {ToonClientError} If client is not started\n */\n async stop(): Promise<void> {\n if (!this.state) {\n throw new ToonClientError('Client not started', 'INVALID_STATE');\n }\n\n try {\n // Disconnect BTP client if connected\n if (this.state.btpClient) {\n await this.state.btpClient.disconnect();\n }\n\n // Clear state\n this.state = null;\n } catch (error) {\n throw new ToonClientError(\n 'Failed to stop client',\n 'STOP_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Returns true if the client is currently started.\n */\n isStarted(): boolean {\n return this.state !== null;\n }\n\n /**\n * Gets the number of peers discovered during bootstrap.\n *\n * @returns Number of peers discovered\n * @throws {ToonClientError} If client is not started\n */\n getPeersCount(): number {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n return this.state.peersDiscovered;\n }\n\n /**\n * Gets the list of peers discovered by the relay monitor.\n *\n * @returns Array of discovered peer objects\n * @throws {ToonClientError} If client is not started\n */\n getDiscoveredPeers() {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n return this.state.discoveryTracker.getDiscoveredPeers();\n }\n}\n","import { generateSecretKey } from 'nostr-tools/pure';\nimport {\n resolveClientNetwork,\n type NetworkFamilyStatus,\n} from '@toon-protocol/core';\nimport { ValidationError } from './errors.js';\nimport {\n validateMnemonic,\n deriveNostrKeyFromMnemonic,\n} from './keys/KeyDerivation.js';\nimport type { ToonClientConfig } from './types.js';\n\n/**\n * Settlement info produced by buildSettlementInfo().\n * Extends the core SettlementConfig shape with ilpAddress for client use.\n */\nexport interface ClientSettlementInfo {\n ilpAddress?: string;\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n}\n\n/**\n * Applies named-network preset defaults to a client config.\n *\n * When `config.network` is set and != `'custom'`, the settlement-related\n * fields are defaulted from the shared core presets (`resolveClientNetwork`):\n * RPC/GraphQL URLs, supported chain identifiers, preferred tokens, EVM\n * TokenNetwork addresses, and the Solana/Mina channel params. Any explicit\n * per-chain field on `config` OVERRIDES the preset (explicit always wins).\n *\n * `'custom'` and the unset case both pass `config` through untouched, keeping\n * the fully-manual path and full backward compatibility.\n *\n * @returns A shallow copy with preset defaults merged in (never mutates input).\n */\nexport function applyNetworkPresets(\n config: ToonClientConfig\n): ToonClientConfig {\n const { network } = config;\n if (!network || network === 'custom') return config;\n\n const presets = resolveClientNetwork(network);\n\n // Merge a preset record under an explicit one (explicit keys win).\n const mergeRecord = (\n explicit: Record<string, string> | undefined,\n preset: Record<string, string>\n ): Record<string, string> => ({ ...preset, ...explicit });\n\n // supportedChains: union (preset first), preserving any explicit extras.\n const supportedChains = config.supportedChains\n ? Array.from(\n new Set([...presets.supportedChains, ...config.supportedChains])\n )\n : presets.supportedChains;\n\n return {\n ...config,\n supportedChains,\n chainRpcUrls: mergeRecord(config.chainRpcUrls, presets.chainRpcUrls),\n preferredTokens: mergeRecord(\n config.preferredTokens,\n presets.preferredTokens\n ),\n tokenNetworks: mergeRecord(config.tokenNetworks, presets.tokenNetworks),\n // settlementAddresses are identity-derived (per-client), so they have no\n // preset; pass any explicit value through unchanged.\n ...(config.settlementAddresses && {\n settlementAddresses: config.settlementAddresses,\n }),\n // Channel params: preset fills the deployed programId/zkApp + URLs unless\n // the caller supplied their own (explicit object wins wholesale).\n ...(presets.solanaChannel && {\n solanaChannel: config.solanaChannel ?? presets.solanaChannel,\n }),\n ...(presets.minaChannel && {\n minaChannel: config.minaChannel ?? presets.minaChannel,\n }),\n };\n}\n\n/**\n * Returns per-chain settlement readiness for the configured `network` tier,\n * mirroring the relay node's status. Returns `undefined` when `network` is\n * unset or `'custom'` (no preset tier to report on).\n */\nexport function getNetworkStatus(\n config: ToonClientConfig\n): NetworkFamilyStatus | undefined {\n const { network } = config;\n if (!network || network === 'custom') return undefined;\n return resolveClientNetwork(network).status;\n}\n\n/**\n * Normalize a connector-proxy base URL into its `POST /ilp` endpoint.\n *\n * `https://proxy.devnet.toonprotocol.dev` → `https://proxy.devnet.toonprotocol.dev/ilp`\n * `https://proxy.devnet.toonprotocol.dev/ilp` → unchanged (idempotent)\n * `https://proxy.devnet.toonprotocol.dev/` → `https://proxy.devnet.toonprotocol.dev/ilp`\n *\n * Returns `undefined` for an empty/falsy input so callers can `??`-chain it.\n */\nexport function proxyIlpEndpoint(proxyUrl: string | undefined): string | undefined {\n if (!proxyUrl) return undefined;\n const trimmed = proxyUrl.replace(/\\/+$/, '');\n return /\\/ilp$/i.test(trimmed) ? trimmed : `${trimmed}/ilp`;\n}\n\n/**\n * Validates ToonClient configuration.\n *\n * This story implements HTTP mode only. Embedded mode validation will be added in a future epic.\n *\n * @throws {ValidationError} If configuration is invalid\n */\nexport function validateConfig(config: ToonClientConfig): void {\n // Reject embedded mode (not implemented in this story)\n if (config.connector !== undefined) {\n throw new ValidationError(\n 'Embedded mode not yet implemented in ToonClient. Use connectorUrl for HTTP mode.'\n );\n }\n\n // Require an HTTP edge for HTTP mode — either an explicit `connectorUrl` or a\n // connector-`proxyUrl` (the devnet payment-proxy). `applyDefaults` derives\n // `connectorUrl` from `proxyUrl` when only the proxy is given.\n if (!config.connectorUrl && !config.proxyUrl) {\n throw new ValidationError(\n 'connectorUrl (or proxyUrl) is required for HTTP mode. Example: \"http://localhost:8080\"'\n );\n }\n\n // Validate connectorUrl format\n if (config.connectorUrl) {\n try {\n const url = new URL(config.connectorUrl);\n if (!url.protocol.startsWith('http')) {\n throw new Error('Must be HTTP or HTTPS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid connectorUrl: must be a valid HTTP/HTTPS URL (e.g., \"http://localhost:8080\"). ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate proxyUrl / faucetUrl format when provided (both are HTTP(S) URLs).\n for (const [field, value] of [\n ['proxyUrl', config.proxyUrl],\n ['faucetUrl', config.faucetUrl],\n ] as const) {\n if (value === undefined) continue;\n try {\n const url = new URL(value);\n if (!url.protocol.startsWith('http')) {\n throw new Error('Must be HTTP or HTTPS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid ${field}: must be a valid HTTP/HTTPS URL. ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate secretKey only when provided\n if (config.secretKey !== undefined) {\n if (!config.secretKey || config.secretKey.length !== 32) {\n throw new ValidationError(\n 'secretKey must be 32 bytes (Nostr private key)'\n );\n }\n }\n\n // Validate mnemonic when provided. The mnemonic derives the Nostr/EVM +\n // Solana/Mina identity, so it cannot coexist with an explicit secretKey\n // (that would split the Nostr identity from the Solana/Mina identity). An\n // explicit evmPrivateKey override IS allowed (documented hardware-wallet case).\n if (config.mnemonic !== undefined) {\n if (config.secretKey !== undefined) {\n throw new ValidationError(\n 'Provide either `mnemonic` or `secretKey`, not both — the mnemonic ' +\n 'derives the Nostr key, so a separate secretKey would yield an ' +\n 'inconsistent cross-chain identity. (An `evmPrivateKey` override is allowed.)'\n );\n }\n if (\n typeof config.mnemonic !== 'string' ||\n !validateMnemonic(config.mnemonic)\n ) {\n throw new ValidationError('mnemonic must be a valid BIP-39 phrase');\n }\n }\n\n // Validate mnemonicAccountIndex when provided (must be a non-negative\n // integer within the BIP-32 non-hardened range, matching the SDK guard).\n if (config.mnemonicAccountIndex !== undefined) {\n const idx = config.mnemonicAccountIndex;\n if (!Number.isInteger(idx) || idx < 0 || idx > 0x7fffffff) {\n throw new ValidationError(\n 'mnemonicAccountIndex must be a non-negative integer (0 to 2147483647)'\n );\n }\n }\n\n if (!config.ilpInfo?.ilpAddress) {\n throw new ValidationError('ilpInfo.ilpAddress is required');\n }\n\n if (!config.toonEncoder || typeof config.toonEncoder !== 'function') {\n throw new ValidationError('toonEncoder function is required');\n }\n\n if (!config.toonDecoder || typeof config.toonDecoder !== 'function') {\n throw new ValidationError('toonDecoder function is required');\n }\n\n // Validate evmPrivateKey format when provided\n if (config.evmPrivateKey !== undefined) {\n if (config.evmPrivateKey instanceof Uint8Array) {\n if (config.evmPrivateKey.length !== 32) {\n throw new ValidationError('evmPrivateKey must be 32 bytes');\n }\n } else if (typeof config.evmPrivateKey === 'string') {\n const hex = config.evmPrivateKey.startsWith('0x')\n ? config.evmPrivateKey.slice(2)\n : config.evmPrivateKey;\n if (!/^[0-9a-fA-F]{64}$/.test(hex)) {\n throw new ValidationError('evmPrivateKey must be a 32-byte hex string');\n }\n } else {\n throw new ValidationError(\n 'evmPrivateKey must be a hex string or Uint8Array'\n );\n }\n }\n\n // Validate btpUrl when provided\n if (config.btpUrl !== undefined) {\n try {\n const url = new URL(config.btpUrl);\n if (!url.protocol.startsWith('ws')) {\n throw new Error('Must be WS or WSS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid btpUrl: must be a valid WebSocket URL (e.g., \"ws://localhost:3000\"). ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate chainRpcUrls keys match supportedChains when both present\n if (config.chainRpcUrls && config.supportedChains) {\n for (const chain of Object.keys(config.chainRpcUrls)) {\n if (!config.supportedChains.includes(chain)) {\n throw new ValidationError(\n `chainRpcUrls key \"${chain}\" is not in supportedChains`\n );\n }\n }\n }\n}\n\n/**\n * The resolved config type after defaults are applied.\n * secretKey is guaranteed to be present (auto-generated if omitted).\n */\nexport type ResolvedConfig = Required<\n Omit<\n ToonClientConfig,\n | 'connector'\n | 'mnemonic'\n | 'mnemonicAccountIndex'\n | 'evmPrivateKey'\n | 'network'\n | 'supportedChains'\n | 'settlementAddresses'\n | 'preferredTokens'\n | 'tokenNetworks'\n | 'btpUrl'\n | 'btpAuthToken'\n | 'btpPeerId'\n | 'connectorHttpEndpoint'\n | 'proxyUrl'\n | 'faucetUrl'\n | 'connectorSupportsUpgrade'\n | 'chainRpcUrls'\n | 'initialDeposit'\n | 'settlementTimeout'\n | 'solanaChannel'\n | 'minaChannel'\n | 'swapMinaMakerSignatures'\n | 'channelStorePath'\n | 'knownPeers'\n | 'destinationAddress'\n >\n> & {\n connector?: unknown;\n /** Always present after applyDefaults() — derived from secretKey if not explicitly provided */\n evmPrivateKey: string | Uint8Array;\n /**\n * BIP-39 phrase retained so `ToonClient.start()` can derive the Solana/Mina\n * keys asynchronously and register the corresponding signers. The Nostr/EVM\n * keys are already resolved synchronously into `secretKey`/`evmPrivateKey`.\n */\n mnemonic?: string;\n /**\n * BIP-44 account index for mnemonic-based derivation (defaults to 0).\n * Retained so `ToonClient.start()` derives the Solana/Mina signers at the\n * same index as the synchronously-resolved Nostr/EVM keys.\n */\n mnemonicAccountIndex?: number;\n /** Named network tier, retained for `getNetworkStatus()`. */\n network?: ToonClientConfig['network'];\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n btpUrl?: string;\n btpAuthToken?: string;\n btpPeerId?: string;\n connectorHttpEndpoint?: string;\n proxyUrl?: string;\n faucetUrl?: string;\n connectorSupportsUpgrade?: boolean;\n chainRpcUrls?: Record<string, string>;\n initialDeposit?: string;\n settlementTimeout?: number;\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n swapMinaMakerSignatures?: ToonClientConfig['swapMinaMakerSignatures'];\n channelStorePath?: string;\n knownPeers?: {\n pubkey: string;\n relayUrl: string;\n btpEndpoint?: string;\n }[];\n destinationAddress: string;\n};\n\n/**\n * Applies default values to optional configuration fields.\n * Auto-generates a Nostr keypair when secretKey is omitted.\n * Derives btpUrl from connectorUrl when not provided.\n */\nexport function applyDefaults(rawConfig: ToonClientConfig): ResolvedConfig {\n // Fill settlement-related defaults from the named-network presets first\n // (explicit per-chain fields always win). No-op for unset/`custom`.\n const config = applyNetworkPresets(rawConfig);\n\n // Resolve the Nostr secret key. Precedence:\n // 1. explicit secretKey\n // 2. derived from mnemonic (Nostr/EVM only — Solana/Mina are derived\n // asynchronously in start(), which is why the mnemonic is retained)\n // 3. auto-generated ephemeral key\n const secretKey =\n config.secretKey ??\n (config.mnemonic\n ? deriveNostrKeyFromMnemonic(\n config.mnemonic,\n config.mnemonicAccountIndex ?? 0\n ).secretKey\n : generateSecretKey());\n\n // Derive the connector-proxy `POST /ilp` endpoint from `proxyUrl` (unless an\n // explicit `connectorHttpEndpoint` was given — explicit always wins). When set\n // this makes `selectIlpTransport` prefer the stateless HttpIlpClient transport\n // for one-shot writes, routing through the devnet payment-proxy.\n const connectorHttpEndpoint =\n config.connectorHttpEndpoint ?? proxyIlpEndpoint(config.proxyUrl);\n\n // `connectorUrl` is required by validateConfig but can be satisfied by\n // `proxyUrl`; fall back to the proxy base so downstream code (HttpRuntimeClient\n // fallback, destination derivation) always has an HTTP edge URL.\n const connectorUrl =\n config.connectorUrl ?? config.proxyUrl?.replace(/\\/+$/, '');\n\n // Derive btpUrl from connectorUrl when not explicitly provided\n // http://host:8080 → ws://host:3000.\n // SKIP this auto-derivation when an HTTP/proxy transport is configured: the\n // proxy edge serves ILP-over-HTTP and may not expose BTP, so we must not open\n // (or require) a BTP socket. Writes route through HttpIlpClient instead.\n let btpUrl = config.btpUrl;\n if (!btpUrl && connectorUrl && !connectorHttpEndpoint) {\n try {\n const url = new URL(connectorUrl);\n const wsProtocol = url.protocol === 'https:' ? 'wss:' : 'ws:';\n btpUrl = `${wsProtocol}//${url.hostname}:3000`;\n } catch {\n // connectorUrl already validated, this shouldn't happen\n }\n }\n\n // Derive destinationAddress from connectorUrl port when not explicitly provided\n // This provides sensible defaults for local development:\n // - http://localhost:8080 → g.toon.genesis (genesis node)\n // - http://localhost:8090 → g.toon.peer1 (peer1 node)\n // For production, explicitly set destinationAddress in config\n let destinationAddress = config.destinationAddress;\n if (!destinationAddress && connectorUrl) {\n try {\n const url = new URL(connectorUrl);\n if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {\n // Map common local ports to known nodes\n if (url.port === '8080') {\n destinationAddress = 'g.toon.genesis';\n } else if (url.port === '8090') {\n destinationAddress = 'g.toon.peer1';\n } else if (url.port === '8100') {\n destinationAddress = 'g.toon.peer2';\n } else {\n // Fallback: use ilpInfo.ilpAddress if available\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n } else {\n // Production: default to ilpInfo.ilpAddress\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n } catch {\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n }\n\n // Derive EVM private key from Nostr secret key when not explicitly provided.\n // Both Nostr and EVM use secp256k1, so a single 32-byte key works for both.\n const evmPrivateKey = config.evmPrivateKey ?? secretKey;\n\n return {\n ...config,\n secretKey,\n evmPrivateKey,\n // Satisfied by connectorUrl OR proxyUrl (validateConfig enforced one of them).\n connectorUrl: connectorUrl as string,\n // Surface the derived `POST /ilp` endpoint so HTTP mode selects HttpIlpClient.\n ...(connectorHttpEndpoint ? { connectorHttpEndpoint } : {}),\n // Last-resort relay default. An explicit `config.relayUrl` always wins;\n // `applyNetworkPresets` does not set a per-network relay, so this fallback\n // points at the public devnet relay rather than a dead localhost socket.\n relayUrl: config.relayUrl ?? 'wss://relay-ws.devnet.toonprotocol.dev',\n queryTimeout: config.queryTimeout ?? 30000,\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n btpUrl,\n destinationAddress: destinationAddress as string, // Always set by logic above\n };\n}\n\n/**\n * Builds SettlementConfig from client config.\n * Returns undefined if no settlement-related config is present.\n */\nexport function buildSettlementInfo(\n rawConfig: ToonClientConfig\n): ClientSettlementInfo | undefined {\n // Resolve named-network preset defaults so a `network`-only config still\n // produces settlement info (explicit fields win; no-op for unset/`custom`).\n const config = applyNetworkPresets(rawConfig);\n\n if (\n !config.supportedChains?.length &&\n !config.settlementAddresses &&\n !config.preferredTokens &&\n !config.tokenNetworks\n ) {\n return undefined;\n }\n\n return {\n ilpAddress: config.ilpInfo?.ilpAddress,\n supportedChains: config.supportedChains,\n settlementAddresses: config.settlementAddresses,\n preferredTokens: config.preferredTokens,\n tokenNetworks: config.tokenNetworks,\n };\n}\n","/**\n * Base error class for all TOON client errors.\n */\nexport class ToonClientError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'ToonClientError';\n }\n}\n\n/**\n * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).\n * These errors trigger retry logic with exponential backoff.\n */\nexport class NetworkError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Connector error for 5xx server errors.\n * These errors indicate the connector is unavailable or malfunctioning.\n */\nexport class ConnectorError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONNECTOR_ERROR', cause);\n this.name = 'ConnectorError';\n }\n}\n\n/**\n * Validation error for invalid input parameters.\n * These errors are thrown before making any HTTP requests.\n */\nexport class ValidationError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'VALIDATION_ERROR', cause);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Unauthorized error for 401 responses from connector admin API.\n * Indicates missing or invalid authentication credentials.\n */\nexport class UnauthorizedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'UNAUTHORIZED', cause);\n this.name = 'UnauthorizedError';\n }\n}\n\n/**\n * Peer not found error for 404 responses when removing a peer.\n * Indicates the specified peer ID does not exist in the connector.\n */\nexport class PeerNotFoundError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'PEER_NOT_FOUND', cause);\n this.name = 'PeerNotFoundError';\n }\n}\n\n/**\n * Peer already exists error for 409 responses when adding a peer.\n * Indicates a peer with the same ID already exists in the connector.\n */\nexport class PeerAlreadyExistsError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'PEER_ALREADY_EXISTS', cause);\n this.name = 'PeerAlreadyExistsError';\n }\n}\n\n/**\n * Thrown when the one-time on-chain payment-channel OPEN reverts because the\n * local settlement wallet has no native gas to pay for its own\n * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN\n * only — per-write settlement rides ILP-over-HTTP and never spends gas. We\n * remap ONLY this case so callers get an actionable message (fund the wallet)\n * instead of the raw viem \"...exceeds the balance of the account\" string\n * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC\n * error is preserved as `cause`.\n */\nexport class ChannelFundingError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_FUNDING', cause);\n this.name = 'ChannelFundingError';\n }\n}\n\n/**\n * Substrings that mark an insufficient-native-gas revert from an on-chain\n * channel-open tx. viem surfaces the node's message verbatim and the exact\n * phrasing varies by RPC (anvil/geth/hardhat), so we match a set of known\n * markers case-insensitively.\n */\nconst INSUFFICIENT_GAS_MARKERS = [\n 'exceeds the balance of the account',\n 'insufficient funds for gas',\n 'insufficient funds for intrinsic transaction cost',\n 'insufficient funds for transfer',\n];\n\n/**\n * True when `err` (or any error in its nested `cause` chain) is an\n * insufficient-native-gas revert. viem wraps the node error one or more levels\n * deep, so the whole chain is flattened and scanned.\n */\nexport function isInsufficientGasError(err: unknown): boolean {\n const parts: string[] = [];\n let cur: unknown = err;\n for (let i = 0; i < 10 && cur != null; i++) {\n parts.push(cur instanceof Error ? cur.message : String(cur));\n cur = cur instanceof Error ? (cur as { cause?: unknown }).cause : undefined;\n }\n const text = parts.join(' | ').toLowerCase();\n return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));\n}\n","import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport type { ToonIdentity } from './types.js';\n\n/**\n * Generate a new 12-word BIP-39 mnemonic.\n */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/**\n * Validate a BIP-39 mnemonic phrase.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/**\n * Maximum valid BIP-32 non-hardened child index (2^31 - 1).\n * Values at or above 2^31 are reserved for hardened derivation.\n */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\n/**\n * Validate a BIP-44 account index. Mirrors the SDK's `fromMnemonic` guard so\n * the client and SDK reject the same out-of-range indices.\n */\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `Invalid accountIndex: expected a non-negative integer (0 to ${MAX_BIP32_INDEX}), got ${String(accountIndex)}`\n );\n }\n}\n\n/**\n * Derive the Nostr secp256k1 key from mnemonic using NIP-06 path:\n * m/44'/1237'/0'/0/{accountIndex}. At accountIndex 0 this is the canonical\n * m/44'/1237'/0'/0/0, matching the SDK's `fromMnemonic`/`fromMnemonicFull`.\n */\nfunction deriveNostrKey(\n seed: Uint8Array,\n accountIndex = 0\n): {\n secretKey: Uint8Array;\n pubkey: string;\n} {\n const master = HDKey.fromMasterSeed(seed);\n const child = master.derive(`m/44'/1237'/0'/0/${accountIndex}`);\n if (!child.privateKey) {\n throw new Error('Failed to derive Nostr private key from seed');\n }\n const secretKey = new Uint8Array(child.privateKey);\n const pubkey = getPublicKey(secretKey);\n return { secretKey, pubkey };\n}\n\n/**\n * Derive the EVM address from the same secp256k1 key (shares curve with Nostr).\n */\nfunction deriveEvmIdentity(secretKey: Uint8Array): {\n privateKey: Uint8Array;\n address: string;\n} {\n const account = privateKeyToAccount(toHex(secretKey));\n return {\n privateKey: secretKey,\n address: account.address,\n };\n}\n\n/**\n * Derive Solana Ed25519 keypair using SLIP-0010 path:\n * m/44'/501'/{accountIndex}'/0' (all hardened). At accountIndex 0 this is the\n * canonical m/44'/501'/0'/0', matching the SDK's `deriveSolanaIdentity`.\n * Dynamically imports @noble/curves for Ed25519 operations.\n */\nasync function deriveSolanaKey(\n seed: Uint8Array,\n accountIndex = 0\n): Promise<{\n secretKey: Uint8Array;\n publicKey: string;\n}> {\n // SLIP-0010 Ed25519 derivation (hardened only)\n // Uses HMAC-SHA512 with \"ed25519 seed\" as key\n const { hmac } = await import('@noble/hashes/hmac');\n const { sha512 } = await import('@noble/hashes/sha512');\n const { ed25519 } = await import('@noble/curves/ed25519.js');\n\n // SLIP-0010 master key derivation for ed25519\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive path: m/44'/501'/{accountIndex}'/0' (all hardened)\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // Write index as big-endian uint32\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes: Uint8Array = ed25519.getPublicKey(key);\n\n // Solana keypair = 32-byte private key + 32-byte public key = 64 bytes\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n // Base58 encode the public key\n const publicKey = toBase58(publicKeyBytes);\n\n return { secretKey: keypair, publicKey };\n}\n\n/**\n * Derive Mina Pallas key using path: m/44'/12586'/{accountIndex}'/0/0. At\n * accountIndex 0 this is the canonical m/44'/12586'/0'/0/0, matching the SDK's\n * `deriveMinaIdentity`.\n * Dynamically imports mina-signer.\n */\nasync function deriveMinaKey(\n seed: Uint8Array,\n accountIndex = 0\n): Promise<{\n privateKey: string;\n publicKey: string;\n}> {\n const master = HDKey.fromMasterSeed(seed);\n // Mina coin type = 12586 (0x312A)\n const child = master.derive(`m/44'/12586'/${accountIndex}'/0/0`);\n if (!child.privateKey) {\n throw new Error('Failed to derive Mina private key from seed');\n }\n const keyBytes = new Uint8Array(child.privateKey);\n\n // Clamp the top 2 bits so the scalar is within the Pallas base-field order\n // (matches @toon-protocol/swap's `deriveSwapKeys`). Without this, the raw\n // BIP-32 child scalar can exceed the field order and mina-signer rejects it.\n keyBytes[0] = (keyBytes[0] ?? 0) & 0x3f;\n\n // mina-signer needs the Mina base58check (`EK…`) private-key format, NOT a\n // raw hex scalar (raw hex fails with \"invalid checksum\"). Convert via the\n // shared @toon-protocol/core helper before deriving the public key.\n try {\n const MinaSignerLib = await import('mina-signer');\n const Client =\n 'default' in MinaSignerLib ? MinaSignerLib.default : MinaSignerLib;\n const client = new Client({ network: 'mainnet' });\n\n const hexKey = Array.from(keyBytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n const minaPrivateKey = hexToMinaBase58PrivateKey(hexKey);\n const publicKey = client.derivePublicKey(minaPrivateKey);\n return {\n // Store the clamped big-endian hex scalar; consumers (e.g. the client's\n // MinaSigner) re-convert to base58check via hexToMinaBase58PrivateKey.\n privateKey: hexKey,\n publicKey,\n };\n } catch {\n throw new Error(\n 'mina-signer is required for Mina key derivation. Install it as an optional dependency.'\n );\n }\n}\n\n/**\n * Synchronously derive ONLY the Nostr secp256k1 key (NIP-06) from a mnemonic.\n *\n * The EVM key shares this same secp256k1 key. Solana (Ed25519) and Mina\n * (Pallas) require async dynamic imports — use {@link deriveFullIdentity} for\n * those. This sync subset exists so `ToonClient`'s synchronous constructor can\n * resolve the Nostr/EVM identity from a `mnemonic` config field without an\n * async factory; the client derives Solana/Mina lazily in `start()`.\n */\nexport function deriveNostrKeyFromMnemonic(\n mnemonic: string,\n accountIndex = 0\n): {\n secretKey: Uint8Array;\n pubkey: string;\n} {\n assertValidAccountIndex(accountIndex);\n const seed = mnemonicToSeedSync(mnemonic);\n const result = deriveNostrKey(seed, accountIndex);\n seed.fill(0); // Zero seed after derivation (F7 fix)\n return result;\n}\n\n/**\n * Derive a full multi-chain ToonIdentity from a BIP-39 mnemonic.\n *\n * All four chains vary by `accountIndex` (default 0), matching the SDK's\n * {@link https://www.npmjs.com/package/@toon-protocol/sdk `fromMnemonicFull`}\n * path-per-index scheme so a non-zero index produces the SAME addresses as\n * `fromMnemonicFull(mnemonic, { accountIndex })`. Index 0 is unchanged from the\n * historical fixed paths (back-compat).\n *\n * Chains derived:\n * - Nostr (secp256k1): m/44'/1237'/0'/0/{accountIndex}\n * - EVM (secp256k1): same key as Nostr\n * - Solana (Ed25519): m/44'/501'/{accountIndex}'/0' (SLIP-0010)\n * - Mina (Pallas): m/44'/12586'/{accountIndex}'/0/0\n *\n * @param mnemonic - A valid BIP-39 mnemonic (12 or 24 words).\n * @param accountIndex - BIP-44 account index (default 0).\n */\nexport async function deriveFullIdentity(\n mnemonic: string,\n accountIndex = 0\n): Promise<ToonIdentity> {\n assertValidAccountIndex(accountIndex);\n const seed = mnemonicToSeedSync(mnemonic);\n\n const nostr = deriveNostrKey(seed, accountIndex);\n const evm = deriveEvmIdentity(nostr.secretKey);\n\n // Solana and Mina can fail if optional deps are missing — derive independently\n let solana: ToonIdentity['solana'];\n try {\n solana = await deriveSolanaKey(seed, accountIndex);\n } catch {\n solana = { secretKey: new Uint8Array(64), publicKey: '' };\n }\n\n let mina: ToonIdentity['mina'];\n try {\n mina = await deriveMinaKey(seed, accountIndex);\n } catch {\n mina = { privateKey: '', publicKey: '' };\n }\n\n // Zero seed after derivation (F7 fix)\n seed.fill(0);\n\n return { nostr, evm, solana, mina };\n}\n\n/**\n * Derive a partial identity from an nsec (Nostr-only private key).\n * Nostr + EVM share the same secp256k1 key.\n * Solana and Mina get empty placeholders (not deterministically linked).\n */\nexport function deriveFromNsec(secretKey: Uint8Array): ToonIdentity {\n // Copy input to avoid caller mutation corrupting identity keys\n const keyCopy = new Uint8Array(secretKey);\n const pubkey = getPublicKey(keyCopy);\n const evm = deriveEvmIdentity(keyCopy);\n\n return {\n nostr: { secretKey: keyCopy, pubkey },\n evm,\n solana: { secretKey: new Uint8Array(64), publicKey: '' },\n mina: { privateKey: '', publicKey: '' },\n };\n}\n\n/**\n * Generate a random identity (no mnemonic — for testing or ephemeral use).\n */\nexport function generateRandomIdentity(): ToonIdentity {\n const secretKey = generateSecretKey();\n return deriveFromNsec(secretKey);\n}\n\n// --- Utility ---\n\nconst BASE58_ALPHABET =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction toBase58(bytes: Uint8Array): string {\n let num = BigInt(0);\n for (const b of bytes) num = num * 256n + BigInt(b);\n let result = '';\n while (num > 0n) {\n result = BASE58_ALPHABET[Number(num % 58n)] + result;\n num = num / 58n;\n }\n for (const b of bytes) {\n if (b === 0) result = '1' + result;\n else break;\n }\n return result;\n}\n","/**\n * Isomorphic binary helpers — works in both Node.js and browser\n * without requiring Buffer polyfills.\n *\n * These replace Buffer usage throughout the client package so that\n * browser consumers (e.g. ditto) don't need the `buffer` npm polyfill.\n */\n\n/** Convert a Uint8Array to a base64 string (browser + Node compatible). */\nexport function toBase64(bytes: Uint8Array): string {\n // Node.js Buffer is a Uint8Array subclass and has toString('base64')\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(bytes)) {\n return (bytes as Buffer).toString('base64');\n }\n // Browser path: use btoa with binary string\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/** Convert a base64 string to a Uint8Array (browser + Node compatible). */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Convert a Uint8Array to a hex string. */\nexport function toHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Convert a hex string to a Uint8Array. */\nexport function fromHex(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') ? hex.slice(2) : hex;\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Convert a UTF-8 string to Uint8Array. */\nexport function encodeUtf8(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/** Convert a Uint8Array to a UTF-8 string. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Check if a string is valid base64. */\nexport function isBase64(str: string): boolean {\n return /^[A-Za-z0-9+/]*={0,2}$/.test(str);\n}\n","/**\n * Ask a terminating connector who it is and what it charges — the step that\n * has to happen BEFORE a packet can be formed at all.\n *\n * ADR 0018 makes holding the terminating connector's public key a\n * precondition of forming a packet: `Prepare.data` is sealed to that key, and\n * sealing to the wrong one is a confidentiality failure, not a delivery\n * failure. ADR 0022 says the connector *answers* — it never announces — so\n * both facts are fetched from the connector's own client edge, on the same\n * origin this client already POSTs `/ilp` to\n * (`docs/protocol/client-edge-spec.md` §1.7):\n *\n * - `GET /ilp/identity` → `{ \"keyId\": \"...\", \"publicKey\": \"0x04...\" }` — the\n * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.\n * - `GET /ilp/routes/price?destination=<ILP address>` →\n * `{ \"destination\": \"...\", \"price\": 100 }`, or `404` when no\n * locally-terminated route matches.\n *\n * Both are unauthenticated and neither changes state.\n *\n * ─── What this module refuses to do ────────────────────────────────────────\n * Unlike the 402-challenge parser next door (which degrades gracefully so an\n * unrecognised connector shape falls back to the vanilla 402), an identity is\n * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not\n * valid hex is refused with a distinguishable error rather than carried\n * forward: a half-understood key would be sealed to, and the failure would be\n * silent. There is no \"best effort\" reading of a public key.\n *\n * Pure transport + parsing: no keys are held, nothing is signed, and the only\n * state is the identity cache.\n */\n\nimport { NetworkError, ToonClientError } from '../errors.js';\n\n// ─── Identity ───────────────────────────────────────────────────────────────\n\n/** The terminating connector's own identity, as reported by `GET /ilp/identity`. */\nexport interface ConnectorIdentity {\n /** The key id identifying the key (opaque to this client). */\n keyId: string;\n /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */\n publicKey: Uint8Array;\n /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */\n publicKeyHex: string;\n /** The normalized client-edge base URL this identity was read from. */\n endpoint: string;\n}\n\n/** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */\nexport interface ConnectorRoutePrice {\n /** The ILP destination that was asked about (echoed by the connector). */\n destination: string;\n /** The price in ILP base units of the route `destination` matched. */\n price: bigint;\n}\n\n/**\n * Every distinguishable way asking a connector for its identity or terms can\n * fail. Each code names exactly one cause; there is no catch-all, because the\n * caller's next move differs per cause (retry a transport failure; never\n * retry a malformed key).\n */\nexport type ConnectorEdgeErrorCode =\n /** Non-2xx from `GET /ilp/identity`. */\n | 'IDENTITY_HTTP_STATUS'\n /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */\n | 'IDENTITY_MALFORMED'\n /** `publicKey` is present but is not `0x`-prefixed even-length hex. */\n | 'IDENTITY_KEY_NOT_HEX'\n /** `publicKey` decodes, but not to exactly 65 bytes. */\n | 'IDENTITY_KEY_LENGTH'\n /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */\n | 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */\n | 'ROUTE_PRICE_HTTP_STATUS'\n /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */\n | 'ROUTE_PRICE_MALFORMED'\n /** A destination that cannot be put in a query string was asked about. */\n | 'INVALID_DESTINATION';\n\n/**\n * A refusal to carry a connector's answer forward. Distinct from\n * {@link NetworkError} (which this module throws for a transport failure), so\n * \"the connector is unreachable\" and \"the connector answered something I will\n * not seal to\" are never confused.\n */\nexport class ConnectorEdgeError extends ToonClientError {\n /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */\n declare readonly code: ConnectorEdgeErrorCode;\n\n constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error) {\n super(message, code, cause);\n this.name = 'ConnectorEdgeError';\n }\n}\n\n// ─── URL handling ───────────────────────────────────────────────────────────\n\n/**\n * Normalize any client-edge URL a caller already holds into the base the\n * `/ilp/*` routes hang off.\n *\n * Callers reach this module holding whatever the x402 offer or their config\n * gave them — `https://apex.example`, `https://apex.example/`, or the\n * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the\n * same client edge, so all three normalize to `https://apex.example`.\n */\nexport function connectorEdgeBaseUrl(endpoint: string): string {\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch (error) {\n throw new ConnectorEdgeError(\n `not a valid connector endpoint URL: ${endpoint}`,\n 'IDENTITY_MALFORMED',\n error instanceof Error ? error : undefined\n );\n }\n // Drop a trailing `/ilp` (the POST endpoint) and any trailing slashes.\n let path = url.pathname.replace(/\\/+$/, '');\n if (path.endsWith('/ilp')) path = path.slice(0, -'/ilp'.length);\n url.pathname = path;\n url.search = '';\n url.hash = '';\n return url.toString().replace(/\\/+$/, '');\n}\n\n// ─── Parsing (pure, exported so the wire shape is testable without a server) ─\n\nconst UNCOMPRESSED_KEY_BYTES = 65;\nconst SEC1_UNCOMPRESSED_TAG = 0x04;\n\n/**\n * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing\n * anything that is not exactly one uncompressed secp256k1 key.\n */\nexport function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array {\n const trimmed = publicKeyHex.trim();\n if (!/^0x[0-9a-fA-F]*$/.test(trimmed) || trimmed.length % 2 !== 0) {\n throw new ConnectorEdgeError(\n `connector publicKey is not 0x-prefixed hex: ${publicKeyHex}`,\n 'IDENTITY_KEY_NOT_HEX'\n );\n }\n const hex = trimmed.slice(2);\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n if (bytes.length !== UNCOMPRESSED_KEY_BYTES) {\n throw new ConnectorEdgeError(\n `connector publicKey must be ${UNCOMPRESSED_KEY_BYTES} bytes, got ${bytes.length}`,\n 'IDENTITY_KEY_LENGTH'\n );\n }\n const tag = bytes[0] ?? 0;\n if (tag !== SEC1_UNCOMPRESSED_TAG) {\n throw new ConnectorEdgeError(\n `connector publicKey must be SEC1-uncompressed (0x04 prefix), got 0x${tag.toString(16).padStart(2, '0')}`,\n 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n );\n }\n return bytes;\n}\n\n/**\n * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the\n * connector actually emits can be pinned without standing up a server.\n */\nexport function parseConnectorIdentity(\n body: unknown,\n endpoint: string\n): ConnectorIdentity {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity did not answer a JSON object',\n 'IDENTITY_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const keyId = record['keyId'];\n const publicKeyHex = record['publicKey'];\n if (typeof keyId !== 'string' || keyId.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a keyId',\n 'IDENTITY_MALFORMED'\n );\n }\n if (typeof publicKeyHex !== 'string' || publicKeyHex.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a publicKey',\n 'IDENTITY_MALFORMED'\n );\n }\n return {\n keyId,\n publicKey: decodeConnectorPublicKey(publicKeyHex),\n publicKeyHex: publicKeyHex.trim().toLowerCase(),\n endpoint,\n };\n}\n\n/** Parse an already-decoded `GET /ilp/routes/price` 200 body. */\nexport function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price did not answer a JSON object',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const destination = record['destination'];\n const price = record['price'];\n if (typeof destination !== 'string' || destination.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price answered without a destination',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n if (\n typeof price !== 'number' ||\n !Number.isFinite(price) ||\n !Number.isInteger(price) ||\n price < 0\n ) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered a non-integer price: ${String(price)}`,\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n return { destination, price: BigInt(price) };\n}\n\n// ─── Client ─────────────────────────────────────────────────────────────────\n\nexport interface ConnectorEdgeClientConfig {\n /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 10_000. */\n timeout?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * Separator between a client-edge base URL and an ILP destination in a price\n * cache key. NUL can appear in neither, so no pair can be spelled two ways\n * and no two pairs can collide.\n */\nconst PRICE_KEY_SEPARATOR = '\\u0000';\n\n/** Cache key for one (client edge, destination) pair. */\nfunction priceCacheKey(base: string, destination: string): string {\n return `${base}${PRICE_KEY_SEPARATOR}${destination}`;\n}\n\n/**\n * The prefix every key for `base` shares — `priceCacheKey`'s own output for\n * an empty destination, so the two cannot drift into disagreeing about the\n * separator. They once did, and the endpoint-wide invalidation below then\n * silently matched nothing.\n */\nfunction priceCacheKeyPrefix(base: string): string {\n return priceCacheKey(base, '');\n}\n\n/**\n * Asks connectors for their identity and their terms, caching each identity\n * per client-edge endpoint and each route price per (endpoint, destination).\n *\n * The cache is per endpoint rather than per client instance because a sender\n * routinely speaks to several connectors, and re-fetching a key per packet\n * would put a network round trip in front of every send. Nothing here expires\n * on a timer: an operator key rotation, or a route being repriced, is a\n * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}\n * are how a stale answer is dropped.\n *\n * A price is cached the same way and for the same reason (toon-client#452):\n * under ADR 0020 a route's price is FLAT — one handler, one price — so it does\n * not vary with what is being sent, and asking again per packet would buy\n * nothing but latency.\n */\nexport class ConnectorEdgeClient {\n private readonly fetchImpl: typeof fetch;\n private readonly timeout: number;\n private readonly identities = new Map<string, Promise<ConnectorIdentity>>();\n private readonly prices = new Map<\n string,\n Promise<ConnectorRoutePrice | null>\n >();\n\n constructor(config: ConnectorEdgeClientConfig = {}) {\n this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * The terminating connector's public key, fetched once per endpoint.\n *\n * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getIdentity(\n endpoint: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorIdentity> {\n const base = connectorEdgeBaseUrl(endpoint);\n if (options.forceRefresh) this.identities.delete(base);\n\n const cached = this.identities.get(base);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever.\n const inFlight = this.fetchIdentity(base).catch((error: unknown) => {\n this.identities.delete(base);\n throw error;\n });\n this.identities.set(base, inFlight);\n return inFlight;\n }\n\n /**\n * Drop a cached identity — one endpoint's, or every endpoint's when\n * `endpoint` is omitted. The way to react to a key rotation.\n */\n invalidateIdentity(endpoint?: string): void {\n if (endpoint === undefined) {\n this.identities.clear();\n return;\n }\n this.identities.delete(connectorEdgeBaseUrl(endpoint));\n }\n\n /** Whether an identity for `endpoint` is already held (no request is made). */\n hasCachedIdentity(endpoint: string): boolean {\n return this.identities.has(connectorEdgeBaseUrl(endpoint));\n }\n\n /**\n * What `destination` costs at this connector, or `null` when the connector\n * answers `404` — no locally-terminated route matches it.\n *\n * `null` is the answer to \"you do not terminate this\", which is information;\n * a transport failure throws {@link NetworkError} instead, so a caller can\n * always tell \"not mine\" from \"could not ask\".\n *\n * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a\n * price flat per handler, so it does not vary with the packet — a route\n * being repriced is an operator event, and {@link invalidateRoutePrice} is\n * how a caller reacts to one.\n *\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getRoutePrice(\n endpoint: string,\n destination: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorRoutePrice | null> {\n if (typeof destination !== 'string' || destination.trim().length === 0) {\n throw new ConnectorEdgeError(\n 'a route price needs a non-empty ILP destination',\n 'INVALID_DESTINATION'\n );\n }\n const base = connectorEdgeBaseUrl(endpoint);\n const key = priceCacheKey(base, destination);\n if (options.forceRefresh) this.prices.delete(key);\n\n const cached = this.prices.get(key);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever. A\n // `404` IS cached: \"this connector does not terminate that\" is an answer.\n const inFlight = this.fetchRoutePrice(base, destination).catch(\n (error: unknown) => {\n this.prices.delete(key);\n throw error;\n }\n );\n this.prices.set(key, inFlight);\n return inFlight;\n }\n\n /**\n * Drop a cached route price — one (endpoint, destination)'s, every\n * destination's at one endpoint when `destination` is omitted, or all of\n * them when both are. The way to react to a route being repriced.\n */\n invalidateRoutePrice(endpoint?: string, destination?: string): void {\n if (endpoint === undefined) {\n this.prices.clear();\n return;\n }\n const base = connectorEdgeBaseUrl(endpoint);\n if (destination !== undefined) {\n this.prices.delete(priceCacheKey(base, destination));\n return;\n }\n const prefix = priceCacheKeyPrefix(base);\n for (const key of this.prices.keys()) {\n if (key.startsWith(prefix)) this.prices.delete(key);\n }\n }\n\n /**\n * Whether a price for `(endpoint, destination)` is already held (no request\n * is made).\n */\n hasCachedRoutePrice(endpoint: string, destination: string): boolean {\n return this.prices.has(\n priceCacheKey(connectorEdgeBaseUrl(endpoint), destination)\n );\n }\n\n private async fetchRoutePrice(\n base: string,\n destination: string\n ): Promise<ConnectorRoutePrice | null> {\n const url = `${base}/ilp/routes/price?destination=${encodeURIComponent(destination)}`;\n const response = await this.get(url);\n\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered ${response.status}`,\n 'ROUTE_PRICE_HTTP_STATUS'\n );\n }\n return parseConnectorRoutePrice(\n await this.readJson(response, 'ROUTE_PRICE_MALFORMED')\n );\n }\n\n private async fetchIdentity(base: string): Promise<ConnectorIdentity> {\n const response = await this.get(`${base}/ilp/identity`);\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/identity answered ${response.status}`,\n 'IDENTITY_HTTP_STATUS'\n );\n }\n return parseConnectorIdentity(\n await this.readJson(response, 'IDENTITY_MALFORMED'),\n base\n );\n }\n\n private async readJson(\n response: Response,\n code: ConnectorEdgeErrorCode\n ): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new ConnectorEdgeError(\n 'connector answered a body that is not JSON',\n code,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */\n private async get(url: string): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchImpl(url, {\n method: 'GET',\n headers: { accept: 'application/json' },\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${url}`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n }\n}\n","/**\n * Canonical OER length primitives (RFC-0030), ported byte-for-byte from\n * `connector_domain::oer` so the Rust and TypeScript fleets agree on the wire.\n *\n * \"Canonical\" is the whole point (ADR 0023): every value has exactly ONE\n * encoding, and a decoder that quietly accepts a second spelling of the same\n * value is a decoder two implementations can disagree through. So a\n * determinant is refused unless the bytes it introduces are exactly what\n * {@link encodeVarUint} would have produced:\n *\n * - `0x81 0x03` — a long form for `3`, which `0x03` already encodes — is\n * {@link OerErrorKind.NonCanonicalLength}, not `3`.\n * - `0x80` — a zero-byte long form aliasing `0x00` — is\n * {@link OerErrorKind.NonCanonicalLength}, not `0`.\n * - `0x89 …` — nine length bytes, which cannot fit a `u64` without silently\n * discarding the high-order ones — is\n * {@link OerErrorKind.LengthDeterminantOverflow}, not a truncated read.\n *\n * Values are `bigint` because the wire type is `u64` and `number` cannot hold\n * one; the caller narrows.\n *\n * Pure: no I/O, no keys, no clock.\n */\n\n/** The three, and only three, ways a length determinant can be refused. */\nexport enum OerErrorKind {\n /** The buffer ends before the field it declares does. */\n BufferUnderflow = 'buffer_underflow',\n /** A determinant that is not the minimal encoding of its own value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A determinant wider than eight bytes (cannot be a `u64`). */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n}\n\n/** A refusal from the length primitives, carrying which of the three it is. */\nexport class OerError extends Error {\n constructor(readonly kind: OerErrorKind) {\n super(OER_ERROR_MESSAGES[kind]);\n this.name = 'OerError';\n }\n}\n\nconst OER_ERROR_MESSAGES: Record<OerErrorKind, string> = {\n [OerErrorKind.BufferUnderflow]: 'buffer underflow: the value is truncated',\n [OerErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [OerErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n};\n\nconst MAX_DETERMINANT_BYTES = 8;\n\n/** Encode a VarUInt: `0..=127` as one byte, `128+` as a length-prefixed BE value. */\nexport function encodeVarUint(value: bigint): Uint8Array {\n if (value < 0n)\n throw new RangeError('VarUInt cannot encode a negative value');\n if (value <= 127n) return Uint8Array.of(Number(value));\n\n const body: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n body.unshift(Number(remaining & 0xffn));\n remaining >>= 8n;\n }\n if (body.length > MAX_DETERMINANT_BYTES) {\n throw new RangeError('VarUInt cannot encode a value wider than 8 bytes');\n }\n return Uint8Array.from([0x80 | body.length, ...body]);\n}\n\n/** A decoded field: its value, and how many bytes it consumed. */\nexport interface Decoded<T> {\n value: T;\n consumed: number;\n}\n\n/**\n * Decode a VarUInt at `offset`, refusing any non-canonical spelling.\n *\n * @throws {OerError} and nothing else — arbitrary bytes never produce a\n * `RangeError`, a `TypeError`, or a plausible-but-wrong value.\n */\nexport function decodeVarUint(\n buf: Uint8Array,\n offset: number\n): Decoded<bigint> {\n const first = buf[offset];\n if (first === undefined) throw new OerError(OerErrorKind.BufferUnderflow);\n if (first <= 127) return { value: BigInt(first), consumed: 1 };\n\n const length = first & 0x7f;\n if (length > MAX_DETERMINANT_BYTES) {\n throw new OerError(OerErrorKind.LengthDeterminantOverflow);\n }\n const start = offset + 1;\n const end = start + length;\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n let value = 0n;\n for (let i = start; i < end; i++) {\n value = (value << 8n) | BigInt(buf[i] as number);\n }\n const consumed = 1 + length;\n\n // The canonicality test, exactly as `connector_domain::oer` states it:\n // re-encode and demand the same bytes back. This is what rejects the\n // non-minimal long form and the zero-length alias in one check.\n const canonical = encodeVarUint(value);\n if (\n canonical.length !== consumed ||\n !canonical.every((byte, i) => byte === buf[offset + i])\n ) {\n throw new OerError(OerErrorKind.NonCanonicalLength);\n }\n return { value, consumed };\n}\n\n/** Encode a VarOctetString: a VarUInt length prefix followed by the bytes. */\nexport function encodeVarOctetString(data: Uint8Array): Uint8Array {\n const prefix = encodeVarUint(BigInt(data.length));\n const out = new Uint8Array(prefix.length + data.length);\n out.set(prefix, 0);\n out.set(data, prefix.length);\n return out;\n}\n\n/**\n * Decode a VarOctetString at `offset`.\n *\n * @throws {OerError} and nothing else.\n */\nexport function decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): Decoded<Uint8Array> {\n const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);\n\n // A declared length larger than the whole buffer is underflow, checked in\n // `bigint` BEFORE any `Number` conversion so a `u64`-scale length can never\n // wrap into a plausible small one.\n if (length > BigInt(buf.length)) {\n throw new OerError(OerErrorKind.BufferUnderflow);\n }\n const start = offset + lengthBytes;\n const end = start + Number(length);\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n // A copy, not a view: a decoded body that aliases the input buffer would\n // change under a caller who reuses that buffer.\n return {\n value: buf.slice(start, end),\n consumed: lengthBytes + Number(length),\n };\n}\n","/**\n * The structured envelope (ADR 0018): what a packet carries between a\n * connector and the app behind it, encoded with the same OER primitives an ILP\n * packet already uses rather than as HTTP text.\n *\n * A faithful port of `connector_domain::envelope`\n * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered\n * headers and body going in; a two-byte big-endian status, headers and body\n * coming back. `vectors/wire-vectors.json` is the contract this is checked\n * against, and `wire-vectors.test.ts` is where that check happens; the prose\n * here describes the same thing but the bytes decide.\n *\n * ─── Why not HTTP text ─────────────────────────────────────────────────────\n * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and\n * `utils/fulfill-http.ts` hand-parses a status line and scans for `\\r\\n\\r\\n`,\n * which is how they acquired leniencies nobody chose: a missing header/body\n * separator yielding an empty body, blank header lines skipped, spaces\n * tolerated inside the target. A structured encoding has exactly one\n * representation per message and nothing to smuggle. This module lands BESIDE\n * those two rather than replacing them — the swap is a later child — so it can\n * be reviewed against the vectors in isolation.\n *\n * ─── Headers are a list, not a map ─────────────────────────────────────────\n * A count prefix then `(name, value)` pairs in order. Both header ORDER and\n * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a\n * `Record<string, string>` would silently destroy each.\n *\n * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.\n */\n\nimport {\n OerError,\n OerErrorKind,\n decodeVarOctetString,\n decodeVarUint,\n encodeVarOctetString,\n encodeVarUint,\n} from './oer.js';\n\nconst TYPE_ENVELOPE_REQUEST = 1;\nconst TYPE_ENVELOPE_RESPONSE = 2;\n\n/**\n * Every distinguishable way an envelope can fail to decode. These strings are\n * the vector file's `expected_error` values verbatim — the same names\n * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,\n * not just \"it threw\".\n *\n * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a\n * decoder that can be lenient without anyone noticing.\n */\nexport enum EnvelopeErrorKind {\n /** The buffer ends before the envelope does. */\n BufferUnderflow = 'buffer_underflow',\n /** A length determinant that is not the minimal encoding of its value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A length determinant wider than eight bytes. */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n /** The type byte is not the one the requested direction requires. */\n InvalidType = 'invalid_type',\n /** A field that must be UTF-8 is not. */\n InvalidUtf8 = 'invalid_utf8',\n /** Bytes remain after a fully decoded envelope. */\n TrailingBytes = 'trailing_bytes',\n}\n\n/**\n * A refusal to decode. `kind` is the machine-readable reason; `field` names\n * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching\n * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.\n */\nexport class EnvelopeError extends Error {\n constructor(\n readonly kind: EnvelopeErrorKind,\n readonly field?: string\n ) {\n super(\n field === undefined\n ? ENVELOPE_ERROR_MESSAGES[kind]\n : `${ENVELOPE_ERROR_MESSAGES[kind]} (field '${field}')`\n );\n this.name = 'EnvelopeError';\n }\n}\n\nconst ENVELOPE_ERROR_MESSAGES: Record<EnvelopeErrorKind, string> = {\n [EnvelopeErrorKind.BufferUnderflow]:\n 'buffer underflow: envelope is truncated',\n [EnvelopeErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [EnvelopeErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n [EnvelopeErrorKind.InvalidType]:\n 'invalid envelope type byte: expected 1 (REQUEST) or 2 (RESPONSE)',\n [EnvelopeErrorKind.InvalidUtf8]: 'invalid UTF-8 in envelope field',\n [EnvelopeErrorKind.TrailingBytes]:\n 'trailing bytes after a fully decoded envelope',\n};\n\n/** One `(name, value)` header, in wire order. Duplicates are legal. */\nexport type EnvelopeHeader = readonly [name: string, value: string];\n\n/** The request a connector is to make of the app behind a terminated route. */\nexport interface EnvelopeRequest {\n method: string;\n target: string;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** The app's response back to the connector. */\nexport interface EnvelopeResponse {\n /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */\n status: number;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** Either direction, tagged — the shape the vector file's `decoded` carries. */\nexport type Envelope =\n | ({ direction: 'request' } & EnvelopeRequest)\n | ({ direction: 'response' } & EnvelopeResponse);\n\n// ─── Shared helpers ─────────────────────────────────────────────────────────\n\nconst UTF8_ENCODER = new TextEncoder();\n/** `fatal` is load-bearing: a lenient decoder would turn bad bytes into U+FFFD. */\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true });\n\n/** Map an {@link OerError} onto its envelope-level counterpart, 1:1. */\nfunction fromOerError(error: unknown): EnvelopeError {\n if (error instanceof OerError) {\n switch (error.kind) {\n case OerErrorKind.BufferUnderflow:\n return new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n case OerErrorKind.NonCanonicalLength:\n return new EnvelopeError(EnvelopeErrorKind.NonCanonicalLength);\n case OerErrorKind.LengthDeterminantOverflow:\n return new EnvelopeError(EnvelopeErrorKind.LengthDeterminantOverflow);\n }\n }\n throw error;\n}\n\nfunction decodeOctets(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; consumed: number } {\n try {\n return decodeVarOctetString(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\nfunction decodeCount(\n buf: Uint8Array,\n offset: number\n): {\n value: bigint;\n consumed: number;\n} {\n try {\n return decodeVarUint(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\n/** Decode a VarOctetString and validate it as UTF-8 in one step. */\nfunction decodeStringField(\n buf: Uint8Array,\n offset: number,\n field: string\n): { value: string; consumed: number } {\n const { value: bytes, consumed } = decodeOctets(buf, offset);\n try {\n return { value: UTF8_DECODER.decode(bytes), consumed };\n } catch {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidUtf8, field);\n }\n}\n\nfunction checkTypeByte(buf: Uint8Array, expected: number): number {\n const typeByte = buf[0];\n if (typeByte === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n if (typeByte !== expected) {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidType);\n }\n return 1;\n}\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction encodeHeaders(headers: readonly EnvelopeHeader[]): Uint8Array {\n const parts: Uint8Array[] = [encodeVarUint(BigInt(headers.length))];\n for (const [name, value] of headers) {\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));\n }\n return concat(parts);\n}\n\nfunction decodeHeaders(\n buf: Uint8Array,\n offset: number\n): { value: EnvelopeHeader[]; consumed: number } {\n const { value: count, consumed: countBytes } = decodeCount(buf, offset);\n\n // Every header costs at least two bytes, so a count exceeding what remains\n // cannot be honoured. Checked in `bigint`, before any loop, so a `u64`-scale\n // count is refused as underflow instead of spinning.\n if (count * 2n > BigInt(buf.length - offset - countBytes)) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n\n let consumed = countBytes;\n const headers: EnvelopeHeader[] = [];\n for (let i = 0n; i < count; i++) {\n const name = decodeStringField(buf, offset + consumed, 'header name');\n consumed += name.consumed;\n const value = decodeStringField(buf, offset + consumed, 'header value');\n consumed += value.consumed;\n headers.push([name.value, value.value]);\n }\n return { value: headers, consumed };\n}\n\n// ─── Request ────────────────────────────────────────────────────────────────\n\n/** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */\nexport function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array {\n return concat([\n Uint8Array.of(TYPE_ENVELOPE_REQUEST),\n encodeVarOctetString(UTF8_ENCODER.encode(request.method)),\n encodeVarOctetString(UTF8_ENCODER.encode(request.target)),\n encodeHeaders(request.headers),\n encodeVarOctetString(request.body),\n ]);\n}\n\n/**\n * Decode a request envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_REQUEST);\n\n const method = decodeStringField(buf, offset, 'method');\n offset += method.consumed;\n\n const target = decodeStringField(buf, offset, 'target');\n offset += target.consumed;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return {\n method: method.value,\n target: target.value,\n headers: headers.value,\n body: body.value,\n };\n}\n\n// ─── Response ───────────────────────────────────────────────────────────────\n\n/** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */\nexport function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array {\n if (\n !Number.isInteger(response.status) ||\n response.status < 0 ||\n response.status > 0xffff\n ) {\n throw new RangeError(\n `envelope status must fit two bytes, got ${response.status}`\n );\n }\n return concat([\n Uint8Array.of(\n TYPE_ENVELOPE_RESPONSE,\n (response.status >> 8) & 0xff,\n response.status & 0xff\n ),\n encodeHeaders(response.headers),\n encodeVarOctetString(response.body),\n ]);\n}\n\n/**\n * Decode a response envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_RESPONSE);\n\n const high = buf[offset];\n const low = buf[offset + 1];\n if (high === undefined || low === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n const status = (high << 8) | low;\n offset += 2;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return { status, headers: headers.value, body: body.value };\n}\n\n// ─── Direction-tagged façade ────────────────────────────────────────────────\n\n/** Encode either direction from its tagged form. */\nexport function encodeEnvelope(envelope: Envelope): Uint8Array {\n return envelope.direction === 'request'\n ? encodeEnvelopeRequest(envelope)\n : encodeEnvelopeResponse(envelope);\n}\n\n/**\n * Decode as the named direction. The direction is an INPUT, never guessed from\n * the type byte: a caller that asked for a request and got a response has been\n * handed the wrong bytes, and `invalid_type` is the honest answer.\n */\nexport function decodeEnvelope(\n buf: Uint8Array,\n direction: 'request' | 'response'\n): Envelope {\n return direction === 'request'\n ? { direction, ...decodeEnvelopeRequest(buf) }\n : { direction, ...decodeEnvelopeResponse(buf) };\n}\n","/**\n * The gift wrap (ADR 0018) and the fulfilment a shared secret derives (ADR\n * 0019): the seal around the {@link ./envelope.js | envelope}, so a packet\n * payload is readable only by the connector that terminates it and the\n * preimage that pays for it needs no app participation.\n *\n * A faithful port of `connector_signer::giftwrap`\n * (`crates/connector-signer/src/giftwrap.rs` on toon-protocol/connector `main`)\n * and of `connector_domain::condition::derive_condition`\n * (`crates/connector-domain/src/condition.rs:27`). `vectors/wire-vectors.json`'s\n * `giftwrap` and `fulfilment` sections are the contract, replayed byte-for-byte\n * in `wire-vectors.test.ts`; the prose here describes the same thing but the\n * bytes decide.\n *\n * ─── The mechanism, as read off the Rust ────────────────────────────────────\n * Recorded here because it cannot be inferred from the vector file's field\n * names, and because the acceptance criterion for toon-client#449 asks for it\n * in writing. Every line below is cited to\n * `crates/connector-signer/src/giftwrap.rs` unless stated otherwise.\n *\n * - **Curve and ECDH.** The receiver's identity key is secp256k1; the value a\n * real connector reports from `GET /ilp/identity` is its 65-byte\n * uncompressed form (`0x04 ‖ X ‖ Y`). The sender ECDHs a fresh, per-packet\n * ephemeral key against it and uses the **raw X-coordinate** of the\n * resulting point — `crypto.rs`'s `ecdh_x_coordinate` does\n * `tweak_mul_assign` then `serialize_compressed()[1..]`, deliberately *not*\n * `libsecp256k1::SharedSecret`'s digest-mixing variant. So: not hashed, and\n * not the 33-byte compressed point.\n * - **Key derivation.** `HKDF-SHA256`, **no salt** (`Hkdf::new(None, ikm)`,\n * i.e. HKDF-Extract with an all-zero salt), expanded to 32 bytes under one\n * of three fixed ASCII `info` strings — `giftwrap.rs`'s `hkdf_key`:\n * - `toon-giftwrap-request` — the request AEAD key, over the ECDH X.\n * - `toon-giftwrap-response` — the response AEAD key, over the shared secret.\n * - `toon-giftwrap-fulfillment` — the fulfilment, over the shared secret.\n * (American spelling on the wire; the vector *section* is `fulfilment`.)\n * These three strings are the only domain separation between two AEAD keys\n * and a payment preimage all derived from the same input, so one wrong\n * character silently yields bytes that decrypt nothing and satisfy no\n * condition.\n * - **AEAD.** ChaCha20-Poly1305 (RFC 8439), 12-byte nonce, **no** additional\n * authenticated data.\n * - **Request framing.** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖\n * ciphertext`, where the encrypted plaintext is `shared_secret(32) ‖\n * encoded_envelope`. The secret rides *inside* the sealed request, which is\n * what lets the response be sealed with no second key exchange.\n * - **Response framing.** `0x02 ‖ nonce(12) ‖ ciphertext`, the plaintext being\n * just the encoded envelope. Sealed directly with the request's shared\n * secret.\n * - **Fulfilment and condition.** `fulfilment = HKDF-SHA256(shared_secret,\n * \"toon-giftwrap-fulfillment\")`; the condition a sender mints is\n * `sha256(fulfilment)` — `condition.rs`'s `derive_condition`. A sender knows\n * the secret before it seals, so it can mint the condition first; the\n * terminating connector recovers the secret by opening the wrap and derives\n * the preimage without asking the app anything.\n * - **Telling a sealed reject from a plaintext one.** The leading type byte,\n * and only that (`looks_like_sealed_response`). A reject raised short of the\n * termination shares no secret with the sender and carries empty `data`; an\n * empty `data` is never sealed, so a sealed reject is positive proof that\n * the destination itself said no.\n *\n * ─── Two failure modes, two types ───────────────────────────────────────────\n * A wrap that cannot be OPENED throws {@link GiftWrapError}. A wrap that opens\n * cleanly but whose recovered plaintext is not a valid envelope throws\n * `EnvelopeError`, from `envelope.ts` — a different class entirely, raised\n * above this module rather than by it. The Rust keeps the same separation\n * (`GiftWrapError` vs `connector_domain::EnvelopeError`) for the same reason:\n * \"I could not read this\" and \"I read this and it was malformed\" are different\n * facts about a peer, and collapsing them loses the distinction at every call\n * site.\n *\n * ─── Additive ───────────────────────────────────────────────────────────────\n * Nothing in this client's live send path calls this yet — `publishEvent` is\n * still the latin1 HTTP framing in `utils/store-envelope.ts`. Rewiring it is a\n * later child (toon-client#450).\n */\n\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { chacha20poly1305 } from '@noble/ciphers/chacha.js';\nimport { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\n\n// ─── Constants (giftwrap.rs:36-46) ──────────────────────────────────────────\n\n/** ChaCha20-Poly1305 nonce length. */\nexport const GIFTWRAP_NONCE_LENGTH = 12;\n/** The shared secret carried inside a sealed request, and the fulfilment. */\nexport const GIFTWRAP_SECRET_LENGTH = 32;\n/** The uncompressed secp256k1 public key a sealed request carries. */\nexport const GIFTWRAP_PUBLIC_KEY_LENGTH = 65;\n\nconst REQUEST_INFO = 'toon-giftwrap-request';\nconst RESPONSE_INFO = 'toon-giftwrap-response';\nconst FULFILLMENT_INFO = 'toon-giftwrap-fulfillment';\n\n/** `TYPE_GIFTWRAP_REQUEST` — the leading byte of a sealed request. */\nexport const GIFTWRAP_TYPE_REQUEST = 1;\n/** `TYPE_GIFTWRAP_RESPONSE` — the leading byte of a sealed response. */\nexport const GIFTWRAP_TYPE_RESPONSE = 2;\n\n/** Poly1305 tag length — the minimum a non-empty ciphertext can be. */\nconst TAG_LENGTH = 16;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n/**\n * Every distinguishable way a wrap can fail to open — the four variants of\n * `GiftWrapError` in `giftwrap.rs:57-71`, named the same way. There is\n * deliberately no catch-all: this module must never be able to fail \"somehow\".\n *\n * None of these ever carries decrypted plaintext, matching the Rust's own\n * guarantee.\n */\nexport enum GiftWrapErrorKind {\n /** The leading byte is not the one this direction requires. */\n InvalidType = 'invalid_type',\n /** The bytes end before the framing does. */\n Truncated = 'truncated',\n /** An ephemeral or receiver public key that is not a usable curve point. */\n InvalidKey = 'invalid_key',\n /** The AEAD refused: wrong key, wrong nonce, or a tampered ciphertext. */\n OpenFailed = 'open_failed',\n}\n\nconst GIFTWRAP_ERROR_MESSAGES: Record<GiftWrapErrorKind, string> = {\n [GiftWrapErrorKind.InvalidType]: 'invalid gift wrap type byte',\n [GiftWrapErrorKind.Truncated]: 'gift wrap is truncated',\n [GiftWrapErrorKind.InvalidKey]: 'invalid ephemeral or peer public key',\n [GiftWrapErrorKind.OpenFailed]: 'gift wrap failed to decrypt',\n};\n\n/**\n * A refusal to open a wrap. `kind` is the machine-readable reason;\n * `expectedType` names the type byte that was required, for\n * {@link GiftWrapErrorKind.InvalidType} — mirroring\n * `GiftWrapError::InvalidType(u8)`.\n */\nexport class GiftWrapError extends Error {\n constructor(\n readonly kind: GiftWrapErrorKind,\n readonly expectedType?: number\n ) {\n super(\n expectedType === undefined\n ? GIFTWRAP_ERROR_MESSAGES[kind]\n : `${GIFTWRAP_ERROR_MESSAGES[kind]}: expected ${expectedType}`\n );\n this.name = 'GiftWrapError';\n }\n}\n\n// ─── Shapes ─────────────────────────────────────────────────────────────────\n\n/**\n * What sealing a request produces: the bytes to carry as `Prepare.data`, and\n * the shared secret that both derives this packet's fulfilment and opens the\n * answer. The sender must keep the secret — it is the only thing that opens\n * the response, and the only thing that proves the fulfilment it is paid\n * against was earned rather than guessed.\n */\nexport interface SealedRequest {\n /** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖ ciphertext`. */\n readonly wrapped: Uint8Array;\n /** The 32 random bytes sealed inside `wrapped`. */\n readonly sharedSecret: Uint8Array;\n}\n\n/** What opening a sealed request recovers. */\nexport interface OpenedRequest {\n /** The encoded envelope — feed to `decodeEnvelopeRequest`. */\n readonly envelopeBytes: Uint8Array;\n /** The 32-byte secret the sender chose, for the fulfilment and the answer. */\n readonly sharedSecret: Uint8Array;\n}\n\n/**\n * A key agreement that never hands out secret key material — the TypeScript\n * counterpart of `giftwrap.rs`'s dependency on `Signer::ecdh`, and the reason\n * {@link openRequest} takes this rather than a raw private key: a remote or\n * hardware-backed identity can open a wrap without its key leaving its own\n * boundary.\n *\n * Returns the raw 32-byte ECDH X-coordinate, or throws.\n */\nexport interface GiftWrapEcdh {\n ecdh(ephemeralPublicKey: Uint8Array): Uint8Array;\n}\n\n// ─── Primitives ─────────────────────────────────────────────────────────────\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * `HKDF-SHA256(ikm, salt = none, info, L = 32)` — `giftwrap.rs`'s `hkdf_key`.\n * The absent salt is load-bearing: HKDF-Extract runs with an all-zero salt, so\n * passing a salt of any kind produces a different, silently-wrong key.\n */\nfunction hkdfKey(ikm: Uint8Array, info: string): Uint8Array {\n return hkdf(sha256, ikm, undefined, info, 32);\n}\n\n/** `giftwrap.rs`'s `encrypt_with_nonce`: `nonce ‖ ciphertext`. */\nfunction encryptWithNonce(\n key: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n return concat([nonce, chacha20poly1305(key, nonce).encrypt(plaintext)]);\n}\n\n/** `giftwrap.rs`'s `decrypt`: splits `nonce ‖ ciphertext` and opens it. */\nfunction decrypt(key: Uint8Array, nonceAndCiphertext: Uint8Array): Uint8Array {\n if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n const nonce = nonceAndCiphertext.subarray(0, GIFTWRAP_NONCE_LENGTH);\n const ciphertext = nonceAndCiphertext.subarray(GIFTWRAP_NONCE_LENGTH);\n // A ciphertext shorter than the Poly1305 tag cannot be an AEAD output at\n // all. `@noble/ciphers` throws a plain `Error` for that rather than failing\n // the tag check, so classify it here instead of letting a foreign error type\n // escape this module.\n if (ciphertext.length < TAG_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n try {\n return chacha20poly1305(key, nonce).decrypt(ciphertext);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.OpenFailed);\n }\n}\n\n/**\n * The raw ECDH X-coordinate of `secret * public` — `crypto.rs`'s\n * `ecdh_x_coordinate`. `@noble/curves` returns the compressed point, whose\n * bytes `1..33` are exactly the `serialize_compressed()[1..]` the Rust takes.\n */\nfunction ecdhXCoordinate(\n secretKey: Uint8Array,\n publicKey: Uint8Array\n): Uint8Array {\n let compressed: Uint8Array;\n try {\n compressed = secp256k1.getSharedSecret(secretKey, publicKey, true);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n return compressed.slice(1);\n}\n\n/**\n * The ordinary local case of {@link GiftWrapEcdh}: a 32-byte secp256k1 secret\n * key held in this process. `openRequest` accepts a bare key too and wraps it\n * in this.\n */\nexport function localGiftWrapEcdh(secretKey: Uint8Array): GiftWrapEcdh {\n return {\n ecdh: (ephemeralPublicKey) =>\n ecdhXCoordinate(secretKey, ephemeralPublicKey),\n };\n}\n\n// ─── Request direction ──────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealRequest}, parameterized on every value\n * a real seal draws at random — the counterpart of the Rust's\n * `seal_request_with_randomness`, which that crate gates behind a `test-util`\n * feature for a reason worth repeating: **reusing a (key, nonce) pair under\n * ChaCha20-Poly1305 is catastrophic**, so caller-supplied randomness is a\n * footgun, not a convenience. Use {@link sealRequest} unless you are replaying\n * a fixed vector.\n *\n * `receiverPublicKey` may be the 65-byte uncompressed form a connector's\n * `GET /ilp/identity` reports, or the 33-byte compressed form; the ECDH result\n * is the same point either way. The ephemeral key is always emitted\n * uncompressed, because that is what the framing pins.\n */\nexport function sealRequestWithRandomness(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array,\n ephemeralSecretKey: Uint8Array,\n sharedSecret: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n let ephemeralPublicKey: Uint8Array;\n try {\n ephemeralPublicKey = secp256k1.getPublicKey(ephemeralSecretKey, false);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const aeadKey = hkdfKey(\n ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),\n REQUEST_INFO\n );\n const inner = concat([sharedSecret, plaintext]);\n\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_REQUEST),\n ephemeralPublicKey,\n encryptWithNonce(aeadKey, inner, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` (an encoded envelope) to `receiverPublicKey`. A fresh\n * ephemeral key pair, shared secret and nonce are drawn for this call alone,\n * so no two sealed requests — even to the same receiver, even with the same\n * plaintext — share any of the three.\n *\n * Returns the wire bytes and the shared secret. Mint the packet's execution\n * condition as {@link deriveCondition}({@link deriveFulfillment}(secret))\n * before sending: the terminating connector recovers the same secret by\n * opening this wrap, so the preimage it is paid against is one it derived, not\n * one anybody handed it.\n */\nexport function sealRequest(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array\n): SealedRequest {\n const ephemeralSecretKey = secp256k1.utils.randomSecretKey();\n const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);\n const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);\n\n return {\n wrapped: sealRequestWithRandomness(\n plaintext,\n receiverPublicKey,\n ephemeralSecretKey,\n sharedSecret,\n nonce\n ),\n sharedSecret,\n };\n}\n\n/**\n * Open a sealed request addressed to `identity`, recovering the encoded\n * envelope and the shared secret carried alongside it.\n *\n * `identity` is either a 32-byte secp256k1 secret key or a {@link GiftWrapEcdh}\n * that never exposes one. Nothing in this client terminates packets today, so\n * this exists to make the seal testable from both ends — and to make the\n * vectors' \"opening it with the fixture's secret key must recover the envelope\n * and the secret exactly\" a check this repo can actually run.\n */\nexport function openRequest(\n bytes: Uint8Array,\n identity: Uint8Array | GiftWrapEcdh\n): OpenedRequest {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_REQUEST) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_REQUEST\n );\n }\n if (bytes.length < 1 + GIFTWRAP_PUBLIC_KEY_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n const ephemeralPublicKey = bytes.slice(1, 1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n const ciphertext = bytes.subarray(1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n\n const agreement =\n identity instanceof Uint8Array ? localGiftWrapEcdh(identity) : identity;\n let ecdhSecret: Uint8Array;\n try {\n ecdhSecret = agreement.ecdh(ephemeralPublicKey);\n } catch (error) {\n throw error instanceof GiftWrapError\n ? error\n : new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const plaintext = decrypt(hkdfKey(ecdhSecret, REQUEST_INFO), ciphertext);\n if (plaintext.length < GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n return {\n envelopeBytes: plaintext.slice(GIFTWRAP_SECRET_LENGTH),\n sharedSecret: plaintext.slice(0, GIFTWRAP_SECRET_LENGTH),\n };\n}\n\n// ─── Response direction ─────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealResponse}, parameterized on the nonce.\n * Same footgun, same warning as {@link sealRequestWithRandomness}: a nonce\n * reused under one shared secret destroys the confidentiality of both\n * responses sealed with it.\n */\nexport function sealResponseWithRandomness(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),\n encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` — an encoded response envelope, or a reject's diagnostic\n * bytes — with the request's own `sharedSecret`. No second key exchange: the\n * secret is bidirectional by construction, which is also why a sealed reject\n * can only have come from the termination.\n */\nexport function sealResponse(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array\n): Uint8Array {\n return sealResponseWithRandomness(\n sharedSecret,\n plaintext,\n randomBytes(GIFTWRAP_NONCE_LENGTH)\n );\n}\n\n/**\n * Open a sealed response with the shared secret {@link sealRequest} returned\n * for the request it answers. No signer, no key exchange, no identity key.\n */\nexport function openResponse(\n sharedSecret: Uint8Array,\n bytes: Uint8Array\n): Uint8Array {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_RESPONSE) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_RESPONSE\n );\n }\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return decrypt(hkdfKey(sharedSecret, RESPONSE_INFO), bytes.subarray(1));\n}\n\n/**\n * Whether `bytes` is shaped like a sealed response — the leading type byte and\n * nothing else, exactly as `looks_like_sealed_response` does it. This is how a\n * sender tells a reject raised BY the destination from one raised on the way\n * to it, without holding the secret to try opening it.\n *\n * Empty `data`, which every reject raised short of a termination carries, is\n * never sealed.\n */\nexport function looksLikeSealedResponse(bytes: Uint8Array): boolean {\n return bytes.length > 0 && bytes[0] === GIFTWRAP_TYPE_RESPONSE;\n}\n\n// ─── Fulfilment and condition ───────────────────────────────────────────────\n\n/**\n * The fulfilment a request's shared secret derives (ADR 0019):\n * `HKDF-SHA256(shared_secret, \"toon-giftwrap-fulfillment\")`, 32 bytes.\n * Domain-separated by its own `info` string from both AEAD keys the same\n * secret also derives, so it can never collide with either.\n */\nexport function deriveFulfillment(sharedSecret: Uint8Array): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return hkdfKey(sharedSecret, FULFILLMENT_INFO);\n}\n\n/**\n * The condition a `fulfillment` satisfies: `sha256(fulfillment)` —\n * `connector_domain::condition::derive_condition`. Hashing only ever runs in\n * this direction; there is deliberately no function here that goes from a\n * condition back to a fulfilment.\n *\n * The hash is the same one `utils/condition.ts` already uses; what ADR 0019\n * changes is where the preimage comes from. `mintExecutionCondition` there\n * draws a random preimage the sender must then carry to the FULFILL itself;\n * here the preimage is DERIVED from the secret sealed inside the packet, so\n * the terminating connector can produce it without the sender or the app\n * handing it over. Checking a returned fulfilment against a condition is\n * unchanged either way — use `fulfillmentMatchesCondition` from\n * `utils/condition.ts` for that rather than a second copy of it here.\n */\nexport function deriveCondition(fulfillment: Uint8Array): Uint8Array {\n return sha256(fulfillment);\n}\n","/**\n * One sealed request/answer exchange with a terminating connector (ADR 0018,\n * ADR 0019, ADR 0020) — the whole shape of a packet's payload, from the\n * envelope going out to the answer coming back, behind two functions.\n *\n * A sender's obligations on this wire are not independent of one another, and\n * getting any of them separately wrong is silent:\n *\n * - The `data` is a gift wrap addressed to the connector that TERMINATES the\n * route, around an OER envelope — never HTTP text, never a bare payload.\n * - The execution condition is `sha256` of the fulfilment DERIVED from the\n * very secret that wrap carries. A random condition would never be\n * fulfilled; an all-zero one is refused outright by the connector\n * (`connector-domain`'s `condition_is_present`), which is why the publish\n * path could not work against it at all before this module existed.\n * - The answer is sealed with that same secret, so opening it requires having\n * kept it from the seal.\n *\n * {@link sealExchange} produces all three from one call so they cannot drift\n * apart, and {@link readExchangeOutcome} is the only thing that reads the\n * answer. The secret is the token joining them.\n *\n * ─── Why the outcome is a tagged union ─────────────────────────────────────\n * ADR 0018 gives a sender something it never had: a REJECT sealed with the\n * request's own secret can ONLY have come from the termination, because only\n * the termination could recover that secret. A reject raised short of it is\n * necessarily plaintext — an intermediate hop shares no secret and cannot\n * seal. So \"the destination said no\" and \"somebody on the path said no\" are\n * now genuinely different facts, and flattening both into one error string\n * would throw away the distinction the seal was introduced to create.\n *\n * ADR 0020 draws the other line this union encodes: an HTTP status inside a\n * response envelope is envelope CONTENT, not a packet outcome. A 404 arrives\n * on a FULFILL and value moved. {@link ExchangeOutcome.Answered} therefore\n * carries any status at all, and it is the caller's business — not this\n * module's — whether a given status means its own operation succeeded.\n *\n * Pure: no I/O, no clock, no network. Randomness only through\n * {@link sealRequest}.\n */\n\nimport {\n decodeEnvelopeResponse,\n encodeEnvelopeRequest,\n EnvelopeError,\n type EnvelopeRequest,\n type EnvelopeResponse,\n} from './envelope.js';\nimport {\n deriveCondition,\n deriveFulfillment,\n GiftWrapError,\n looksLikeSealedResponse,\n openResponse,\n sealRequest,\n} from './giftwrap.js';\n\n/**\n * A sealed request, ready to become a PREPARE: what goes in `data`, what goes\n * on `executionCondition`, and the secret needed to read the answer.\n *\n * The three are produced together and belong together. Sending `data` under a\n * condition minted any other way produces a packet no honest connector can\n * fulfil; opening the answer with any other secret fails.\n */\nexport interface SealedExchange {\n /** The gift wrap to carry as the PREPARE's `data`. */\n readonly data: Uint8Array;\n /**\n * The PREPARE's `executionCondition`: `sha256(deriveFulfillment(secret))`.\n * Derived, never random and never caller-supplied — the terminating\n * connector recovers the same secret and derives the same fulfilment\n * without the app participating (ADR 0019).\n */\n readonly condition: Uint8Array;\n /**\n * The 32-byte secret sealed inside the wrap. Keep it until the answer is\n * read; it is the only thing that opens the response. Never send it\n * anywhere else, and never reuse it for a second packet.\n */\n readonly sharedSecret: Uint8Array;\n /**\n * The fulfilment the terminating connector will return. Held so a caller\n * can check the FULFILL preimage it actually got, rather than only that it\n * hashes to the condition.\n */\n readonly fulfillment: Uint8Array;\n}\n\n/**\n * How an exchange ended. Three outcomes, deliberately not two: a refusal's\n * ORIGIN is the fact ADR 0018 makes knowable for the first time.\n */\nexport type ExchangeOutcome =\n /**\n * The termination answered. `response` is whatever it said, at whatever\n * status — a non-2xx here is a real answer that was paid for (ADR 0020),\n * not a failure of the packet.\n */\n | { readonly kind: 'answered'; readonly response: EnvelopeResponse }\n /**\n * The DESTINATION refused, provably: the reject's `data` was sealed with\n * this exchange's own secret, which only the terminating connector could\n * hold. `detail` is whatever it sealed alongside (often empty).\n */\n | {\n readonly kind: 'destination-refused';\n readonly code: string;\n readonly message: string;\n readonly detail: Uint8Array;\n }\n /**\n * Somebody ON THE PATH refused — no route, expiry, a ceiling, a rejected\n * claim — short of the termination, so nothing was sealed. Unauthenticated\n * by construction: any hop can produce this, and it should be read as a\n * hint, not a verdict from the destination.\n */\n | {\n readonly kind: 'path-refused';\n readonly code: string;\n readonly message: string;\n };\n\n/**\n * Why an answer that arrived could not be read. Distinct from an\n * {@link ExchangeOutcome}: these are not the destination's answer at all, but\n * bytes that failed to be one.\n */\nexport type SealedResponseErrorKind =\n /** A FULFILL whose `data` is absent, or does not begin with the sealed-response type byte. */\n | 'not-sealed'\n /** The wrap is shaped right but does not open under this exchange's secret. */\n | 'unopenable'\n /** It opened, and what came out is not a response envelope. */\n | 'malformed-envelope';\n\n/** A refusal to read an answer. Never carries recovered plaintext. */\nexport class SealedResponseError extends Error {\n constructor(\n readonly kind: SealedResponseErrorKind,\n message: string,\n override readonly cause?: Error\n ) {\n super(message);\n this.name = 'SealedResponseError';\n }\n}\n\n/**\n * Seal `request` to `connectorPublicKey` — the identity of the connector that\n * TERMINATES the destination, as read from its own client edge\n * (`ConnectorEdgeClient`). Sealing to any other key is a confidentiality\n * failure that presents as an undeliverable packet.\n *\n * @param request the envelope to seal.\n * @param connectorPublicKey the terminating connector's 65-byte uncompressed\n * secp256k1 identity key.\n */\nexport function sealExchange(\n request: EnvelopeRequest,\n connectorPublicKey: Uint8Array\n): SealedExchange {\n const { wrapped, sharedSecret } = sealRequest(\n encodeEnvelopeRequest(request),\n connectorPublicKey\n );\n const fulfillment = deriveFulfillment(sharedSecret);\n return {\n data: wrapped,\n condition: deriveCondition(fulfillment),\n sharedSecret,\n fulfillment,\n };\n}\n\n/**\n * Read what came back.\n *\n * `accepted` distinguishes a FULFILL from a REJECT; `data` is the packet's\n * payload bytes, absent when it carried none. Both come straight off the\n * transport's result, so this stays testable without a socket.\n *\n * A FULFILL must be sealed and must decode: value moved, so bytes that are\n * neither are a broken counterparty, and this throws rather than inventing an\n * outcome. A REJECT is classified instead of thrown on — an unopenable one is\n * simply a path reject that happened to carry bytes.\n *\n * @throws {SealedResponseError} for a FULFILL that is not a readable sealed\n * response envelope.\n */\nexport function readExchangeOutcome(\n result: { accepted: boolean; code?: string; message?: string },\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): ExchangeOutcome {\n if (result.accepted) {\n return { kind: 'answered', response: openAnswer(data, sharedSecret) };\n }\n\n const code = result.code ?? 'F00';\n const message = result.message ?? '';\n\n // Only the termination could have sealed this, so only a wrap that actually\n // OPENS proves the destination refused. A leading type byte alone is a\n // claim, not evidence — an intermediary can write one byte.\n if (data !== undefined && looksLikeSealedResponse(data)) {\n try {\n return {\n kind: 'destination-refused',\n code,\n message,\n detail: openResponse(sharedSecret, data),\n };\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n // Fall through: bytes that pose as sealed but do not open are not the\n // destination's word, and must not be reported as if they were.\n }\n }\n\n return { kind: 'path-refused', code, message };\n}\n\nfunction openAnswer(\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): EnvelopeResponse {\n if (data === undefined || data.length === 0) {\n throw new SealedResponseError(\n 'not-sealed',\n 'FULFILL carried no data; a terminated route always seals a response envelope'\n );\n }\n if (!looksLikeSealedResponse(data)) {\n throw new SealedResponseError(\n 'not-sealed',\n `FULFILL data is not a sealed response (leading byte 0x${(data[0] ?? 0)\n .toString(16)\n .padStart(2, '0')}, expected 0x02)`\n );\n }\n\n let opened: Uint8Array;\n try {\n opened = openResponse(sharedSecret, data);\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n throw new SealedResponseError(\n 'unopenable',\n 'FULFILL data did not open under this packet\\'s shared secret',\n error\n );\n }\n\n try {\n return decodeEnvelopeResponse(opened);\n } catch (error) {\n if (!(error instanceof EnvelopeError)) throw error;\n throw new SealedResponseError(\n 'malformed-envelope',\n `sealed answer opened but did not decode as a response envelope: ${error.message}`,\n error\n );\n }\n}\n\n/** Read a response header, case-insensitively; the first match wins. */\nexport function envelopeHeader(\n response: EnvelopeResponse,\n name: string\n): string | undefined {\n const wanted = name.toLowerCase();\n for (const [header, value] of response.headers) {\n if (header.toLowerCase() === wanted) return value;\n }\n return undefined;\n}\n","import { BootstrapService, createDiscoveryTracker } from '@toon-protocol/core';\nimport type { BootstrapServiceConfig } from '@toon-protocol/core';\nimport { HttpRuntimeClient } from '../adapters/HttpRuntimeClient.js';\nimport { BtpRuntimeClient } from '../adapters/BtpRuntimeClient.js';\nimport { HttpIlpClient } from '../adapters/HttpIlpClient.js';\nimport {\n selectIlpTransport,\n readDiscoveredIlpPeer,\n} from '../adapters/selectIlpTransport.js';\nimport { OnChainChannelClient } from '../channel/OnChainChannelClient.js';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { buildSettlementInfo } from '../config.js';\nimport type { ResolvedConfig } from '../config.js';\nimport type { HttpModeInitialization } from './types.js';\n\n/**\n * Initializes HTTP mode for ToonClient.\n *\n * HTTP mode uses external connector service via HTTP/WebSocket.\n * This function creates all necessary clients and services for operating in HTTP mode.\n *\n * @param config - ToonClient configuration (must have connectorUrl)\n * @returns Initialized HTTP mode components\n */\nexport async function initializeHttpMode(\n config: ResolvedConfig\n): Promise<HttpModeInitialization> {\n const effectiveBtpUrl = config.btpUrl;\n const effectiveConnectorUrl = config.connectorUrl;\n\n // Build settlement info from config\n const settlementInfo = buildSettlementInfo(config);\n\n // Select the ILP transport for the uplink connector.\n //\n // The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port\n // (connector PR #181). A peer advertises the `POST /ilp` URL in discovery via\n // `IlpPeerInfo.httpEndpoint` (+ `supportsUpgrade`) added in toon PR #29.\n //\n // The client SDK's only \"peer\" at init time is its uplink connector, so we\n // build a DiscoveredIlpPeer from the connector endpoints we know: the derived\n // BTP WebSocket URL plus an optional explicit `connectorHttpEndpoint` (which\n // mirrors the on-wire `httpEndpoint`). `readDiscoveredIlpPeer` reads those\n // fields defensively so this stays compatible with the installed\n // @toon-protocol/core 1.4.2 (pre-PR-#29).\n //\n // NOTE(dep): once a @toon-protocol/core release with the PR-#29\n // `httpEndpoint`/`supportsUpgrade` IlpPeerInfo fields is published (latest on\n // npm is still 1.4.2), bump the dep and feed real discovered peer info here\n // instead of (or in addition to) the explicit config field.\n //\n // FALLBACK GUARANTEE: when no `httpEndpoint` is present (the default — no\n // connector advertises one yet, and `connectorHttpEndpoint` is unset),\n // `selectIlpTransport` returns `{ kind: 'btp' }`, which is exactly the prior\n // behavior. Existing BTP-only flows are unchanged.\n const discoveredPeer = readDiscoveredIlpPeer({\n btpEndpoint: effectiveBtpUrl,\n httpEndpoint: config.connectorHttpEndpoint,\n supportsUpgrade: config.connectorSupportsUpgrade,\n });\n\n // The client SDK's runtime client is a one-shot consumer (it sends ILP\n // packets and reads the synchronous FULFILL/REJECT). It does not need a duplex\n // session at the transport-selection layer, so `needsDuplex` stays false and\n // HTTP is preferred when advertised. A `btpEndpoint` is always present when\n // `btpUrl` is configured, so HTTP is only ever selected when an httpEndpoint\n // is explicitly available.\n const transportChoice =\n discoveredPeer.httpEndpoint || discoveredPeer.btpEndpoint\n ? selectIlpTransport(discoveredPeer, { needsDuplex: false })\n : null;\n\n // Create BTP runtime client — the duplex transport for the client SDK.\n // The client connects to the connector via BTP WebSocket to send ILP packets\n // AND to receive server-initiated packets / act as a peer. We always open it\n // when a btpUrl is configured (publishing, swaps and payments require it), so\n // ToonClient's `btpClient`-gated paths keep working even when one-shot writes\n // go over HTTP.\n let btpClient: BtpRuntimeClient | null = null;\n if (effectiveBtpUrl) {\n btpClient = new BtpRuntimeClient({\n btpUrl: effectiveBtpUrl,\n peerId: config.btpPeerId ?? `client`,\n authToken: config.btpAuthToken ?? '',\n });\n await btpClient.connect();\n }\n\n // Build the HTTP one-shot client when the transport policy selected it.\n let httpIlpClient: HttpIlpClient | null = null;\n if (\n transportChoice &&\n (transportChoice.kind === 'http' ||\n transportChoice.kind === 'http-upgradable')\n ) {\n httpIlpClient = new HttpIlpClient({\n httpEndpoint: transportChoice.httpEndpoint,\n ...(config.btpPeerId !== undefined ? { peerId: config.btpPeerId } : {}),\n ...(config.btpAuthToken !== undefined\n ? { authToken: config.btpAuthToken }\n : {}),\n timeout: config.queryTimeout,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n });\n }\n\n // Runtime client precedence for sending ILP packets:\n // 1. HttpIlpClient — when the connector advertises an httpEndpoint (PR #29).\n // 2. BtpRuntimeClient — the BTP WebSocket (existing default; FALLBACK).\n // 3. HttpRuntimeClient — connector-admin-style HTTP when no btpUrl at all.\n const runtimeClient =\n httpIlpClient ??\n btpClient ??\n new HttpRuntimeClient({\n connectorUrl: effectiveConnectorUrl,\n timeout: config.queryTimeout,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n });\n\n // Create on-chain channel client when chain RPC URLs are configured.\n // evmPrivateKey is always present (derived from secretKey by default).\n let onChainChannelClient: OnChainChannelClient | null = null;\n if (config.chainRpcUrls) {\n const evmSigner = new EvmSigner(config.evmPrivateKey);\n onChainChannelClient = new OnChainChannelClient({\n evmSigner,\n chainRpcUrls: config.chainRpcUrls,\n });\n }\n\n // Create BootstrapService\n const bootstrapConfig: BootstrapServiceConfig = {\n knownPeers: (config.knownPeers || []).map((p) => ({\n pubkey: p.pubkey,\n relayUrl: p.relayUrl,\n btpEndpoint: p.btpEndpoint ?? '',\n })),\n queryTimeout: config.queryTimeout,\n ardriveEnabled: true,\n defaultRelayUrl: config.relayUrl,\n settlementInfo,\n ownIlpAddress: config.ilpInfo.ilpAddress,\n toonEncoder: config.toonEncoder,\n toonDecoder: config.toonDecoder,\n // No `basePricePerByte`: ADR 0020 removed per-byte pricing, and a packet's\n // amount now comes from `GET /ilp/routes/price` at the terminating\n // connector (toon-client#452). Nothing here may state a local rate.\n };\n\n const bootstrapService = new BootstrapService(\n bootstrapConfig,\n config.secretKey,\n config.ilpInfo\n );\n\n // Wire ILP client into bootstrap service\n bootstrapService.setIlpClient(runtimeClient);\n\n // Wire on-chain channel client if available\n if (onChainChannelClient) {\n bootstrapService.setChannelClient(onChainChannelClient);\n }\n\n // Do NOT wire ConnectorAdmin — addPeer() at line 472 is skipped when connectorAdmin is null\n // This is intentional: the client is a standalone peer, not an admin interface\n\n // Create DiscoveryTracker\n const discoveryTracker = createDiscoveryTracker({\n secretKey: config.secretKey,\n settlementInfo,\n });\n\n return {\n bootstrapService,\n discoveryTracker,\n runtimeClient,\n adminClient: null,\n btpClient,\n onChainChannelClient,\n };\n}\n","/**\n * Configuration options for retry behavior with exponential backoff.\n */\nexport interface RetryOptions {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n /** Initial delay in milliseconds between retries (default: 1000) */\n retryDelay: number;\n /** Use exponential backoff for delays (default: true) */\n exponentialBackoff?: boolean;\n /** Maximum delay cap in milliseconds (default: 30000) */\n maxDelay?: number;\n /** Custom predicate to determine if an error should trigger a retry */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Executes an async operation with retry logic and exponential backoff.\n *\n * @param operation - The async function to execute\n * @param options - Retry configuration options\n * @returns The result of the successful operation\n * @throws The last error if all retries are exhausted\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * async () => fetchData(),\n * {\n * maxRetries: 3,\n * retryDelay: 1000,\n * shouldRetry: (err) => err.name === 'NetworkError'\n * }\n * );\n * ```\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: RetryOptions\n): Promise<T> {\n const {\n maxRetries,\n retryDelay,\n exponentialBackoff = true,\n maxDelay = 30000,\n shouldRetry,\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if we should retry this error\n if (shouldRetry && !shouldRetry(lastError)) {\n throw lastError;\n }\n\n // If this was the last attempt, throw the error\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Calculate delay with exponential backoff\n const currentDelay = exponentialBackoff\n ? Math.min(retryDelay * Math.pow(2, attempt), maxDelay)\n : retryDelay;\n\n // Wait before retrying\n await new Promise((resolve) => setTimeout(resolve, currentDelay));\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw lastError ?? new Error('Unknown error during retry');\n}\n","import type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport { NetworkError, ConnectorError, ValidationError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { isBase64 } from '../utils/binary.js';\n\n/**\n * Configuration options for HttpRuntimeClient.\n */\nexport interface HttpRuntimeClientConfig {\n /** Connector runtime API base URL (e.g., 'http://localhost:8080') */\n connectorUrl: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts for network failures (default: 3) */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** HTTP client implementation (for testing) */\n httpClient?: typeof fetch;\n}\n\n/**\n * HTTP client for sending ILP packets to an external connector runtime API.\n *\n * Implements the IlpClient interface for use with TOON agents\n * that need to send ILP packets without embedding a full connector.\n *\n * Features:\n * - Request validation (destination, amount, data)\n * - Retry logic with exponential backoff for transient network failures\n * - Typed error handling (NetworkError, ConnectorError, ValidationError)\n * - Connection pooling and keep-alive (via Node.js fetch)\n *\n * @example\n * ```typescript\n * const client = new HttpRuntimeClient({\n * connectorUrl: 'http://localhost:8080'\n * });\n *\n * const result = await client.sendIlpPacket({\n * destination: 'g.toon.alice',\n * amount: '1000',\n * data: 'base64EncodedToonData==',\n * });\n *\n * if (result.accepted) {\n * console.log('Payment accepted');\n * } else {\n * console.error('Payment rejected:', result.code, result.message);\n * }\n * ```\n */\nexport class HttpRuntimeClient implements IlpClient {\n private readonly connectorUrl: string;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n\n constructor(config: HttpRuntimeClientConfig) {\n // Normalize connector URL (remove trailing slash)\n this.connectorUrl = config.connectorUrl.replace(/\\/$/, '');\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n }\n\n /**\n * Send an ILP packet to the connector runtime API.\n *\n * @param params - ILP packet parameters\n * @returns ILP packet response with acceptance status\n * @throws {ValidationError} If request parameters are invalid\n * @throws {NetworkError} If network connection fails after retries\n * @throws {ConnectorError} If connector returns 5xx server error\n */\n async sendIlpPacket(params: {\n destination: string;\n amount: string;\n data: string;\n timeout?: number;\n }): Promise<IlpSendResult> {\n // Validate request parameters\n this.validateRequest(params);\n\n // Wrap HTTP request with retry logic\n return withRetry(async () => this.sendHttpRequest(params), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors (ECONNREFUSED, ETIMEDOUT)\n // Do not retry on validation errors, 4xx, or 5xx errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Validate ILP packet request parameters.\n *\n * @throws {ValidationError} If any parameter is invalid\n */\n private validateRequest(params: {\n destination: string;\n amount: string;\n data: string;\n }): void {\n // Validate destination: non-empty, valid ILP address format\n if (!params.destination || params.destination.trim() === '') {\n throw new ValidationError('Destination cannot be empty');\n }\n if (!params.destination.startsWith('g.')) {\n throw new ValidationError(\n `Invalid ILP address format: \"${params.destination}\" (must start with \"g.\")`\n );\n }\n\n // Validate amount: non-empty, parseable as bigint, positive\n if (!params.amount || params.amount.trim() === '') {\n throw new ValidationError('Amount cannot be empty');\n }\n try {\n const amountBigInt = BigInt(params.amount);\n if (amountBigInt <= 0n) {\n throw new ValidationError(\n `Amount must be positive: \"${params.amount}\"`\n );\n }\n } catch (error) {\n if (error instanceof ValidationError) throw error;\n throw new ValidationError(\n `Amount must be a valid integer: \"${params.amount}\"`,\n error instanceof Error ? error : undefined\n );\n }\n\n // Validate data: non-empty, valid Base64 encoding\n if (!params.data || params.data.trim() === '') {\n throw new ValidationError('Data cannot be empty');\n }\n try {\n if (!isBase64(params.data)) {\n throw new ValidationError(\n `Data must be valid Base64 encoding: \"${params.data}\"`\n );\n }\n } catch (error) {\n if (error instanceof ValidationError) throw error;\n throw new ValidationError(\n `Data must be valid Base64 encoding: \"${params.data}\"`,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Send HTTP POST request to connector runtime API.\n *\n * @throws {NetworkError} On connection failures (ECONNREFUSED, ETIMEDOUT)\n * @throws {ConnectorError} On 5xx server errors\n * @returns IlpSendResult with acceptance status\n */\n private async sendHttpRequest(params: {\n destination: string;\n amount: string;\n data: string;\n timeout?: number;\n }): Promise<IlpSendResult> {\n const requestTimeout = params.timeout ?? this.timeout;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), requestTimeout);\n\n try {\n // NOTE: Using admin endpoint /admin/ilp/send since connector doesn't have public /ilp endpoint yet\n const response = await this.httpClient(\n `${this.connectorUrl}/admin/ilp/send`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n destination: params.destination,\n amount: params.amount,\n data: params.data,\n }),\n signal: controller.signal,\n }\n );\n\n clearTimeout(timeoutId);\n\n // Handle response by status code\n if (response.ok) {\n // 200 OK: Parse response as IlpSendResult\n const result = (await response.json()) as Record<string, unknown>;\n return {\n accepted: (result['accepted'] as boolean) ?? false,\n data: result['data'] as string | undefined,\n code: result['code'] as string | undefined,\n message: result['message'] as string | undefined,\n };\n } else if (response.status >= 400 && response.status < 500) {\n // 4xx: Client error - return as failed ILP response (no retry)\n const errorBody = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n return {\n accepted: false,\n code: `HTTP_${response.status}`,\n message:\n (errorBody['message'] as string) ??\n (errorBody['error'] as string) ??\n response.statusText,\n };\n } else if (response.status >= 500 && response.status < 600) {\n // 5xx: Server error - throw ConnectorError (no retry)\n const errorBody = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n throw new ConnectorError(\n `Connector server error (${response.status}): ${\n (errorBody['message'] as string) ??\n (errorBody['error'] as string) ??\n response.statusText\n }`\n );\n }\n\n // Unexpected status code (not 2xx, 4xx, or 5xx)\n throw new ConnectorError(\n `Unexpected HTTP status: ${response.status} ${response.statusText}`\n );\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Handle AbortController timeout\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request timeout after ${requestTimeout}ms`,\n error\n );\n }\n\n // Handle network errors (ECONNREFUSED, ETIMEDOUT, etc.)\n if (\n error instanceof TypeError &&\n (error.message.includes('fetch failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('network'))\n ) {\n throw new NetworkError(\n `Network connection failed: ${error.message}`,\n error\n );\n }\n\n // Re-throw known error types\n if (\n error instanceof NetworkError ||\n error instanceof ConnectorError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n\n // Unknown error\n throw new ConnectorError(\n `Unexpected error during HTTP request: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : undefined\n );\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- bounds-checked binary parsing */\n/**\n * Isomorphic BTP + ILP binary protocol.\n * Uses Uint8Array and DataView — no Buffer, no Node.js dependencies.\n *\n * BTP (Bilateral Transfer Protocol) message format:\n * 1 byte — message type\n * 4 bytes — request ID (uint32 BE)\n * variable — payload (MESSAGE data or ERROR data)\n *\n * ILP (Interledger Protocol) OER-encoded packets:\n * PREPARE (type 12), FULFILL (type 13), REJECT (type 14)\n */\n\n// ─── Text codec (isomorphic) ────────────────────────────────────────────────\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n// ─── BTP types ──────────────────────────────────────────────────────────────\n\nexport const BTPMessageType = {\n RESPONSE: 1,\n ERROR: 2,\n MESSAGE: 6,\n} as const;\n\nexport const ILPPacketType = {\n PREPARE: 12,\n FULFILL: 13,\n REJECT: 14,\n} as const;\n\nexport interface BTPProtocolData {\n protocolName: string;\n contentType: number;\n data: Uint8Array;\n}\n\nexport interface BTPMessageData {\n protocolData: BTPProtocolData[];\n ilpPacket?: Uint8Array;\n}\n\nexport interface BTPMessage {\n type: number;\n requestId: number;\n data: BTPMessageData | BTPErrorData;\n}\n\nexport interface BTPErrorData {\n code: string;\n name: string;\n triggeredAt: string;\n /** The trailing `data` octet string decoded as UTF-8 — the human-readable error text. */\n message: string;\n data: Uint8Array;\n}\n\nexport interface ILPPreparePacket {\n type: typeof ILPPacketType.PREPARE;\n amount: bigint;\n destination: string;\n executionCondition: Uint8Array;\n expiresAt: Date;\n data: Uint8Array;\n}\n\nexport interface ILPFulfillPacket {\n type: typeof ILPPacketType.FULFILL;\n /**\n * The 32-byte fulfillment preimage from the wire. All-zero on legacy\n * (zero-condition) packets; on sender-chosen conditions (toon-client#350)\n * the transport verifies `sha256(fulfillment) == executionCondition`.\n */\n fulfillment: Uint8Array;\n data: Uint8Array;\n}\n\nexport interface ILPRejectPacket {\n type: typeof ILPPacketType.REJECT;\n code: string;\n message: string;\n data: Uint8Array;\n}\n\nexport type ILPResponsePacket = ILPFulfillPacket | ILPRejectPacket;\n\n// ─── Byte helpers ───────────────────────────────────────────────────────────\n\nfunction concat(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const a of arrays) {\n result.set(a, offset);\n offset += a.length;\n }\n return result;\n}\n\nfunction readUint8(buf: Uint8Array, offset: number): number {\n if (offset >= buf.length) throw new Error('Buffer underflow reading uint8');\n return buf[offset]!;\n}\n\nfunction readUint16BE(buf: Uint8Array, offset: number): number {\n if (offset + 2 > buf.length)\n throw new Error('Buffer underflow reading uint16');\n return (buf[offset]! << 8) | buf[offset + 1]!;\n}\n\nfunction readUint32BE(buf: Uint8Array, offset: number): number {\n if (offset + 4 > buf.length)\n throw new Error('Buffer underflow reading uint32');\n return (\n ((buf[offset]! << 24) |\n (buf[offset + 1]! << 16) |\n (buf[offset + 2]! << 8) |\n buf[offset + 3]!) >>>\n 0\n );\n}\n\nfunction writeUint8(value: number): Uint8Array {\n return new Uint8Array([value]);\n}\n\nfunction writeUint16BE(value: number): Uint8Array {\n return new Uint8Array([(value >> 8) & 0xff, value & 0xff]);\n}\n\nfunction writeUint32BE(value: number): Uint8Array {\n return new Uint8Array([\n (value >> 24) & 0xff,\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff,\n ]);\n}\n\nfunction sliceUtf8(buf: Uint8Array, offset: number, length: number): string {\n return textDecoder.decode(buf.slice(offset, offset + length));\n}\n\n// ─── OER encoding (ILP wire format) ─────────────────────────────────────────\n\nfunction encodeVarUInt(value: bigint): Uint8Array {\n if (value >= 0n && value <= 127n) {\n return new Uint8Array([Number(value)]);\n }\n const bytes: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n bytes.unshift(Number(remaining & 0xffn));\n remaining = remaining >> 8n;\n }\n return new Uint8Array([0x80 | bytes.length, ...bytes]);\n}\n\nfunction decodeVarUInt(\n buf: Uint8Array,\n offset: number\n): { value: bigint; bytesRead: number } {\n const firstByte = readUint8(buf, offset);\n if (firstByte <= 127) {\n return { value: BigInt(firstByte), bytesRead: 1 };\n }\n const length = firstByte & 0x7f;\n if (offset + 1 + length > buf.length)\n throw new Error('VarUInt buffer underflow');\n let value = 0n;\n for (let i = 0; i < length; i++) {\n value = (value << 8n) | BigInt(buf[offset + 1 + i]!);\n }\n return { value, bytesRead: 1 + length };\n}\n\nfunction encodeVarOctetString(data: Uint8Array): Uint8Array {\n return concat(encodeVarUInt(BigInt(data.length)), data);\n}\n\nfunction decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; bytesRead: number } {\n const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);\n const dataLen = Number(length);\n const start = offset + lenBytes;\n if (start + dataLen > buf.length)\n throw new Error('VarOctetString buffer underflow');\n return {\n value: buf.slice(start, start + dataLen),\n bytesRead: lenBytes + dataLen,\n };\n}\n\nfunction encodeGeneralizedTime(date: Date): Uint8Array {\n const y = date.getUTCFullYear().toString().padStart(4, '0');\n const mo = (date.getUTCMonth() + 1).toString().padStart(2, '0');\n const d = date.getUTCDate().toString().padStart(2, '0');\n const h = date.getUTCHours().toString().padStart(2, '0');\n const mi = date.getUTCMinutes().toString().padStart(2, '0');\n const s = date.getUTCSeconds().toString().padStart(2, '0');\n const ms = date.getUTCMilliseconds().toString().padStart(3, '0');\n return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);\n}\n\n// ─── ILP packet serialization ───────────────────────────────────────────────\n\nexport function serializeIlpPrepare(packet: ILPPreparePacket): Uint8Array {\n const condition =\n packet.executionCondition.length === 32\n ? packet.executionCondition\n : new Uint8Array(32);\n return concat(\n writeUint8(ILPPacketType.PREPARE),\n encodeVarUInt(packet.amount),\n encodeGeneralizedTime(packet.expiresAt),\n condition,\n encodeVarOctetString(textEncoder.encode(packet.destination)),\n encodeVarOctetString(packet.data)\n );\n}\n\nexport function deserializeIlpPacket(buf: Uint8Array): ILPResponsePacket {\n if (buf.length === 0) throw new Error('Empty ILP packet');\n const type = buf[0]!;\n if (type === ILPPacketType.FULFILL) return deserializeIlpFulfill(buf);\n if (type === ILPPacketType.REJECT) return deserializeIlpReject(buf);\n throw new Error(`Unknown ILP packet type: ${type}`);\n}\n\nfunction deserializeIlpFulfill(buf: Uint8Array): ILPFulfillPacket {\n let offset = 1; // skip type byte\n // 32-byte fulfillment preimage. Was skipped (\"unused in TOON\") before\n // sender-chosen execution conditions (toon-client#350) made it load-bearing.\n if (buf.length < offset + 32) {\n throw new Error('Buffer underflow reading FULFILL fulfillment');\n }\n const fulfillment = buf.slice(offset, offset + 32);\n offset += 32;\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.FULFILL, fulfillment, data };\n}\n\nfunction deserializeIlpReject(buf: Uint8Array): ILPRejectPacket {\n let offset = 1; // skip type byte\n // 3-byte error code\n const code = sliceUtf8(buf, offset, 3);\n offset += 3;\n // triggeredBy (skip)\n const { bytesRead: tbBytes } = decodeVarOctetString(buf, offset);\n offset += tbBytes;\n // message\n const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(\n buf,\n offset\n );\n offset += msgBytes;\n const message = textDecoder.decode(msgBuf);\n // data\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.REJECT, code, message, data };\n}\n\n// ─── BTP message serialization ──────────────────────────────────────────────\n\nexport function serializeBtpMessage(message: BTPMessage): Uint8Array {\n const parts: Uint8Array[] = [\n writeUint8(message.type),\n writeUint32BE(message.requestId),\n ];\n\n const data = message.data as BTPMessageData;\n const protocolData = data.protocolData ?? [];\n\n // Protocol data count\n parts.push(writeUint8(protocolData.length));\n\n // Each protocol data entry\n for (const pd of protocolData) {\n const nameBytes = textEncoder.encode(pd.protocolName);\n parts.push(writeUint8(nameBytes.length));\n parts.push(nameBytes);\n parts.push(writeUint16BE(pd.contentType));\n parts.push(writeUint32BE(pd.data.length));\n if (pd.data.length > 0) parts.push(pd.data);\n }\n\n // ILP packet\n const ilpPacket = data.ilpPacket ?? new Uint8Array(0);\n parts.push(writeUint32BE(ilpPacket.length));\n if (ilpPacket.length > 0) parts.push(ilpPacket);\n\n return concat(...parts);\n}\n\nexport function parseBtpMessage(buf: Uint8Array): BTPMessage {\n if (buf.length < 5) throw new Error('BTP message too short');\n let offset = 0;\n\n const type = readUint8(buf, offset);\n offset += 1;\n const requestId = readUint32BE(buf, offset);\n offset += 4;\n\n if (type === BTPMessageType.ERROR) {\n // code\n const codeLen = readUint8(buf, offset);\n offset += 1;\n const code = sliceUtf8(buf, offset, codeLen);\n offset += codeLen;\n // name\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const name = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n // triggeredAt\n const taLen = readUint8(buf, offset);\n offset += 1;\n const triggeredAt = sliceUtf8(buf, offset, taLen);\n offset += taLen;\n // data\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n const message = textDecoder.decode(data);\n return {\n type,\n requestId,\n data: { code, name, triggeredAt, message, data },\n };\n }\n\n // MESSAGE or RESPONSE\n const pdCount = readUint8(buf, offset);\n offset += 1;\n const protocolData: BTPProtocolData[] = [];\n for (let i = 0; i < pdCount; i++) {\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const protocolName = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n const contentType = readUint16BE(buf, offset);\n offset += 2;\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n offset += dataLen;\n protocolData.push({ protocolName, contentType, data });\n }\n\n let ilpPacket: Uint8Array | undefined;\n if (offset + 4 <= buf.length) {\n const ilpLen = readUint32BE(buf, offset);\n offset += 4;\n if (ilpLen > 0 && offset + ilpLen <= buf.length) {\n ilpPacket = buf.slice(offset, offset + ilpLen);\n }\n }\n\n return { type, requestId, data: { protocolData, ilpPacket } };\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- ws is guaranteed non-null when _isConnected */\n/**\n * Isomorphic BTP client — works in both browser and Node.js.\n * Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).\n * No dependency on `ws`, `events`, or `Buffer`.\n *\n * Replaces the @toon-protocol/connector BTPClient for the client SDK.\n */\n\nimport {\n BTPMessageType,\n ILPPacketType,\n serializeBtpMessage,\n serializeIlpPrepare,\n parseBtpMessage,\n deserializeIlpPacket,\n type BTPProtocolData,\n type BTPMessageData,\n type BTPErrorData,\n type ILPPreparePacket,\n type ILPResponsePacket,\n} from './protocol.js';\n\nconst textEncoder = new TextEncoder();\n\nexport interface IsomorphicBtpClientConfig {\n url: string;\n peerId: string;\n authToken: string;\n sendTimeoutMs?: number;\n authTimeoutMs?: number;\n /** Custom WebSocket constructor (e.g., the Node `ws` package, or for testing). */\n createWebSocket?: (url: string) => WebSocket;\n}\n\ninterface PendingRequest {\n resolve: (packet: ILPResponsePacket) => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nexport class BtpConnectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpConnectionError';\n }\n}\n\nexport class BtpAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpAuthError';\n }\n}\n\n/**\n * Lightweight BTP client that speaks the BTP binary protocol over WebSocket.\n * Handles: connect → authenticate → send ILP packets → receive responses.\n */\nexport class IsomorphicBtpClient {\n private ws: WebSocket | null = null;\n private _isConnected = false;\n private requestIdCounter = 0;\n private readonly pendingRequests = new Map<number, PendingRequest>();\n private readonly config: Required<\n Omit<IsomorphicBtpClientConfig, 'createWebSocket'>\n > &\n Pick<IsomorphicBtpClientConfig, 'createWebSocket'>;\n\n constructor(config: IsomorphicBtpClientConfig) {\n this.config = {\n sendTimeoutMs: 30_000,\n authTimeoutMs: 5_000,\n ...config,\n };\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n async connect(): Promise<void> {\n if (this._isConnected) return;\n\n return new Promise<void>((resolve, reject) => {\n try {\n this.ws = this.config.createWebSocket\n ? this.config.createWebSocket(this.config.url)\n : new WebSocket(this.config.url);\n this.ws.binaryType = 'arraybuffer';\n } catch (err) {\n reject(\n new BtpConnectionError(\n `Failed to create WebSocket: ${err instanceof Error ? err.message : String(err)}`\n )\n );\n return;\n }\n\n this.ws.onopen = async () => {\n try {\n await this.authenticate();\n this._isConnected = true;\n resolve();\n } catch (err) {\n this._isConnected = false;\n this.ws?.close();\n reject(err);\n }\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.ws.onerror = (event: any) => {\n const underlying = event?.error ?? event?.message;\n const detail =\n underlying instanceof Error\n ? underlying.message\n : typeof underlying === 'string'\n ? underlying\n : null;\n reject(\n new BtpConnectionError(\n detail\n ? `WebSocket connection error: ${detail}`\n : 'WebSocket connection error'\n )\n );\n };\n\n this.ws.onclose = () => {\n this._isConnected = false;\n // Reject all pending requests\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Connection closed'));\n this.pendingRequests.delete(id);\n }\n };\n });\n }\n\n async disconnect(): Promise<void> {\n this._isConnected = false;\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Disconnected'));\n this.pendingRequests.delete(id);\n }\n }\n\n /**\n * Send an ILP PREPARE packet, optionally with protocol data (e.g. payment channel claim).\n * Returns the ILP response (FULFILL or REJECT).\n */\n async sendPacket(\n packet: ILPPreparePacket,\n protocolData?: BTPProtocolData[]\n ): Promise<ILPResponsePacket> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const serializedIlp = serializeIlpPrepare(packet);\n const requestId = this.nextRequestId();\n\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: protocolData ?? [],\n ilpPacket: serializedIlp,\n },\n });\n\n this.ws.send(btpMessage);\n\n // Calculate timeout from packet expiry or default\n let timeoutMs = this.config.sendTimeoutMs;\n if (packet.expiresAt) {\n const remaining = packet.expiresAt.getTime() - Date.now();\n timeoutMs = Math.max(remaining - 500, 1000);\n }\n\n return new Promise<ILPResponsePacket>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n reject(new BtpConnectionError(`Packet send timeout (${timeoutMs}ms)`));\n }, timeoutMs);\n\n this.pendingRequests.set(requestId, { resolve, reject, timeoutId });\n });\n }\n\n /**\n * Send a fire-and-forget BTP MESSAGE carrying only protocol data (no ILP\n * packet). Used for out-of-band claim notifications that the connector's\n * ClaimReceiver consumes via `handleClaimMessage` — there is no RESPONSE\n * frame, so we resolve immediately after the WebSocket buffers the bytes.\n *\n * Mirrors `sendPacket` wire-format construction but uses an empty ILP\n * payload and does not enroll a pending request.\n */\n async sendProtocolData(\n protocolName: string,\n contentType: number,\n data: Uint8Array\n ): Promise<void> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const requestId = this.nextRequestId();\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [{ protocolName, contentType, data }],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n this.ws.send(btpMessage);\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private async authenticate(): Promise<void> {\n if (!this.ws) throw new BtpAuthError('WebSocket not connected');\n\n const authData = JSON.stringify({\n peerId: this.config.peerId,\n secret: this.config.authToken,\n });\n\n const requestId = this.nextRequestId();\n const authMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [\n {\n protocolName: 'auth',\n contentType: 0,\n data: textEncoder.encode(authData),\n },\n ],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n return new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new BtpAuthError('Authentication timeout'));\n }, this.config.authTimeoutMs);\n\n // Temporarily intercept messages for auth response\n const originalHandler = this.ws!.onmessage;\n this.ws!.onmessage = (event: MessageEvent) => {\n try {\n const data = this.toUint8Array(event.data);\n\n // Try JSON parse first (server may respond with JSON)\n try {\n const jsonStr = new TextDecoder().decode(data);\n if (jsonStr.startsWith('{')) {\n // JSON response — not a BTP binary auth response, ignore\n }\n } catch {\n /* not JSON */\n }\n\n // Parse as BTP binary\n const message = parseBtpMessage(data);\n if (message.requestId === requestId) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n reject(\n new BtpAuthError(\n `Authentication failed: ${errData.code} msg=${errData.message ?? ''} trigger=${errData.triggeredAt ?? ''}`\n )\n );\n } else if (message.type === BTPMessageType.RESPONSE) {\n resolve();\n }\n }\n } catch (err) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n reject(\n new BtpAuthError(err instanceof Error ? err.message : String(err))\n );\n }\n };\n\n this.ws!.send(authMessage);\n });\n }\n\n private handleMessage(raw: unknown): void {\n // Try JSON first (server can send JSON FULFILL/REJECT responses)\n try {\n const data = this.toUint8Array(raw);\n const jsonStr = new TextDecoder().decode(data);\n if (jsonStr.startsWith('{')) {\n const json = JSON.parse(jsonStr) as Record<string, unknown>;\n if (json['type'] === 'FULFILL' || json['type'] === 'REJECT') {\n const first = this.pendingRequests.entries().next();\n if (!first.done) {\n const [id, pending] = first.value;\n clearTimeout(pending.timeoutId);\n this.pendingRequests.delete(id);\n\n if (json['type'] === 'FULFILL') {\n const responseData = json['data']\n ? this.base64ToUint8Array(json['data'] as string)\n : new Uint8Array(0);\n // JSON FULFILLs may carry the fulfillment preimage as base64;\n // absent means all-zero (legacy). A sender-chosen condition\n // (toon-client#350) then fails verification — fail-closed.\n const fulfillment = json['fulfillment']\n ? this.base64ToUint8Array(json['fulfillment'] as string)\n : new Uint8Array(32);\n pending.resolve({\n type: ILPPacketType.FULFILL,\n fulfillment,\n data: responseData,\n });\n } else {\n pending.resolve({\n type: ILPPacketType.REJECT,\n code: (json['code'] as string) || 'F00',\n message: (json['message'] as string) || 'Unknown error',\n data: json['data']\n ? this.base64ToUint8Array(json['data'] as string)\n : new Uint8Array(0),\n });\n }\n }\n return;\n }\n }\n } catch {\n /* not JSON, try BTP binary */\n }\n\n // BTP binary response\n try {\n const data = this.toUint8Array(raw);\n const message = parseBtpMessage(data);\n\n if (\n message.type === BTPMessageType.RESPONSE ||\n message.type === BTPMessageType.ERROR\n ) {\n const pending = this.pendingRequests.get(message.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timeoutId);\n this.pendingRequests.delete(message.requestId);\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n pending.reject(\n new BtpConnectionError(`BTP error: ${errData.code} ${errData.name}`)\n );\n return;\n }\n\n const msgData = message.data as BTPMessageData;\n if (msgData.ilpPacket && msgData.ilpPacket.length > 0) {\n const ilpResponse = deserializeIlpPacket(msgData.ilpPacket);\n pending.resolve(ilpResponse);\n }\n }\n } catch {\n // Unparseable message — ignore\n }\n }\n\n private toUint8Array(data: unknown): Uint8Array {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (data instanceof Uint8Array) return data;\n if (typeof data === 'string') return textEncoder.encode(data);\n throw new Error(`Unexpected WebSocket data type: ${typeof data}`);\n }\n\n private base64ToUint8Array(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n\n private nextRequestId(): number {\n this.requestIdCounter = (this.requestIdCounter + 1) & 0xffffffff;\n return this.requestIdCounter;\n }\n}\n","/**\n * Sender-chosen ILP execution conditions (toon-client#350, rolling-swap\n * prerequisite — toon-meta#145 §3 R1/R2).\n *\n * Contract (normative: connector `docs/local-delivery-fulfillment-contract.md`,\n * connector#309):\n * - An ABSENT or ALL-ZERO (32×0x00) `executionCondition` is the LEGACY\n * class: no hashlock, no verification — today's publish/upload writes.\n * - Any NON-ZERO condition is SENDER-CHOSEN: the sender mints a fresh\n * random 32-byte preimage `P` per packet, sets `C = sha256(P)` on the\n * PREPARE, and on FULFILL MUST verify that the returned fulfillment\n * hashes back to `C` — a missing/malformed/mismatching fulfillment is a\n * hard failure (the packet is counted failed, never silently accepted).\n *\n * Isomorphic: @noble/hashes only (no Buffer, no node:crypto).\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\n\n/** Exact byte length of an ILP execution condition / fulfillment preimage. */\nexport const CONDITION_LENGTH = 32;\n\n/** A freshly minted per-packet hashlock: `condition = sha256(preimage)`. */\nexport interface ExecutionConditionPair {\n /** Random 32-byte preimage `P` — reveal is the commit act; never reuse. */\n preimage: Uint8Array;\n /** `C = sha256(P)` — goes on the PREPARE's `executionCondition`. */\n condition: Uint8Array;\n}\n\n/**\n * Mint a fresh random 32-byte preimage and its sha256 condition (spec R1).\n * Mint one PER PACKET: a reused preimage lets any observer of packet *i*\n * fulfill packet *i+1* without the sender's consent.\n */\nexport function mintExecutionCondition(): ExecutionConditionPair {\n const preimage = randomBytes(CONDITION_LENGTH);\n return { preimage, condition: sha256(preimage) };\n}\n\n/**\n * True when `condition` selects the LEGACY (unverified) class: absent or\n * all-zero. The OER wire treats absent and 32×0x00 identically.\n */\nexport function isZeroCondition(condition: Uint8Array | undefined): boolean {\n if (condition === undefined) return true;\n for (const byte of condition) {\n if (byte !== 0) return false;\n }\n return true;\n}\n\n/**\n * Validate a caller-supplied execution condition before it goes on the wire.\n * @throws {Error} When the condition is not exactly 32 bytes — the OER\n * serializer would otherwise silently zero-fill it, downgrading a\n * sender-chosen packet to the legacy unverified class.\n */\nexport function assertValidCondition(condition: Uint8Array): void {\n if (condition.length !== CONDITION_LENGTH) {\n throw new Error(\n `executionCondition must be exactly ${CONDITION_LENGTH} bytes, got ${condition.length}`\n );\n }\n}\n\n/**\n * True iff `fulfillment` is exactly 32 bytes and `sha256(fulfillment)`\n * equals `condition` — the sender-side FULFILL check (spec R6's mirror).\n * Fail-closed: an undefined/short/long fulfillment never matches.\n */\nexport function fulfillmentMatchesCondition(\n fulfillment: Uint8Array | undefined,\n condition: Uint8Array\n): boolean {\n if (fulfillment === undefined || fulfillment.length !== CONDITION_LENGTH) {\n return false;\n }\n const digest = sha256(fulfillment);\n // Plain comparison is fine: both operands are locally computed/received\n // values on the sender; there is no secret to protect from timing here.\n for (let i = 0; i < CONDITION_LENGTH; i++) {\n if (digest[i] !== condition[i]) return false;\n }\n return true;\n}\n","/**\n * Shared sender-side plumbing for sender-chosen execution conditions\n * (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,\n * connector#309; spec: toon-meta `docs/rolling-swap.md` §3).\n *\n * Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send\n * params and map FULFILL/REJECT responses through the SAME verifier so the\n * two paths cannot drift:\n *\n * - absent/all-zero `executionCondition` → legacy class: today's behavior,\n * byte-for-byte (zero condition on the wire, no FULFILL verification);\n * - non-zero `executionCondition` → sender-chosen: the condition goes on\n * the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash\n * back to it — a missing/malformed/mismatching preimage is surfaced as a\n * FAILED result (never a silent accept, never retried).\n */\n\nimport type { IlpSendResult } from '@toon-protocol/core';\nimport { ILPPacketType, type ILPResponsePacket } from '../btp/protocol.js';\nimport { toBase64 } from '../utils/binary.js';\nimport {\n fulfillmentMatchesCondition,\n isZeroCondition,\n} from '../utils/condition.js';\n\n/**\n * Send parameters accepted by both ILP transports. Extends the\n * `@toon-protocol/core` `IlpClient` param shape with the sender-chosen\n * condition and an explicit expiry — plain `IlpClient` callers keep working\n * unchanged (both extras are optional; omitting them is the legacy path).\n */\nexport interface IlpSendParams {\n destination: string;\n amount: string;\n /** Base64 ILP `data` payload. */\n data: string;\n /** Transport timeout in ms; also the default expiry window. */\n timeout?: number;\n /**\n * Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).\n * Absent or all-zero = legacy unverified packet (default — ordinary\n * publish/upload writes MUST keep this default).\n */\n executionCondition?: Uint8Array;\n /**\n * Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,\n * preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —\n * `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.\n */\n expiresAt?: Date | string;\n}\n\n/** Normalize an `IlpSendParams.expiresAt` to a `Date` (default: now + timeout). */\nexport function resolveExpiresAt(\n expiresAt: Date | string | undefined,\n timeoutMs: number\n): Date {\n if (expiresAt === undefined) return new Date(Date.now() + timeoutMs);\n return expiresAt instanceof Date ? new Date(expiresAt.getTime()) : new Date(expiresAt);\n}\n\n/**\n * `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition\n * was verified. Only populated on the sender-chosen path so legacy result\n * objects stay byte-identical.\n */\nexport interface IlpSendResultWithFulfillment extends IlpSendResult {\n /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */\n fulfillment?: string;\n}\n\n/** ILP code used for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_CODE = 'F99';\n\n/** Message for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_MESSAGE =\n 'FULFILL fulfillment does not match execution condition ' +\n '(sha256(fulfillment) != executionCondition) — packet counted failed';\n\n/**\n * Map a parsed ILP response packet to an `IlpSendResult`, enforcing the\n * sender-chosen condition when one was sent.\n *\n * Verification is fail-closed: when `sentCondition` is non-zero, a FULFILL\n * whose fulfillment is absent, not exactly 32 bytes, or does not sha256-hash\n * to the condition yields `accepted: false` (code F99). The result shape —\n * not a thrown error — is deliberate: transports only retry thrown\n * `NetworkError`s, so a forged/wrong FULFILL is never retried (re-sending\n * would re-spend the attached claim), and packet counters (`streamSwap`\n * rejections) count it failed.\n */\nexport function mapIlpResponse(\n packet: ILPResponsePacket,\n sentCondition?: Uint8Array\n): IlpSendResultWithFulfillment {\n if (packet.type === ILPPacketType.FULFILL) {\n const dataField =\n packet.data.length > 0 ? { data: toBase64(packet.data) } : {};\n\n // Legacy class: absent/all-zero condition → accept without verification\n // (pre-#350 behavior, byte-for-byte).\n if (sentCondition === undefined || isZeroCondition(sentCondition)) {\n return { accepted: true, ...dataField };\n }\n\n // Sender-chosen class: the FULFILL preimage MUST hash to the condition.\n if (!fulfillmentMatchesCondition(packet.fulfillment, sentCondition)) {\n return {\n accepted: false,\n code: FULFILLMENT_MISMATCH_CODE,\n message: FULFILLMENT_MISMATCH_MESSAGE,\n ...dataField,\n };\n }\n\n return {\n accepted: true,\n fulfillment: toBase64(packet.fulfillment),\n ...dataField,\n };\n }\n\n // REJECT\n return {\n accepted: false,\n code: packet.code,\n message: packet.message,\n ...(packet.data.length > 0 ? { data: toBase64(packet.data) } : {}),\n };\n}\n","import {\n IsomorphicBtpClient,\n BtpConnectionError,\n} from '../btp/IsomorphicBtpClient.js';\nimport { type BTPProtocolData } from '../btp/protocol.js';\nimport type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport { withRetry } from '../utils/retry.js';\nimport { fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport { mapIlpResponse, resolveExpiresAt, type IlpSendParams } from './ilp-send.js';\nimport { assertValidCondition, isZeroCondition } from '../utils/condition.js';\n\nexport interface BtpRuntimeClientConfig {\n btpUrl: string;\n peerId: string;\n authToken: string;\n /** Max reconnection attempts on send failure (default: 3) */\n maxRetries?: number;\n /** Delay between reconnection attempts in ms (default: 1000) */\n retryDelay?: number;\n /** Custom WebSocket constructor (for testing / custom transports). */\n createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * Returns true if the error is a connection-level error worth retrying.\n * ILP application-level rejects (F02, T01, etc.) are NOT retried.\n */\nfunction isConnectionError(error: Error): boolean {\n const msg = error.message.toLowerCase();\n return (\n msg.includes('not connected') ||\n msg.includes('connection') ||\n msg.includes('websocket') ||\n msg.includes('econnrefused') ||\n msg.includes('econnreset') ||\n msg.includes('socket hang up') ||\n msg.includes('timeout')\n );\n}\n\n/**\n * BTP transport implementing IlpClient.\n * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).\n */\nexport class BtpRuntimeClient implements IlpClient {\n private btpClient: IsomorphicBtpClient | null = null;\n private readonly config: BtpRuntimeClientConfig;\n private _isConnected = false;\n\n constructor(config: BtpRuntimeClientConfig) {\n this.config = config;\n }\n\n /**\n * Connects to the BTP peer via WebSocket.\n */\n async connect(): Promise<void> {\n this.btpClient = new IsomorphicBtpClient({\n url: this.config.btpUrl,\n peerId: this.config.peerId,\n authToken: this.config.authToken,\n createWebSocket: this.config.createWebSocket,\n });\n\n await this.btpClient.connect();\n this._isConnected = true;\n }\n\n /**\n * Attempts to reconnect by creating a fresh client and connecting.\n */\n async reconnect(): Promise<void> {\n if (this.btpClient) {\n try {\n await this.btpClient.disconnect();\n } catch {\n // Ignore disconnect errors during reconnect\n }\n this.btpClient = null;\n this._isConnected = false;\n }\n\n await this.connect();\n }\n\n /**\n * Disconnects from the BTP peer.\n */\n async disconnect(): Promise<void> {\n if (this.btpClient) {\n await this.btpClient.disconnect();\n this._isConnected = false;\n this.btpClient = null;\n }\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Sends an ILP packet via BTP with auto-reconnect on connection errors.\n * Satisfies IlpClient interface.\n *\n * `params` may carry a sender-chosen `executionCondition` and an explicit\n * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition\n * path, unchanged. With a non-zero condition the FULFILL preimage is\n * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced\n * as a failed result — see `mapIlpResponse`.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketOnce(params), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.\n * Auto-reconnects on connection errors.\n *\n * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are\n * identical to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketWithClaimOnce(params, claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet\n * attached). The connector's ClaimReceiver consumes this fire-and-forget\n * to register cumulative claim state independently of the per-packet\n * forwarding path. Auto-reconnects on connection errors.\n */\n async sendClaimMessage(claim: Record<string, unknown>): Promise<void> {\n return withRetry(() => this._sendClaimMessageOnce(claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n private async _sendClaimMessageOnce(\n claim: Record<string, unknown>\n ): Promise<void> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n await this.btpClient.sendProtocolData(\n 'payment-channel-claim',\n 1,\n encodeUtf8(JSON.stringify(claim))\n );\n }\n\n /**\n * Build the ILP PREPARE for a send, applying the sender-chosen condition /\n * explicit expiry when provided (toon-client#350) and validating that a\n * non-zero condition is exactly 32 bytes (the OER serializer would\n * otherwise silently zero-fill it, downgrading the packet to the legacy\n * unverified class).\n */\n private buildPrepare(params: IlpSendParams): {\n prepare: {\n type: 12;\n amount: bigint;\n destination: string;\n executionCondition: Uint8Array;\n expiresAt: Date;\n data: Uint8Array;\n };\n condition: Uint8Array | undefined;\n } {\n const condition = params.executionCondition;\n if (condition !== undefined && !isZeroCondition(condition)) {\n assertValidCondition(condition);\n }\n return {\n prepare: {\n type: 12 as const,\n amount: BigInt(params.amount),\n destination: params.destination,\n executionCondition: condition ?? new Uint8Array(32),\n expiresAt: resolveExpiresAt(params.expiresAt, params.timeout ?? 30000),\n data: fromBase64(params.data),\n },\n condition,\n };\n }\n\n /**\n * Single-attempt ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketOnce(\n params: IlpSendParams\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n const { prepare, condition } = this.buildPrepare(params);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by reconnect() above\n const response = await this.btpClient!.sendPacket(prepare);\n\n return mapIlpResponse(response, condition);\n }\n\n /**\n * Single-attempt claim + ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketWithClaimOnce(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n const protocolData: BTPProtocolData[] = [\n {\n protocolName: 'payment-channel-claim',\n contentType: 1,\n data: encodeUtf8(JSON.stringify(claim)),\n },\n ];\n\n const { prepare, condition } = this.buildPrepare(params);\n const response = await this.btpClient.sendPacket(prepare, protocolData);\n\n return mapIlpResponse(response, condition);\n }\n}\n","/**\n * ILP-over-HTTP (RFC-0035) transport for the TOON client.\n *\n * The connector now serves ILP-over-HTTP on the SAME port as BTP (connector\n * PR #181). This adapter lets a client do stateless one-shot writes over HTTP\n * (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive\n * server-initiated packets or act as a peer.\n *\n * Wire contract (targets connector PR #181's `/ilp`):\n * - One-shot write: `POST /ilp`\n * body: OER-encoded ILP PREPARE (`application/octet-stream`)\n * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the\n * SAME claim JSON the BTP path attaches as the\n * `payment-channel-claim` protocolData entry.\n * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.\n * response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is\n * reserved for TRANSPORT errors (400/401/413/5xx); ILP-level\n * rejects come back as a 200 + REJECT body.\n * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`\n * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector\n * pre-authenticates the BTP session from those headers (continuity), so\n * after `101` we send BTP frames WITHOUT a separate in-band auth frame.\n * Omitting the auth headers falls back to the normal BTP auth-frame flow.\n *\n * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —\n * the SAME OER codec the BTP path uses. Claim signing/construction is owned by\n * the caller (BootstrapService); this transport never builds or signs claims.\n */\n\nimport type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport type WSModule from 'ws';\nimport {\n ILPPacketType,\n serializeIlpPrepare,\n deserializeIlpPacket,\n} from '../btp/protocol.js';\nimport { BtpRuntimeClient } from './BtpRuntimeClient.js';\nimport { NetworkError, ConnectorError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { toBase64, fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport { mapIlpResponse, resolveExpiresAt, type IlpSendParams } from './ilp-send.js';\nimport { assertValidCondition, isZeroCondition } from '../utils/condition.js';\n\n/** Header carrying the base64(JSON) payment-channel claim. */\nexport const ILP_CLAIM_HEADER = 'ILP-Payment-Channel-Claim';\n/** Header carrying the peer identity. */\nexport const ILP_PEER_ID_HEADER = 'ILP-Peer-Id';\n\nexport interface HttpIlpClientConfig {\n /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */\n httpEndpoint: string;\n /**\n * Optional peer identity. With no `peerId`/`authToken` the connector treats\n * the request as an anonymous no-auth peer (permissionless default) and\n * derives an ephemeral id from the claim signer.\n */\n peerId?: string;\n /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */\n authToken?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n /** Max retry attempts for transport-level network failures (default: 3). */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000). */\n retryDelay?: number;\n /** Custom fetch implementation (for testing / custom transports). */\n httpClient?: typeof fetch;\n /**\n * Custom WebSocket constructor for the BTP upgrade path (for testing /\n * custom transports). Forwarded to the underlying BtpRuntimeClient.\n */\n createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * Stateless ILP-over-HTTP transport implementing `IlpClient`.\n *\n * Use this for pure one-shot consumers (publish-and-forget writes). When the\n * client needs a duplex session — to receive server-initiated packets or to act\n * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient\n * that reuses the existing BTP code path.\n */\nexport class HttpIlpClient implements IlpClient {\n private readonly httpEndpoint: string;\n private readonly peerId: string | undefined;\n private readonly authToken: string | undefined;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n private readonly createWebSocket: ((url: string) => WebSocket) | undefined;\n\n constructor(config: HttpIlpClientConfig) {\n this.httpEndpoint = config.httpEndpoint;\n this.peerId = config.peerId;\n this.authToken = config.authToken;\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n this.createWebSocket = config.createWebSocket;\n }\n\n /**\n * The client edge this transport pays — the origin `GET /ilp/identity` and\n * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the\n * trailing `/ilp` away). Exposed because a sealed write must ask the\n * connector it is ACTUALLY paying for its key, not a configured guess.\n */\n get clientEdgeEndpoint(): string {\n return this.httpEndpoint;\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts\n * this only on free/zero-amount routes; paid writes must use\n * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.\n *\n * `params` may carry a sender-chosen `executionCondition` and an explicit\n * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition\n * path, unchanged. With a non-zero condition the FULFILL preimage is\n * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced\n * as a failed result — see {@link mapIlpResponse}.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached\n * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object\n * the BTP path attaches as the `payment-channel-claim` protocolData entry —\n * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.\n *\n * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are\n * identical to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params, claim), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Upgrade to a duplex BTP session over the SAME endpoint.\n *\n * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with\n * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`\n * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers\n * are present the connector pre-authenticates the session (no in-band auth\n * frame); without them the BtpRuntimeClient falls back to the normal BTP\n * auth-frame flow.\n *\n * NOTE: passing per-connection headers + a subprotocol to a WebSocket is\n * Node-only (the `ws` package). Browsers cannot set arbitrary request headers\n * on a WebSocket handshake, so a browser consumer must use the gateway\n * transport or BTP-with-auth-frame instead.\n */\n async upgradeToBtp(): Promise<BtpRuntimeClient> {\n const btpUrl = httpEndpointToBtpUrl(this.httpEndpoint);\n\n // Default WS factory negotiates `btp` + carries the auth headers so the\n // connector pre-authenticates. Built lazily (Node-only) — browsers must\n // pass an explicit `createWebSocket` (they can't set handshake headers).\n const createWebSocket =\n this.createWebSocket ?? (await makeBtpWebSocketFactory(this.authHeaders()));\n\n const client = new BtpRuntimeClient({\n btpUrl,\n // BtpRuntimeClient sends an auth frame using these; when the connector\n // pre-authenticated via Upgrade headers it accepts the (redundant) frame.\n peerId: this.peerId ?? 'client',\n authToken: this.authToken ?? '',\n createWebSocket,\n });\n await client.connect();\n return client;\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n private authHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n if (this.peerId) headers[ILP_PEER_ID_HEADER] = this.peerId;\n if (this.authToken) headers['Authorization'] = `Bearer ${this.authToken}`;\n return headers;\n }\n\n /**\n * Single attempt: serialize the PREPARE, POST it, and map the response.\n * @throws {NetworkError} On connection/timeout failures (retried).\n * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).\n */\n private async postPrepare(\n params: IlpSendParams,\n claim?: unknown\n ): Promise<IlpSendResult> {\n const requestTimeout = params.timeout ?? this.timeout;\n\n // Sender-chosen condition (toon-client#350): validate length up front so\n // the OER serializer can never silently zero-fill a malformed condition\n // and downgrade the packet to the legacy unverified class.\n const condition = params.executionCondition;\n if (condition !== undefined && !isZeroCondition(condition)) {\n assertValidCondition(condition);\n }\n\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: BigInt(params.amount),\n destination: params.destination,\n executionCondition: condition ?? new Uint8Array(32),\n expiresAt: resolveExpiresAt(params.expiresAt, requestTimeout),\n data: fromBase64(params.data),\n });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/octet-stream',\n ...this.authHeaders(),\n };\n if (claim !== undefined) {\n headers[ILP_CLAIM_HEADER] = toBase64(\n encodeUtf8(JSON.stringify(claim))\n );\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), requestTimeout);\n\n try {\n const response = await this.httpClient(this.httpEndpoint, {\n method: 'POST',\n headers,\n // Copy into a fresh ArrayBuffer so fetch sees a clean body, not a view.\n body: prepare.slice(),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return await this.mapResponse(response, condition);\n } catch (error) {\n clearTimeout(timeoutId);\n throw this.mapTransportError(error, requestTimeout);\n }\n }\n\n /**\n * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx\n * to a transport error. Per the wire contract, ILP-level rejects arrive as a\n * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.\n *\n * When `sentCondition` is non-zero the FULFILL preimage is verified against\n * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,\n * identical to the BTP path).\n */\n private async mapResponse(\n response: Response,\n sentCondition?: Uint8Array\n ): Promise<IlpSendResult> {\n if (response.ok) {\n const buf = new Uint8Array(await response.arrayBuffer());\n if (buf.length === 0) {\n throw new ConnectorError('Empty 200 body from /ilp (expected OER ILP response)');\n }\n return mapIlpResponse(deserializeIlpPacket(buf), sentCondition);\n }\n\n // Transport-level error (400 malformed, 401 auth, 413 too large, 5xx).\n const body = await response.text().catch(() => '');\n const detail = body ? `: ${body}` : '';\n if (response.status >= 500) {\n throw new ConnectorError(\n `Connector transport error (${response.status} ${response.statusText})${detail}`\n );\n }\n // 4xx — non-retryable client/transport error.\n throw new ConnectorError(\n `ILP-over-HTTP request rejected (${response.status} ${response.statusText})${detail}`\n );\n }\n\n private mapTransportError(error: unknown, requestTimeout: number): Error {\n if (error instanceof ConnectorError || error instanceof NetworkError) {\n return error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return new NetworkError(`Request timeout after ${requestTimeout}ms`, error);\n }\n if (\n error instanceof TypeError &&\n (error.message.includes('fetch failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ECONNRESET') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('network'))\n ) {\n return new NetworkError(`Network connection failed: ${error.message}`, error);\n }\n return new ConnectorError(\n `Unexpected error during ILP-over-HTTP request: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector\n * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).\n */\nexport function httpEndpointToBtpUrl(httpEndpoint: string): string {\n return httpEndpoint\n .replace(/^https:\\/\\//i, 'wss://')\n .replace(/^http:\\/\\//i, 'ws://');\n}\n\n/**\n * Build a WebSocket factory that opens the BTP upgrade with a `btp` subprotocol\n * and the given handshake headers. Node-only — lazily loads the `ws` package via\n * a dynamically-imported `createRequire` so the node-only `node:module`/`ws`\n * deps never enter a browser bundle (per-connection headers aren't settable on\n * the browser WebSocket anyway).\n */\nasync function makeBtpWebSocketFactory(\n headers: Record<string, string>\n): Promise<(url: string) => WebSocket> {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const WS = require('ws') as typeof WSModule;\n\n // CJS/ESM interop: walk the constructor ladder (class / .default / .WebSocket)\n // so this works under any loader.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ws = WS as any;\n const WSClass = (typeof ws === 'function'\n ? ws\n : typeof ws.default === 'function'\n ? ws.default\n : typeof ws.WebSocket === 'function'\n ? ws.WebSocket\n : null) as unknown as typeof WSModule.prototype.constructor;\n if (WSClass === null) {\n throw new Error(\n \"makeBtpWebSocketFactory: require('ws') did not yield a constructor on .default, .WebSocket, or the module root.\"\n );\n }\n\n // `ws` accepts (url, protocols, options); the connector negotiates `btp` and\n // pre-authenticates the session from the `ILP-Peer-Id`/`Authorization` headers.\n return (url: string): WebSocket =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (WSClass as any)(url, 'btp', { headers }) as unknown as WebSocket;\n}\n","/**\n * Transport selection policy for the client ILP layer.\n *\n * The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port\n * (connector PR #181). A peer advertises this in discovery via the toon-core\n * `IlpPeerInfo` fields added in toon PR #29:\n * - `httpEndpoint?: string` — the `POST /ilp` URL.\n * - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.\n *\n * Those fields may not yet exist on the installed `@toon-protocol/core`\n * `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).\n *\n * Policy:\n * - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer\n * advertises an `httpEndpoint` — stateless, no persistent socket.\n * - Clients that must receive server-initiated packets or act as a peer\n * (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`\n * and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we\n * connect to the BTP endpoint directly.\n */\n\n/**\n * The subset of discovery fields this policy reads. Structurally compatible with\n * core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a\n * pre-PR-#29 `IlpPeerInfo` can be passed through a cast.\n */\nexport interface DiscoveredIlpPeer {\n /** BTP WebSocket endpoint (always present on a TOON peer). */\n btpEndpoint?: string;\n /** `POST /ilp` URL (toon PR #29). */\n httpEndpoint?: string;\n /** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */\n supportsUpgrade?: boolean;\n}\n\nexport type IlpTransportChoice =\n /** Stateless one-shot writes via `POST /ilp`. */\n | { kind: 'http'; httpEndpoint: string; canUpgrade: boolean }\n /** Duplex BTP session via the WebSocket endpoint. */\n | { kind: 'btp'; btpEndpoint: string }\n /**\n * Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.\n * Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no\n * separate `btpEndpoint`.\n */\n | { kind: 'http-upgradable'; httpEndpoint: string };\n\nexport interface SelectIlpTransportOptions {\n /**\n * Whether the client needs a duplex session (receive server-initiated\n * packets / act as a peer). Default: false (pure one-shot consumer).\n */\n needsDuplex?: boolean;\n}\n\n/**\n * Read discovery fields defensively from a (possibly pre-PR-#29) peer info\n * object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.\n */\nexport function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer {\n const p = (peer ?? {}) as Record<string, unknown>;\n return {\n btpEndpoint:\n typeof p['btpEndpoint'] === 'string' ? (p['btpEndpoint'] as string) : undefined,\n httpEndpoint:\n typeof p['httpEndpoint'] === 'string'\n ? (p['httpEndpoint'] as string)\n : undefined,\n supportsUpgrade:\n typeof p['supportsUpgrade'] === 'boolean'\n ? (p['supportsUpgrade'] as boolean)\n : undefined,\n };\n}\n\n/**\n * Choose the ILP transport for a discovered peer given the consumer's needs.\n *\n * @throws {Error} If the peer advertises no usable endpoint at all.\n */\nexport function selectIlpTransport(\n peer: DiscoveredIlpPeer,\n options: SelectIlpTransportOptions = {}\n): IlpTransportChoice {\n const needsDuplex = options.needsDuplex ?? false;\n const http = peer.httpEndpoint?.trim() || undefined;\n const btp = peer.btpEndpoint?.trim() || undefined;\n const canUpgrade = peer.supportsUpgrade === true;\n\n if (needsDuplex) {\n // Duplex consumers prefer a real BTP endpoint; fall back to HTTP-upgrade\n // only when the host advertises it.\n if (btp) return { kind: 'btp', btpEndpoint: btp };\n if (http && canUpgrade) return { kind: 'http-upgradable', httpEndpoint: http };\n throw new Error(\n 'Duplex transport required but peer exposes neither a btpEndpoint nor an upgradable httpEndpoint'\n );\n }\n\n // One-shot consumers prefer stateless HTTP when available.\n if (http) return { kind: 'http', httpEndpoint: http, canUpgrade };\n if (btp) return { kind: 'btp', btpEndpoint: btp };\n throw new Error('Peer exposes neither an httpEndpoint nor a btpEndpoint');\n}\n","import {\n createPublicClient,\n createWalletClient,\n http,\n maxUint256,\n decodeEventLog,\n defineChain,\n type Hex,\n type TransactionReceipt,\n} from 'viem';\nimport type {\n ConnectorChannelClient,\n OpenChannelParams,\n OpenChannelResult,\n ChannelState,\n} from '@toon-protocol/core';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode } from '@toon-protocol/core';\nimport type { EvmSigner } from '../signing/evm-signer.js';\nimport { ChannelFundingError, isInsufficientGasError } from '../errors.js';\nimport {\n openSolanaChannel as openSolanaChannelOnChain,\n getChannelAccountState as getSolanaChannelAccountState,\n depositSolanaChannel,\n deriveAssociatedTokenAccount,\n} from './solana-payment-channel.js';\nimport { openMinaChannelOnChain } from './mina-channel-open.js';\n\n// TokenNetwork ABI — only the functions we need\nconst TOKEN_NETWORK_ABI = [\n {\n name: 'openChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'participant2', type: 'address' },\n { name: 'settlementTimeout', type: 'uint256' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'setTotalDeposit',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'participant', type: 'address' },\n { name: 'totalDeposit', type: 'uint256' },\n ],\n outputs: [],\n },\n {\n name: 'closeChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'settleChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'channels',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }],\n outputs: [\n { name: 'settlementTimeout', type: 'uint256' },\n { name: 'state', type: 'uint8' },\n { name: 'closedAt', type: 'uint256' },\n { name: 'openedAt', type: 'uint256' },\n { name: 'participant1', type: 'address' },\n { name: 'participant2', type: 'address' },\n ],\n },\n {\n name: 'participants',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }, { type: 'address' }],\n outputs: [\n { name: 'deposit', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n ],\n },\n {\n name: 'ChannelOpened',\n type: 'event',\n inputs: [\n { name: 'channelId', type: 'bytes32', indexed: true },\n { name: 'participant1', type: 'address', indexed: true },\n { name: 'participant2', type: 'address', indexed: true },\n { name: 'settlementTimeout', type: 'uint256', indexed: false },\n ],\n },\n] as const;\n\n// ERC20 ABI — only approve and allowance\nconst ERC20_ABI = [\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n] as const;\n\n/** Maps on-chain state uint8 to ChannelState status */\nconst STATE_MAP: Record<number, ChannelState['status']> = {\n 0: 'settled',\n 1: 'open',\n 2: 'closed',\n 3: 'settled',\n};\n\nexport interface SolanaChannelConfig {\n rpcUrl: string;\n /**\n * Ed25519 keypair material. Accepts either a 32-byte seed or a 64-byte\n * `secretKey` (seed || pubkey, as produced by `deriveFullIdentity`). The first\n * 32 bytes are the signing seed; the public key is derived from it.\n */\n keypair: Uint8Array;\n programId: string;\n /**\n * SPL token mint (base58) for PDA derivation. Optional — the per-channel\n * negotiated token (`OpenChannelParams.token`) takes precedence when present.\n */\n tokenMint?: string;\n /**\n * Challenge-period duration in seconds for `initialize_channel`. Defaults to\n * `OpenChannelParams.settlementTimeout` or 86400.\n */\n challengeDuration?: number;\n /**\n * Optional deposit amount (base units, string) + the payer's funded SPL token\n * account (ATA, base58). When omitted, the channel is opened (initialized)\n * without an on-chain deposit — the connector accepts the claim on channel\n * `opened` status + participant membership; deposit is only consumed at\n * on-chain claim/settle time.\n */\n deposit?: { amount: string; payerTokenAccount: string };\n}\n\nexport interface MinaChannelConfig {\n graphqlUrl: string;\n privateKey: string;\n /**\n * Deployed payment-channel zkApp address (B62). Optional when `autoDeploy`\n * is set — the open path then resolves (or deploys) a pair-owned zkApp\n * itself; see `mina-channel-deploy.ts`.\n */\n zkAppAddress?: string;\n /**\n * Per-pair zkApp auto-deploy (the Mina `PaymentChannel` zkApp is\n * single-pair: one deployment serves exactly one client↔connector pair).\n * When set, `openMinaChannel` first resolves a zkApp that is provably OURS\n * — the recorded `deployed` one, or `zkAppAddress` when its on-chain\n * channelHash matches this pair — and deploys a fresh one otherwise\n * (compile ≈1-3 min; inclusion ≈3-6 min; costs ~1.1 MINA + fees).\n * Without it, behavior is exactly the pre-autoDeploy contract: the\n * configured `zkAppAddress` is required and used verbatim.\n */\n autoDeploy?: {\n /** A previously recorded own deployment for this identity, if any. */\n deployed?: { zkAppAddress: string; zkAppPrivateKey: string };\n /**\n * Persist hook — called with the zkApp address + key BEFORE the deploy tx\n * is sent (and before the circuit compiles), so a crash between send and\n * on-chain confirmation reuses the SAME zkApp next run instead of\n * deploying (and paying ~1.1 MINA for) a second one.\n */\n onDeploying?: (record: {\n zkAppAddress: string;\n zkAppPrivateKey: string;\n feePayer: string;\n }) => void | Promise<void>;\n /** Persist hook — called BEFORE the open proceeds on a fresh deploy. */\n onDeployed?: (record: {\n zkAppAddress: string;\n zkAppPrivateKey: string;\n feePayer: string;\n deployTxHash?: string;\n vkHash?: string;\n }) => void | Promise<void>;\n /** Progress lines (compile/deploy/inclusion phases take minutes). */\n onProgress?: (line: string) => void;\n };\n /**\n * Channel settlement timeout in slots for `initializeChannel`. Defaults to\n * `OpenChannelParams.settlementTimeout` or 86400.\n */\n challengeDuration?: number;\n /**\n * Mina token id field (decimal string) for `initializeChannel`. Default '1'\n * (native MINA). The connector reads this only as on-chain channel metadata.\n */\n tokenId?: string;\n /**\n * Optional on-chain deposit (base units, string) submitted after the channel\n * is initialized. When omitted, the channel is opened (OPEN state) without a\n * deposit — the connector accepts the claim on `opened` status; deposit is\n * only consumed at on-chain settle time.\n */\n deposit?: { amount: string };\n /** Mina network id for the account/Schnorr prefix. Default 'devnet'. */\n networkId?: 'devnet' | 'mainnet';\n}\n\nexport interface OnChainChannelClientConfig {\n evmSigner: EvmSigner;\n chainRpcUrls: Record<string, string>;\n solanaConfig?: SolanaChannelConfig;\n minaConfig?: MinaChannelConfig;\n}\n\n/**\n * Implements ConnectorChannelClient using viem for direct on-chain\n * interaction with TokenNetwork smart contract.\n *\n * Fully non-custodial — the client deposits its own funds on-chain.\n */\nexport class OnChainChannelClient implements ConnectorChannelClient {\n private readonly evmSigner: EvmSigner;\n private readonly chainRpcUrls: Record<string, string>;\n private solanaConfig?: SolanaChannelConfig;\n private minaConfig?: MinaChannelConfig;\n private readonly channelContext = new Map<\n string,\n { chain: string; tokenNetworkAddress: string; tokenAddress?: string }\n >();\n\n constructor(config: OnChainChannelClientConfig) {\n this.evmSigner = config.evmSigner;\n this.chainRpcUrls = config.chainRpcUrls;\n this.solanaConfig = config.solanaConfig;\n this.minaConfig = config.minaConfig;\n }\n\n /**\n * Late-binds the Solana channel config.\n *\n * `ToonClient.start()` derives the Solana Ed25519 keypair from the client's\n * mnemonic asynchronously (after this client is constructed), so the keypair\n * is injected here rather than at construction. Same keypair as the\n * registered Solana signer — guarantees the channel-open key and the\n * claim-signing key match.\n */\n setSolanaConfig(config: SolanaChannelConfig): void {\n this.solanaConfig = config;\n }\n\n /**\n * Late-binds the Mina channel config.\n *\n * Parallel to `setSolanaConfig`: `ToonClient.start()` derives the Mina private\n * key from the client's mnemonic asynchronously (after this client is\n * constructed), so the key is injected here rather than at construction. Same\n * key as the registered Mina signer.\n */\n setMinaConfig(config: MinaChannelConfig): void {\n this.minaConfig = config;\n }\n\n /**\n * Parse chain identifier to extract chainId.\n * Format: \"evm:{network}:{chainId}\" e.g., \"evm:anvil:31337\"\n */\n private parseChainId(chain: string): number {\n const parts = chain.split(':');\n if (parts.length < 2) {\n throw new Error(\n `Invalid chain format: \"${chain}\". Expected \"evm:{network}:{chainId}\" or \"evm:{chainId}\".`\n );\n }\n // Accept both the canonical 3-part `evm:{network}:{chainId}` and the 2-part\n // `evm:{chainId}` form some connectors advertise (e.g. `evm:31337`).\n const chainIdStr = parts.length >= 3 ? parts[2] : parts[1];\n if (!chainIdStr) {\n throw new Error(\n `Invalid chain format: \"${chain}\". Expected \"evm:{network}:{chainId}\".`\n );\n }\n const chainId = parseInt(chainIdStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid chainId in chain \"${chain}\".`);\n }\n return chainId;\n }\n\n /**\n * Create viem clients for a given chain.\n */\n private createClients(chain: string) {\n const rpcUrl = this.chainRpcUrls[chain];\n if (!rpcUrl) {\n throw new Error(\n `No RPC URL configured for chain \"${chain}\". Available: ${Object.keys(this.chainRpcUrls).join(', ')}`\n );\n }\n\n const chainId = this.parseChainId(chain);\n\n const viemChain = defineChain({\n id: chainId,\n name: chain,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [rpcUrl] } },\n });\n\n const publicClient = createPublicClient({\n transport: http(rpcUrl),\n chain: viemChain,\n });\n\n const walletClient = createWalletClient({\n account: this.evmSigner.account,\n transport: http(rpcUrl),\n chain: viemChain,\n });\n\n return { publicClient, walletClient };\n }\n\n /**\n * Opens a new payment channel on-chain.\n *\n * 1. Approve token spend if needed\n * 2. Call TokenNetwork.openChannel()\n * 3. Extract channelId from ChannelOpened event\n * 4. Deposit initial funds if specified\n */\n async openChannel(params: OpenChannelParams): Promise<OpenChannelResult> {\n const chainPrefix = params.chain.split(':')[0];\n\n // Dispatch to chain-specific opener\n if (chainPrefix === 'solana') return this.openSolanaChannel(params);\n if (chainPrefix === 'mina') return this.openMinaChannel(params);\n\n // EVM path (default)\n return this.openEvmChannel(params);\n }\n\n /**\n * Deposit additional collateral into an already-open channel. `amount` is the\n * DELTA to add (base units). Dispatches by the channel's cached chain context;\n * `currentDeposit` is the channel's current locked total (tracked off-chain by\n * the caller) — required for EVM, whose `setTotalDeposit` takes the new\n * cumulative total, not a delta. Returns the new on-chain deposit total.\n *\n * Non-custodial: the client deposits its OWN funds and signs its OWN tx.\n * EVM is live; Solana/Mina deposit extraction is a follow-up (PR B.1).\n */\n async depositToChannel(\n channelId: string,\n amount: bigint,\n opts: { currentDeposit: bigint }\n ): Promise<{ txHash?: string; depositTotal: bigint }> {\n if (amount <= 0n) throw new Error('Deposit amount must be positive.');\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana') {\n return this.depositSolana(channelId, amount, opts.currentDeposit);\n }\n if (chainPrefix === 'mina') {\n throw new Error(\n 'Deposit on mina is not yet supported (EVM + Solana today; Mina follow-up).'\n );\n }\n return this.depositEvm(channelId, amount, opts.currentDeposit, ctx);\n }\n\n /**\n * Solana deposit: fire the standalone `deposit` instruction against the channel\n * vault. Incremental on-chain (the program adds `amount`), so the new total is\n * the caller-tracked current plus the delta. Requires the funded payer token\n * account (the funded ATA) from the Solana channel config.\n */\n private async depositSolana(\n channelId: string,\n amount: bigint,\n currentDeposit: bigint\n ): Promise<{ txHash: string; depositTotal: bigint }> {\n if (!this.solanaConfig) {\n throw new Error('Solana channel config not set — cannot deposit.');\n }\n const cfg = this.solanaConfig;\n const payerSeed = cfg.keypair.slice(0, 32);\n const payerPubkey = base58Encode(\n new Uint8Array(ed25519.getPublicKey(payerSeed))\n );\n // The funded token account is deterministically the payer's ATA for the\n // channel mint, so derive it when the caller didn't pass one explicitly\n // (config need not carry payerTokenAccount — it's owner+mint, both known here).\n let payerTokenAccount = cfg.deposit?.payerTokenAccount;\n if (!payerTokenAccount) {\n if (!cfg.tokenMint) {\n throw new Error(\n 'Solana deposit requires solanaConfig.deposit.payerTokenAccount or solanaConfig.tokenMint to derive the payer ATA.'\n );\n }\n payerTokenAccount = deriveAssociatedTokenAccount(\n payerPubkey,\n cfg.tokenMint\n );\n }\n const { depositTxSignature } = await depositSolanaChannel({\n rpcUrl: cfg.rpcUrl,\n programId: cfg.programId,\n channelPDA: channelId,\n payerSeed,\n payerPubkey,\n payerTokenAccount,\n amount,\n });\n return {\n txHash: depositTxSignature,\n depositTotal: currentDeposit + amount,\n };\n }\n\n /**\n * EVM deposit: approve the token-network for the delta if the allowance is\n * short, then `setTotalDeposit(channelId, participant, current + delta)` —\n * the contract takes the new cumulative total, so we add the delta to the\n * caller-supplied current locked amount.\n */\n private async depositEvm(\n channelId: string,\n amount: bigint,\n currentDeposit: bigint,\n ctx: { chain: string; tokenNetworkAddress: string; tokenAddress?: string }\n ): Promise<{ txHash: string; depositTotal: bigint }> {\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const tokenNetworkAddr = ctx.tokenNetworkAddress as Hex;\n const myAddress = this.evmSigner.address as Hex;\n const newTotal = currentDeposit + amount;\n\n // Approve the additional collateral if the current allowance can't cover it.\n if (ctx.tokenAddress) {\n const tokenAddr = ctx.tokenAddress as Hex;\n const allowance = await publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [myAddress, tokenNetworkAddr],\n });\n if ((allowance as bigint) < amount) {\n const approveHash = await walletClient.writeContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [tokenNetworkAddr, maxUint256],\n });\n await publicClient.waitForTransactionReceipt({ hash: approveHash });\n }\n }\n\n const depositHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, myAddress, newTotal],\n });\n await publicClient.waitForTransactionReceipt({ hash: depositHash });\n return { txHash: depositHash, depositTotal: newTotal };\n }\n\n /**\n * Close a channel to begin the settlement grace period. Dispatches by the\n * channel's cached chain context. EVM `closeChannel` is unilateral (channelId\n * only); after it confirms we read the `channels()` view for the AUTHORITATIVE\n * `closedAt` + `settlementTimeout` (block-timestamp seconds) and compute\n * `settleableAt = closedAt + settlementTimeout`. Solana/Mina are follow-ups.\n */\n async closeChannel(\n channelId: string\n ): Promise<{\n txHash?: string;\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `Close on ${chainPrefix} is not yet supported (EVM today; Solana/Mina follow-up).`\n );\n }\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const tokenNetworkAddr = ctx.tokenNetworkAddress as Hex;\n const closeHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'closeChannel',\n args: [channelId as Hex],\n });\n await publicClient.waitForTransactionReceipt({ hash: closeHash });\n\n const info = await this.readEvmChannel(\n publicClient,\n tokenNetworkAddr,\n channelId\n );\n return {\n txHash: closeHash,\n closedAt: info.closedAt,\n settlementTimeout: info.settlementTimeout,\n settleableAt: info.closedAt + info.settlementTimeout,\n };\n }\n\n /**\n * Settle a closed channel after its grace period to release collateral. EVM\n * `settleChannel` is unilateral (channelId only); the contract itself reverts\n * before `closedAt + settlementTimeout`, so an early call surfaces as a tx\n * revert here — but the caller (ToonClient/daemon) enforces the time guard\n * BEFORE spending gas. Solana/Mina are follow-ups.\n */\n async settleChannel(channelId: string): Promise<{ txHash?: string }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `Settle on ${chainPrefix} is not yet supported (EVM today; Solana/Mina follow-up).`\n );\n }\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const settleHash = await walletClient.writeContract({\n address: ctx.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'settleChannel',\n args: [channelId as Hex],\n });\n await publicClient.waitForTransactionReceipt({ hash: settleHash });\n return { txHash: settleHash };\n }\n\n /**\n * Read the EVM channel's close-relevant fields so a restarted daemon can\n * recompute the grace timer from chain (chain is authoritative). EVM-only.\n */\n async getChannelCloseInfo(channelId: string): Promise<{\n status: ChannelState['status'];\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx)\n throw new Error(`No on-chain context for channel \"${channelId}\".`);\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `getChannelCloseInfo on ${chainPrefix} is not supported.`\n );\n }\n const { publicClient } = this.createClients(ctx.chain);\n const info = await this.readEvmChannel(\n publicClient,\n ctx.tokenNetworkAddress as Hex,\n channelId\n );\n return {\n status: STATE_MAP[info.state] ?? 'open',\n closedAt: info.closedAt,\n settlementTimeout: info.settlementTimeout,\n settleableAt: info.closedAt + info.settlementTimeout,\n };\n }\n\n /** Read + destructure the EVM `channels(bytes32)` view. */\n private async readEvmChannel(\n publicClient: ReturnType<\n OnChainChannelClient['createClients']\n >['publicClient'],\n tokenNetworkAddr: Hex,\n channelId: string\n ): Promise<{ settlementTimeout: bigint; state: number; closedAt: bigint }> {\n const res = (await publicClient.readContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channels',\n args: [channelId as Hex],\n })) as readonly [bigint, number, bigint, bigint, string, string];\n return {\n settlementTimeout: res[0],\n state: Number(res[1]),\n closedAt: res[2],\n };\n }\n\n /**\n * Read a participant's on-chain channel state — `deposit` (locked collateral),\n * `nonce`, and `transferredAmount` — straight from the `participants` mapping.\n * Takes the chain + token-network explicitly so it works for a channel that\n * was RESUMED from disk (no in-memory `channelContext` yet), which is exactly\n * when the daemon needs to re-hydrate the deposit it doesn't persist.\n */\n async readEvmParticipantState(opts: {\n chain: string;\n tokenNetworkAddress: string;\n channelId: string;\n participant: string;\n }): Promise<{ deposit: bigint; nonce: bigint; transferredAmount: bigint }> {\n const { publicClient } = this.createClients(opts.chain);\n const res = (await publicClient.readContract({\n address: opts.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'participants',\n args: [opts.channelId as Hex, opts.participant as Hex],\n })) as readonly [bigint, bigint, bigint];\n return { deposit: res[0], nonce: res[1], transferredAmount: res[2] };\n }\n\n /**\n * Opens a REAL on-chain Solana payment channel.\n *\n * Derives the connector-parity channel PDA\n * (`[b\"channel\", min_pubkey, max_pubkey, token_mint]`), submits the\n * `initialize_channel` instruction (+ optional `deposit`) to the deployed\n * payment-channel program, and returns the base58 PDA as the channel id. That\n * PDA is what the claim carries as `channelAccount`, and the on-chain channel\n * is what the connector's `verifySolanaClaim` reads via\n * `provider.getChannelState` before accepting the claim.\n *\n * Mirrors `openEvmChannel`'s open(+deposit) structure. Idempotent: if the\n * channel account already exists on-chain, returns its PDA without\n * re-initializing.\n */\n private async openSolanaChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n if (!this.solanaConfig) {\n throw new Error(\n 'Solana channel config not provided — cannot open Solana channel'\n );\n }\n\n const cfg = this.solanaConfig;\n // First 32 bytes are the Ed25519 signing seed (config may pass a 64-byte\n // secretKey of seed||pubkey, or a bare 32-byte seed).\n const payerSeed = cfg.keypair.slice(0, 32);\n const payerPubkey = base58Encode(\n new Uint8Array(ed25519.getPublicKey(payerSeed))\n );\n\n // PDA mint: per-channel negotiated token takes precedence over config default.\n const tokenMint = params.token ?? cfg.tokenMint;\n if (!tokenMint) {\n throw new Error(\n 'Solana channel requires a token mint (OpenChannelParams.token or solanaConfig.tokenMint)'\n );\n }\n if (!params.peerAddress) {\n throw new Error(\n 'Solana channel requires peerAddress (apex settlement pubkey, base58)'\n );\n }\n\n const challengeDuration = BigInt(\n cfg.challengeDuration ?? params.settlementTimeout ?? 86400\n );\n\n const deposit = cfg.deposit\n ? {\n amount: BigInt(cfg.deposit.amount),\n // Derive the payer ATA (owner + channel mint) when not supplied — it is\n // deterministic, so the caller need not thread payerTokenAccount through.\n payerTokenAccount:\n cfg.deposit.payerTokenAccount ||\n deriveAssociatedTokenAccount(payerPubkey, tokenMint),\n }\n : undefined;\n\n const { channelPDA } = await openSolanaChannelOnChain({\n rpcUrl: cfg.rpcUrl,\n programId: cfg.programId,\n tokenMint,\n payerSeed,\n payerPubkey,\n peerPubkey: params.peerAddress,\n challengeDuration,\n deposit,\n });\n\n // Cache context (PDA is the channel id / channelAccount).\n this.channelContext.set(channelPDA, {\n chain: params.chain,\n tokenNetworkAddress: cfg.programId,\n });\n\n return { channelId: channelPDA, status: 'opening' };\n }\n\n /**\n * Opens a REAL on-chain Mina payment channel on the deployed `PaymentChannel`\n * zkApp.\n *\n * The zkApp is deployed out-of-band (the operator/e2e harness deploys it\n * deterministically and advertises its B62 address). This client then calls\n * `initializeChannel` on that zkApp so its on-chain `channelState` becomes\n * `OPEN` — which is what the connector's `MinaPaymentChannelSDK.getChannelState`\n * reads to return status `'opened'` (claim verification otherwise fails with\n * `mina_claim_verification_failed`). The deployed zkApp address IS the channel\n * id: `MinaClaimMessage.zkAppAddress` is both the claim's channel identifier\n * AND the channel-hash preimage the off-chain proof binds to (see\n * `mina-payment-channel.ts`), so the channel-open id and the claim's channel id\n * are guaranteed identical.\n *\n * This is the Mina analog of `openSolanaChannel` (connector#105): the client\n * opens its own per-channel on-chain state (initialize + optional deposit). The\n * heavyweight o1js + `@toon-protocol/mina-zkapp` proof work is lazily imported\n * inside `openMinaChannelOnChain` so npm consumers who never open a Mina\n * channel don't pay the o1js cost.\n *\n * Idempotent: if the on-chain channel is already `OPEN`, the opener returns\n * without re-initializing.\n *\n * NOTE: full on-chain Mina SETTLE remains gated by the connector-side\n * settlement-executor (the same blocker that stops the Solana SETTLE); reaching\n * `opened` + a stored claim is parity with Solana.\n */\n private async openMinaChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n if (!this.minaConfig) {\n throw new Error(\n 'Mina channel config not provided — cannot open Mina channel'\n );\n }\n // The apex's Mina settlement B62 (participantB) is REQUIRED so the channel is\n // opened TWO-party. The off-chain claim is signed in participant form\n // (`Poseidon([client.x, apex.x, 0])`); without participantB the on-chain\n // channel records empty/duplicate participants and the connector's\n // participant-form verification fails on settle (`Invalid balance proof\n // signature`, `participants:[\"\",\"\"]`). Mirrors the Solana peerAddress guard.\n // (Checked before auto-deploy too — the pair hash needs participantB.)\n if (!params.peerAddress) {\n throw new Error(\n 'Mina channel requires peerAddress (apex Mina settlement B62) so the ' +\n 'on-chain channel is opened two-party — the participant-form claim ' +\n 'cannot settle against a single-party channel'\n );\n }\n // The deployed zkApp address IS the channel id (claim `zkAppAddress`).\n // With autoDeploy, resolve a zkApp that is provably OURS for this pair\n // (reusing the recorded/configured one when its on-chain channelHash\n // matches; deploying a dedicated one otherwise) — the Mina PaymentChannel\n // zkApp is single-pair, so a shared/announced address can never serve a\n // second identity. Lazily imported: only autoDeploy users pay the cost.\n let zkAppAddress = this.minaConfig.zkAppAddress;\n if (this.minaConfig.autoDeploy) {\n const { ensureOwnedMinaZkApp } = await import('./mina-channel-deploy.js');\n const ensured = await ensureOwnedMinaZkApp({\n graphqlUrl: this.minaConfig.graphqlUrl,\n payerPrivateKey: this.minaConfig.privateKey,\n peerPublicKey: params.peerAddress,\n ...(this.minaConfig.autoDeploy.deployed\n ? { deployed: this.minaConfig.autoDeploy.deployed }\n : {}),\n ...(zkAppAddress ? { candidateZkAppAddress: zkAppAddress } : {}),\n ...(this.minaConfig.autoDeploy.onDeploying\n ? { onDeploying: this.minaConfig.autoDeploy.onDeploying }\n : {}),\n ...(this.minaConfig.autoDeploy.onDeployed\n ? { onDeployed: this.minaConfig.autoDeploy.onDeployed }\n : {}),\n ...(this.minaConfig.autoDeploy.onProgress\n ? { onProgress: this.minaConfig.autoDeploy.onProgress }\n : {}),\n });\n zkAppAddress = ensured.zkAppAddress;\n }\n if (!zkAppAddress) {\n throw new Error(\n 'Mina channel requires a deployed zkAppAddress (minaConfig.zkAppAddress)'\n );\n }\n\n const timeout = BigInt(\n this.minaConfig.challengeDuration ?? params.settlementTimeout ?? 86400\n );\n const deposit = this.minaConfig.deposit\n ? { amount: BigInt(this.minaConfig.deposit.amount) }\n : undefined;\n\n const openResult = await openMinaChannelOnChain({\n graphqlUrl: this.minaConfig.graphqlUrl,\n zkAppAddress,\n payerPrivateKey: this.minaConfig.privateKey,\n // params.peerAddress is the apex Mina settlement B62 pubkey (participantB).\n peerPublicKey: params.peerAddress,\n timeout,\n tokenId: this.minaConfig.tokenId,\n deposit,\n networkId: this.minaConfig.networkId,\n });\n\n // The deployed zkApp address IS the channel id (claim `zkAppAddress`).\n this.channelContext.set(zkAppAddress, {\n chain: params.chain,\n tokenNetworkAddress: zkAppAddress,\n });\n\n // Surface the CURRENT on-chain depositTotal so the Mina signer can bind\n // `balanceB = depositTotal − balanceA` (connector#133). Read at open time so\n // a re-deposited channel signs against the live value, not a stale config.\n return {\n channelId: zkAppAddress,\n status: 'opening',\n depositTotal: openResult.depositTotal,\n };\n }\n\n /**\n * Opens an EVM payment channel on-chain, remapping the one-time\n * insufficient-native-gas revert into an actionable {@link ChannelFundingError}\n * so callers surface \"fund the wallet\" instead of the raw viem\n * \"...exceeds the balance of the account\" string (toon-meta#65). Only the gas\n * case is remapped; every other error propagates unchanged.\n */\n private async openEvmChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n try {\n return await this.openEvmChannelUnchecked(params);\n } catch (err) {\n if (!isInsufficientGasError(err)) throw err;\n // `chain` is a CAIP-ish id (e.g. \"evm:anvil:31337\"); surface just the\n // family so the remedy reads \"no gas on evm\", not the full slug.\n const chainFamily = params.chain.split(':')[0] || params.chain;\n throw new ChannelFundingError(\n `Settlement wallet ${this.evmSigner.address} has no gas on ` +\n `${chainFamily} to open a payment channel. Run toon_fund_wallet ` +\n `(or fund the wallet) and retry.`,\n err instanceof Error ? err : undefined\n );\n }\n }\n\n /**\n * Raw EVM channel-open (no gas-error remapping — see {@link openEvmChannel}).\n *\n * 1. Approve token spend if needed\n * 2. Call TokenNetwork.openChannel()\n * 3. Extract channelId from ChannelOpened event\n * 4. Deposit initial funds if specified\n */\n private async openEvmChannelUnchecked(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n const {\n chain,\n tokenNetwork,\n peerAddress,\n initialDeposit,\n settlementTimeout,\n } = params;\n\n if (!tokenNetwork) {\n throw new Error(\n 'tokenNetwork address is required for on-chain channel opening'\n );\n }\n\n const { publicClient, walletClient } = this.createClients(chain);\n const tokenNetworkAddr = tokenNetwork as Hex;\n const deposit = initialDeposit ? BigInt(initialDeposit) : 0n;\n\n // If deposit > 0, ensure token approval\n if (deposit > 0n && params.token) {\n const tokenAddr = params.token as Hex;\n const myAddress = this.evmSigner.address as Hex;\n\n const currentAllowance = await publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [myAddress, tokenNetworkAddr],\n });\n\n if ((currentAllowance as bigint) < deposit) {\n const approveHash = await walletClient.writeContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [tokenNetworkAddr, maxUint256],\n });\n await publicClient.waitForTransactionReceipt({ hash: approveHash });\n }\n }\n\n // Open channel\n const timeout = BigInt(settlementTimeout ?? 86400);\n const openHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'openChannel',\n args: [peerAddress as Hex, timeout],\n });\n\n const receipt: TransactionReceipt =\n await publicClient.waitForTransactionReceipt({ hash: openHash });\n\n // Extract channelId from ChannelOpened event\n let channelId: string | undefined;\n for (const log of receipt.logs) {\n try {\n const decoded = decodeEventLog({\n abi: TOKEN_NETWORK_ABI,\n data: log.data,\n topics: log.topics,\n });\n if (decoded.eventName === 'ChannelOpened') {\n channelId = (decoded.args as Record<string, unknown>)[\n 'channelId'\n ] as string;\n break;\n }\n } catch {\n // Not our event, skip\n }\n }\n\n if (!channelId) {\n throw new Error('Failed to extract channelId from ChannelOpened event');\n }\n\n // Cache context for getChannelState + later deposits (the token address is\n // needed to approve additional collateral on a standalone deposit).\n this.channelContext.set(channelId, {\n chain,\n tokenNetworkAddress: tokenNetwork,\n ...(params.token ? { tokenAddress: params.token } : {}),\n });\n\n // Deposit initial funds if specified\n if (deposit > 0n) {\n const depositHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, this.evmSigner.address as Hex, deposit],\n });\n await publicClient.waitForTransactionReceipt({ hash: depositHash });\n }\n\n return { channelId, status: 'opening' };\n }\n\n /**\n * Gets the current state of a payment channel from on-chain data.\n */\n async getChannelState(channelId: string): Promise<ChannelState> {\n const context = this.channelContext.get(channelId);\n if (!context) {\n throw new Error(\n `No context for channel \"${channelId}\". Channel must be opened via this client first.`\n );\n }\n\n // Mina channels are opened/deployed out-of-band; the connector performs the\n // authoritative on-chain `getChannelState(zkAppAddress)` check at claim\n // verification. Reading zkApp state client-side would require the o1js WASM\n // runtime, which the lightweight client intentionally avoids. Report `open`\n // for the configured deployed zkApp.\n if (context.chain.split(':')[0] === 'mina') {\n return { channelId, status: 'open', chain: context.chain };\n }\n\n // Solana channels read on-chain state from the PDA account, not an EVM contract.\n if (context.chain.split(':')[0] === 'solana' && this.solanaConfig) {\n const account = await getSolanaChannelAccountState(\n this.solanaConfig.rpcUrl,\n channelId\n );\n const status: ChannelState['status'] = !account.exists\n ? 'settled'\n : account.state === 'opened'\n ? 'open'\n : account.state === 'closed'\n ? 'closed'\n : 'settled';\n return { channelId, status, chain: context.chain };\n }\n\n const { publicClient } = this.createClients(context.chain);\n\n const result = await publicClient.readContract({\n address: context.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channels',\n args: [channelId as Hex],\n });\n\n const [, state] = result as [\n bigint,\n number,\n bigint,\n bigint,\n string,\n string,\n ];\n const status = STATE_MAP[state] ?? 'settled';\n\n return {\n channelId,\n status,\n chain: context.chain,\n };\n }\n}\n","/**\n * Solana payment-channel primitives — connector-parity.\n *\n * Pure, dependency-light helpers that reproduce the EXACT on-chain contract the\n * connector's `SolanaPaymentChannelSDK` (`@toon-protocol/connector`\n * `settlement/solana-payment-channel-sdk.ts`) implements, so a client-issued\n * Solana payment-channel claim is accepted by connector 3.9.0's\n * `verifySolanaClaim` path:\n *\n * 1. PDA derivation — `[b\"channel\", min_pubkey, max_pubkey, token_mint]` sorted\n * lexicographically by raw 32-byte pubkey, derived against the program id.\n * This base58 PDA is the claim's `channelAccount` and the channel-state\n * account the connector reads via `provider.getChannelState`.\n * 2. The 48-byte balance-proof message the connector verifies the Ed25519\n * signature over: `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)`.\n * NOTE: this is NOT the swap-claim `balanceProofHashSolana` shape used by the\n * swap peer ↔ sender wire / SDK `verifyEd25519Signature`; the connector's on-chain\n * payment-channel verifier (`solana-payment-channel-provider.verifyBalanceProof`)\n * verifies this raw 48-byte message, un-hashed.\n * 3. The `initialize_channel` (+ `deposit`) instructions, built and submitted\n * over raw Solana JSON-RPC (no `@solana/web3.js` / `@solana/kit` runtime\n * dependency — only `@noble/curves` + `@noble/hashes`, already client deps).\n *\n * Every byte layout / discriminator / account-meta order here is mirrored from\n * the connector SDK and the SDK reference E2E\n * (`packages/sdk/tests/e2e/docker-solana-settlement-e2e.test.ts`). Keep them in\n * lock-step; a mismatch makes the connector reject the claim (ON_CHAIN_VERIFICATION_FAILED\n * or INVALID_SIGNATURE).\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { base58Encode, base58Decode } from '@toon-protocol/core';\n\n// ---------------------------------------------------------------------------\n// Constants (must match the Rust program + connector SDK exactly)\n// ---------------------------------------------------------------------------\n\n/** Well-known Solana program addresses (base58). */\nconst TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';\nconst RENT_SYSVAR_ID = 'SysvarRent111111111111111111111111111111111';\n\n/** Instruction discriminators — first byte of an 8-byte LE tag. */\nconst IX_INITIALIZE_CHANNEL = new Uint8Array([0x01, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_DEPOSIT = new Uint8Array([0x02, 0, 0, 0, 0, 0, 0, 0]);\n\n/** On-chain channel-account discriminator: ASCII \"pchannel\". */\nconst CHANNEL_DISCRIMINATOR = new Uint8Array([\n 0x70, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c,\n]);\n\n/** Channel-state account size in bytes. */\nconst CHANNEL_ACCOUNT_SIZE = 178;\n\n// ---------------------------------------------------------------------------\n// Byte helpers\n// ---------------------------------------------------------------------------\n\nconst MAX_U64 = (1n << 64n) - 1n;\n\nfunction writeU64LE(buf: Uint8Array, offset: number, value: bigint): void {\n if (value < 0n || value > MAX_U64) {\n throw new RangeError(`Value ${value} outside u64 range [0, 2^64-1]`);\n }\n for (let i = 0; i < 8; i++) {\n buf[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);\n }\n}\n\n/** Left-pad / trim a byte array to exactly 32 bytes. */\nfunction padTo32(bytes: Uint8Array): Uint8Array {\n if (bytes.length === 32) return bytes;\n if (bytes.length > 32) return bytes.slice(bytes.length - 32);\n const padded = new Uint8Array(32);\n padded.set(bytes, 32 - bytes.length);\n return padded;\n}\n\n/** Sort two 32-byte pubkeys lexicographically by raw bytes (matches Rust). */\nfunction sortPubkeys(a: Uint8Array, b: Uint8Array): [Uint8Array, Uint8Array] {\n for (let i = 0; i < 32; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n if (ai < bi) return [a, b];\n if (ai > bi) return [b, a];\n }\n return [a, b];\n}\n\n// ---------------------------------------------------------------------------\n// Ed25519 curve check + PDA derivation (matches Solana find_program_address)\n// ---------------------------------------------------------------------------\n\nfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {\n let result = 1n;\n base = ((base % mod) + mod) % mod;\n while (exp > 0n) {\n if (exp & 1n) result = (result * base) % mod;\n exp >>= 1n;\n base = (base * base) % mod;\n }\n return result;\n}\n\nfunction modInverse(a: bigint, m: bigint): bigint {\n return modPow(((a % m) + m) % m, m - 2n, m);\n}\n\n/** True if 32 bytes lie on the Ed25519 curve. A valid PDA must NOT be on-curve. */\nfunction isOnCurve(bytes: Uint8Array): boolean {\n const P = (1n << 255n) - 19n;\n const yBytes = new Uint8Array(32);\n yBytes.set(bytes);\n yBytes[31] = (yBytes[31] ?? 0) & 0x7f;\n\n let y = 0n;\n for (let i = 0; i < 32; i++) {\n y |= BigInt(yBytes[i] ?? 0) << BigInt(i * 8);\n }\n if (y >= P) return true;\n\n const y2 = (y * y) % P;\n const D = (P - ((121665n * modInverse(121666n, P)) % P) + P) % P;\n const numerator = (y2 - 1n + P) % P;\n const denominator = (D * y2 + 1n) % P;\n const x2 = (numerator * modInverse(denominator, P)) % P;\n if (x2 === 0n) return true;\n return modPow(x2, (P - 1n) / 2n, P) === 1n;\n}\n\nfunction findProgramAddress(\n seeds: Uint8Array[],\n programId: Uint8Array\n): { pda: Uint8Array; bump: number } {\n const PDA_MARKER = new TextEncoder().encode('ProgramDerivedAddress');\n for (let bump = 255; bump >= 0; bump--) {\n const allSeeds = [...seeds, new Uint8Array([bump])];\n let totalLen = programId.length + PDA_MARKER.length;\n for (const s of allSeeds) totalLen += s.length;\n\n const input = new Uint8Array(totalLen);\n let offset = 0;\n for (const s of allSeeds) {\n input.set(s, offset);\n offset += s.length;\n }\n input.set(programId, offset);\n offset += programId.length;\n input.set(PDA_MARKER, offset);\n\n const hash = sha256(input);\n if (!isOnCurve(hash)) return { pda: hash, bump };\n }\n throw new Error('Could not find a viable PDA bump seed');\n}\n\n/**\n * Derive the channel PDA — connector-parity.\n * Seeds: `[b\"channel\", min_pubkey, max_pubkey, token_mint]` (participants sorted).\n *\n * @returns base58 PDA + bump.\n */\nexport function deriveChannelPDA(\n participantA: string,\n participantB: string,\n tokenMint: string,\n programId: string\n): { pda: string; bump: number } {\n const a = padTo32(base58Decode(participantA));\n const b = padTo32(base58Decode(participantB));\n const mint = padTo32(base58Decode(tokenMint));\n const program = padTo32(base58Decode(programId));\n const [min, max] = sortPubkeys(a, b);\n const seeds = [new TextEncoder().encode('channel'), min, max, mint];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\n}\n\n/**\n * Derive the Associated Token Account (ATA) for an owner + SPL mint — the\n * standard SPL ATA PDA over seeds `[owner, TOKEN_PROGRAM_ID, mint]` under the\n * Associated-Token-Account program. Deterministic from `(owner, mint)`, so\n * callers (e.g. a Solana channel deposit) need not supply the funded token\n * account explicitly — it is always the owner's ATA for the channel's mint.\n *\n * @param owner - base58 wallet pubkey that owns the token account.\n * @param tokenMint - base58 SPL mint.\n * @returns base58 ATA address.\n */\nexport function deriveAssociatedTokenAccount(owner: string, tokenMint: string): string {\n // Canonical mainnet/devnet SPL program ids (same on every cluster).\n const TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n const ASSOCIATED_TOKEN_PROGRAM_ID = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n const seeds = [\n padTo32(base58Decode(owner)),\n padTo32(base58Decode(TOKEN_PROGRAM_ID)),\n padTo32(base58Decode(tokenMint)),\n ];\n const { pda } = findProgramAddress(seeds, padTo32(base58Decode(ASSOCIATED_TOKEN_PROGRAM_ID)));\n return base58Encode(pda);\n}\n\n/**\n * Derive the vault PDA for a channel — connector-parity.\n * Seeds: `[b\"vault\", channel_pda]`.\n */\nexport function deriveVaultPDA(\n channelPDA: string,\n programId: string\n): { pda: string; bump: number } {\n const channel = padTo32(base58Decode(channelPDA));\n const program = padTo32(base58Decode(programId));\n const seeds = [new TextEncoder().encode('vault'), channel];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\n}\n\n// ---------------------------------------------------------------------------\n// Balance-proof message + signing (connector-parity)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the connector's canonical 48-byte balance-proof message:\n * `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)`.\n *\n * Mirrors `SolanaPaymentChannelSDK._buildBalanceProofMessage`. This is the EXACT\n * message the connector's `solana-payment-channel-provider.verifyBalanceProof`\n * reconstructs and Ed25519-verifies (un-hashed).\n */\nexport function buildBalanceProofMessage(\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint\n): Uint8Array {\n const message = new Uint8Array(48);\n message.set(padTo32(base58Decode(channelPDA)), 0);\n writeU64LE(message, 32, nonce);\n writeU64LE(message, 40, transferredAmount);\n return message;\n}\n\n/** Sign the 48-byte balance-proof message with a 32-byte Ed25519 seed. */\nexport function signBalanceProofMessage(\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint,\n seed: Uint8Array\n): Uint8Array {\n const message = buildBalanceProofMessage(\n channelPDA,\n nonce,\n transferredAmount\n );\n return ed25519.sign(message, seed);\n}\n\n// ---------------------------------------------------------------------------\n// On-chain channel open (initialize_channel + deposit) over raw JSON-RPC\n// ---------------------------------------------------------------------------\n\ninterface InstructionKey {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\ninterface RawInstruction {\n programId: string;\n keys: InstructionKey[];\n data: Uint8Array;\n}\n\ninterface Signer {\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n}\n\nlet rpcIdCounter = 1;\n\nasync function solanaRpc(\n rpcUrl: string,\n method: string,\n params: unknown[] = []\n): Promise<unknown> {\n const res = await fetch(rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n method,\n params,\n id: rpcIdCounter++,\n }),\n signal: AbortSignal.timeout(30000),\n });\n const json = (await res.json()) as {\n result?: unknown;\n error?: { message: string; code: number };\n };\n if (json.error) {\n throw new Error(\n `Solana RPC error [${method}]: ${json.error.message} (code ${json.error.code})`\n );\n }\n return json.result;\n}\n\nasync function getLatestBlockhash(rpcUrl: string): Promise<string> {\n const result = (await solanaRpc(rpcUrl, 'getLatestBlockhash', [\n { commitment: 'confirmed' },\n ])) as { value: { blockhash: string } };\n return result.value.blockhash;\n}\n\ninterface AccountInfo {\n data: [string, string];\n owner: string;\n lamports: number;\n}\n\nasync function getAccountInfo(\n rpcUrl: string,\n pubkey: string\n): Promise<AccountInfo | null> {\n const result = (await solanaRpc(rpcUrl, 'getAccountInfo', [\n pubkey,\n { encoding: 'base64', commitment: 'confirmed' },\n ])) as { value: AccountInfo | null };\n return result.value;\n}\n\nasync function waitForConfirmation(\n rpcUrl: string,\n signature: string,\n timeoutMs = 30000\n): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n const result = (await solanaRpc(rpcUrl, 'getSignatureStatuses', [\n [signature],\n ])) as {\n value: ({ confirmationStatus: string; err?: unknown } | null)[];\n };\n const status = result.value[0];\n if (\n status?.confirmationStatus === 'confirmed' ||\n status?.confirmationStatus === 'finalized'\n ) {\n if (status.err) {\n throw new Error(\n `Transaction ${signature} failed: ${JSON.stringify(status.err)}`\n );\n }\n return;\n }\n await new Promise((r) => setTimeout(r, 500));\n }\n throw new Error(\n `Transaction ${signature} not confirmed within ${timeoutMs}ms`\n );\n}\n\nfunction compactU16Size(value: number): number {\n if (value > 0xffff) {\n throw new RangeError(`compact-u16 value ${value} exceeds u16 max (0xFFFF)`);\n }\n return value < 0x80 ? 1 : value < 0x4000 ? 2 : 3;\n}\n\nfunction writeCompactU16(\n buf: Uint8Array,\n offset: number,\n value: number\n): number {\n if (value < 0x80) {\n buf[offset++] = value;\n } else if (value < 0x4000) {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = value >> 7;\n } else {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = ((value >> 7) & 0x7f) | 0x80;\n buf[offset++] = value >> 14;\n }\n return offset;\n}\n\ninterface AccountEntry {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/**\n * Build, sign, and send a Solana legacy transaction over raw JSON-RPC, then wait\n * for confirmation. Mirrors the SDK reference E2E's `buildAndSendTransaction`.\n */\nasync function buildAndSendTransaction(\n rpcUrl: string,\n feePayer: Signer,\n instructions: RawInstruction[],\n additionalSigners: Signer[] = []\n): Promise<string> {\n const blockhash = await getLatestBlockhash(rpcUrl);\n const feePayerPubkey = base58Encode(feePayer.publicKey);\n\n const accountMap = new Map<string, AccountEntry>();\n accountMap.set(feePayerPubkey, {\n pubkey: feePayerPubkey,\n isSigner: true,\n isWritable: true,\n });\n for (const ix of instructions) {\n for (const key of ix.keys) {\n const existing = accountMap.get(key.pubkey);\n if (existing) {\n existing.isSigner = existing.isSigner || key.isSigner;\n existing.isWritable = existing.isWritable || key.isWritable;\n } else {\n accountMap.set(key.pubkey, { ...key });\n }\n }\n if (!accountMap.has(ix.programId)) {\n accountMap.set(ix.programId, {\n pubkey: ix.programId,\n isSigner: false,\n isWritable: false,\n });\n }\n }\n\n const accounts = [...accountMap.values()].sort((a, b) => {\n if (a.pubkey === feePayerPubkey) return -1;\n if (b.pubkey === feePayerPubkey) return 1;\n const aScore = (a.isSigner ? 2 : 0) + (a.isWritable ? 1 : 0);\n const bScore = (b.isSigner ? 2 : 0) + (b.isWritable ? 1 : 0);\n return bScore - aScore;\n });\n\n const numSigners = accounts.filter((a) => a.isSigner).length;\n const numReadonlySigners = accounts.filter(\n (a) => a.isSigner && !a.isWritable\n ).length;\n const numReadonlyNonSigners = accounts.filter(\n (a) => !a.isSigner && !a.isWritable\n ).length;\n\n const accountIndexMap = new Map<string, number>();\n accounts.forEach((a, i) => accountIndexMap.set(a.pubkey, i));\n\n const compiled = instructions.map((ix) => ({\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- programId added to accountMap above\n programIdIndex: accountIndexMap.get(ix.programId)!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- every key added to accountMap above\n accountIndices: ix.keys.map((k) => accountIndexMap.get(k.pubkey)!),\n data: ix.data,\n }));\n\n const blockhashBytes = base58Decode(blockhash);\n\n let instructionSize = compactU16Size(compiled.length);\n for (const ix of compiled) {\n instructionSize += 1;\n instructionSize +=\n compactU16Size(ix.accountIndices.length) + ix.accountIndices.length;\n instructionSize += compactU16Size(ix.data.length) + ix.data.length;\n }\n\n const messageSize =\n 3 +\n compactU16Size(accounts.length) +\n 32 * accounts.length +\n 32 +\n instructionSize;\n const message = new Uint8Array(messageSize);\n let offset = 0;\n\n message[offset++] = numSigners;\n message[offset++] = numReadonlySigners;\n message[offset++] = numReadonlyNonSigners;\n\n offset = writeCompactU16(message, offset, accounts.length);\n for (const acct of accounts) {\n message.set(padTo32(base58Decode(acct.pubkey)), offset);\n offset += 32;\n }\n\n message.set(padTo32(blockhashBytes), offset);\n offset += 32;\n\n offset = writeCompactU16(message, offset, compiled.length);\n for (const ix of compiled) {\n message[offset++] = ix.programIdIndex;\n offset = writeCompactU16(message, offset, ix.accountIndices.length);\n for (const idx of ix.accountIndices) message[offset++] = idx;\n offset = writeCompactU16(message, offset, ix.data.length);\n message.set(ix.data, offset);\n offset += ix.data.length;\n }\n\n const finalMessage = message.slice(0, offset);\n\n const allSigners = [feePayer, ...additionalSigners];\n const signerPubkeys = accounts.filter((a) => a.isSigner).map((a) => a.pubkey);\n const signatures: Uint8Array[] = [];\n for (const signerPubkey of signerPubkeys) {\n const signer = allSigners.find(\n (s) => base58Encode(s.publicKey) === signerPubkey\n );\n if (!signer) throw new Error(`Missing signer for ${signerPubkey}`);\n signatures.push(ed25519.sign(finalMessage, signer.privateKey));\n }\n\n const txSize =\n compactU16Size(signatures.length) +\n signatures.length * 64 +\n finalMessage.length;\n const tx = new Uint8Array(txSize);\n let txOffset = 0;\n txOffset = writeCompactU16(tx, txOffset, signatures.length);\n for (const sig of signatures) {\n tx.set(sig, txOffset);\n txOffset += 64;\n }\n tx.set(finalMessage, txOffset);\n\n const txBase64 = Buffer.from(tx).toString('base64');\n const txSig = (await solanaRpc(rpcUrl, 'sendTransaction', [\n txBase64,\n {\n encoding: 'base64',\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n },\n ])) as string;\n await waitForConfirmation(rpcUrl, txSig);\n return txSig;\n}\n\n/** Parsed status of an on-chain channel account. */\nexport interface SolanaChannelAccountState {\n exists: boolean;\n /** 'opened' | 'closed' | 'settled' when the account exists with valid data. */\n state?: 'opened' | 'closed' | 'settled';\n participantA?: string;\n participantB?: string;\n}\n\nconst STATE_MAP = ['opened', 'closed', 'settled'] as const;\n\n/** Fetch + minimally parse the on-chain channel account at a PDA. */\nexport async function getChannelAccountState(\n rpcUrl: string,\n channelPDA: string\n): Promise<SolanaChannelAccountState> {\n const info = await getAccountInfo(rpcUrl, channelPDA);\n if (!info) return { exists: false };\n const data = new Uint8Array(Buffer.from(info.data[0], 'base64'));\n if (data.length < CHANNEL_ACCOUNT_SIZE) return { exists: false };\n for (let i = 0; i < 8; i++) {\n if (data[i] !== CHANNEL_DISCRIMINATOR[i]) return { exists: false };\n }\n return {\n exists: true,\n state: STATE_MAP[data[160] ?? 0] ?? 'opened',\n participantA: base58Encode(data.slice(8, 40)),\n participantB: base58Encode(data.slice(40, 72)),\n };\n}\n\nexport interface OpenSolanaChannelParams {\n rpcUrl: string;\n programId: string;\n tokenMint: string;\n /** Client's 32-byte Ed25519 seed (participant A + fee payer). */\n payerSeed: Uint8Array;\n /** Client's base58 pubkey (participant A). */\n payerPubkey: string;\n /** Apex's base58 settlement pubkey (participant B). */\n peerPubkey: string;\n /** Challenge-period duration in seconds. */\n challengeDuration: bigint;\n /** Optional deposit amount + funded SPL token account (ATA) of the payer. */\n deposit?: { amount: bigint; payerTokenAccount: string };\n}\n\nexport interface OpenSolanaChannelResult {\n channelPDA: string;\n /** True if a fresh on-chain initialize_channel tx was submitted. */\n opened: boolean;\n initTxSignature?: string;\n depositTxSignature?: string;\n}\n\n/**\n * Open (initialize) — and optionally deposit into — a real on-chain Solana\n * payment channel at the connector-parity PDA. Idempotent: if the channel\n * account already exists on-chain, returns the PDA without re-initializing.\n *\n * The Ed25519 keypair derives both the participant-A identity and the fee\n * payer; the apex pubkey is participant B. The returned `channelPDA` (base58) is\n * the value carried in the claim's `channelAccount`.\n */\nexport async function openSolanaChannel(\n params: OpenSolanaChannelParams\n): Promise<OpenSolanaChannelResult> {\n const {\n rpcUrl,\n programId,\n tokenMint,\n payerSeed,\n payerPubkey,\n peerPubkey,\n challengeDuration,\n } = params;\n\n const { pda: channelPDA } = deriveChannelPDA(\n payerPubkey,\n peerPubkey,\n tokenMint,\n programId\n );\n\n // Idempotent: skip initialize if the channel account already exists.\n const existing = await getChannelAccountState(rpcUrl, channelPDA);\n if (existing.exists) {\n return { channelPDA, opened: false };\n }\n\n const payerPublicKey = padTo32(base58Decode(payerPubkey));\n const payer: Signer = { publicKey: payerPublicKey, privateKey: payerSeed };\n\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // initialize_channel: discriminator(8) + challenge_duration(8 LE)\n const initData = new Uint8Array(16);\n initData.set(IX_INITIALIZE_CHANNEL, 0);\n writeU64LE(initData, 8, challengeDuration);\n\n const initTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: true },\n { pubkey: payerPubkey, isSigner: false, isWritable: false }, // participant A\n { pubkey: peerPubkey, isSigner: false, isWritable: false }, // participant B\n { pubkey: tokenMint, isSigner: false, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: RENT_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data: initData,\n },\n ]);\n\n let depositTxSignature: string | undefined;\n if (params.deposit && params.deposit.amount > 0n) {\n ({ depositTxSignature } = await depositSolanaChannel({\n rpcUrl,\n programId,\n channelPDA,\n payerSeed,\n payerPubkey,\n payerTokenAccount: params.deposit.payerTokenAccount,\n amount: params.deposit.amount,\n }));\n }\n\n return { channelPDA, opened: true, initTxSignature, depositTxSignature };\n}\n\nexport interface DepositSolanaChannelParams {\n rpcUrl: string;\n programId: string;\n /** The channel PDA (base58) — the Solana channel id. */\n channelPDA: string;\n /** Ed25519 signing seed (32 bytes) of the payer. */\n payerSeed: Uint8Array;\n /** Payer public key (base58). */\n payerPubkey: string;\n /** Funded SPL token account (ATA, base58) the collateral is pulled from. */\n payerTokenAccount: string;\n /** Delta to deposit (base units). The on-chain `deposit` ix adds this amount. */\n amount: bigint;\n}\n\n/**\n * Deposit additional collateral into an existing on-chain Solana channel — the\n * standalone `deposit` instruction (discriminator + amount LE), the same one the\n * open flow fires post-init. Incremental: the program adds `amount` to the\n * channel vault. Returns the deposit tx signature.\n */\nexport async function depositSolanaChannel(\n params: DepositSolanaChannelParams\n): Promise<{ depositTxSignature: string }> {\n const { rpcUrl, programId, channelPDA, payerSeed, payerPubkey, payerTokenAccount, amount } =\n params;\n if (amount <= 0n) throw new Error('Solana deposit amount must be positive.');\n\n const payer: Signer = {\n publicKey: padTo32(base58Decode(payerPubkey)),\n privateKey: payerSeed,\n };\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // deposit: discriminator(8) + amount(8 LE)\n const depositData = new Uint8Array(16);\n depositData.set(IX_DEPOSIT, 0);\n writeU64LE(depositData, 8, amount);\n\n const depositTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: false },\n { pubkey: payerTokenAccount, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: depositData,\n },\n ]);\n return { depositTxSignature };\n}\n\n// Internal helpers exported for unit tests (parity assertions).\nexport const __testing = { padTo32, sortPubkeys, isOnCurve };\n","import { privateKeyToAccount, type PrivateKeyAccount } from 'viem/accounts';\nimport { type Hex, toHex } from 'viem';\nimport type { BalanceProofParams, SignedBalanceProof } from '../types.js';\n// Types re-exported for convenience\nexport type { ClaimMessage } from './types.js';\n\n/**\n * EVM claim message for BTP protocol data.\n * Matches @toon-protocol/connector's EVMClaimMessage interface.\n *\n * The connector's validateClaimMessage() requires envelope fields\n * (version, messageId, timestamp) plus EVM claim fields, and optionally\n * chainId + tokenNetworkAddress for self-describing signature verification.\n */\nexport interface EVMClaimMessage {\n version: '1.0';\n blockchain: 'evm';\n messageId: string;\n timestamp: string;\n senderId: string;\n channelId: string;\n nonce: number;\n transferredAmount: string;\n lockedAmount: string;\n locksRoot: string;\n signature: string;\n signerAddress: string;\n /** Chain ID for self-describing EIP-712 verification */\n chainId: number;\n /** TokenNetwork address for self-describing EIP-712 verification */\n tokenNetworkAddress: string;\n /** ERC-20 token address for self-describing claim verification */\n tokenAddress?: string;\n}\n\n/**\n * EIP-712 domain for TokenNetwork balance proofs.\n * Must match connector's eip712-helper.js getDomainSeparator().\n */\nfunction getBalanceProofDomain(chainId: number, tokenNetworkAddress: string) {\n return {\n name: 'TokenNetwork' as const,\n version: '1' as const,\n chainId,\n verifyingContract: tokenNetworkAddress as Hex,\n };\n}\n\n/**\n * EIP-712 types for balance proofs.\n * Must match connector's eip712-helper.js getBalanceProofTypes().\n */\nconst BALANCE_PROOF_TYPES = {\n BalanceProof: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n { name: 'lockedAmount', type: 'uint256' },\n { name: 'locksRoot', type: 'bytes32' },\n ],\n} as const;\n\n/**\n * EVM signer for EIP-712 balance proofs and on-chain transactions.\n *\n * Encapsulates the private key — no getPrivateKey() method is exposed.\n */\nexport class EvmSigner {\n readonly chainType = 'evm' as const;\n private readonly _account: PrivateKeyAccount;\n\n /**\n * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array\n */\n constructor(privateKey: string | Uint8Array) {\n let hexKey: Hex;\n if (privateKey instanceof Uint8Array) {\n hexKey = toHex(privateKey);\n } else {\n hexKey = (\n privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`\n ) as Hex;\n }\n this._account = privateKeyToAccount(hexKey);\n }\n\n /** Derived 0x EVM address */\n get address(): string {\n return this._account.address;\n }\n\n /** ChainSigner identifier — EVM address */\n get signerIdentifier(): string {\n return this._account.address;\n }\n\n /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */\n get account(): PrivateKeyAccount {\n return this._account;\n }\n\n /**\n * Signs a balance proof using EIP-712 typed data.\n *\n * @param params - Balance proof parameters plus chain context\n * @returns Signed balance proof with signature\n */\n async signBalanceProof(\n params: BalanceProofParams & {\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n }\n ): Promise<SignedBalanceProof> {\n const domain = getBalanceProofDomain(\n params.chainId,\n params.tokenNetworkAddress\n );\n\n const signature = await this._account.signTypedData({\n domain,\n types: BALANCE_PROOF_TYPES,\n primaryType: 'BalanceProof',\n message: {\n channelId: params.channelId as Hex,\n nonce: BigInt(params.nonce),\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot as Hex,\n },\n });\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature,\n signerAddress: this._account.address,\n chainId: params.chainId,\n tokenNetworkAddress: params.tokenNetworkAddress,\n ...(params.tokenAddress && { tokenAddress: params.tokenAddress }),\n };\n }\n\n /**\n * Builds an EVMClaimMessage from a signed balance proof.\n * Static so it can be called without an EvmSigner instance.\n *\n * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)\n * @param senderId - Nostr pubkey or identifier of the sender\n * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL\n */\n static buildClaimMessage(\n proof: SignedBalanceProof,\n senderId: string\n ): EVMClaimMessage {\n return {\n version: '1.0',\n blockchain: 'evm',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n channelId: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n lockedAmount: proof.lockedAmount.toString(),\n locksRoot: proof.locksRoot,\n signature: proof.signature,\n signerAddress: proof.signerAddress,\n chainId: proof.chainId,\n tokenNetworkAddress: proof.tokenNetworkAddress,\n ...(proof.tokenAddress && { tokenAddress: proof.tokenAddress }),\n };\n }\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode } from '@toon-protocol/core';\nimport type { SignedBalanceProof } from '../types.js';\nimport type {\n ChainSigner,\n ChainMetadata,\n ClaimMessage,\n SolanaClaimMessage,\n} from './types.js';\nimport { toHex as bytesToHex } from '../utils/binary.js';\nimport { buildBalanceProofMessage } from '../channel/solana-payment-channel.js';\n\n/**\n * Solana signer for the connector payment-channel claim path.\n *\n * Signs the connector's on-chain payment-channel balance-proof message — the\n * raw 48-byte `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)` (see\n * `@toon-protocol/connector` `SolanaPaymentChannelSDK._buildBalanceProofMessage`\n * + `solana-payment-channel-provider.verifyBalanceProof`). The produced 64-byte\n * Ed25519 signature verifies on the connector's `verifySolanaClaim` path, which\n * is what makes a client-issued Solana payment-channel claim (paying the apex\n * to write) acceptable on connector 3.9.0.\n *\n * NOTE: this is a DIFFERENT message from the swap peer ↔ sender swap-claim wire\n * contract (`balanceProofHashSolana`, SDK `verifyEd25519Signature`). The client\n * here is paying a payment-channel claim to the apex, not issuing a swap claim,\n * so it must sign the connector's on-chain payment-channel message. `channelId`\n * MUST be the base58 channel PDA (produced by `OnChainChannelClient.openChannel`).\n */\nexport class SolanaSigner implements ChainSigner {\n readonly chainType = 'solana' as const;\n /** 32-byte Ed25519 seed. */\n private readonly privateKey: Uint8Array;\n private pubkeyBase58Cache?: string;\n\n /**\n * @param privateKey - 32-byte Ed25519 seed (e.g. `identity.solana.secretKey.slice(0, 32)`).\n * @param publicKeyBase58 - Optional base58 public key (e.g. `identity.solana.publicKey`).\n * When omitted it is derived lazily from `privateKey`.\n */\n constructor(privateKey: Uint8Array, publicKeyBase58?: string) {\n if (privateKey.length !== 32) {\n throw new Error(\n `SolanaSigner requires a 32-byte Ed25519 seed, got ${privateKey.length} bytes`\n );\n }\n this.privateKey = privateKey;\n this.pubkeyBase58Cache = publicKeyBase58;\n }\n\n private ensurePublicKey(): string {\n if (this.pubkeyBase58Cache) return this.pubkeyBase58Cache;\n const pk = ed25519.getPublicKey(this.privateKey);\n this.pubkeyBase58Cache = base58Encode(new Uint8Array(pk));\n return this.pubkeyBase58Cache;\n }\n\n get signerIdentifier(): string {\n return this.pubkeyBase58Cache ?? 'uninitialized';\n }\n\n async signBalanceProof(params: {\n channelId: string;\n nonce: number;\n transferredAmount: bigint;\n lockedAmount: bigint;\n locksRoot: string;\n recipient: string;\n metadata: ChainMetadata;\n }): Promise<SignedBalanceProof> {\n if (params.metadata.chainType !== 'solana') {\n throw new Error(\n `SolanaSigner cannot sign for chain type: ${params.metadata.chainType}`\n );\n }\n\n const base58 = this.ensurePublicKey();\n\n // Connector on-chain payment-channel balance-proof message:\n // channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)\n // `channelId` is the base58 channel PDA (from OnChainChannelClient.openChannel).\n // cumulativeAmount == transferredAmount. No recipient term — the connector's\n // verifyBalanceProof reconstructs exactly these three fields.\n const message = buildBalanceProofMessage(\n params.channelId,\n BigInt(params.nonce),\n params.transferredAmount\n );\n\n const signature = ed25519.sign(message, this.privateKey);\n const signatureHex = '0x' + bytesToHex(new Uint8Array(signature));\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature: signatureHex,\n signerAddress: base58,\n chainId: 0,\n tokenNetworkAddress: params.metadata.programId,\n recipient: params.recipient,\n };\n }\n\n buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage {\n // The connector verifies a base64 Ed25519 signature; the signed proof carries\n // a 0x-prefixed 64-byte hex signature, so convert hex -> bytes -> base64.\n const sigHex = proof.signature.startsWith('0x')\n ? proof.signature.slice(2)\n : proof.signature;\n const sigBytes = Uint8Array.from(\n sigHex.match(/.{1,2}/g)?.map((b) => parseInt(b, 16)) ?? []\n );\n const signatureBase64 = Buffer.from(sigBytes).toString('base64');\n\n const claim: SolanaClaimMessage = {\n version: '1.0',\n blockchain: 'solana',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n // channelId IS the base58 channel PDA -> connector's channelAccount.\n channelAccount: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n signature: signatureBase64,\n signerPublicKey: this.pubkeyBase58Cache ?? proof.signerAddress,\n programId: proof.tokenNetworkAddress,\n };\n return claim;\n }\n}\n","import { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { SignedBalanceProof } from '../types.js';\nimport type {\n ChainSigner,\n ChainMetadata,\n ClaimMessage,\n MinaClaimMessage,\n} from './types.js';\nimport {\n buildMinaPaymentChannelProof,\n loadMinaPaymentChannelBindings,\n} from '../channel/mina-payment-channel.js';\nimport { readMinaDepositTotal } from '../channel/mina-deposit.js';\n\n/** Reads a channel zkApp's on-chain `depositTotal` (base units). */\nexport type MinaDepositReader = (zkAppAddress: string) => Promise<bigint>;\n\n/** Optional `MinaSigner` wiring for on-chain `depositTotal` resolution. */\nexport interface MinaSignerOptions {\n /**\n * Mina GraphQL URL used to read the channel's on-chain `depositTotal` when a\n * caller doesn't supply it to `signBalanceProof`. Enables conserved\n * `balanceB = depositTotal − balanceA` claims (settleable on funded zkApps).\n */\n graphqlUrl?: string;\n /** Inject a deposit reader (tests / custom transport). Overrides `graphqlUrl`. */\n depositReader?: MinaDepositReader;\n}\n\n/** Default Mina token id when the metadata omits one. */\nconst DEFAULT_MINA_TOKEN_ID = 'MINA';\n\n/** Mina network id carried in the claim (matches the connector devnet prefix). */\nconst MINA_CLAIM_NETWORK = 'devnet' as const;\n\n/**\n * Pallas base-field-safe salt derived from `(zkAppAddress, nonce)`.\n *\n * The commitment binds an arbitrary salt; we derive it deterministically so the\n * same (channel, nonce) reproduces the same proof, and take the first 240 bits\n * of `sha256` to stay safely inside the Pallas field (< 2^254). Non-zero by\n * construction (connector `validateMinaClaim` requires a non-empty `salt`).\n */\nexport function deriveMinaSalt(zkAppAddress: string, nonce: number): bigint {\n const digestHex = bytesToHex(\n sha256(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))\n );\n const salt = BigInt('0x' + digestHex.slice(0, 60));\n return salt === 0n ? 1n : salt;\n}\n\n/**\n * Mina (Pallas) signer for the connector payment-channel claim path.\n *\n * Produces the connector 3.9.0 `MinaClaimMessage` contract — `{ zkAppAddress,\n * tokenId, balanceCommitment, proof (base64), salt, nonce }` — by reproducing\n * `MinaPaymentChannelSDK.signBalanceProof` exactly (via\n * {@link buildMinaPaymentChannelProof}):\n *\n * commitment = Poseidon([Field(balanceA), Field(0), Field(salt)])\n * channelHashField = Poseidon([participantA.x, participantB.x, 0]) (see below)\n * proof = base64(JSON{ commitment, signature: { r, s }, nonce, signerPublicKey })\n *\n * with the Schnorr signature computed over `[commitment, Field(nonce),\n * channelHashField]` using the Mina `'devnet'` network id (matching o1js's\n * hardcoded `Signature.create` prefix). Verified field-by-field against the\n * connector's o1js `Signature.fromJSON({r,s}).verify` (see the package tests).\n *\n * `channelHashField` is the ON-CHAIN participant form\n * (`Poseidon([client.x, apex.x, 0])`, participantA=client, participantB=apex)\n * whenever the apex's Mina pubkey is known (the negotiated `recipient`), so the\n * claim can SETTLE on-chain via the zkApp's `claimFromChannel` (which only\n * verifies the participant form). When the apex pubkey is unavailable the signer\n * falls back to the legacy zkApp-x form (`Poseidon([zkApp.x])`); the connector's\n * off-chain `verifyBalanceProof` accepts EITHER, so off-chain store/FULFILL works\n * in both cases — only on-chain settle requires the participant form.\n *\n * NOTE: this is a DIFFERENT message + format from the swap peer ↔ sender swap-claim\n * wire contract (`balanceProofFieldsMina` in `@toon-protocol/core`, verified by\n * the SDK's `verifyMinaSignature`). The client here pays a payment-channel claim\n * to the apex, so it signs the connector's on-chain payment-channel scheme; the\n * swap-format hash is left untouched (mirrors the Solana #105 separation).\n *\n * `channelId` MUST be the deployed payment-channel zkApp B62 address (the same\n * address the apex's Mina provider resolves on-chain via `getChannelState`),\n * which is what `OnChainChannelClient.openMinaChannel` returns.\n *\n * `mina-signer` is an OPTIONAL dependency: its crypto (Poseidon, Pallas Schnorr,\n * the base58 signature codec) is loaded dynamically so the client builds and runs\n * for non-Mina users without it installed, and WITHOUT pulling the o1js WASM\n * circuit runtime.\n */\nexport class MinaSigner implements ChainSigner {\n readonly chainType = 'mina' as const;\n /** Big-endian hex scalar (or already-`EK…` base58) Mina private key. */\n private readonly privateKey: string;\n private publicKeyBase58?: string;\n private readonly depositReader?: MinaDepositReader;\n /** Per-zkApp `depositTotal` cache (deposits are rare; the connector re-reads). */\n private readonly depositCache = new Map<string, bigint>();\n\n /**\n * @param privateKey - Mina private key as big-endian hex scalar (the form\n * `deriveFullIdentity()` emits, `identity.mina.privateKey`) or an `EK…`\n * base58 key. Converted to the base58check form mina-signer requires.\n * @param publicKeyBase58 - Optional base58 public key (e.g.\n * `identity.mina.publicKey`). When omitted it is derived during signing.\n * @param options - Optional on-chain `depositTotal` resolution (graphqlUrl or\n * an injected reader) so claims conserve balances on funded zkApps.\n */\n constructor(\n privateKey: string,\n publicKeyBase58?: string,\n options?: MinaSignerOptions\n ) {\n this.privateKey = privateKey;\n this.publicKeyBase58 = publicKeyBase58;\n if (options?.depositReader) {\n this.depositReader = options.depositReader;\n } else if (options?.graphqlUrl) {\n const url = options.graphqlUrl;\n this.depositReader = (zkAppAddress) =>\n readMinaDepositTotal(url, zkAppAddress);\n }\n }\n\n /**\n * Resolve the channel's on-chain `depositTotal`, caching per zkApp. Returns\n * `undefined` when no reader is configured or the read fails — callers then\n * fall back to the legacy `balanceB = 0` commitment.\n */\n private async resolveDepositTotal(\n zkAppAddress: string\n ): Promise<bigint | undefined> {\n if (this.depositCache.has(zkAppAddress)) {\n return this.depositCache.get(zkAppAddress);\n }\n if (!this.depositReader) return undefined;\n try {\n const depositTotal = await this.depositReader(zkAppAddress);\n this.depositCache.set(zkAppAddress, depositTotal);\n return depositTotal;\n } catch {\n return undefined;\n }\n }\n\n get signerIdentifier(): string {\n return this.publicKeyBase58 ?? 'uninitialized';\n }\n\n /** Derive this signer's B62 public key from its (base58) private key. */\n private async deriveOwnPublicKey(\n minaPrivateKeyBase58: string\n ): Promise<string> {\n const { Client } = await loadMinaPaymentChannelBindings();\n return new Client({ network: MINA_CLAIM_NETWORK }).derivePublicKey(\n minaPrivateKeyBase58\n );\n }\n\n async signBalanceProof(params: {\n channelId: string;\n nonce: number;\n transferredAmount: bigint;\n lockedAmount: bigint;\n locksRoot: string;\n recipient: string;\n metadata: ChainMetadata;\n /**\n * On-chain channel `depositTotal`. When provided (>0), the signed commitment\n * binds `balanceB = depositTotal − balanceA` (the funder's remaining\n * balance), matching the connector's claimFromChannel reconstruction\n * (toon-protocol/connector#133) and the on-chain circuit's\n * `balanceA + balanceB == depositTotal` invariant. Omitted/0 keeps the\n * legacy `balanceB = 0` form (off-chain-store-only, non-settleable).\n */\n depositTotal?: bigint;\n }): Promise<SignedBalanceProof> {\n if (params.metadata.chainType !== 'mina') {\n throw new Error(\n `MinaSigner cannot sign for chain type: ${params.metadata.chainType}`\n );\n }\n\n // The zkApp address IS the channel id: it is the channel-hash preimage the\n // connector binds the proof to and the on-chain account it reads. Prefer the\n // negotiated channelId, fall back to the metadata zkAppAddress.\n const zkAppAddress = params.channelId || params.metadata.zkAppAddress;\n if (!zkAppAddress) {\n throw new Error(\n 'MinaSigner requires a zkAppAddress (channel id) to sign a balance proof'\n );\n }\n\n const minaPrivateKey = hexToMinaBase58PrivateKey(this.privateKey);\n const tokenId = params.metadata.tokenId ?? DEFAULT_MINA_TOKEN_ID;\n const salt = deriveMinaSalt(zkAppAddress, params.nonce);\n\n // Derive the client's own Mina pubkey now (needed as participantA for the\n // on-chain channelHash). `buildMinaPaymentChannelProof` derives it too, but\n // we need it here to pass the participant pair.\n const clientPubKey =\n this.publicKeyBase58 ?? (await this.deriveOwnPublicKey(minaPrivateKey));\n this.publicKeyBase58 = clientPubKey;\n\n // The apex's Mina settlement pubkey (B62) is the channel counterparty\n // (participantB). It flows through as the negotiated recipient. When present,\n // sign over the on-chain participant-form channelHash so the claim can SETTLE\n // on-chain (the zkApp's claimFromChannel verifies sigA over\n // Poseidon([client.x, apex.x, 0])). Order matches the open:\n // participantA = client (payer), participantB = apex (peer).\n const apexPubKey =\n params.recipient && /^B62[a-zA-Z0-9]{40,60}$/.test(params.recipient)\n ? params.recipient\n : undefined;\n\n // Conserved counterparty balance for the signed commitment. The on-chain\n // PaymentChannel.claimFromChannel circuit verifies signatureA over\n // Poseidon([balanceA, balanceB, salt]) AND asserts balanceA + balanceB ==\n // depositTotal. The connector reconstructs balanceB = depositTotal − balanceA\n // from the public on-chain depositTotal (toon-protocol/connector#133), so the\n // CLIENT must sign over that same balanceB or signatureA fails verification\n // (\"participant A signature verification failed\") at proof generation. When\n // depositTotal is unknown (legacy/off-chain-only), fall back to balanceB = 0.\n // Prefer a caller-supplied depositTotal; otherwise self-resolve it from\n // chain (when this signer was configured with a graphqlUrl / reader) so the\n // claim conserves balances on a FUNDED zkApp. Falls back to balanceB = 0\n // (legacy, off-chain-store-only) when neither is available.\n const depositTotal =\n params.depositTotal ?? (await this.resolveDepositTotal(zkAppAddress));\n let balanceB = 0n;\n if (depositTotal != null && depositTotal > 0n) {\n if (params.transferredAmount > depositTotal) {\n throw new Error(\n `Mina claim balanceA (${params.transferredAmount}) exceeds on-chain ` +\n `depositTotal (${depositTotal}) — cannot conserve balances`\n );\n }\n balanceB = depositTotal - params.transferredAmount;\n }\n\n const built = await buildMinaPaymentChannelProof({\n zkAppAddress,\n minaPrivateKeyBase58: minaPrivateKey,\n signerPublicKey: clientPubKey,\n // Recipient-credit (unidirectional): party A carries the cumulative amount;\n // party B carries the funder's remaining balance (depositTotal − balanceA)\n // so the signed commitment conserves and the on-chain claimFromChannel\n // signatureA check passes. `signatureB` remains apex-co-signed downstream.\n balanceA: params.transferredAmount,\n balanceB,\n salt,\n nonce: BigInt(params.nonce),\n // Participant-form channelHash (on-chain-settleable) when the apex pubkey\n // is known; otherwise the legacy zkApp-x form (off-chain-store only).\n ...(apexPubKey\n ? { participantA: clientPubKey, participantB: apexPubKey }\n : {}),\n });\n this.publicKeyBase58 = built.signerPublicKey;\n\n return {\n channelId: zkAppAddress,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n // `signature` is unused on the Mina wire (the proof carries the Schnorr\n // signature); keep the base64 proof here too for symmetry / debugging.\n signature: built.proof,\n signerAddress: built.signerPublicKey,\n chainId: 0,\n tokenNetworkAddress: zkAppAddress,\n recipient: params.recipient,\n mina: {\n balanceCommitment: built.balanceCommitment,\n proof: built.proof,\n salt: built.salt,\n tokenId,\n },\n };\n }\n\n buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage {\n if (!proof.mina) {\n throw new Error(\n 'MinaSigner.buildClaimMessage requires a Mina-signed proof (missing `mina` fields)'\n );\n }\n const claim: MinaClaimMessage = {\n version: '1.0',\n blockchain: 'mina',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n zkAppAddress: proof.channelId,\n tokenId: proof.mina.tokenId,\n balanceCommitment: proof.mina.balanceCommitment,\n nonce: proof.nonce,\n proof: proof.mina.proof,\n salt: proof.mina.salt,\n transferredAmount: proof.transferredAmount.toString(),\n // Surface the signer's Mina pubkey top-level (it is also embedded in the\n // base64 `proof`). The connector's SettlementExecutor reads\n // `latestClaim.signerPublicKey` to resolve participant keys for the\n // on-chain claimFromChannel on an inbound/externally-opened channel;\n // without it the Mina SDK throws ACCOUNT_NOT_FOUND. `signerAddress`\n // carries the B62 base58 pubkey for Mina proofs (see MinaSigner.sign*).\n signerPublicKey: proof.signerAddress,\n network: MINA_CLAIM_NETWORK,\n };\n return claim;\n }\n}\n","/**\n * Mina payment-channel primitives — connector-parity.\n *\n * Pure, dependency-light helpers that reproduce the EXACT off-chain\n * balance-proof contract the connector's `MinaPaymentChannelSDK`\n * (`@toon-protocol/connector` `settlement/mina-payment-channel-sdk.ts`)\n * implements, so a client-issued Mina payment-channel claim is structurally\n * accepted by connector 3.9.0's `validateMinaClaim` PREPARE gate and (once the\n * connector's proof-encoding bug is fixed, see below) verified by its\n * `verifyMinaClaim` / `verifyBalanceProof` settlement path.\n *\n * ## The connector's payment-channel scheme (authoritative, from 3.9.0 dist)\n *\n * `MinaPaymentChannelSDK.signBalanceProof(channel, balA, balB, salt, nonce)`:\n *\n * commitment = Poseidon.hash([Field(balA), Field(balB), Field(salt)])\n * channelHashField = Poseidon.hash([PublicKey.fromBase58(zkAppAddress).x])\n * message = [commitment, Field(nonce), channelHashField]\n * signature = Signature.create(privKey, message) // Schnorr, Pallas\n * proof (string) = JSON.stringify({\n * commitment: commitment.toString(),\n * signature: { r, s }, // o1js JSON form\n * nonce: nonce.toString(),\n * })\n *\n * `MinaPaymentChannelSDK.verifyBalanceProof(channel, balanceCommitment, proof, nonce)`\n * re-derives `channelHashField` from `channel`, parses `proof` as the JSON above,\n * checks `proof.commitment === balanceCommitment` and `BigInt(proof.nonce) === nonce`,\n * then `Signature.fromJSON({r,s}).verify(signerPubKey, [commitment, Field(nonce),\n * channelHashField])`. The signer prefix is HARDCODED to `'devnet'` inside o1js\n * `Signature.create` / `.verify`, so the off-chain signature MUST be produced\n * with the Mina `'devnet'` network id (NOT `'mainnet'`).\n *\n * This is DISTINCT from the swap peer ↔ sender swap-claim wire contract\n * (`balanceProofFieldsMina` in `@toon-protocol/core` — a Schnorr signature over\n * `[minaHashToField(channelId), amount, nonce, minaHashToField(recipient)]`).\n * That format is unchanged; this module is the separate payment-channel path\n * (mirrors the Solana #105 precedent: a payment-channel-specific message\n * distinct from the swap-format hash).\n *\n * ## Why mina-signer (not o1js)\n *\n * Poseidon, the Pallas Schnorr signature, the base58 signature codec and the\n * Pallas `PublicKey` field decode are all shipped INSIDE `mina-signer` (the same\n * implementations o1js re-exports). We reach them via a file-URL deep import off\n * the resolved `mina-signer` package root, so the client reproduces the\n * connector's scheme byte-for-byte WITHOUT pulling the multi-hundred-MB o1js\n * WASM circuit runtime. `mina-signer` is an OPTIONAL dependency.\n *\n * ## ⚠️ Connector 3.9.0 proof-encoding bug (documented, NOT worked around here)\n *\n * `validateMinaClaim` requires `claim.proof` to match `/^[A-Za-z0-9+/]+=*$/`\n * (base64), but `verifyBalanceProof` (and the connector's OWN claim producer\n * `per-packet-claim-service`) treat `proof` as RAW JSON (`JSON.parse(proof)` with\n * no base64 decode — and the connector emits the raw `JSON.stringify(...)` above).\n * Raw JSON fails the base64 regex, so a raw-JSON proof is REJECTED at the PREPARE\n * gate (no FULFILL). To pass the PREPARE gate (the FULFILL-deciding path) the\n * client MUST base64-encode the proof JSON. The connector's settlement-side\n * `JSON.parse` then fails on the base64 string — but that is post-FULFILL and is\n * the connector's own inconsistency (its producer and consumer disagree with its\n * validator). For non-EVM dynamic hidden-service peers settlement is gated by\n * connector#88 (`No chain configured for peer`) regardless, so this is a\n * documented connector follow-up, not a client defect. See\n * {@link buildMinaPaymentChannelProof} `proofEncoding`.\n *\n * @module\n */\n\n/** Result of building a connector-parity Mina payment-channel proof. */\nexport interface MinaPaymentChannelProof {\n /** `Poseidon([balanceA, balanceB, salt]).toString()` — the claim's `balanceCommitment`. */\n balanceCommitment: string;\n /**\n * The claim's `proof` field: base64-encoded JSON\n * `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. Base64 is\n * REQUIRED to pass connector 3.9.0 `validateMinaClaim` (see module note).\n */\n proof: string;\n /** Decimal salt string — the claim's `salt` field. */\n salt: string;\n /** Base58 signer public key — echoed for convenience. */\n signerPublicKey: string;\n}\n\ninterface MinaSignerClientLike {\n signFields(fields: bigint[], privateKey: string): { signature: string };\n derivePublicKey(privateKey: string): string;\n}\ntype MinaSignerClientCtor = new (opts: {\n network: string;\n}) => MinaSignerClientLike;\n\ninterface PoseidonLike {\n hash(input: bigint[]): bigint;\n}\ninterface SignatureCodecLike {\n fromBase58(base58: string): { r: bigint; s: bigint };\n}\ninterface PublicKeyCodecLike {\n fromBase58(base58: string): { x: bigint; y: bigint };\n}\n\ninterface MinaCryptoBindings {\n Client: MinaSignerClientCtor;\n Poseidon: PoseidonLike;\n Signature: SignatureCodecLike;\n PublicKey: PublicKeyCodecLike;\n}\n\nlet cachedBindings: MinaCryptoBindings | null = null;\n\n/**\n * Resolve the `mina-signer` package and load both its public `Client` and the\n * internal Poseidon / Signature / PublicKey codecs via file-URL deep import.\n *\n * `mina-signer`'s `package.json` `exports` map does NOT expose its\n * `bindings/crypto/poseidon.js` or `mina-signer/src/{signature,curve-bigint}.js`\n * subpaths, so a bare-specifier deep import (`import('mina-signer/.../poseidon.js')`)\n * is blocked (`ERR_PACKAGE_PATH_NOT_EXPORTED`). Node only applies the exports\n * gate to bare specifiers, NOT to `file://` URLs — so we resolve the main entry\n * to a URL and navigate to the sibling internal files. These are the same\n * implementations o1js ships; reaching them here gives byte-for-byte parity with\n * the connector's o1js verify without the o1js WASM runtime.\n */\nexport async function loadMinaPaymentChannelBindings(): Promise<MinaCryptoBindings> {\n if (cachedBindings) return cachedBindings;\n\n const specifier = 'mina-signer';\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const lib: any = await import(/* @vite-ignore */ specifier);\n const Client: MinaSignerClientCtor = 'default' in lib ? lib.default : lib;\n\n // Resolve the main entry to a file URL, then navigate to the internal modules.\n // mina-signer main: <root>/dist/node/mina-signer/mina-signer.js\n //\n // import.meta.resolve is unavailable under some module transforms (notably\n // vitest's SSR, which replaces import.meta and drops `.resolve` → throws\n // \"__vite_ssr_import_meta__.resolve is not a function\"). Fall back to Node's\n // createRequire().resolve and convert to a file URL. Both the ESM and CJS\n // entries live in dist/node/mina-signer/, so the relative navigation below is\n // identical either way.\n const resolveFn = (import.meta as { resolve?: (specifier: string) => string })\n .resolve;\n let mainUrl: string;\n if (typeof resolveFn === 'function') {\n mainUrl = resolveFn(specifier);\n } else {\n const { createRequire } = await import('node:module');\n const { pathToFileURL } = await import('node:url');\n mainUrl = pathToFileURL(\n createRequire(import.meta.url).resolve(specifier)\n ).href;\n }\n const minaSignerDir = new URL('./', mainUrl); // .../dist/node/mina-signer/\n const poseidonUrl = new URL('../bindings/crypto/poseidon.js', minaSignerDir)\n .href;\n const signatureUrl = new URL('./src/signature.js', minaSignerDir).href;\n const curveUrl = new URL('./src/curve-bigint.js', minaSignerDir).href;\n\n const [poseidonMod, signatureMod, curveMod] = await Promise.all([\n import(/* @vite-ignore */ poseidonUrl),\n import(/* @vite-ignore */ signatureUrl),\n import(/* @vite-ignore */ curveUrl),\n ]);\n\n cachedBindings = {\n Client,\n Poseidon: poseidonMod.Poseidon as PoseidonLike,\n Signature: signatureMod.Signature as SignatureCodecLike,\n PublicKey: curveMod.PublicKey as PublicKeyCodecLike,\n };\n return cachedBindings;\n}\n\n/** Reset the cached bindings (test hook). */\nexport function _resetMinaBindingsCache(): void {\n cachedBindings = null;\n}\n\n/**\n * Compute the connector's Mina balance commitment:\n * `Poseidon.hash([Field(balanceA), Field(balanceB), Field(salt)])`.\n */\nexport function minaBalanceCommitment(\n poseidon: PoseidonLike,\n balanceA: bigint,\n balanceB: bigint,\n salt: bigint\n): bigint {\n return poseidon.hash([balanceA, balanceB, salt]);\n}\n\n/**\n * Compute the connector's LEGACY channel-hash field, bound into the signed\n * message: `Poseidon.hash([PublicKey.fromBase58(zkAppAddress).x])`.\n *\n * This is the off-chain-only form. The connector's `verifyBalanceProof` accepts\n * a signature over EITHER this OR the participant form (see\n * {@link minaParticipantChannelHashField}), but the on-chain\n * `PaymentChannel.claimFromChannel` only accepts the PARTICIPANT form — so for a\n * claim that must SETTLE on-chain, sign the participant form instead.\n */\nexport function minaChannelHashField(\n poseidon: PoseidonLike,\n publicKeyCodec: PublicKeyCodecLike,\n zkAppAddress: string\n): bigint {\n const zkAppPubKey = publicKeyCodec.fromBase58(zkAppAddress);\n return poseidon.hash([zkAppPubKey.x]);\n}\n\n/**\n * Compute the ON-CHAIN channel-hash field the zkApp stores and verifies:\n * `Poseidon.hash([participantA.x, participantB.x, channelNonce])`.\n *\n * This MUST byte-for-byte reproduce what `PaymentChannel.initializeChannel`\n * wrote (`Poseidon([participantA.x, participantB.x, nonce])`, see\n * `packages/mina-zkapp/src/PaymentChannel.ts`) so that:\n * 1. the on-chain `claimFromChannel` signature check\n * (`signatureA.verify(participantA, [commitment, nonce, storedChannelHash])`)\n * passes, and\n * 2. the connector's off-chain `verifyBalanceProof` accepts it via its\n * on-chain-channelHash message branch.\n *\n * Participant ORDER must match how the channel was opened. The client opens with\n * `participantA = client (payer)`, `participantB = apex (peer)`\n * (`OnChainChannelClient.openMinaChannel` → `openMinaChannelOnChain`), so the\n * client signs `Poseidon([client.x, apex.x, 0])`. The connector tries both\n * orderings when reconstructing, so it resolves the matching one regardless.\n */\nexport function minaParticipantChannelHashField(\n poseidon: PoseidonLike,\n publicKeyCodec: PublicKeyCodecLike,\n participantA_B62: string,\n participantB_B62: string,\n channelNonce: bigint\n): bigint {\n const a = publicKeyCodec.fromBase58(participantA_B62);\n const b = publicKeyCodec.fromBase58(participantB_B62);\n return poseidon.hash([a.x, b.x, channelNonce]);\n}\n\n/**\n * Build a connector-parity Mina payment-channel balance proof.\n *\n * Reproduces `MinaPaymentChannelSDK.signBalanceProof` exactly: computes the\n * Poseidon balance commitment, the Poseidon channel-hash field, signs the\n * `[commitment, Field(nonce), channelHashField]` Pallas Schnorr message with the\n * `'devnet'` network id (matching o1js's hardcoded prefix), decodes the base58\n * signature to `{ r, s }` (o1js JSON form), and serializes\n * `{ commitment, signature: { r, s }, nonce, signerPublicKey }`.\n *\n * @param params.zkAppAddress Deployed payment-channel zkApp B62 address — the\n * claim's `zkAppAddress` AND the channel-hash preimage. MUST be the SAME\n * address the apex's Mina provider resolves on-chain.\n * @param params.minaPrivateKeyBase58 Signer's Mina `EK…` base58 private key.\n * @param params.balanceA Cumulative amount credited to the recipient (apex).\n * @param params.balanceB Counterparty balance (0 for the unidirectional\n * recipient-credit direction; `balanceB`/`signatureB` are OPTIONAL at\n * connector validation, so single-party suffices).\n * @param params.salt Commitment salt (bigint).\n * @param params.nonce Monotonic claim nonce.\n * @param params.proofEncoding `'base64'` (default) base64-encodes the proof JSON\n * so it passes connector 3.9.0 `validateMinaClaim`'s base64 regex (REQUIRED for\n * FULFILL). `'json'` emits the raw JSON the connector's `verifyBalanceProof`\n * actually parses (rejected at the PREPARE gate today; provided for forward\n * compatibility / tests once the connector's regex is fixed). See module note.\n */\nexport async function buildMinaPaymentChannelProof(params: {\n zkAppAddress: string;\n minaPrivateKeyBase58: string;\n signerPublicKey?: string;\n balanceA: bigint;\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n proofEncoding?: 'base64' | 'json';\n /**\n * Participant pubkeys (B62) of the on-chain channel. When BOTH are supplied,\n * the proof is signed over the ON-CHAIN participant-form channelHash\n * (`Poseidon([participantA.x, participantB.x, channelNonce])`) instead of the\n * legacy zkApp-x form, so the resulting claim can settle on-chain via the\n * zkApp's `claimFromChannel` (which only verifies the participant form). The\n * order MUST match how the channel was opened (participantA = client/payer,\n * participantB = apex/peer). The connector accepts EITHER form off-chain, so\n * this is strictly an enabler for the on-chain settle path.\n */\n participantA?: string;\n participantB?: string;\n /** Channel nonce baked into the on-chain channelHash (default 0). */\n channelNonce?: bigint;\n}): Promise<MinaPaymentChannelProof> {\n const { Client, Poseidon, Signature, PublicKey } =\n await loadMinaPaymentChannelBindings();\n\n // o1js `Signature.create`/`.verify` hardcode the 'devnet' prefix; the off-chain\n // signature must be produced with the matching mina-signer network id.\n const client = new Client({ network: 'devnet' });\n const signerPublicKey =\n params.signerPublicKey ??\n client.derivePublicKey(params.minaPrivateKeyBase58);\n\n const commitment = minaBalanceCommitment(\n Poseidon,\n params.balanceA,\n params.balanceB,\n params.salt\n );\n // Sign over the on-chain participant-form channelHash when both participants\n // are known (enables on-chain settle); otherwise fall back to the legacy\n // zkApp-x form (off-chain-store-only). Both are accepted by the connector's\n // verifyBalanceProof.\n const channelHashField =\n params.participantA && params.participantB\n ? minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n params.participantA,\n params.participantB,\n params.channelNonce ?? 0n\n )\n : minaChannelHashField(Poseidon, PublicKey, params.zkAppAddress);\n\n const message = [commitment, params.nonce, channelHashField];\n const signed = client.signFields(message, params.minaPrivateKeyBase58);\n // mina-signer `signFields` emits a base58 signature string; the connector\n // expects the o1js JSON `{ r, s }` decimal form, reachable by decoding the\n // base58 sig with the shared Pallas codec.\n const { r, s } = Signature.fromBase58(signed.signature);\n\n const proofObject = {\n commitment: commitment.toString(),\n signature: { r: r.toString(), s: s.toString() },\n nonce: params.nonce.toString(),\n signerPublicKey,\n };\n const proofJson = JSON.stringify(proofObject);\n const encoding = params.proofEncoding ?? 'base64';\n const proof =\n encoding === 'base64'\n ? Buffer.from(proofJson, 'utf8').toString('base64')\n : proofJson;\n\n return {\n balanceCommitment: commitment.toString(),\n proof,\n salt: params.salt.toString(),\n signerPublicKey,\n };\n}\n","/**\n * Read a Mina payment-channel zkApp's on-chain `depositTotal` via a plain\n * GraphQL query (no o1js / WASM). Used by {@link MinaSigner} to bind the\n * conserved `balanceB = depositTotal − balanceA` commitment that a FUNDED zkApp\n * requires (connector#133); without it the connector's `claimFromChannel`\n * verification rejects the claim with `F06 - Invalid zk-SNARK proof on claim`.\n *\n * The `PaymentChannel` zkApp app-state field order is\n * `[channelHash, balanceCommitment, nonceField, channelState, depositTotal, …]`\n * (see `mina-channel-open.ts`), so `depositTotal` is `zkappState[4]`.\n */\n\n/** GraphQL response shape (only the fields we read). */\ninterface AccountStateResponse {\n data?: { account?: { zkappState?: string[] | null } | null } | null;\n errors?: { message: string }[];\n}\n\n/**\n * `PaymentChannel` zkApp app-state field order (see `mina-channel-open.ts` and\n * the zkApp's `@state` declarations in `@toon-protocol/mina-zkapp`):\n * [0] channelHash, [1] balanceCommitment, [2] nonceField, [3] channelState,\n * [4] depositTotal, [5] closedAtSlot, [6] settlementTimeout, [7] tokenId_.\n */\nconst CHANNEL_STATE_INDEX = {\n channelHash: 0,\n balanceCommitment: 1,\n nonceField: 2,\n channelState: 3,\n depositTotal: 4,\n} as const;\n\nconst DEPOSIT_TOTAL_STATE_INDEX = CHANNEL_STATE_INDEX.depositTotal;\n\n/**\n * Query `account(publicKey).zkappState` and return the channel's `depositTotal`\n * (base units). Throws when the account/state is unavailable so callers can fall\n * back to the legacy `balanceB = 0` behavior.\n *\n * @param fetchImpl - injectable for tests; defaults to global `fetch`.\n */\nexport async function readMinaDepositTotal(\n graphqlUrl: string,\n zkAppAddress: string,\n fetchImpl: typeof fetch = fetch\n): Promise<bigint> {\n const query = 'query($pk:String!){account(publicKey:$pk){zkappState}}';\n const res = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: zkAppAddress } }),\n });\n if (!res.ok) {\n throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n }\n const json = (await res.json()) as AccountStateResponse;\n if (json.errors && json.errors.length > 0) {\n throw new Error(\n `Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`\n );\n }\n const state = json.data?.account?.zkappState;\n if (!state || state.length <= DEPOSIT_TOTAL_STATE_INDEX) {\n throw new Error(\n `Mina zkApp ${zkAppAddress} has no readable zkappState (account not found or not a zkApp)`\n );\n }\n return BigInt(state[DEPOSIT_TOTAL_STATE_INDEX] as string);\n}\n\n/** Channel-lifecycle enum written to `channelState` (matches the zkApp). */\nexport const MINA_CHANNEL_STATE = {\n UNINITIALIZED: 0,\n OPEN: 1,\n CLOSING: 2,\n SETTLED: 3,\n} as const;\n\n/**\n * On-chain `PaymentChannel` state the receive-side settler needs to assemble a\n * co-signed `claimFromChannel` — all read via plain GraphQL (NO o1js / WASM), so\n * the read path stays lightweight and unit-testable. Field semantics match\n * {@link MinaChannelState} in the connector's Mina SDK.\n */\nexport interface MinaOnChainChannelState {\n /** `Poseidon([participantA.x, participantB.x, channelNonce])`, decimal Field. */\n channelHash: string;\n /** Current `Poseidon([balanceA, balanceB, salt])`, decimal Field. */\n balanceCommitment: string;\n /** Highest claimed nonce recorded on-chain. */\n nonceField: bigint;\n /** {@link MINA_CHANNEL_STATE} enum value. */\n channelState: number;\n /** Total escrowed deposit (base units). */\n depositTotal: bigint;\n}\n\n/**\n * Read the channel's on-chain `PaymentChannel` state via GraphQL.\n *\n * Reuses the same `account(publicKey).zkappState` query as\n * {@link readMinaDepositTotal} and decodes the fields the co-signed\n * `claimFromChannel` assembly binds: `channelHash` (participant identity),\n * `depositTotal` (balance conservation), `nonceField` (monotonicity gate), and\n * `channelState` (must be OPEN). No o1js is loaded — the values are raw Field\n * decimal strings straight off the node.\n *\n * @param fetchImpl - injectable for tests; defaults to global `fetch`.\n */\nexport async function readMinaChannelState(\n graphqlUrl: string,\n zkAppAddress: string,\n fetchImpl: typeof fetch = fetch\n): Promise<MinaOnChainChannelState> {\n const query = 'query($pk:String!){account(publicKey:$pk){zkappState}}';\n const res = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: zkAppAddress } }),\n });\n if (!res.ok) {\n throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n }\n const json = (await res.json()) as AccountStateResponse;\n if (json.errors && json.errors.length > 0) {\n throw new Error(\n `Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`\n );\n }\n const state = json.data?.account?.zkappState;\n if (!state || state.length <= DEPOSIT_TOTAL_STATE_INDEX) {\n throw new Error(\n `Mina zkApp ${zkAppAddress} has no readable zkappState (account not found or not a zkApp)`\n );\n }\n return {\n channelHash: String(state[CHANNEL_STATE_INDEX.channelHash]),\n balanceCommitment: String(state[CHANNEL_STATE_INDEX.balanceCommitment]),\n nonceField: BigInt(state[CHANNEL_STATE_INDEX.nonceField] as string),\n channelState: Number(state[CHANNEL_STATE_INDEX.channelState]),\n depositTotal: BigInt(state[CHANNEL_STATE_INDEX.depositTotal] as string),\n };\n}\n","import { EvmSigner } from '../signing/evm-signer.js';\nimport type { ChainSigner, ChainMetadata } from '../signing/types.js';\nimport type { SignedBalanceProof } from '../types.js';\nimport type { ChannelStore } from './ChannelStore.js';\nimport type { ConnectorChannelClient } from '@toon-protocol/core';\n\ninterface ChannelTracking {\n nonce: number;\n cumulativeAmount: bigint;\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n /**\n * Counterparty settlement address on this channel's chain. Required to sign\n * Solana/Mina balance proofs (folded into the canonical message); unused for\n * the EVM EIP-712 path.\n */\n recipient?: string;\n /**\n * On-chain channel `depositTotal` (base units), captured at channel-open time\n * (#220). Threaded into the Mina signer so it binds `balanceB = depositTotal −\n * balanceA` (toon-protocol/connector#133); the Solana signer ignores it and\n * the EVM path never reads it. When unset (e.g. a channel RESUMED via\n * `trackChannel` rather than opened, or an idempotent re-open that didn't\n * surface it), the Mina signer self-resolves it from chain via its GraphQL URL\n * (#223).\n */\n depositTotal?: bigint;\n /** Withdraw flow (unix SECONDS): set when close is initiated / becomes settleable / settled. */\n closedAt?: bigint;\n settleableAt?: bigint;\n settledAt?: bigint;\n}\n\nexport interface ChannelManagerConfig {\n initialDeposit?: string;\n settlementTimeout?: number;\n}\n\nexport interface PeerNegotiation {\n chain: string;\n chainType: string;\n chainId: number | string;\n settlementAddress: string;\n tokenAddress?: string;\n tokenNetwork?: string;\n initialDeposit?: string;\n settlementTimeout?: number;\n}\n\n/**\n * Local nonce tracking, multi-chain signing, and lazy channel opening.\n *\n * Supports multiple ChainSigner implementations (EVM, Solana, Mina).\n * The ensureChannel() method provides idempotent lazy channel opening.\n */\nexport class ChannelManager {\n private readonly channels = new Map<string, ChannelTracking>();\n private readonly chainSigners = new Map<string, ChainSigner>();\n private readonly peerChannels = new Map<string, string>();\n private readonly pendingOpens = new Map<string, Promise<string>>();\n private readonly store?: ChannelStore;\n private readonly defaultInitialDeposit: string;\n private readonly defaultSettlementTimeout: number;\n private channelClient?: ConnectorChannelClient;\n\n // Legacy: keep EvmSigner reference for backwards compatibility\n private readonly evmSigner?: EvmSigner;\n\n constructor(\n evmSigner?: EvmSigner,\n store?: ChannelStore,\n config?: ChannelManagerConfig\n ) {\n this.evmSigner = evmSigner;\n this.store = store;\n this.defaultInitialDeposit = config?.initialDeposit ?? '100000';\n this.defaultSettlementTimeout = config?.settlementTimeout ?? 86400;\n }\n\n /**\n * Register a chain-specific signer.\n */\n registerChainSigner(chainType: string, signer: ChainSigner): void {\n this.chainSigners.set(chainType, signer);\n }\n\n /**\n * Set the on-chain channel client for lazy channel opening.\n */\n setChannelClient(client: ConnectorChannelClient): void {\n this.channelClient = client;\n }\n\n /**\n * Get the signer for a tracked channel's chain type.\n * For EVM, returns an adapter wrapping the EvmSigner.\n */\n getSignerForChannel(channelId: string): ChainSigner {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n\n // Check non-EVM signers first\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer) return signer;\n\n // EVM: wrap EvmSigner as ChainSigner adapter\n if (tracking.chainType === 'evm' && this.evmSigner) {\n const evmSigner = this.evmSigner;\n return {\n chainType: 'evm' as const,\n signerIdentifier: evmSigner.address,\n async signBalanceProof(params) {\n if (params.metadata.chainType !== 'evm')\n throw new Error('Expected EVM metadata');\n return evmSigner.signBalanceProof({\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n chainId: params.metadata.chainId,\n tokenNetworkAddress: params.metadata.tokenNetworkAddress,\n tokenAddress: params.metadata.tokenAddress,\n });\n },\n buildClaimMessage(proof, senderId) {\n return EvmSigner.buildClaimMessage(proof, senderId);\n },\n };\n }\n\n throw new Error(\n `No signer registered for chain type: ${tracking.chainType}`\n );\n }\n\n /**\n * Lazily open a channel for a peer. Idempotent — returns existing channel\n * if already open. Deduplicates concurrent opens for the same peer.\n */\n async ensureChannel(\n peerId: string,\n negotiation: PeerNegotiation\n ): Promise<string> {\n // Return existing channel\n const existing = this.peerChannels.get(peerId);\n if (existing) return existing;\n\n // Deduplicate concurrent opens\n const pending = this.pendingOpens.get(peerId);\n if (pending) return pending;\n\n if (!this.channelClient) {\n throw new Error(\n 'No channel client configured — cannot open payment channel'\n );\n }\n\n const openPromise = (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- channelClient checked in constructor\n const result = await this.channelClient!.openChannel({\n peerId,\n chain: negotiation.chain,\n token: negotiation.tokenAddress,\n tokenNetwork: negotiation.tokenNetwork,\n peerAddress: negotiation.settlementAddress,\n initialDeposit:\n negotiation.initialDeposit ?? this.defaultInitialDeposit,\n settlementTimeout:\n negotiation.settlementTimeout ?? this.defaultSettlementTimeout,\n });\n\n this.trackChannel(result.channelId, {\n chainType: negotiation.chainType,\n chainId:\n typeof negotiation.chainId === 'number' ? negotiation.chainId : 0,\n tokenNetworkAddress: negotiation.tokenNetwork ?? '',\n tokenAddress: negotiation.tokenAddress,\n recipient: negotiation.settlementAddress,\n // On-chain depositTotal (Mina only) — needed so the Mina signer binds\n // balanceB = depositTotal − balanceA (connector#133).\n depositTotal: result.depositTotal,\n });\n this.peerChannels.set(peerId, result.channelId);\n return result.channelId;\n } finally {\n this.pendingOpens.delete(peerId);\n }\n })();\n\n this.pendingOpens.set(peerId, openPromise);\n return openPromise;\n }\n\n /**\n * Get channel ID for a peer (if any).\n */\n getChannelForPeer(peerId: string): string | undefined {\n return this.peerChannels.get(peerId);\n }\n\n /**\n * Start tracking a channel.\n * Called after bootstrap returns a channelId.\n *\n * @param channelId - Payment channel identifier\n * @param chainContext - Chain context for signing (chainType + chainId + tokenNetworkAddress)\n * @param initialNonce - Starting nonce (default: 0)\n * @param initialAmount - Starting cumulative amount (default: 0n)\n */\n trackChannel(\n channelId: string,\n chainContext?: {\n chainType?: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n depositTotal?: bigint;\n },\n initialNonce = 0,\n initialAmount = 0n\n ): void {\n const cId = chainContext?.chainId ?? 31337;\n const tnAddr =\n chainContext?.tokenNetworkAddress ??\n '0x0000000000000000000000000000000000000000';\n\n // If store has persisted state for this channel, resume from it\n if (this.store) {\n const persisted = this.store.load(channelId);\n if (persisted) {\n this.channels.set(channelId, {\n nonce: persisted.nonce,\n cumulativeAmount: persisted.cumulativeAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n // Resume the withdraw-flow timers so a daemon restart mid-grace\n // doesn't strand funds (the gate can't be evaluated without them).\n ...(persisted.closedAt !== undefined ? { closedAt: persisted.closedAt } : {}),\n ...(persisted.settleableAt !== undefined ? { settleableAt: persisted.settleableAt } : {}),\n ...(persisted.settledAt !== undefined ? { settledAt: persisted.settledAt } : {}),\n });\n return;\n }\n }\n\n this.channels.set(channelId, {\n nonce: initialNonce,\n cumulativeAmount: initialAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n });\n }\n\n /**\n * Signs a balance proof for the given channel.\n * Auto-increments nonce and adds to cumulative amount.\n * Routes to the correct ChainSigner based on the channel's chain type.\n *\n * @param channelId - Payment channel identifier\n * @param additionalAmount - Amount to add to cumulative transferred amount\n * @returns Signed balance proof\n * @throws Error if channel is not being tracked\n */\n async signBalanceProof(\n channelId: string,\n additionalAmount: bigint\n ): Promise<SignedBalanceProof> {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(\n `Channel \"${channelId}\" is not being tracked. Call trackChannel() first.`\n );\n }\n\n tracking.nonce += 1;\n tracking.cumulativeAmount += additionalAmount;\n\n // Persist updated state (preserving any withdraw-flow timers).\n this.persist(channelId);\n\n // Route to appropriate signer for non-EVM chains\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer && tracking.chainType !== 'evm') {\n if (!tracking.recipient) {\n throw new Error(\n `Channel \"${channelId}\" (${tracking.chainType}) has no recipient settlement address; ` +\n 'cannot sign a Solana/Mina balance proof. Ensure the peer negotiation supplied a settlementAddress.'\n );\n }\n const metadata = this.buildMetadata(tracking);\n return signer.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot:\n '0x0000000000000000000000000000000000000000000000000000000000000000',\n recipient: tracking.recipient,\n metadata,\n // On-chain depositTotal captured at open time (#220) — the Mina signer\n // binds balanceB = depositTotal − balanceA (connector#133); the Solana\n // signer ignores it. When undefined (resume / idempotent re-open) the\n // Mina signer self-resolves it from chain (#223).\n depositTotal: tracking.depositTotal,\n });\n }\n\n // EVM path (backwards compatible — uses EvmSigner directly)\n if (!this.evmSigner) {\n throw new Error('No EVM signer configured for EVM channel signing.');\n }\n return this.evmSigner.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot:\n '0x0000000000000000000000000000000000000000000000000000000000000000',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n });\n }\n\n private buildMetadata(tracking: ChannelTracking): ChainMetadata {\n switch (tracking.chainType) {\n case 'solana':\n return { chainType: 'solana', programId: tracking.tokenNetworkAddress };\n case 'mina':\n return {\n chainType: 'mina',\n zkAppAddress: tracking.tokenNetworkAddress,\n };\n default:\n return {\n chainType: 'evm',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n };\n }\n }\n\n /**\n * Gets the current nonce for a tracked channel.\n */\n getNonce(channelId: string): number {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.nonce;\n }\n\n /**\n * Gets the cumulative transferred amount for a tracked channel.\n */\n getCumulativeAmount(channelId: string): bigint {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.cumulativeAmount;\n }\n\n /**\n * Gets the on-chain deposit total (collateral locked at open / via deposits)\n * for a tracked channel, or `0n` when none was captured. The available\n * (spendable) balance is `depositTotal - cumulativeAmount`.\n */\n getDepositTotal(channelId: string): bigint {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.depositTotal ?? 0n;\n }\n\n /**\n * Update the tracked on-chain deposit total after a successful deposit, so the\n * available balance (`depositTotal - cumulativeAmount`) reflects the new\n * collateral on the next read.\n */\n setDepositTotal(channelId: string, total: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.depositTotal = total;\n }\n\n /** Persist a channel's full nonce/amount + withdraw-timer state to the store. */\n private persist(channelId: string): void {\n if (!this.store) return;\n const t = this.channels.get(channelId);\n if (!t) return;\n this.store.save(channelId, {\n nonce: t.nonce,\n cumulativeAmount: t.cumulativeAmount,\n ...(t.closedAt !== undefined ? { closedAt: t.closedAt } : {}),\n ...(t.settleableAt !== undefined ? { settleableAt: t.settleableAt } : {}),\n ...(t.settledAt !== undefined ? { settledAt: t.settledAt } : {}),\n });\n }\n\n /**\n * Record that a channel was closed (withdraw flow): stores `closedAt` +\n * `settleableAt` (unix SECONDS) so the grace timer survives a daemon restart.\n */\n setChannelClosed(channelId: string, closedAt: bigint, settleableAt: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.closedAt = closedAt;\n tracking.settleableAt = settleableAt;\n this.persist(channelId);\n }\n\n /** Record that a channel was settled (collateral released). */\n setChannelSettled(channelId: string, settledAt: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.settledAt = settledAt;\n this.persist(channelId);\n }\n\n /** The `settleableAt` timestamp (unix seconds) for a closed channel, if set. */\n getSettleableAt(channelId: string): bigint | undefined {\n return this.channels.get(channelId)?.settleableAt;\n }\n\n /**\n * Where a channel sits in the withdraw journey, from the tracked timers:\n * `open` (never closed) → `closing` (closed, grace not elapsed) →\n * `settleable` (grace elapsed) → `settled`. `nowSec` is injectable for tests.\n */\n getChannelCloseState(\n channelId: string,\n nowSec = BigInt(Math.floor(Date.now() / 1000))\n ): 'open' | 'closing' | 'settleable' | 'settled' {\n const t = this.channels.get(channelId);\n if (!t || t.closedAt === undefined) return 'open';\n if (t.settledAt !== undefined) return 'settled';\n if (t.settleableAt !== undefined && nowSec >= t.settleableAt) return 'settleable';\n return 'closing';\n }\n\n /**\n * Gets all tracked channel IDs.\n */\n getTrackedChannels(): string[] {\n return Array.from(this.channels.keys());\n }\n\n /**\n * Returns true if the channel is being tracked.\n */\n isTracking(channelId: string): boolean {\n return this.channels.has(channelId);\n }\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\n\nexport interface ChannelStoreEntry {\n nonce: number;\n cumulativeAmount: bigint;\n /** Unix SECONDS when close was initiated (withdraw flow). */\n closedAt?: bigint;\n /** Unix SECONDS the channel becomes settleable (= closedAt + settlementTimeout). */\n settleableAt?: bigint;\n /** Unix SECONDS the channel was settled (collateral released). */\n settledAt?: bigint;\n}\n\n/**\n * Persistence interface for payment channel nonce/amount state.\n */\nexport interface ChannelStore {\n save(channelId: string, tracking: ChannelStoreEntry): void;\n load(channelId: string): ChannelStoreEntry | undefined;\n list(): string[];\n delete(channelId: string): void;\n}\n\ninterface JsonEntry {\n nonce: number;\n /** Stored as string to preserve bigint precision */\n cumulativeAmount: string;\n /** Withdraw-flow timers, string-encoded SECONDS (bigint precision). */\n closedAt?: string;\n settleableAt?: string;\n settledAt?: string;\n}\n\n/**\n * JSON file-backed ChannelStore.\n * Uses synchronous I/O to match ChannelManager's sync API surface.\n */\nexport class JsonFileChannelStore implements ChannelStore {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n save(channelId: string, tracking: ChannelStoreEntry): void {\n const data = this.readFile();\n data[channelId] = {\n nonce: tracking.nonce,\n cumulativeAmount: tracking.cumulativeAmount.toString(),\n ...(tracking.closedAt !== undefined ? { closedAt: tracking.closedAt.toString() } : {}),\n ...(tracking.settleableAt !== undefined ? { settleableAt: tracking.settleableAt.toString() } : {}),\n ...(tracking.settledAt !== undefined ? { settledAt: tracking.settledAt.toString() } : {}),\n };\n this.writeFile(data);\n }\n\n load(channelId: string): ChannelStoreEntry | undefined {\n const data = this.readFile();\n const entry = data[channelId];\n if (!entry) return undefined;\n return {\n nonce: entry.nonce,\n cumulativeAmount: BigInt(entry.cumulativeAmount),\n ...(entry.closedAt !== undefined ? { closedAt: BigInt(entry.closedAt) } : {}),\n ...(entry.settleableAt !== undefined ? { settleableAt: BigInt(entry.settleableAt) } : {}),\n ...(entry.settledAt !== undefined ? { settledAt: BigInt(entry.settledAt) } : {}),\n };\n }\n\n list(): string[] {\n return Object.keys(this.readFile());\n }\n\n delete(channelId: string): void {\n const data = this.readFile();\n const { [channelId]: _, ...rest } = data;\n this.writeFile(rest);\n }\n\n private readFile(): Record<string, JsonEntry> {\n if (!existsSync(this.filePath)) {\n return {};\n }\n const raw = readFileSync(this.filePath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonEntry>;\n }\n\n private writeFile(data: Record<string, JsonEntry>): void {\n writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');\n }\n}\n","/**\n * Read-only on-chain wallet balances.\n *\n * Reports the settlement-token balance of the client's OWN wallet on each\n * configured chain — a free read, no signing, no fund movement. Each per-chain\n * reader is independent and injectable (viem for EVM; raw JSON-RPC / GraphQL\n * `fetch` for Solana / Mina, mirroring the existing channel modules) so they\n * unit-test without a live chain. The caller ({@link ../ToonClient}) treats each\n * chain best-effort: a missing config or a failed read drops that chain rather\n * than failing the whole wallet view.\n */\nimport { createPublicClient, http, defineChain } from 'viem';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\n/** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */\nexport interface WalletBalance {\n chain: 'evm' | 'solana' | 'mina';\n address: string;\n amount: string;\n /** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */\n asset?: string;\n /** Token decimals, when resolved. */\n assetScale?: number;\n}\n\n/**\n * One asset amount within a chain's wallet view — the native coin or one token.\n * `amount` is a base-unit integer, decimal string.\n */\nexport interface WalletTokenAmount {\n /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */\n symbol?: string;\n /** Base-unit integer, decimal string. */\n amount: string;\n /** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */\n decimals?: number;\n /** Token contract / SPL mint address. Absent for the native coin. */\n address?: string;\n}\n\n/**\n * The full wallet view for ONE chain the identity is configured for: the native\n * coin plus every configured token, keyed by the chain's full key (e.g.\n * `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at\n * all — the caller renders a per-chain notice rather than crashing.\n */\nexport interface WalletChainBalances {\n chain: 'evm' | 'solana' | 'mina';\n /** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */\n chainKey: string;\n address: string;\n /** Native-coin balance, when readable. */\n native?: WalletTokenAmount;\n /** Configured token balances (e.g. USDC), each best-effort. */\n tokens: WalletTokenAmount[];\n /** True when nothing on this chain could be read (RPC unreachable). */\n unreadable?: boolean;\n /** First read error, when any read failed (for diagnostics). */\n error?: string;\n}\n\n/** Minimal ERC-20 read ABI (balance + metadata). */\nconst ERC20_READ_ABI = [\n { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }] },\n { name: 'decimals', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },\n { name: 'symbol', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },\n] as const;\n\n/** Extract the numeric chainId from an `evm:{network}:{chainId}` / `evm:{chainId}` key. */\nexport function parseEvmChainId(chainKey: string): number {\n const parts = chainKey.split(':');\n const idStr = parts.length >= 3 ? parts[2] : parts[1];\n const id = Number.parseInt(idStr ?? '', 10);\n if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key \"${chainKey}\".`);\n return id;\n}\n\n/**\n * Per-request network timeout (ms) for ONE wallet-balance RPC/GraphQL call.\n * Node's global `fetch` has NO default timeout, so a single stalled socket would\n * otherwise hang the entire multi-chain read until the caller's outer bound —\n * making one flaky endpoint hide the balances of every chain. Bounding each call\n * (viem's own `timeout` for EVM; an AbortSignal for the Solana/Mina `fetch`)\n * lets a slow endpoint degrade only its own chain to `unreadable`. Env override\n * `TOON_WALLET_RPC_TIMEOUT_MS` (`0` disables).\n */\nconst RPC_TIMEOUT_ENV = 'TOON_WALLET_RPC_TIMEOUT_MS';\nconst DEFAULT_RPC_TIMEOUT_MS = 8_000;\n\nfunction rpcTimeoutMs(): number {\n const raw =\n typeof process !== 'undefined' ? process.env?.[RPC_TIMEOUT_ENV] : undefined;\n const n = raw === undefined || raw === '' ? NaN : Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;\n}\n\n/** AbortSignal firing after {@link rpcTimeoutMs}; undefined when disabled (`0`). */\nfunction rpcAbortSignal(): AbortSignal | undefined {\n const ms = rpcTimeoutMs();\n return ms > 0 ? AbortSignal.timeout(ms) : undefined;\n}\n\n/** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */\nexport async function readEvmTokenBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n tokenAddress: string;\n owner: string;\n}): Promise<WalletBalance> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: http(opts.rpcUrl, { timeout: rpcTimeoutMs() || undefined, retryCount: 1 }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const token = opts.tokenAddress as `0x${string}`;\n const owner = opts.owner as `0x${string}`;\n const [amount, decimals, symbol] = await Promise.all([\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'balanceOf', args: [owner] }),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'decimals' }).catch(() => undefined),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'symbol' }).catch(() => undefined),\n ]);\n const out: WalletBalance = { chain: 'evm', address: opts.owner, amount: (amount as bigint).toString() };\n if (typeof symbol === 'string' && symbol) out.asset = symbol;\n if (decimals !== undefined) out.assetScale = Number(decimals);\n return out;\n}\n\n/** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */\nexport async function readEvmNativeBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n owner: string;\n}): Promise<WalletTokenAmount> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: http(opts.rpcUrl, { timeout: rpcTimeoutMs() || undefined, retryCount: 1 }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const wei = await client.getBalance({ address: opts.owner as `0x${string}` });\n return { symbol: 'ETH', amount: wei.toString(), decimals: 18 };\n}\n\n/** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */\nexport async function readSolanaNativeBalance(opts: {\n rpcUrl: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletTokenAmount> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getBalance',\n params: [opts.owner, { commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: number | string };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n const lamports = BigInt(json.result?.value ?? 0);\n return { symbol: 'SOL', amount: lamports.toString(), decimals: 9 };\n}\n\n/** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */\nexport async function readSolanaTokenBalance(opts: {\n rpcUrl: string;\n mint: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [opts.owner, { mint: opts.mint }, { encoding: 'jsonParsed', commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: { account?: { data?: { parsed?: { info?: { tokenAmount?: { amount?: string; decimals?: number } } } } } }[] };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n let amount = 0n;\n let decimals: number | undefined;\n for (const acc of json.result?.value ?? []) {\n const ta = acc.account?.data?.parsed?.info?.tokenAmount;\n if (ta?.amount) amount += BigInt(ta.amount);\n if (ta?.decimals !== undefined) decimals = ta.decimals;\n }\n const out: WalletBalance = { chain: 'solana', address: opts.owner, amount: amount.toString() };\n if (decimals !== undefined) out.assetScale = decimals;\n return out;\n}\n\n/** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */\nexport async function readMinaBalance(opts: {\n graphqlUrl: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const query = 'query($pk:String!){account(publicKey:$pk){balance{total}}}';\n const res = await fetchImpl(opts.graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: opts.owner } }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n data?: { account?: { balance?: { total?: string } | null } | null };\n errors?: { message?: string }[];\n };\n if (json.errors && json.errors.length > 0) {\n throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`);\n }\n return {\n chain: 'mina',\n address: opts.owner,\n amount: String(json.data?.account?.balance?.total ?? '0'),\n asset: 'MINA',\n assetScale: 9,\n };\n}\n\nconst BASE58_ALPHABET =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/** base58-encode raw bytes (Bitcoin/Mina alphabet, leading-zero preserving). */\nfunction base58encode(bytes: Uint8Array): string {\n let num = 0n;\n for (const b of bytes) num = num * 256n + BigInt(b);\n let out = '';\n while (num > 0n) {\n out = BASE58_ALPHABET[Number(num % 58n)] + out;\n num /= 58n;\n }\n for (const b of bytes) {\n if (b === 0) out = '1' + out;\n else break;\n }\n return out;\n}\n\n/**\n * Encode a Mina token id (a Field, given as a decimal string) into the base58\n * `TokenId` scalar the Mina GraphQL `account(publicKey, token)` query expects.\n *\n * Mina's base58check layout is `0x1c` version byte ++ the 32-byte\n * little-endian field ++ a 4-byte double-SHA256 checksum. (The client avoids the\n * heavy o1js dependency — `TokenId.toBase58` — so this reproduces its encoding;\n * it round-trips the native token id `1` to\n * `wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf`.) The decimal form the\n * GraphQL layer rejects outright, hence this conversion.\n */\nexport function minaTokenIdToBase58(tokenId: string): string {\n if (!/^\\d+$/.test(tokenId)) {\n throw new Error(`Mina tokenId must be a decimal Field string: \"${tokenId}\"`);\n }\n let field = BigInt(tokenId);\n const le = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n le[i] = Number(field & 0xffn);\n field >>= 8n;\n }\n const body = new Uint8Array(1 + 32);\n body[0] = 0x1c;\n body.set(le, 1);\n const checksum = sha256(sha256(body)).slice(0, 4);\n const raw = new Uint8Array(body.length + 4);\n raw.set(body, 0);\n raw.set(checksum, body.length);\n return base58encode(raw);\n}\n\n/**\n * Read a CUSTOM Mina token balance (e.g. the settlement USDC) for `owner`.\n *\n * Unlike {@link readMinaBalance} (native MINA), this passes the settlement\n * `tokenId` so the GraphQL `account(publicKey, token)` query returns the\n * token-specific balance. An account holding none of the token resolves to\n * `null` → reported as `0`. Reported at the 6-decimal settlement-USDC scale —\n * NOT native MINA's 9 (see the `assetScale` comment below).\n */\nexport async function readMinaTokenBalance(opts: {\n graphqlUrl: string;\n owner: string;\n tokenId: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const token = minaTokenIdToBase58(opts.tokenId);\n const query =\n 'query($pk:PublicKey!,$t:TokenId){account(publicKey:$pk,token:$t){balance{total}}}';\n const res = await fetchImpl(opts.graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n data?: { account?: { balance?: { total?: string } | null } | null };\n errors?: { message?: string }[];\n };\n if (json.errors && json.errors.length > 0) {\n throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`);\n }\n return {\n chain: 'mina',\n address: opts.owner,\n amount: String(json.data?.account?.balance?.total ?? '0'),\n asset: 'USDC',\n // TOON's settlement USDC is 6-decimal on every chain (assetScale 6), unlike\n // native MINA's 9. The Mina custom-token amount is a raw u64, so scale it at\n // 6 — otherwise a 50 USDC balance (50_000000) misreads as 0.05.\n assetScale: 6,\n };\n}\n\n/**\n * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the\n * identity's address on that chain, and the configured token (USDC) — sourced by\n * the caller from the network topology / presets, never hardcoded here. A chain\n * key absent from the object is simply not read.\n */\nexport interface WalletBalanceSources {\n evm?: { chainKey: string; rpcUrl: string; owner: string; tokenAddress?: string };\n solana?: { chainKey?: string; rpcUrl: string; owner: string; tokenMint?: string };\n mina?: {\n chainKey?: string;\n graphqlUrl: string;\n owner: string;\n /** Settlement-token Field id (decimal). Reads the token balance when set. */\n tokenId?: string;\n };\n /** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */\n fetchImpl?: typeof fetch;\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** Fold a settled native read into the chain view, recording any failure. */\nfunction foldNative(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletTokenAmount>,\n errors: string[]\n): void {\n if (settled.status === 'fulfilled') out.native = settled.value;\n else errors.push(errText(settled.reason));\n}\n\n/** Fold a settled token read (a `WalletBalance`) into the chain view. */\nfunction foldToken(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletBalance | undefined>,\n tokenAddress: string | undefined,\n errors: string[]\n): void {\n if (settled.status === 'rejected') {\n errors.push(errText(settled.reason));\n return;\n }\n const bal = settled.value;\n if (!bal) return;\n out.tokens.push({\n symbol: bal.asset,\n amount: bal.amount,\n decimals: bal.assetScale,\n ...(tokenAddress ? { address: tokenAddress } : {}),\n });\n}\n\n/** Mark a chain unreadable when nothing could be read; attach the first error. */\nfunction finalizeChain(out: WalletChainBalances, errors: string[]): void {\n if (errors.length > 0) out.error = errors[0];\n if (out.native === undefined && out.tokens.length === 0) out.unreadable = true;\n}\n\n/**\n * Read the full wallet view — native coin + configured tokens — for every chain\n * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is\n * read independently and in parallel; a chain whose RPC is unreachable degrades\n * to `{ unreadable: true, error }` instead of failing the others. Within a chain\n * the native and token reads are independent, so a native read can succeed even\n * if the token read fails (and vice versa).\n */\nexport async function readWalletBalances(\n sources: WalletBalanceSources\n): Promise<WalletChainBalances[]> {\n const { fetchImpl } = sources;\n const tasks: Promise<WalletChainBalances>[] = [];\n\n if (sources.evm) {\n const { chainKey, rpcUrl, owner, tokenAddress } = sources.evm;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'evm', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readEvmNativeBalance({ rpcUrl, chainKey, owner }),\n tokenAddress\n ? readEvmTokenBalance({ rpcUrl, chainKey, tokenAddress, owner })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n foldToken(out, tokenR, tokenAddress, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n if (sources.solana) {\n const { chainKey = 'solana', rpcUrl, owner, tokenMint } = sources.solana;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'solana', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readSolanaNativeBalance({ rpcUrl, owner, fetchImpl }),\n tokenMint\n ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n // Solana SPL reads carry no symbol from `getTokenAccountsByOwner`; the\n // negotiated settlement token is USDC on every configured chain.\n if (tokenR.status === 'fulfilled' && tokenR.value && tokenR.value.asset === undefined) {\n tokenR.value.asset = 'USDC';\n }\n foldToken(out, tokenR, tokenMint, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n if (sources.mina) {\n const { chainKey = 'mina', graphqlUrl, owner, tokenId } = sources.mina;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'mina', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n // Native MINA (gas) plus, when the deployment settles a custom token,\n // that token's balance (USDC) — read via the tokenId. Independent reads.\n const [nativeR, tokenR] = await Promise.allSettled([\n readMinaBalance({ graphqlUrl, owner, fetchImpl }),\n tokenId\n ? readMinaTokenBalance({ graphqlUrl, owner, tokenId, fetchImpl })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(\n out,\n nativeR.status === 'fulfilled'\n ? {\n status: 'fulfilled',\n value: {\n symbol: nativeR.value.asset,\n amount: nativeR.value.amount,\n decimals: nativeR.value.assetScale,\n },\n }\n : nativeR,\n errors\n );\n foldToken(out, tokenR, undefined, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n return Promise.all(tasks);\n}\n","/**\n * Client-side helper for kind:5094 Arweave blob storage DVM requests.\n *\n * This composes the three steps a caller previously had to wire by hand:\n * 1. Build the kind:5094 event via `buildBlobStorageRequest()` (@toon-protocol/core).\n * 2. Publish it to the DVM destination over ILP via `ToonClient.publishEvent()`\n * (reusing the existing claim / channel plumbing).\n * 3. Decode the FULFILL `data` field into the Arweave transaction ID.\n *\n * ## FULFILL data contract\n *\n * The deployed connector is a payment-proxy (HTTP-in-ILP): a successful blob\n * upload returns the DVM's verbatim **HTTP/1.1 response message** in the ILP\n * FULFILL `data` field. For a single-packet (non-chunked) upload the body is a\n * JSON object:\n *\n * HTTP/1.1 200 OK\\r\\n\n * content-length: 189\\r\\n\n * \\r\\n\n * {\"accept\":true,\"txId\":\"<43-char base64url>\",\"data\":\"<base64 of txId>\",...}\n *\n * We parse the HTTP envelope, fail on a non-2xx status (or `accept:false`), and\n * read the Arweave tx ID from `txId` (falling back to base64-decoding `data`).\n * An Arweave tx ID is a 43-character base64url string (32 raw bytes). A legacy\n * fallback still accepts a bare `base64(utf8(txId))` FULFILL (no HTTP envelope)\n * so non-proxy providers do not regress. See {@link extractArweaveTxId}.\n *\n * See `packages/sdk/src/arweave/arweave-dvm-handler.ts` for the server side and\n * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts` for the reference\n * end-to-end flow this helper mirrors.\n *\n * Chunked uploads (multi-packet, via `uploadId` / `chunkIndex` / `totalChunks`\n * params) are intentionally out of scope for this single-packet helper — the\n * provider returns `ack:<n>` for intermediate chunks and the tx ID only on the\n * final chunk. Callers needing chunking should drive `publishEvent()` directly\n * (see the chunked case in the reference E2E test). Tracked as a follow-up.\n */\n\nimport type { NostrEvent } from 'nostr-tools/pure';\nimport { buildBlobStorageRequest } from '@toon-protocol/core';\nimport { fromBase64, decodeUtf8 } from './utils/binary.js';\nimport type { EnvelopeResponse } from './wire/envelope.js';\nimport type { ToonClient } from './ToonClient.js';\nimport type { SignedBalanceProof } from './types.js';\n\n/** Arweave tx IDs are base64url-encoded 32-byte values (43 chars, no padding). */\nconst ARWEAVE_TX_ID_REGEX = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * Parameters for {@link requestBlobStorage}.\n */\nexport interface RequestBlobStorageParams {\n /** The raw blob data to store on Arweave. */\n blobData: Uint8Array;\n\n /**\n * MIME type of the blob. Defaults to `'application/octet-stream'`\n * (matching `buildBlobStorageRequest`).\n */\n contentType?: string;\n\n /**\n * Bid amount in USDC micro-units, as a string (declared in the event's\n * `bid` tag). Defaults to the stringified `ilpAmount` when omitted.\n *\n * At least one of `bid` / `ilpAmount` should be provided so the declared\n * bid and the paid ILP amount agree.\n */\n bid?: string;\n\n /**\n * ILP destination address of the DVM that performs the upload\n * (e.g. `'g.toon.peer1'`). Falls back to the client's configured\n * `destinationAddress` when omitted.\n */\n destination?: string;\n\n /**\n * Pre-signed balance proof claim for this packet. When omitted, the\n * client's channel manager auto-opens a channel and auto-signs a claim\n * (same lazy-channel behavior as `publishEvent`).\n */\n claim?: SignedBalanceProof;\n\n /**\n * Explicit ILP payment amount (bigint micro-units). When omitted,\n * `publishEvent` computes it from the encoded event size. When `bid`\n * is omitted, this value is stringified to populate the event's bid tag.\n */\n ilpAmount?: bigint;\n}\n\n/**\n * Typed result of {@link requestBlobStorage}.\n */\nexport interface RequestBlobStorageResult {\n /** Whether the upload succeeded and a tx ID was decoded. */\n success: boolean;\n\n /** The Arweave transaction ID (43-char base64url) when `success` is true. */\n txId?: string;\n\n /** The id of the kind:5094 event that was published. */\n eventId?: string;\n\n /** Error message when `success` is false. */\n error?: string;\n}\n\n/**\n * Requests permanent Arweave blob storage from a DVM in a single ILP packet.\n *\n * Mirrors the single-packet flow in\n * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts`: builds a signed\n * kind:5094 event, publishes it through the supplied {@link ToonClient}\n * (reusing its claim/channel plumbing), and decodes the FULFILL `data` field\n * into an Arweave transaction ID.\n *\n * @param client - A started `ToonClient` (call `client.start()` first).\n * @param secretKey - The Nostr secret key used to sign the kind:5094 event.\n * @param params - Blob, content type, bid, destination, and payment options.\n * @returns `{ success, txId?, eventId?, error? }`.\n */\nexport async function requestBlobStorage(\n client: ToonClient,\n secretKey: Uint8Array,\n params: RequestBlobStorageParams\n): Promise<RequestBlobStorageResult> {\n const bid =\n params.bid ??\n (params.ilpAmount !== undefined ? String(params.ilpAmount) : undefined);\n\n if (bid === undefined || bid === '') {\n return {\n success: false,\n error: 'requestBlobStorage requires a bid (or ilpAmount to derive it)',\n };\n }\n\n // buildBlobStorageRequest expects a Node Buffer (it calls .toString('base64')).\n // ToonClient surfaces Uint8Array for browser-compat, so normalize here.\n const blobBuffer = Buffer.from(\n params.blobData.buffer,\n params.blobData.byteOffset,\n params.blobData.byteLength\n );\n\n let event: NostrEvent;\n try {\n event = buildBlobStorageRequest(\n {\n blobData: blobBuffer,\n contentType: params.contentType,\n bid,\n },\n secretKey\n );\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n const result = await client.publishEvent(event, {\n destination: params.destination,\n claim: params.claim,\n ilpAmount: params.ilpAmount,\n // No proxyPath: the store DESTINATION's route already terminates at the\n // store backend's own endpoint, and ADR 0025 resolves the envelope\n // target strictly beneath that handler path — '' (the default) means\n // \"the handler's own path\". The old absolute '/store' is refused by the\n // connector as an escape attempt (F00).\n });\n\n if (!result.success) {\n return {\n success: false,\n eventId: result.eventId ?? event.id,\n error: result.error ?? 'Blob storage request rejected',\n };\n }\n\n if (!result.response) {\n return {\n success: false,\n eventId: event.id,\n error:\n 'FULFILL carried no sealed response envelope; expected the store\\'s answer with the Arweave tx ID',\n };\n }\n\n let txId: string;\n try {\n txId = extractArweaveTxId(result.response);\n } catch (error) {\n return {\n success: false,\n eventId: event.id,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n return {\n success: true,\n txId,\n eventId: event.id,\n };\n}\n\n/**\n * Extract the Arweave tx ID from the FULFILL `data` of a successful blob upload.\n *\n * The terminating connector seals the store's answer as a response envelope\n * (ADR 0018), which `publishEvent` opens and hands back as\n * `PublishEventResult.response`. For a successful single-packet upload its\n * body is `{\"accept\":true,\"txId\":\"<43-char base64url>\",\"data\":\"<base64 of\n * txId>\",…}`.\n *\n * We fail on a non-2xx status or `accept:false`, then read `txId` (preferred)\n * from the JSON body — falling back to base64-decoding the `data` field when\n * `txId` is absent.\n *\n * Exported for callers that drive `publishEvent` directly with a hand-built\n * kind:5094 event (e.g. git-object uploads carrying Git-SHA/Git-Type/Repo\n * tags, toon-client#227) and need the same FULFILL→txId decode this helper\n * applies.\n *\n * @throws {Error} If the response is non-2xx, `accept:false`, the body is not\n * parseable JSON, or no valid Arweave tx ID can be extracted.\n */\nexport function extractArweaveTxId(response: EnvelopeResponse): string {\n if (response.status < 200 || response.status >= 300) {\n const detail =\n response.body.length > 0 ? ` - ${decodeUtf8(response.body)}` : '';\n throw new Error(\n `Blob upload failed: the store answered HTTP ${response.status}${detail}`\n );\n }\n\n const text = decodeUtf8(response.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(`Blob upload response body was not valid JSON: \"${text}\"`);\n }\n\n const body = parsed as {\n accept?: boolean;\n txId?: unknown;\n data?: unknown;\n error?: unknown;\n };\n\n if (body.accept === false) {\n const reason = typeof body.error === 'string' ? `: ${body.error}` : '';\n throw new Error(`Blob upload rejected by DVM (accept:false)${reason}`);\n }\n\n // Preferred: explicit txId field.\n if (typeof body.txId === 'string' && ARWEAVE_TX_ID_REGEX.test(body.txId)) {\n return body.txId;\n }\n\n // Fallback: base64-encoded tx id in the `data` field.\n if (typeof body.data === 'string' && body.data.length > 0) {\n const decoded = decodeUtf8(fromBase64(body.data));\n if (ARWEAVE_TX_ID_REGEX.test(decoded)) {\n return decoded;\n }\n }\n\n throw new Error(\n `Blob upload response did not contain a valid Arweave tx ID: \"${text}\"`\n );\n}\n","/**\n * Payment-aware HTTP fetch over TOON (the \"h402\" flow).\n *\n * This adapter makes paying for an HTTP resource transparent: it issues an\n * ordinary HTTP request, and when the origin answers `402 Payment Required`\n * with an x402-style challenge that offers a `toon-channel` payment option, it\n * opens/reuses a payment channel, signs a balance-proof claim, and re-sends the\n * SAME HTTP request as a \"transparent HTTP-in-ILP\" packet to the connector's\n * `POST /ilp` endpoint (via {@link HttpIlpClient}). The connector terminates the\n * payment, forwards the request to the origin, and returns the origin's HTTP\n * response inside the ILP FULFILL `data`. We reconstruct a normal Web `Response`\n * from those bytes — the caller never sees ILP.\n *\n * ─── x402 wire contract (the 402 challenge body) ────────────────────────────\n * The shipped connector answers x402 **v2** terms (`client-edge-spec.md` §1.4,\n * `crates/connector-client-edge/src/lib.rs`), and that is the shape pinned by\n * `Http402Client.connectorTerms.test.ts`:\n *\n * ```jsonc\n * {\n * \"x402Version\": 2,\n * \"resource\": { \"url\": \"g.example.app\" },\n * \"accepts\": [\n * {\n * \"scheme\": \"toon-channel\",\n * \"network\": \"g.example.app\",\n * \"amount\": \"100\",\n * \"payTo\": \"g.example.app\",\n * \"maxTimeoutSeconds\": 60,\n * \"httpEndpoint\": \"/ilp\", // RELATIVE to the resource's origin.\n * \"extra\": { \"ilpAddress\": \"g.example.app\", \"endpoint\": \"/ilp\", \"price\": \"100\" }\n * }\n * ]\n * }\n * ```\n *\n * Two things that shape forces, both easy to get wrong:\n * - The ILP address, the endpoint and the price live under **`extra`**. The\n * top-level `payTo` happens to equal the destination today, so reading it\n * appears to work — that is a coincidence of the connector's current code,\n * not a contract, so `extra` is read first.\n * - `httpEndpoint` is **relative**; it is resolved against the URL that\n * answered `402` (`Response.url`, or `parseX402Body`'s `baseUrl` argument).\n *\n * Everything is still parsed DEFENSIVELY (mirroring `readDiscoveredIlpPeer` in\n * selectIlpTransport.ts): an unrecognised connector shape degrades to the\n * vanilla 402 rather than throwing. Field aliases (first present wins):\n * - destination: `extra.ilpAddress` | `extra.destination` | `destination` |\n * `ilpAddress` | `payTo`. (We do NOT invent a value — a missing\n * destination makes the entry unusable and we fall back to the vanilla 402.)\n * - amount: `extra.price` | `extra.amount` | `amount` | `price` |\n * `maxAmountRequired`.\n * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `extra.httpEndpoint` |\n * `extra.endpoint` | `endpoint`.\n * - upgrade: `supportsUpgrade` | `upgradable`.\n *\n * ─── What the paid request is made of ───────────────────────────────────────\n * The paid re-send is an OER `EnvelopeRequest` sealed to the terminating\n * connector's identity, under a condition derived from the secret that seal\n * carries — the same `sealExchange` / `readExchangeOutcome` pair\n * `ToonClient.publishEvent` uses (ADR 0018/0019, toon-client#450, #451). This\n * adapter used to carry its own HTTP/1.1 codec; it does not any more, and\n * `packages/client` now has exactly one encoder.\n *\n * Two consequences of the envelope replacing HTTP text, both deliberate:\n *\n * - **`Host` and `Content-Length` are not synthesised.** The old codec added\n * both. The connector strips them either way and lets its HTTP client\n * recompute them (`connector-runtime/src/app_client.rs` skips `host` and\n * `content-length` by name), and the envelope already carries the body\n * length as an OER length determinant, so emitting them was writing bytes\n * the far side throws away. A caller that sets either explicitly still has\n * it carried verbatim, and the connector still drops it.\n * - **A response has no reason phrase.** An `EnvelopeResponse` status is two\n * bytes; `HTTP/1.1 201 Created`'s \"Created\" has nowhere to live on this\n * wire. `Response.statusText` is therefore empty, and the status is the\n * fact to read.\n *\n * A malformed answer now fails the way it fails everywhere else in this\n * package — `SealedResponseError` from `readExchangeOutcome` — rather than\n * this file's old `ConnectorError` on a bad status line while `fulfill-http.ts`\n * quietly returned `{isHttp:false}` for the very same bytes.\n *\n * Claim signing/construction is owned by the CALLER (ToonClient wires the live\n * ChannelManager + signer). This adapter never builds or validates claims —\n * payment-claim validation lives ONLY in the connector.\n */\n\nimport type { IlpSendResult } from '@toon-protocol/core';\nimport { HttpIlpClient } from './HttpIlpClient.js';\nimport {\n selectIlpTransport,\n type DiscoveredIlpPeer,\n type IlpTransportChoice,\n} from './selectIlpTransport.js';\nimport { ConnectorEdgeClient } from './ConnectorEdgeClient.js';\nimport { ConnectorError, ToonClientError } from '../errors.js';\nimport { toBase64, fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport type { EnvelopeHeader, EnvelopeResponse } from '../wire/envelope.js';\nimport { readExchangeOutcome, sealExchange } from '../wire/sealed-exchange.js';\n\n// ─── x402 challenge types (documented wire contract above) ──────────────────\n\n/** A single parsed `accepts` entry that offers the `toon-channel` scheme. */\nexport interface ToonChannelAccept {\n /** Always `'toon-channel'` for a matched entry. */\n scheme: 'toon-channel';\n /** Optional chain key, e.g. `evm:base:8453` — informational. */\n network?: string;\n /** ILP destination address to pay (the connector route fronting the URL). */\n destination: string;\n /** Price in ILP base units. */\n amount: bigint;\n /** The connector's `POST /ilp` URL. */\n httpEndpoint: string;\n /** Whether the host accepts the BTP upgrade over the HTTP endpoint. */\n supportsUpgrade: boolean;\n}\n\n/** The parsed x402 402 body, with the selected `toon-channel` entry (if any). */\nexport interface ParsedX402Challenge {\n x402Version?: number;\n /** The first usable `toon-channel` accepts entry, or `undefined`. */\n toonChannel?: ToonChannelAccept;\n}\n\n// ─── h402Fetch options (PINNED PUBLIC CONTRACT) ─────────────────────────────\n\n/** Options for {@link Http402Client.fetch} / `ToonClient.h402Fetch`. */\nexport interface H402FetchOptions {\n /** HTTP method. Default `'GET'`. */\n method?: string;\n /** Request headers. */\n headers?: Record<string, string>;\n /** Request body. */\n body?: string | Uint8Array;\n /** Request timeout in milliseconds. */\n timeout?: number;\n /** Optional explicit ILP destination override (else the x402 entry's value). */\n destination?: string;\n}\n\n/**\n * Caller-supplied hook that signs a balance-proof claim for `(destination,\n * amount)` and returns the chain-appropriate claim message to attach to the ILP\n * PREPARE. ToonClient wires this to its ChannelManager + per-chain signer (the\n * exact same plumbing as `publishEvent`). The returned value is forwarded\n * opaquely as the `ILP-Payment-Channel-Claim` header by {@link HttpIlpClient}.\n */\nexport type ClaimResolver = (\n destination: string,\n amount: bigint\n) => Promise<unknown>;\n\n/** Factory for an {@link HttpIlpClient} given a resolved `POST /ilp` endpoint. */\nexport type HttpIlpClientFactory = (httpEndpoint: string) => HttpIlpClient;\n\nexport interface Http402ClientConfig {\n /**\n * Underlying HTTP fetch for the INITIAL (un-paid) request that probes for a\n * 402. Default: global `fetch`.\n */\n fetch?: typeof fetch;\n /**\n * Resolves + signs the payment-channel claim. REQUIRED to pay; if omitted,\n * a 402 with a `toon-channel` offer is surfaced unchanged (vanilla challenge).\n */\n resolveClaim?: ClaimResolver;\n /**\n * Builds the {@link HttpIlpClient} for a resolved endpoint. Default: construct\n * a new `HttpIlpClient({ httpEndpoint })`. Injectable for tests.\n */\n createIlpClient?: HttpIlpClientFactory;\n /**\n * AC4: request a duplex transport for the paid send. When `true` and the\n * toon-channel entry advertises `supportsUpgrade`, {@link selectIlpTransport}\n * returns `http-upgradable` and the send path calls\n * {@link HttpIlpClient.upgradeToBtp} before writing — the wiring for\n * large/streaming responses. Default `false` (stateless one-shot HTTP).\n *\n * NOTE (v1 limitation): even on the upgrade path the actual write is still a\n * one-shot `sendIlpPacketWithClaim`; full duplex body streaming over the BTP\n * session is a documented follow-up. The selection + upgrade CALL PATH is\n * wired and exercised here so the streaming consumer can take over the\n * returned session in a later iteration.\n */\n needsDuplex?: boolean;\n /**\n * Asks the connector named by the 402 offer for its identity key, so the\n * paid request can be sealed to it. Default: a fresh\n * {@link ConnectorEdgeClient} over this config's `fetch`. Injectable so a\n * caller that already holds one shares its identity cache rather than\n * re-fetching a key per paid request.\n */\n connectorEdge?: ConnectorEdgeClient;\n}\n\n/**\n * Reusable h402 fetch engine. `ToonClient.h402Fetch` is a thin wrapper that\n * constructs this with the live claim/channel plumbing.\n */\nexport class Http402Client {\n private readonly fetchImpl: typeof fetch;\n private readonly resolveClaim?: ClaimResolver;\n private readonly createIlpClient: HttpIlpClientFactory;\n private readonly needsDuplex: boolean;\n private readonly connectorEdge: ConnectorEdgeClient;\n\n constructor(config: Http402ClientConfig = {}) {\n this.fetchImpl = config.fetch ?? fetch;\n this.resolveClaim = config.resolveClaim;\n this.createIlpClient =\n config.createIlpClient ??\n ((httpEndpoint) => new HttpIlpClient({ httpEndpoint }));\n this.needsDuplex = config.needsDuplex ?? false;\n this.connectorEdge =\n config.connectorEdge ??\n new ConnectorEdgeClient({\n // Same `fetch` the probe uses: a host that installs its own (and a\n // test that swaps one in) must be the one the identity comes from.\n fetch: (input, init) => this.fetchImpl(input, init),\n });\n }\n\n /**\n * `fetch()`-like entry point. Issues the request; on `402` parses the x402\n * challenge and — when a usable `toon-channel` offer is present and a claim\n * resolver is configured — pays over TOON and returns the reconstructed\n * `Response`. Otherwise returns the original 402 unchanged (AC5).\n */\n async fetch(url: string, opts: H402FetchOptions = {}): Promise<Response> {\n const method = (opts.method ?? 'GET').toUpperCase();\n\n // 1. Probe: issue the ordinary HTTP request.\n const probe = await this.fetchImpl(url, {\n method,\n ...(opts.headers ? { headers: opts.headers } : {}),\n ...(opts.body !== undefined ? { body: opts.body as BodyInit } : {}),\n ...(opts.timeout !== undefined\n ? { signal: AbortSignal.timeout(opts.timeout) }\n : {}),\n });\n\n // 2. Pass-through anything that isn't a 402.\n if (probe.status !== 402) return probe;\n\n // 3. Parse the x402 challenge defensively. We must read the body to inspect\n // `accepts`; clone first so we can still return the ORIGINAL 402 on\n // fallback (a Response body is single-use).\n const challenge = await parseX402Challenge(probe.clone());\n const accept = challenge.toonChannel;\n\n // AC5: no toon-channel offer (or no signer) → surface the vanilla challenge.\n if (!accept || !this.resolveClaim) return probe;\n\n // 4. Pay over TOON and return the reconstructed Response.\n return this.payOverToon(url, method, opts, accept, this.resolveClaim);\n }\n\n /**\n * Open/reuse a channel (via the injected claim resolver), seal the request\n * envelope to the terminating connector, send it to `POST /ilp` with the\n * claim and the matching condition, and open the answer.\n *\n * The identity is fetched BEFORE a packet is formed, and there is no default\n * to fall back to: sealing to the wrong key is a confidentiality failure\n * that merely presents as an undeliverable packet (ADR 0018).\n */\n private async payOverToon(\n url: string,\n method: string,\n opts: H402FetchOptions,\n accept: ToonChannelAccept,\n resolveClaim: ClaimResolver\n ): Promise<Response> {\n const destination = opts.destination ?? accept.destination;\n\n // Sign the balance-proof claim for the demanded price (caller-owned).\n const claim = await resolveClaim(destination, accept.amount);\n\n // The key first — no packet exists without it. The 402 named the endpoint\n // to pay, so that is the connector whose identity must seal this.\n const identity = await this.connectorEdge.getIdentity(accept.httpEndpoint);\n\n // One call mints the seal and the condition that matches it, so the two\n // cannot drift apart.\n const exchange = sealExchange(\n toEnvelopeRequest(url, method, opts),\n identity.publicKey\n );\n\n // AC4: drive transport SELECTION through selectIlpTransport. A streaming\n // response (`needsDuplex`) selects the BTP upgrade path; the one-shot case\n // stays on stateless HTTP. Full duplex byte-streaming is a documented v1\n // limitation (see selectTransport below) — the selection + upgrade call path\n // is wired and unit-tested.\n const peer: DiscoveredIlpPeer = {\n httpEndpoint: accept.httpEndpoint,\n supportsUpgrade: accept.supportsUpgrade,\n };\n const choice = selectIlpTransport(peer, {\n needsDuplex: this.needsDuplex,\n });\n\n const ilpClient = this.createIlpClient(accept.httpEndpoint);\n\n const result = await this.sendOverChoice(\n ilpClient,\n choice,\n {\n destination,\n amount: String(accept.amount),\n data: toBase64(exchange.data),\n executionCondition: exchange.condition,\n ...(opts.timeout !== undefined ? { timeout: opts.timeout } : {}),\n },\n claim\n );\n\n // Open the answer with the secret this packet sealed. A REJECT sealed at\n // the termination is the DESTINATION refusing; a plaintext one is somebody\n // on the path. Both are `ConnectorError` here — `fetch()` has one failure\n // channel — but they no longer read as the same event.\n const outcome = readExchangeOutcome(\n result,\n result.data === undefined ? undefined : fromBase64(result.data),\n exchange.sharedSecret\n );\n\n if (outcome.kind === 'destination-refused') {\n throw new ConnectorError(\n `h402 request refused by the destination: ${outcome.code} ${outcome.message}`.trim()\n );\n }\n if (outcome.kind === 'path-refused') {\n throw new ConnectorError(\n `h402 request refused by a connector on the path: ${outcome.code} ${outcome.message}`.trim()\n );\n }\n\n return toWebResponse(outcome.response);\n }\n\n /**\n * Send the sealed PREPARE over the selected transport.\n *\n * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.\n * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}\n * for the duplex/streaming path (AC4). v1 still drives the actual write over\n * the one-shot HTTP method even after upgrading — full duplex body streaming\n * is a documented follow-up — but the upgrade call path is wired here.\n * - `btp`: not reachable from h402 (the x402 offer only carries an\n * `httpEndpoint`); guarded for completeness.\n */\n private async sendOverChoice(\n ilpClient: HttpIlpClient,\n choice: IlpTransportChoice,\n params: {\n destination: string;\n amount: string;\n data: string;\n executionCondition: Uint8Array;\n timeout?: number;\n },\n claim: unknown\n ): Promise<IlpSendResult> {\n if (choice.kind === 'http-upgradable') {\n // Wire the upgrade path: obtain (and immediately release) a duplex BTP\n // session so a streaming consumer can take it over in a follow-up. The\n // one-shot write below still terminates the payment for v1.\n const btp = await ilpClient.upgradeToBtp();\n try {\n // BtpRuntimeClient types `claim` as Record<string, unknown>; the claim\n // message is an opaque forwarded envelope (same cast ToonClient uses).\n return await btp.sendIlpPacketWithClaim(\n params,\n claim as Record<string, unknown>\n );\n } finally {\n await btp.disconnect().catch(() => undefined);\n }\n }\n if (choice.kind === 'btp') {\n throw new ToonClientError(\n 'h402 offer resolved to a BTP-only transport; the x402 toon-channel entry must advertise an httpEndpoint',\n 'INVALID_STATE'\n );\n }\n // 'http'\n return ilpClient.sendIlpPacketWithClaim(params, claim);\n }\n}\n\n// ─── x402 challenge parsing (defensive) ─────────────────────────────────────\n\n/** First defined string among the given keys on `obj`. */\nfunction readString(\n obj: Record<string, unknown>,\n keys: string[]\n): string | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'string' && v.trim().length > 0) return v.trim();\n }\n return undefined;\n}\n\n/** First parseable bigint among the given keys (string|number) on `obj`. */\nfunction readAmount(\n obj: Record<string, unknown>,\n keys: string[]\n): bigint | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isFinite(v))\n return BigInt(Math.trunc(v));\n if (typeof v === 'string' && /^\\d+$/.test(v.trim()))\n return BigInt(v.trim());\n }\n return undefined;\n}\n\n/**\n * Turn an `httpEndpoint` into something fetchable.\n *\n * The Rust connector emits a RELATIVE endpoint (`\"/ilp\"`), because the terms\n * describe an endpoint on the origin that answered. Resolved against the\n * resource URL it becomes the absolute `POST /ilp` URL this adapter needs. An\n * already-absolute endpoint is returned unchanged; a relative one with no base\n * to resolve against is passed through as before, so nothing that worked\n * previously stops working.\n */\nfunction resolveEndpoint(\n endpoint: string | undefined,\n baseUrl: string | undefined\n): string | undefined {\n if (!endpoint || !baseUrl) return endpoint;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;\n try {\n return new URL(endpoint, baseUrl).toString();\n } catch {\n return endpoint;\n }\n}\n\n/**\n * Parse a 402 `Response` body into a {@link ParsedX402Challenge}, selecting the\n * first usable `toon-channel` entry. Reads every field defensively; a malformed\n * body, a non-JSON body, or an entry missing its `destination`/`httpEndpoint`\n * yields `{ toonChannel: undefined }` so the caller falls back to the vanilla\n * 402 rather than throwing.\n */\nexport async function parseX402Challenge(\n response: Response\n): Promise<ParsedX402Challenge> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return {};\n }\n // `response.url` is the resource that answered 402 — the base a relative\n // `httpEndpoint` (which is what the Rust connector actually emits: `/ilp`)\n // has to be resolved against.\n return parseX402Body(body, response.url || undefined);\n}\n\n/**\n * Pure parser over an already-decoded x402 body (testable without a Response).\n *\n * `baseUrl`, when given, is the absolute URL of the resource that answered\n * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps\n * the old behaviour of passing the endpoint through verbatim.\n */\nexport function parseX402Body(\n body: unknown,\n baseUrl?: string\n): ParsedX402Challenge {\n if (typeof body !== 'object' || body === null) return {};\n const b = body as Record<string, unknown>;\n\n const version =\n typeof b['x402Version'] === 'number'\n ? (b['x402Version'] as number)\n : undefined;\n\n const accepts = Array.isArray(b['accepts'])\n ? (b['accepts'] as unknown[])\n : [];\n\n for (const raw of accepts) {\n if (typeof raw !== 'object' || raw === null) continue;\n const entry = raw as Record<string, unknown>;\n const scheme = readString(entry, ['scheme']);\n if (scheme !== 'toon-channel') continue;\n\n // The Rust connector puts the ILP address, the endpoint and the price\n // under `extra` (`crates/connector-client-edge/src/lib.rs`, client-edge-spec\n // §1.4) — NOT at the entry's top level. `extra` is therefore read as a\n // first-class source, not a fallback: reading `payTo` instead only ever\n // worked because that connector happens to set it to the destination too,\n // which is a coincidence of today's code and not part of the contract.\n const extra =\n typeof entry['extra'] === 'object' && entry['extra'] !== null\n ? (entry['extra'] as Record<string, unknown>)\n : {};\n\n const destination =\n readString(extra, ['ilpAddress', 'destination']) ??\n readString(entry, ['destination', 'ilpAddress', 'payTo']);\n const rawEndpoint =\n readString(entry, ['httpEndpoint', 'ilpEndpoint']) ??\n readString(extra, ['httpEndpoint', 'endpoint']) ??\n readString(entry, ['endpoint']);\n const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);\n const amount =\n readAmount(extra, ['price', 'amount']) ??\n readAmount(entry, ['amount', 'price', 'maxAmountRequired']);\n\n // A usable entry MUST carry where to pay, how much, and how to reach /ilp.\n if (!destination || !httpEndpoint || amount === undefined) continue;\n\n const network = readString(entry, ['network', 'chain']);\n const supportsUpgrade =\n entry['supportsUpgrade'] === true || entry['upgradable'] === true;\n\n return {\n ...(version !== undefined ? { x402Version: version } : {}),\n toonChannel: {\n scheme: 'toon-channel',\n ...(network !== undefined ? { network } : {}),\n destination,\n amount,\n httpEndpoint,\n supportsUpgrade,\n },\n };\n }\n\n return version !== undefined ? { x402Version: version } : {};\n}\n\n// ─── The one envelope, in and out ───────────────────────────────────────────\n\n/** Normalize an optional string|Uint8Array body to bytes. */\nfunction bodyToBytes(body: string | Uint8Array | undefined): Uint8Array {\n if (body === undefined) return new Uint8Array(0);\n return typeof body === 'string' ? encodeUtf8(body) : body;\n}\n\n/**\n * Turn a caller's `fetch`-shaped request into the `EnvelopeRequest` that is\n * sealed into the packet.\n *\n * The target is the URL's path RELATIVE to the origin root (no leading `/`),\n * plus `search`. ADR 0025 (connector #596) resolves an envelope target\n * strictly BENEATH the route's configured handler path — `''` means \"the\n * handler's own path\", and an absolute `/…` target is refused outright\n * (F00) as an escape attempt, so origin-form is no longer speakable on this\n * wire.\n *\n * Headers are carried in the caller's own order, names verbatim. The envelope\n * is a LIST of pairs, not a map, so order and duplicates both survive — which\n * the old `Map`-based serializer destroyed. Nothing is synthesised: `Host` and\n * `Content-Length` are the connector's to recompute (see the module docs).\n */\nfunction toEnvelopeRequest(\n url: string,\n method: string,\n opts: H402FetchOptions\n): {\n method: string;\n target: string;\n headers: EnvelopeHeader[];\n body: Uint8Array;\n} {\n const u = new URL(url);\n const headers: EnvelopeHeader[] = Object.entries(opts.headers ?? {}).map(\n ([name, value]) => [name, value] as EnvelopeHeader\n );\n return {\n method: method.toUpperCase(),\n // Strip the leading '/' — ADR 0025 targets are handler-relative, and\n // the empty string ('' + no search) is exactly \"the handler's path\".\n target: `${u.pathname.replace(/^\\/+/, '')}${u.search}`,\n headers,\n body: bodyToBytes(opts.body),\n };\n}\n\n/**\n * Present a decoded {@link EnvelopeResponse} as the standard Web `Response`\n * this adapter's callers expect.\n *\n * An adaptation, not a codec: nothing is parsed here, because the status,\n * headers and body arrived already separated by the envelope decoder.\n *\n * `statusText` is left empty — the envelope carries a two-byte status and no\n * reason phrase, so there is no \"Created\" to report. `Headers.append` keeps\n * duplicates (`set-cookie`), and a null-body status never gets one, which\n * `Response` would throw over.\n */\nfunction toWebResponse(envelope: EnvelopeResponse): Response {\n const headers = new Headers();\n for (const [name, value] of envelope.headers) {\n // Hop-by-hop framing headers describe an HTTP/1.1 connection that no\n // longer exists once the answer is an envelope; `Response` recomputes its\n // own body length regardless.\n if (name.toLowerCase() === 'content-length') continue;\n headers.append(name, value);\n }\n\n const status = envelope.status;\n const nullBodyStatus =\n status === 101 || status === 204 || status === 205 || status === 304;\n\n return new Response(\n nullBodyStatus || envelope.body.length === 0\n ? null\n : (envelope.body.slice() as unknown as BodyInit),\n { status, headers }\n );\n}\n","/**\n * Receive-side swap settlement (toon-client#352): turn persisted\n * {@link ReceivedClaimEntry} watermarks into on-chain settlement submissions.\n *\n * Building is pure and chain-agnostic — `buildSettlementTx` (sdk) re-verifies\n * the stored claim's signature and produces one {@link SettlementBundle} per\n * `(chain, channelId)` with the FINAL watermark, so N received advances net to\n * one on-chain close per channel (spec §9). Submission is chain-gated:\n *\n * - **EVM** — implemented here ({@link submitEvmSettlement}): the bundle's\n * unsigned RLP is decoded for `to`/calldata, gas is estimated against the\n * configured RPC, and the tx is signed by the client's EVM account (the\n * claim recipient) and broadcast. Real submission is therefore env-gated on\n * `chainRpcUrls[chain]` — absent RPC config yields a built-not-submitted\n * result, never a throw.\n * - **Solana** — the bundle carries a serialized Message; a submission path is\n * not wired yet (follow-up under toon-meta#145).\n * - **Mina** — receive-side redemption needs a co-sign (`claimFromChannel`\n * takes `signatureA` AND `signatureB`) plus o1js proof generation; the\n * client has no receive-side co-sign path. Explicitly out of scope for #352\n * (documented gap; follow-up: toon-client#357).\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n buildSettlementTx,\n SettlementTxError,\n type MinaSignerClientLike,\n type SettlementBundle,\n type SwapSignerConfig,\n} from '@toon-protocol/sdk';\nimport {\n createPublicClient,\n defineChain,\n fromRlp,\n http,\n type Hex,\n type PrivateKeyAccount,\n} from 'viem';\nimport type { ReceivedClaimEntry } from '../channel/ReceivedClaimStore.js';\n\n/** One per-channel settlement build outcome (result-shaped, never thrown). */\nexport interface SwapSettlementBuild {\n chain: string;\n channelId: string;\n /** The bundle, when the claim verified and the chain config sufficed. */\n bundle?: SettlementBundle;\n /** Why no bundle was produced (missing config, failed re-verification, …). */\n error?: { code: string; message: string };\n}\n\nexport interface BuildSwapSettlementsParams {\n /** Persisted watermarks to settle (typically `store.list()`, filtered). */\n entries: readonly ReceivedClaimEntry[];\n /**\n * Per-chain settlement contract: EVM TokenNetwork address / Solana\n * programId, keyed by the FULL chain key (e.g. `evm:base:8453`). Matches the\n * daemon config's `tokenNetworks` map.\n */\n tokenNetworks?: Record<string, string>;\n /** Pre-loaded `mina-signer` client for `mina:*` re-verification. */\n minaSignerClient?: MinaSignerClientLike;\n /**\n * Re-verify the stored claim's signature at settle time (defense in depth\n * over the store file). Default `true` — the published **v2** sdk\n * (`@toon-protocol/sdk@^3`, connector#324 finding #1) verifies EVM claims\n * against the **v2** EIP-712 domain-separated balance-proof digest, the SAME\n * digest the receive-side used (`ingestReceivedClaims`). Reconstructing that\n * EIP-712 domain needs `chainId` + `verifyingContract`, which this builder\n * threads into the sdk signer config from `tokenNetworks` (for EVM claims) —\n * so a claim verified at receipt re-verifies correctly here.\n *\n * Set `false` only to skip the settle-time re-verify entirely (e.g. when the\n * receive-side verify is treated as the sole authoritative gate); the sdk is\n * then used only to BUILD the settlement calldata.\n */\n verifySignatures?: boolean;\n}\n\n/** Rebuild the sdk `AccumulatedClaim` shape from a persisted entry. */\nexport function entryToAccumulatedClaim(\n entry: ReceivedClaimEntry\n): AccumulatedClaim {\n return {\n packetIndex: 0,\n sourceAmount: 0n,\n targetAmount: entry.cumulativeAmount,\n claimBytes: entry.claimBytes,\n swapEphemeralPubkey: '',\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n channelId: entry.channelId,\n nonce: entry.nonce.toString(),\n cumulativeAmount: entry.cumulativeAmount.toString(),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n };\n}\n\n/**\n * Parse the numeric chain id off an `evm:{network}:{chainId}` / `evm:{chainId}`\n * chain key. Returns undefined for malformed keys (reported result-shaped).\n */\nexport function parseEvmChainId(chain: string): number | undefined {\n const parts = chain.split(':');\n const raw = parts.length >= 3 ? parts[2] : parts[1];\n const chainId = Number.parseInt(raw ?? '', 10);\n return Number.isInteger(chainId) && chainId > 0 ? chainId : undefined;\n}\n\n/**\n * Build one settlement bundle per persisted entry via the sdk's\n * `buildSettlementTx` (signature re-verified at settle time — a tampered\n * store never reaches a submission). Per-entry isolation: one bad channel\n * cannot block the others.\n */\nexport function buildSwapSettlements(\n params: BuildSwapSettlementsParams\n): SwapSettlementBuild[] {\n return params.entries.map((entry) => {\n const base = { chain: entry.chain, channelId: entry.channelId };\n const signer: SwapSignerConfig = { address: entry.swapSignerAddress };\n const contract = params.tokenNetworks?.[entry.chain];\n if (entry.chain.startsWith('evm')) {\n const chainId = parseEvmChainId(entry.chain);\n if (!contract || chainId === undefined) {\n return {\n ...base,\n error: {\n code: 'MISSING_CHAIN_CONFIG',\n message:\n `EVM settlement for ${entry.chain} needs tokenNetworks[\"${entry.chain}\"] ` +\n `(TokenNetwork contract) and a numeric chain id in the chain key.`,\n },\n };\n }\n signer.contractAddress = contract;\n signer.chainId = chainId;\n } else if (entry.chain.startsWith('solana')) {\n if (!contract) {\n return {\n ...base,\n error: {\n code: 'MISSING_CHAIN_CONFIG',\n message: `Solana settlement for ${entry.chain} needs tokenNetworks[\"${entry.chain}\"] (programId).`,\n },\n };\n }\n signer.programId = contract;\n }\n try {\n const result = buildSettlementTx({\n claims: [entryToAccumulatedClaim(entry)],\n signers: { [entry.chain]: signer },\n recipients: { [entry.chain]: entry.recipient },\n ...(params.verifySignatures !== undefined\n ? { verifySignatures: params.verifySignatures }\n : {}),\n ...(params.minaSignerClient\n ? { minaSignerClient: params.minaSignerClient }\n : {}),\n });\n const firstRejected = result.rejected[0];\n if (firstRejected) {\n return {\n ...base,\n error: {\n code: firstRejected.reason,\n message:\n firstRejected.details ??\n `stored claim for ${entry.chain}/${entry.channelId} failed settlement re-verification`,\n },\n };\n }\n const bundle = result.bundles[0];\n if (!bundle) {\n return {\n ...base,\n error: {\n code: 'NO_BUNDLE',\n message: `buildSettlementTx produced no bundle for ${entry.chain}/${entry.channelId}`,\n },\n };\n }\n return { ...base, bundle };\n } catch (err) {\n const code = err instanceof SettlementTxError ? err.code : 'BUILD_FAILED';\n return {\n ...base,\n error: {\n code,\n message: err instanceof Error ? err.message : String(err),\n },\n };\n }\n });\n}\n\nexport interface SubmitEvmSettlementParams {\n /** JSON-RPC endpoint of the bundle's chain (`chainRpcUrls[bundle.chain]`). */\n rpcUrl: string;\n /** The claim recipient's EVM account (signs + pays gas for the redeem). */\n account: PrivateKeyAccount;\n /** Receipt wait bound, ms (default 60_000). */\n timeoutMs?: number;\n}\n\nexport interface SubmitEvmSettlementResult {\n txHash: string;\n /** Receipt status when the wait succeeded within the bound. */\n status?: 'success' | 'reverted';\n}\n\n/**\n * Decode the unsigned legacy-RLP tx a settlement bundle carries.\n * Layout (EIP-155 unsigned): [nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0].\n */\nexport function decodeEvmSettlementTx(bundle: SettlementBundle): {\n to: Hex;\n data: Hex;\n chainId: number;\n} {\n const fields = fromRlp(bundle.unsignedTxBytes, 'hex');\n if (!Array.isArray(fields) || fields.length !== 9) {\n throw new Error(\n `settlement bundle RLP is not a 9-field unsigned EVM tx (got ${Array.isArray(fields) ? fields.length : typeof fields})`\n );\n }\n const to = fields[3] as Hex;\n const data = fields[5] as Hex;\n const chainIdHex = fields[6] as Hex;\n const chainId = Number.parseInt(chainIdHex === '0x' ? '0x0' : chainIdHex, 16);\n if (typeof to !== 'string' || to.length !== 42) {\n throw new Error(\n `settlement tx \"to\" is not a 20-byte address: ${String(to)}`\n );\n }\n return { to, data: (data === '0x' ? '0x' : data) as Hex, chainId };\n}\n\n/**\n * Sign + broadcast an EVM settlement bundle from the recipient's account.\n * Gas/nonce are read from the RPC; the tx is signed locally (non-custodial)\n * and sent as a raw transaction, then awaited to a receipt (bounded).\n */\nexport async function submitEvmSettlement(\n bundle: SettlementBundle,\n params: SubmitEvmSettlementParams\n): Promise<SubmitEvmSettlementResult> {\n if (bundle.chainKind !== 'evm') {\n throw new Error(\n `submitEvmSettlement only submits evm bundles (got ${bundle.chainKind} for ${bundle.chain})`\n );\n }\n const { to, data, chainId } = decodeEvmSettlementTx(bundle);\n const chain = defineChain({\n id: chainId,\n name: bundle.chain,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [params.rpcUrl] } },\n });\n const publicClient = createPublicClient({\n chain,\n transport: http(params.rpcUrl),\n });\n\n const [nonce, gasPrice, gas] = await Promise.all([\n publicClient.getTransactionCount({\n address: params.account.address,\n blockTag: 'pending',\n }),\n publicClient.getGasPrice(),\n publicClient.estimateGas({ account: params.account.address, to, data }),\n ]);\n\n const signed = await params.account.signTransaction({\n type: 'legacy',\n chainId,\n nonce,\n gasPrice,\n gas,\n to,\n value: 0n,\n data,\n });\n const txHash = await publicClient.sendRawTransaction({\n serializedTransaction: signed,\n });\n try {\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: params.timeoutMs ?? 60_000,\n });\n return { txHash, status: receipt.status };\n } catch {\n // The tx is broadcast; a slow chain just means the caller re-checks later.\n return { txHash };\n }\n}\n","/**\n * Mina receive-side swap settlement (toon-client#357, part of the rolling-swap\n * epic toon-meta#145; follow-up to the #352 receive-side ingestion PR).\n *\n * #352 shipped VERIFICATION of swapped-in Mina claims but explicitly left\n * REDEMPTION out: `POST /swap/settle` returned `SUBMISSION_UNSUPPORTED` for\n * `mina:*` bundles. This module is the missing redemption seam — it turns a\n * verified accumulated Mina claim into an on-chain co-signed `claimFromChannel`\n * transaction against the payment-channel zkApp.\n *\n * ## Why Mina needs a co-sign (and EVM/Solana do not)\n *\n * The zkApp's `claimFromChannel(newBalanceA, newBalanceB, newSalt, signatureA,\n * signatureB, participantA, participantB, channelNonce, newBalanceCommitment,\n * newNonce)` is DUAL-PARTY (connector#84): it verifies BOTH participants signed\n * the SAME message `[newBalanceCommitment, newNonce, storedChannelHash]`\n * (`packages/mina-zkapp/src/PaymentChannel.ts`). The client's existing\n * {@link MinaSigner} is payer-side only. On the swap RECEIVE side the client is\n * the RECIPIENT of the channel, so it must contribute the recipient's\n * co-signature (`signatureB` for its participant slot).\n *\n * ## Signature-message mismatch — the maker-side dependency\n *\n * The swap-wire claim (`AccumulatedClaim.claimBytes`) carries the maker's\n * Schnorr signature over `balanceProofFieldsMina(channelId, cumulativeAmount,\n * nonce, recipient)` (verified by the sdk's `verifyMinaSignature`). That is a\n * DIFFERENT message than the on-chain `[commitment, nonce, channelHash]`, so it\n * CANNOT be reused as an on-chain participant signature. On-chain redemption\n * therefore needs the maker to ALSO contribute a payment-channel-commitment-form\n * signature over `[commitment, nonce, channelHash]` (the same form the connector\n * payment-channel provider produces from a client claim). Until a maker delivers\n * that, {@link submitMinaSettlement} fails closed with\n * `MINA_MAKER_COSIGN_REQUIRED` (never a silent pass). See the PR body for the\n * cross-repo maker/wire follow-up.\n *\n * ## globalSlot preconditions\n *\n * Unlike `initiateClose`/`settle` (which pin `network.globalSlotSinceGenesis`\n * and were the subject of the #202 exact-slot-precondition bug), the zkApp's\n * `claimFromChannel` binds NO slot precondition — only `channelState == OPEN`,\n * `channelHash`, `depositTotal`, and a strictly-increasing `nonceField`. The\n * redeem path is therefore immune to the #202 slot-drift failure. The eventual\n * close+settle that pays escrow out to the recipient DOES touch the slot window\n * and remains the connector's `settleChannel` responsibility (a separate step).\n *\n * ## What runs where\n *\n * - On-chain STATE READ + co-sign assembly ({@link buildMinaCoSignedClaim}):\n * plain GraphQL + `mina-signer` (Pallas Schnorr / Poseidon) — NO o1js, fully\n * unit-testable in-process.\n * - Proof generation + broadcast ({@link submitMinaSettlement}): drives an\n * injectable {@link MinaClaimSubmitter}; the default is an o1js-backed settler\n * ({@link createO1jsMinaClaimSubmitter}) that dynamically imports `o1js` +\n * `@toon-protocol/mina-zkapp` only when invoked (never loaded by the non-Mina\n * suite). o1js circuit compilation + proving is slow (30-120s) and is exercised\n * only against live devnet Mina behind an env gate.\n */\n\nimport { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport type { SettlementBundle } from '@toon-protocol/sdk';\nimport {\n buildMinaPaymentChannelProof,\n loadMinaPaymentChannelBindings,\n minaBalanceCommitment,\n minaParticipantChannelHashField,\n} from '../channel/mina-payment-channel.js';\nimport {\n readMinaChannelState,\n MINA_CHANNEL_STATE,\n type MinaOnChainChannelState,\n} from '../channel/mina-deposit.js';\nimport { deriveMinaSalt } from '../signing/mina-signer.js';\n\n/** Bare Pallas Schnorr signature in the o1js JSON (decimal `r`/`s`) form. */\nexport interface MinaSignaturePair {\n r: string;\n s: string;\n}\n\n/** Stable failure codes for Mina receive-side settlement. */\nexport type MinaSettlementErrorCode =\n | 'NOT_MINA_BUNDLE'\n | 'NO_GRAPHQL_CONFIGURED'\n | 'CHANNEL_NOT_OPEN'\n | 'NONCE_NOT_ADVANCING'\n | 'CHANNEL_HASH_MISMATCH'\n | 'CUMULATIVE_EXCEEDS_DEPOSIT'\n | 'MINA_MAKER_COSIGN_REQUIRED'\n | 'PROVING_FAILED';\n\n/** Result-shaped-by-throw settlement error carrying a stable {@link code}. */\nexport class MinaSettlementError extends Error {\n readonly code: MinaSettlementErrorCode;\n constructor(code: MinaSettlementErrorCode, message: string) {\n super(`${code}: ${message}`);\n this.name = 'MinaSettlementError';\n this.code = code;\n }\n}\n\n/** Inputs to {@link buildMinaCoSignedClaim} (pure assembly, no o1js). */\nexport interface MinaCoSignInputs {\n /** Deployed payment-channel zkApp address (B62) — the on-chain channel id. */\n channelId: string;\n /** Claim nonce being redeemed (must exceed the on-chain `nonceField`). */\n nonce: bigint;\n /** Cumulative amount credited to the recipient (base units). */\n cumulativeAmount: bigint;\n /** Recipient's Mina B62 pubkey — one channel participant (the co-signer). */\n recipient: string;\n /** Swap maker's Mina B62 pubkey — the other channel participant. */\n swapSignerAddress: string;\n /** On-chain `depositTotal` (base units) for balance conservation. */\n depositTotal: bigint;\n /** On-chain `channelHash` (decimal Field) used to resolve A/B ordering. */\n onChainChannelHash: string;\n /** Recipient's Mina private key (big-endian hex scalar OR `EK…` base58). */\n recipientPrivateKey: string;\n /** Channel nonce baked into the on-chain `channelHash` (default 0). */\n channelNonce?: bigint;\n /** Override the deterministic salt (else {@link deriveMinaSalt}). */\n saltOverride?: bigint;\n /**\n * Maker's payment-channel-commitment-form signature over\n * `[commitment, nonce, channelHash]`. REQUIRED for a fully-redeemable claim;\n * when absent the returned claim reports {@link makerSignatureMissing}.\n */\n makerSignature?: MinaSignaturePair;\n}\n\n/** A dual-party claim assembled for the zkApp's `claimFromChannel`. */\nexport interface MinaCoSignedClaim {\n channelId: string;\n /** Balance credited to `participantA` (base units). */\n balanceA: bigint;\n /** Balance credited to `participantB` (`depositTotal - balanceA`). */\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n channelNonce: bigint;\n /** `Poseidon([balanceA, balanceB, salt])`, decimal Field. */\n balanceCommitment: string;\n /** Participant A B62 (ordered to reproduce the on-chain `channelHash`). */\n participantA: string;\n /** Participant B B62. */\n participantB: string;\n /** Which participant slot the recipient/co-signer occupies. */\n recipientRole: 'A' | 'B';\n /** The recipient's co-signature over `[commitment, nonce, channelHash]`. */\n recipientSignature: MinaSignaturePair;\n /** Signature for participant A (recipient's or maker's per {@link recipientRole}). */\n signatureA?: MinaSignaturePair;\n /** Signature for participant B. */\n signatureB?: MinaSignaturePair;\n /** True when no maker co-signature was supplied (claim not yet redeemable). */\n makerSignatureMissing: boolean;\n}\n\n/** Extract the bare `{ r, s }` from a `buildMinaPaymentChannelProof` proof JSON. */\nfunction parseProofSignature(proofJson: string): MinaSignaturePair {\n const parsed = JSON.parse(proofJson) as {\n signature?: { r?: unknown; s?: unknown };\n };\n const r = parsed.signature?.r;\n const s = parsed.signature?.s;\n if (typeof r !== 'string' || typeof s !== 'string') {\n throw new Error('recipient co-signature proof did not carry string r/s');\n }\n return { r, s };\n}\n\n/**\n * Assemble a dual-party `claimFromChannel` claim from a verified swap claim.\n *\n * Pure crypto (GraphQL-read state is passed in): resolves the on-chain A/B\n * participant ordering by reproducing `channelHash`, conserves balances against\n * `depositTotal`, computes the Poseidon commitment, and produces the recipient's\n * co-signature over `[commitment, nonce, channelHash]` with `mina-signer`. No\n * o1js is loaded.\n *\n * @throws {MinaSettlementError} `CHANNEL_HASH_MISMATCH` when neither ordering of\n * `{recipient, swapSignerAddress}` reproduces `onChainChannelHash`;\n * `CUMULATIVE_EXCEEDS_DEPOSIT` when the credit exceeds the escrow.\n */\nexport async function buildMinaCoSignedClaim(\n inputs: MinaCoSignInputs\n): Promise<MinaCoSignedClaim> {\n const channelNonce = inputs.channelNonce ?? 0n;\n const salt =\n inputs.saltOverride ?? deriveMinaSalt(inputs.channelId, Number(inputs.nonce));\n\n if (inputs.cumulativeAmount > inputs.depositTotal) {\n throw new MinaSettlementError(\n 'CUMULATIVE_EXCEEDS_DEPOSIT',\n `claim cumulativeAmount (${inputs.cumulativeAmount}) exceeds the channel ` +\n `depositTotal (${inputs.depositTotal}) — cannot conserve balances`\n );\n }\n\n const { Poseidon, PublicKey } = await loadMinaPaymentChannelBindings();\n\n // Resolve which participant slot each party occupies by reproducing the\n // on-chain channelHash = Poseidon([A.x, B.x, channelNonce]). The zkApp verifies\n // signatureA against participantA and signatureB against participantB, so the\n // balances + signatures must be assigned to the ordering the channel was\n // opened with.\n const hashRecipientFirst = minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n inputs.recipient,\n inputs.swapSignerAddress,\n channelNonce\n ).toString();\n const hashMakerFirst = minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n inputs.swapSignerAddress,\n inputs.recipient,\n channelNonce\n ).toString();\n\n let participantA: string;\n let participantB: string;\n let recipientRole: 'A' | 'B';\n if (hashRecipientFirst === inputs.onChainChannelHash) {\n participantA = inputs.recipient;\n participantB = inputs.swapSignerAddress;\n recipientRole = 'A';\n } else if (hashMakerFirst === inputs.onChainChannelHash) {\n participantA = inputs.swapSignerAddress;\n participantB = inputs.recipient;\n recipientRole = 'B';\n } else {\n throw new MinaSettlementError(\n 'CHANNEL_HASH_MISMATCH',\n `neither ordering of recipient ${inputs.recipient} / maker ` +\n `${inputs.swapSignerAddress} reproduces the on-chain channelHash ` +\n `${inputs.onChainChannelHash} (channelNonce ${channelNonce})`\n );\n }\n\n // Recipient-credit: the recipient's balance is the cumulative amount; the\n // maker (funder) keeps the remainder. Assign to A/B by the resolved ordering.\n const recipientBalance = inputs.cumulativeAmount;\n const makerBalance = inputs.depositTotal - inputs.cumulativeAmount;\n const balanceA = recipientRole === 'A' ? recipientBalance : makerBalance;\n const balanceB = inputs.depositTotal - balanceA;\n\n const balanceCommitment = minaBalanceCommitment(\n Poseidon,\n balanceA,\n balanceB,\n salt\n ).toString();\n\n // Recipient co-signs [commitment, nonce, channelHash] with its own key over\n // the SAME participant-form channelHash the zkApp stored. Reuse the connector-\n // parity proof builder so signer and on-chain verifier cannot drift.\n const recipientPrivateKeyBase58 = hexToMinaBase58PrivateKey(\n inputs.recipientPrivateKey\n );\n const built = await buildMinaPaymentChannelProof({\n zkAppAddress: inputs.channelId,\n minaPrivateKeyBase58: recipientPrivateKeyBase58,\n signerPublicKey: inputs.recipient,\n balanceA,\n balanceB,\n salt,\n nonce: inputs.nonce,\n participantA,\n participantB,\n channelNonce,\n proofEncoding: 'json',\n });\n if (built.balanceCommitment !== balanceCommitment) {\n // Defense-in-depth: the proof builder recomputes the commitment; a mismatch\n // means the two Poseidon paths diverged (should never happen).\n throw new Error(\n `co-sign commitment drift: builder ${built.balanceCommitment} != ${balanceCommitment}`\n );\n }\n const recipientSignature = parseProofSignature(built.proof);\n\n const signatureA =\n recipientRole === 'A' ? recipientSignature : inputs.makerSignature;\n const signatureB =\n recipientRole === 'B' ? recipientSignature : inputs.makerSignature;\n\n return {\n channelId: inputs.channelId,\n balanceA,\n balanceB,\n salt,\n nonce: inputs.nonce,\n channelNonce,\n balanceCommitment,\n participantA,\n participantB,\n recipientRole,\n recipientSignature,\n ...(signatureA ? { signatureA } : {}),\n ...(signatureB ? { signatureB } : {}),\n makerSignatureMissing: inputs.makerSignature === undefined,\n };\n}\n\n/** Arguments handed to a {@link MinaClaimSubmitter} (o1js proving boundary). */\nexport interface MinaClaimSubmitArgs {\n /** Mina GraphQL endpoint bound as the active o1js network. */\n graphqlUrl: string;\n /** Channel zkApp address (B62). */\n channelId: string;\n balanceA: bigint;\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n /** Participant pubkeys (B62), ordered to match the on-chain `channelHash`. */\n participantA: string;\n participantB: string;\n channelNonce: bigint;\n signatureA: MinaSignaturePair;\n signatureB: MinaSignaturePair;\n /** Fee-payer / submitter Mina private key (hex scalar or `EK…` base58). */\n feePayerPrivateKey: string;\n /** zkApp tx fee (nanomina); the default settler applies 0.1 MINA when unset. */\n txFeeNanomina?: bigint;\n}\n\n/**\n * Generates the o1js proof and broadcasts the `claimFromChannel` tx. Injected so\n * the assembly logic can be unit-tested without loading the WASM circuit runtime.\n */\nexport interface MinaClaimSubmitter {\n claimFromChannel(args: MinaClaimSubmitArgs): Promise<{ txHash: string }>;\n}\n\n/** Read seam for the on-chain channel state (default: plain GraphQL). */\nexport type MinaChannelStateReader = (\n graphqlUrl: string,\n zkAppAddress: string\n) => Promise<MinaOnChainChannelState>;\n\n/** Context for {@link submitMinaSettlement}. */\nexport interface MinaSettlementContext {\n /** Mina GraphQL URL (reads state + binds the o1js network). */\n graphqlUrl?: string;\n /** Recipient's Mina private key (co-signs; also the default fee payer). */\n recipientPrivateKey: string;\n /** Maker's on-chain-form co-signature over `[commitment, nonce, channelHash]`. */\n makerSignature?: MinaSignaturePair;\n /** Fee-payer key override (defaults to `recipientPrivateKey`). */\n feePayerPrivateKey?: string;\n /** zkApp tx fee (nanomina). */\n txFeeNanomina?: bigint;\n /** Channel nonce for the on-chain `channelHash` (default 0). */\n channelNonce?: bigint;\n /** Inject a state reader (tests). Defaults to {@link readMinaChannelState}. */\n reader?: MinaChannelStateReader;\n /** Inject a proof submitter (tests). Defaults to an o1js-backed settler. */\n submitter?: MinaClaimSubmitter;\n}\n\nexport interface MinaSettlementResult {\n txHash: string;\n}\n\n/**\n * Redeem a verified Mina swap claim via a co-signed on-chain `claimFromChannel`.\n *\n * Env/config-gated like the EVM path: with no `graphqlUrl` the caller gets\n * `NO_GRAPHQL_CONFIGURED` (built-not-submitted). Reads the live channel state,\n * asserts it is OPEN and the claim nonce advances the on-chain watermark,\n * assembles the dual-party claim ({@link buildMinaCoSignedClaim}), and — only\n * with a maker co-signature present — drives the o1js proof + broadcast.\n *\n * @throws {MinaSettlementError} with a stable {@link MinaSettlementErrorCode}.\n */\nexport async function submitMinaSettlement(\n bundle: SettlementBundle,\n context: MinaSettlementContext\n): Promise<MinaSettlementResult> {\n if (bundle.chainKind !== 'mina') {\n throw new MinaSettlementError(\n 'NOT_MINA_BUNDLE',\n `submitMinaSettlement only settles mina bundles (got ${bundle.chainKind} for ${bundle.chain})`\n );\n }\n if (!context.graphqlUrl) {\n throw new MinaSettlementError(\n 'NO_GRAPHQL_CONFIGURED',\n `no Mina graphqlUrl configured for \"${bundle.chain}\" — set minaChannel.graphqlUrl to enable receive-side settlement.`\n );\n }\n const graphqlUrl = context.graphqlUrl;\n const channelNonce = context.channelNonce ?? 0n;\n const nonce = BigInt(bundle.nonce);\n const cumulativeAmount = BigInt(bundle.cumulativeAmount);\n\n const read = context.reader ?? readMinaChannelState;\n const state = await read(graphqlUrl, bundle.channelId);\n\n if (state.channelState !== MINA_CHANNEL_STATE.OPEN) {\n throw new MinaSettlementError(\n 'CHANNEL_NOT_OPEN',\n `channel ${bundle.channelId} is not OPEN (channelState=${state.channelState}); claimFromChannel only applies to an OPEN channel.`\n );\n }\n if (nonce <= state.nonceField) {\n throw new MinaSettlementError(\n 'NONCE_NOT_ADVANCING',\n `claim nonce ${nonce} does not advance the on-chain nonceField ${state.nonceField} for ${bundle.channelId} (already claimed).`\n );\n }\n\n const claim = await buildMinaCoSignedClaim({\n channelId: bundle.channelId,\n nonce,\n cumulativeAmount,\n recipient: bundle.recipient,\n swapSignerAddress: bundle.swapSignerAddress,\n depositTotal: state.depositTotal,\n onChainChannelHash: state.channelHash,\n recipientPrivateKey: context.recipientPrivateKey,\n channelNonce,\n ...(context.makerSignature ? { makerSignature: context.makerSignature } : {}),\n });\n\n if (claim.makerSignatureMissing || !claim.signatureA || !claim.signatureB) {\n throw new MinaSettlementError(\n 'MINA_MAKER_COSIGN_REQUIRED',\n `on-chain claimFromChannel is dual-party: it needs the maker's ` +\n `payment-channel-commitment signature over [commitment, nonce, channelHash] ` +\n `in addition to the recipient's co-signature. The swap-wire claim only carries ` +\n `the maker's balanceProofFieldsMina signature (a different message), so the maker ` +\n `must additionally deliver an on-chain-form co-signature. Recipient co-signature ` +\n `assembled and ready (${bundle.channelId} nonce ${nonce}).`\n );\n }\n\n const submitter = context.submitter ?? createO1jsMinaClaimSubmitter();\n const { txHash } = await submitter.claimFromChannel({\n graphqlUrl,\n channelId: bundle.channelId,\n balanceA: claim.balanceA,\n balanceB: claim.balanceB,\n salt: claim.salt,\n nonce: claim.nonce,\n participantA: claim.participantA,\n participantB: claim.participantB,\n channelNonce: claim.channelNonce,\n signatureA: claim.signatureA,\n signatureB: claim.signatureB,\n feePayerPrivateKey:\n context.feePayerPrivateKey ?? context.recipientPrivateKey,\n ...(context.txFeeNanomina !== undefined\n ? { txFeeNanomina: context.txFeeNanomina }\n : {}),\n });\n return { txHash };\n}\n\n/** Default zkApp tx fee (0.1 MINA in nanomina) — real networks reject 0-fee txs. */\nconst DEFAULT_MINA_TX_FEE_NANOMINA = 100_000_000n;\n\n/**\n * Build the default o1js-backed {@link MinaClaimSubmitter}.\n *\n * Mirrors the connector's `MinaPaymentChannelSDK.claimFromChannel`: binds the\n * active Mina network, fetches the channel + fee-payer accounts, deserializes the\n * `{r,s}` signatures, and builds + proves + broadcasts the zkApp\n * `claimFromChannel` method. o1js and `@toon-protocol/mina-zkapp` are imported\n * dynamically INSIDE `claimFromChannel` so the non-Mina test suite never loads\n * the multi-hundred-MB WASM circuit runtime. Compilation + proving are slow\n * (30-120s) and only run against live devnet Mina.\n */\nexport function createO1jsMinaClaimSubmitter(): MinaClaimSubmitter {\n return {\n async claimFromChannel(args: MinaClaimSubmitArgs): Promise<{ txHash: string }> {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const o1js: any = await import('o1js');\n const {\n Mina,\n PrivateKey,\n PublicKey,\n Field,\n Poseidon,\n Signature,\n fetchAccount,\n } = o1js;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const zkAppMod: any = await import('@toon-protocol/mina-zkapp');\n const PaymentChannel = zkAppMod.PaymentChannel;\n\n Mina.setActiveInstance(Mina.Network(args.graphqlUrl));\n\n const feePayerKey = PrivateKey.fromBase58(\n hexToMinaBase58PrivateKey(args.feePayerPrivateKey)\n );\n const feePayerPub = feePayerKey.toPublicKey();\n\n await PaymentChannel.compile();\n\n const zkAppPub = PublicKey.fromBase58(args.channelId);\n await fetchAccount({ publicKey: zkAppPub });\n await fetchAccount({ publicKey: feePayerPub });\n const zkApp = new PaymentChannel(zkAppPub);\n\n const balA = Field(args.balanceA);\n const balB = Field(args.balanceB);\n const saltField = Field(args.salt);\n const newNonce = Field(args.nonce);\n const channelNonce = Field(args.channelNonce);\n const newBalanceCommitment = Poseidon.hash([balA, balB, saltField]);\n const sigA = Signature.fromJSON({\n r: args.signatureA.r,\n s: args.signatureA.s,\n });\n const sigB = Signature.fromJSON({\n r: args.signatureB.r,\n s: args.signatureB.s,\n });\n const partA = PublicKey.fromBase58(args.participantA);\n const partB = PublicKey.fromBase58(args.participantB);\n\n const fee = (\n args.txFeeNanomina ?? DEFAULT_MINA_TX_FEE_NANOMINA\n ).toString();\n const txn = await Mina.transaction(\n { sender: feePayerPub, fee },\n async () => {\n await zkApp.claimFromChannel(\n balA,\n balB,\n saltField,\n sigA,\n sigB,\n partA,\n partB,\n channelNonce,\n newBalanceCommitment,\n newNonce\n );\n }\n );\n await txn.prove();\n const sent = await txn.sign([feePayerKey]).send();\n return { txHash: sent.hash ?? '' };\n } catch (err) {\n throw new MinaSettlementError(\n 'PROVING_FAILED',\n err instanceof Error ? err.message : String(err)\n );\n }\n },\n };\n}\n","import type { ConnectorAdminClient } from '@toon-protocol/core';\nimport {\n ValidationError,\n NetworkError,\n ConnectorError,\n UnauthorizedError,\n PeerNotFoundError,\n PeerAlreadyExistsError,\n} from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\n\n/**\n * Configuration for HttpConnectorAdmin.\n */\nexport interface HttpConnectorAdminConfig {\n /** Admin API base URL (e.g., 'http://localhost:8081') */\n adminUrl: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts for network failures (default: 3) */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** HTTP client for testing (default: global fetch) */\n httpClient?: typeof fetch;\n}\n\n/**\n * Result of a bulk peer operation.\n */\nexport interface PeerOperationResult {\n /** Peer ID that was operated on */\n peerId: string;\n /** Whether the operation succeeded */\n success: boolean;\n /** Error that occurred (if failed) */\n error?: Error;\n}\n\n/**\n * HTTP-based connector admin client for managing ILP peers via REST API.\n *\n * Implements the ConnectorAdminClient interface using HTTP requests to the\n * connector's admin API (typically port 8081).\n *\n * @example\n * ```typescript\n * // Embedded mode (DirectConnectorAdmin)\n * const adminClient = new DirectConnectorAdmin(connectorNode);\n *\n * // HTTP mode (HttpConnectorAdmin)\n * const adminClient = new HttpConnectorAdmin({\n * adminUrl: 'http://localhost:8081'\n * });\n *\n * // Add peer\n * await adminClient.addPeer({\n * id: 'nostr-abc123',\n * url: 'btp+ws://alice.example.com:3000',\n * authToken: 'secret-token',\n * routes: [{ prefix: 'g.toon.alice' }]\n * });\n *\n * // Remove peer\n * await adminClient.removePeer('nostr-abc123');\n * ```\n *\n * @throws {ValidationError} Input validation failed (before HTTP request)\n * @throws {NetworkError} Connection failed (ECONNREFUSED, ETIMEDOUT)\n * @throws {UnauthorizedError} Admin API returned 401 (missing/invalid auth)\n * @throws {PeerAlreadyExistsError} Admin API returned 409 (duplicate peer)\n * @throws {PeerNotFoundError} Admin API returned 404 (peer not found)\n * @throws {ConnectorError} Admin API returned 5xx (server error)\n */\nexport class HttpConnectorAdmin implements ConnectorAdminClient {\n private readonly adminUrl: string;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n\n constructor(config: HttpConnectorAdminConfig) {\n this.adminUrl = config.adminUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n }\n\n /**\n * Add a peer to the connector via the admin API.\n *\n * Validates peer config parameters and sends HTTP POST to /admin/peers.\n *\n * @param config - Peer configuration\n * @param config.id - Unique peer identifier (non-empty string)\n * @param config.url - BTP WebSocket URL (must start with 'btp+ws://' or 'btp+wss://')\n * @param config.authToken - Authentication token (non-empty string)\n * @param config.routes - Optional routing table entries\n * @param config.settlement - Optional settlement configuration\n *\n * @throws {ValidationError} Invalid peer config (missing id, invalid url, etc.)\n * @throws {PeerAlreadyExistsError} Peer with same ID already exists (409 Conflict)\n * @throws {UnauthorizedError} Admin API authentication failed (401)\n * @throws {NetworkError} Connection to admin API failed\n * @throws {ConnectorError} Admin API server error (5xx)\n */\n async addPeer(config: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }): Promise<void> {\n // Validate required fields\n if (\n !config.id ||\n typeof config.id !== 'string' ||\n config.id.trim() === ''\n ) {\n throw new ValidationError('Peer id must be a non-empty string');\n }\n\n if (\n !config.url ||\n typeof config.url !== 'string' ||\n config.url.trim() === ''\n ) {\n throw new ValidationError('Peer url must be a non-empty string');\n }\n\n // Validate BTP URL format (accept both ws:// and btp+ws:// formats)\n const hasWsPrefix =\n config.url.startsWith('ws://') || config.url.startsWith('wss://');\n const hasBtpPrefix =\n config.url.startsWith('btp+ws://') || config.url.startsWith('btp+wss://');\n\n if (!hasWsPrefix && !hasBtpPrefix) {\n throw new ValidationError(\n `Invalid BTP URL format: \"${config.url}\". Must start with 'ws://', 'wss://', 'btp+ws://', or 'btp+wss://'`\n );\n }\n\n // authToken can be empty string for BTP (doesn't require authentication)\n if (\n config.authToken === undefined ||\n config.authToken === null ||\n typeof config.authToken !== 'string'\n ) {\n throw new ValidationError(\n 'Peer authToken must be a string (can be empty for no auth)'\n );\n }\n\n // Validate routes (if provided)\n if (config.routes !== undefined) {\n if (!Array.isArray(config.routes)) {\n throw new ValidationError('Peer routes must be an array');\n }\n\n for (const route of config.routes) {\n if (\n !route.prefix ||\n typeof route.prefix !== 'string' ||\n route.prefix.trim() === ''\n ) {\n throw new ValidationError('Route prefix must be a non-empty string');\n }\n if (\n route.priority !== undefined &&\n typeof route.priority !== 'number'\n ) {\n throw new ValidationError('Route priority must be a number');\n }\n }\n }\n\n // Validate settlement (if provided)\n if (config.settlement !== undefined) {\n if (typeof config.settlement !== 'object' || config.settlement === null) {\n throw new ValidationError('Peer settlement must be an object');\n }\n\n if (\n !config.settlement.preference ||\n typeof config.settlement.preference !== 'string'\n ) {\n throw new ValidationError(\n 'Settlement preference must be a non-empty string'\n );\n }\n }\n\n // Send HTTP POST request with retry logic\n const url = `${this.adminUrl}/admin/peers`;\n\n await withRetry(async () => this.sendAddPeerRequest(url, config), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors (ECONNREFUSED, ETIMEDOUT)\n // Do not retry on validation errors, 4xx, or 5xx errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Remove a peer from the connector via the admin API.\n *\n * Sends HTTP DELETE to /admin/peers/:id.\n *\n * @param peerId - Unique peer identifier to remove (non-empty string)\n *\n * @throws {ValidationError} Invalid peerId (empty string)\n * @throws {PeerNotFoundError} Peer does not exist (404 Not Found)\n * @throws {UnauthorizedError} Admin API authentication failed (401)\n * @throws {NetworkError} Connection to admin API failed\n * @throws {ConnectorError} Admin API server error (5xx)\n */\n async removePeer(peerId: string): Promise<void> {\n // Validate peerId\n if (!peerId || typeof peerId !== 'string' || peerId.trim() === '') {\n throw new ValidationError('peerId must be a non-empty string');\n }\n\n // Send HTTP DELETE request with retry logic\n const url = `${this.adminUrl}/admin/peers/${encodeURIComponent(peerId)}`;\n\n await withRetry(async () => this.sendRemovePeerRequest(url, peerId), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Add multiple peers in parallel for efficient bootstrapping.\n *\n * Uses Promise.allSettled() to execute peer additions concurrently,\n * returning results for each operation regardless of individual failures.\n *\n * @param configs - Array of peer configurations to add\n * @returns Array of results indicating success/failure for each peer\n *\n * @example\n * ```typescript\n * const results = await admin.addPeers([\n * { id: 'peer1', url: 'btp+ws://...', authToken: 'token1' },\n * { id: 'peer2', url: 'btp+ws://...', authToken: 'token2' },\n * ]);\n *\n * results.forEach(result => {\n * if (result.success) {\n * console.log(`Added peer: ${result.peerId}`);\n * } else {\n * console.error(`Failed to add ${result.peerId}:`, result.error);\n * }\n * });\n * ```\n */\n async addPeers(\n configs: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }[]\n ): Promise<PeerOperationResult[]> {\n const results = await Promise.allSettled(\n configs.map((config) => this.addPeer(config))\n );\n\n return results.map((result, index) => {\n const config = configs[index];\n return {\n peerId: config ? config.id : 'unknown',\n success: result.status === 'fulfilled',\n error: result.status === 'rejected' ? result.reason : undefined,\n };\n });\n }\n\n /**\n * Remove multiple peers in parallel.\n *\n * Uses Promise.allSettled() to execute peer removals concurrently,\n * returning results for each operation regardless of individual failures.\n *\n * @param peerIds - Array of peer IDs to remove\n * @returns Array of results indicating success/failure for each peer\n *\n * @example\n * ```typescript\n * const results = await admin.removePeers(['peer1', 'peer2', 'peer3']);\n *\n * const succeeded = results.filter(r => r.success).length;\n * console.log(`Removed ${succeeded}/${results.length} peers`);\n * ```\n */\n async removePeers(peerIds: string[]): Promise<PeerOperationResult[]> {\n const results = await Promise.allSettled(\n peerIds.map((peerId) => this.removePeer(peerId))\n );\n\n return results.map((result, index) => {\n const peerId = peerIds[index];\n return {\n peerId: peerId ?? 'unknown',\n success: result.status === 'fulfilled',\n error: result.status === 'rejected' ? result.reason : undefined,\n };\n });\n }\n\n /**\n * Send HTTP POST request to add a peer.\n * Separated for retry logic wrapping.\n */\n private async sendAddPeerRequest(\n url: string,\n config: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }\n ): Promise<void> {\n // Normalize URL for connector API (expects ws:// or wss://)\n // Strip btp+ prefix if present, or use as-is if already plain ws://\n let connectorUrl = config.url;\n if (connectorUrl.startsWith('btp+')) {\n connectorUrl = connectorUrl.replace(/^btp\\+/, '');\n }\n\n try {\n const response = await this.httpClient(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n ...config,\n url: connectorUrl,\n }),\n signal: AbortSignal.timeout(this.timeout),\n });\n\n if (response.ok) {\n return; // Success (201 Created)\n }\n\n // Handle error responses\n await this.handleErrorResponse(response, `POST ${url}`, config.id);\n } catch (error) {\n this.handleNetworkError(error, url, 'addPeer');\n }\n }\n\n /**\n * Send HTTP DELETE request to remove a peer.\n * Separated for retry logic wrapping.\n */\n private async sendRemovePeerRequest(\n url: string,\n peerId: string\n ): Promise<void> {\n try {\n const response = await this.httpClient(url, {\n method: 'DELETE',\n signal: AbortSignal.timeout(this.timeout),\n });\n\n if (response.ok) {\n return; // Success (204 No Content)\n }\n\n // Handle error responses\n await this.handleErrorResponse(response, `DELETE ${url}`, peerId);\n } catch (error) {\n this.handleNetworkError(error, url, 'removePeer');\n }\n }\n\n /**\n * Handle network errors from HTTP requests.\n *\n * Converts connection failures, timeouts, and unknown errors to NetworkError.\n * Re-throws existing ToonClientError instances.\n *\n * @param error - Error thrown by HTTP client\n * @param url - Request URL (for error messages)\n * @param operation - Operation name (for error messages)\n * @throws {NetworkError} Network connection or timeout error\n */\n private handleNetworkError(\n error: unknown,\n url: string,\n operation: string\n ): never {\n // Timeout errors (AbortSignal)\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request to ${url} timed out after ${this.timeout}ms`,\n error\n );\n }\n\n // Connection errors (ECONNREFUSED, ETIMEDOUT, DNS failures)\n if (\n error instanceof Error &&\n (error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND'))\n ) {\n throw new NetworkError(\n `Failed to connect to connector admin API at ${url}: ${error.message}`,\n error\n );\n }\n\n // Re-throw if already a ToonClientError\n if (\n error instanceof ValidationError ||\n error instanceof PeerAlreadyExistsError ||\n error instanceof PeerNotFoundError ||\n error instanceof UnauthorizedError ||\n error instanceof ConnectorError\n ) {\n throw error;\n }\n\n // Unknown error - wrap in NetworkError\n throw new NetworkError(\n `Unexpected error during ${operation}: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : undefined\n );\n }\n\n /**\n * Handle HTTP error responses from the admin API.\n *\n * Converts HTTP status codes to appropriate error types.\n *\n * @param response - HTTP response from admin API\n * @param endpoint - Endpoint being called (for error messages)\n * @param peerId - Peer ID (for error messages)\n * @throws {UnauthorizedError} 401 Unauthorized\n * @throws {PeerNotFoundError} 404 Not Found\n * @throws {PeerAlreadyExistsError} 409 Conflict\n * @throws {ConnectorError} 5xx Server Error\n */\n private async handleErrorResponse(\n response: Response,\n endpoint: string,\n peerId: string\n ): Promise<never> {\n const status = response.status;\n const statusText = response.statusText;\n\n // Try to extract error message from response body\n let errorMessage = '';\n try {\n const body = await response.text();\n if (body) {\n errorMessage = ` - ${body}`;\n }\n } catch {\n // Ignore body parsing errors\n }\n\n switch (status) {\n case 401:\n throw new UnauthorizedError(\n `Admin API authentication failed for ${endpoint}: ${statusText}${errorMessage}`\n );\n\n case 404:\n throw new PeerNotFoundError(\n `Peer not found: \"${peerId}\" (${endpoint}): ${statusText}${errorMessage}`\n );\n\n case 409:\n throw new PeerAlreadyExistsError(\n `Peer already exists: \"${peerId}\" (${endpoint}): ${statusText}${errorMessage}`\n );\n\n default:\n if (status >= 500) {\n throw new ConnectorError(\n `Connector admin API error (${endpoint}): ${status} ${statusText}${errorMessage}`\n );\n }\n\n // Other 4xx errors (400, 403, etc.)\n throw new ConnectorError(\n `Admin API error (${endpoint}): ${status} ${statusText}${errorMessage}`\n );\n }\n }\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { SwapPair } from '@toon-protocol/core';\n\n/**\n * The persisted receive-side watermark for one swap target channel: the\n * HIGHEST-NONCE verified chain-B claim per `(chain, channelId)` (toon-client\n * issue #352, rolling-swap spec toon-meta docs/rolling-swap.md §3.2/§9).\n *\n * Claims are cumulative balance proofs — a higher-nonce claim supersedes every\n * earlier one — so persisting only the winner per channel is lossless for\n * settlement: `buildSettlementTx` redeems exactly this claim. Superseded claims\n * are informational and dropped.\n */\nexport interface ReceivedClaimEntry {\n /** Target chain the claim settles on (`pair.to.chain`, e.g. `evm:base:8453`). */\n chain: string;\n /** Payment-channel id on the target chain (0x-hex for EVM, base58 otherwise). */\n channelId: string;\n /** Balance-proof nonce (strictly increasing per channel). */\n nonce: bigint;\n /** Cumulative transferred amount, target micro-units. */\n cumulativeAmount: bigint;\n /** Recipient address the claim pays (the sender's `chainRecipient`). */\n recipient: string;\n /** Swap peer's on-chain signer address the signature verified against. */\n swapSignerAddress: string;\n /** The verified signed claim bytes (chain-specific encoding). */\n claimBytes: Uint8Array;\n /** Optional swap-side claim id. */\n claimId?: string;\n /** The SwapPair the claim was priced against (settlement-time routing). */\n pair: SwapPair;\n /** Unix ms the winning claim was accepted off the wire. */\n receivedAt: number;\n /** Unix ms this entry was last advanced. */\n updatedAt: number;\n /** Unix ms of the last successful on-chain settlement submission. */\n settledAt?: number;\n /** Watermark nonce redeemed by that settlement (claims ≤ this are settled). */\n settledNonce?: bigint;\n /** Tx hash of the last settlement submission. */\n settleTxHash?: string;\n}\n\n/**\n * Persistence interface for received (chain-B) swap claims. Mirrors\n * {@link ChannelStore}'s sync surface; keyed by `(chain, channelId)`.\n */\nexport interface ReceivedClaimStore {\n save(entry: ReceivedClaimEntry): void;\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined;\n list(): ReceivedClaimEntry[];\n delete(chain: string, channelId: string): void;\n}\n\ninterface JsonEntry {\n chain: string;\n channelId: string;\n /** Stored as strings to preserve bigint precision. */\n nonce: string;\n cumulativeAmount: string;\n recipient: string;\n swapSignerAddress: string;\n /** base64 */\n claimBytes: string;\n claimId?: string;\n pair: SwapPair;\n receivedAt: number;\n updatedAt: number;\n settledAt?: number;\n settledNonce?: string;\n settleTxHash?: string;\n}\n\nfunction key(chain: string, channelId: string): string {\n return `${chain}|${channelId}`;\n}\n\n/**\n * JSON file-backed {@link ReceivedClaimStore}. Synchronous I/O to match the\n * `JsonFileChannelStore` pattern (`ChannelStore.ts`); the parent directory is\n * created on first save so a fresh daemon home works out of the box.\n */\nexport class JsonFileReceivedClaimStore implements ReceivedClaimStore {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n save(entry: ReceivedClaimEntry): void {\n const data = this.readFile();\n data[key(entry.chain, entry.channelId)] = {\n chain: entry.chain,\n channelId: entry.channelId,\n nonce: entry.nonce.toString(),\n cumulativeAmount: entry.cumulativeAmount.toString(),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n claimBytes: Buffer.from(entry.claimBytes).toString('base64'),\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n updatedAt: entry.updatedAt,\n ...(entry.settledAt !== undefined ? { settledAt: entry.settledAt } : {}),\n ...(entry.settledNonce !== undefined\n ? { settledNonce: entry.settledNonce.toString() }\n : {}),\n ...(entry.settleTxHash !== undefined\n ? { settleTxHash: entry.settleTxHash }\n : {}),\n };\n this.writeFile(data);\n }\n\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined {\n const entry = this.readFile()[key(chain, channelId)];\n return entry ? fromJson(entry) : undefined;\n }\n\n list(): ReceivedClaimEntry[] {\n return Object.values(this.readFile()).map(fromJson);\n }\n\n delete(chain: string, channelId: string): void {\n const data = this.readFile();\n const { [key(chain, channelId)]: _, ...rest } = data;\n this.writeFile(rest);\n }\n\n private readFile(): Record<string, JsonEntry> {\n if (!existsSync(this.filePath)) {\n return {};\n }\n const raw = readFileSync(this.filePath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonEntry>;\n }\n\n private writeFile(data: Record<string, JsonEntry>): void {\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');\n }\n}\n\n/**\n * In-memory {@link ReceivedClaimStore} for tests and path-less configs. NOT\n * restart-safe — a daemon should always be given a `JsonFileReceivedClaimStore`.\n */\nexport class InMemoryReceivedClaimStore implements ReceivedClaimStore {\n private readonly entries = new Map<string, ReceivedClaimEntry>();\n\n save(entry: ReceivedClaimEntry): void {\n this.entries.set(key(entry.chain, entry.channelId), { ...entry });\n }\n\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined {\n const entry = this.entries.get(key(chain, channelId));\n return entry ? { ...entry } : undefined;\n }\n\n list(): ReceivedClaimEntry[] {\n return [...this.entries.values()].map((e) => ({ ...e }));\n }\n\n delete(chain: string, channelId: string): void {\n this.entries.delete(key(chain, channelId));\n }\n}\n\nfunction fromJson(entry: JsonEntry): ReceivedClaimEntry {\n return {\n chain: entry.chain,\n channelId: entry.channelId,\n nonce: BigInt(entry.nonce),\n cumulativeAmount: BigInt(entry.cumulativeAmount),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n claimBytes: new Uint8Array(Buffer.from(entry.claimBytes, 'base64')),\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n updatedAt: entry.updatedAt,\n ...(entry.settledAt !== undefined ? { settledAt: entry.settledAt } : {}),\n ...(entry.settledNonce !== undefined\n ? { settledNonce: BigInt(entry.settledNonce) }\n : {}),\n ...(entry.settleTxHash !== undefined\n ? { settleTxHash: entry.settleTxHash }\n : {}),\n };\n}\n","/**\n * Receive-side swap-claim ingestion + verification (toon-client#352, part of\n * the rolling-swap epic toon-meta#145; spec: toon-meta docs/rolling-swap.md\n * §3.2/§9 dependency 1).\n *\n * The deployed client used to accept swapped-in chain-B claims blind: no\n * signature check, no watermark, no persistence — `buildSettlementTx` /\n * `verifyAccumulatedClaim` had zero call sites in this repo. This module is\n * the missing pipeline: every accumulated claim harvested from a swap stream\n * is VERIFIED at receipt time and, only if it passes, persisted as the\n * highest-nonce watermark for its `(chain, channelId)` in a\n * {@link ReceivedClaimStore}. A claim that fails verification is NEVER counted\n * as value received — failures are loud and result-shaped, not thrown.\n *\n * Verification order per claim (cheapest first, every check fail-closed):\n * 1. settlement metadata completeness — a claim missing any of channelId /\n * nonce / cumulativeAmount / recipient / swapSignerAddress cannot be\n * settled (`MISSING_SETTLEMENT_METADATA` later) and is bucketed `legacy`\n * (the pre-rename-peer path, #349) rather than rejected: the existing\n * loud swap-time warning stays the surface for those.\n * 2. chain consistency — the claim must settle on the session's target chain.\n * 3. recipient — must equal the session `chainRecipient` (EVM\n * case-insensitive), the anti-substitution check.\n * 4. advertised signer — when the caller supplies the maker's advertised\n * `swapSignerAddress` (kind:10032 discovery / operator config), the\n * claim's self-reported signer must match (`SWAP_SIGNER_MISMATCH`,\n * sdk 2.x vocabulary).\n * 5. signature — against the expected signer (advertised address when given,\n * else the claim's self-reported one). EVM claims verify against the\n * **v2 EIP-712 domain-separated** balance-proof digest\n * (`verifyEvmClaimSignature`, connector#324 finding #1) — the digest binds\n * `chainId` + `verifyingContract`, so `tokenNetworks[chain]` (the\n * RollingSwapChannel address) and a numeric chain id are REQUIRED (an EVM\n * claim without them is rejected `MISSING_CHAIN_CONFIG`, fail-closed).\n * Solana/Mina keep the sdk `verifyAccumulatedClaim` path (their domain is\n * folded into the message).\n * 6. signer pinning — a claim may not silently rotate the signer of an\n * already-persisted watermark for the same channel.\n * 7. nonce/cumulative monotonicity vs the locally persisted watermark —\n * strictly increasing nonce AND cumulative; the cumulative advance must\n * cover this packet's `targetAmount` (an under-delivering advance means\n * the maker short-paid the packet).\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n verifyAccumulatedClaim,\n type MinaSignerClientLike,\n} from '@toon-protocol/sdk';\nimport type {\n ReceivedClaimEntry,\n ReceivedClaimStore,\n} from '../channel/ReceivedClaimStore.js';\nimport { verifyEvmClaimSignature } from './evm-claim-digest.js';\nimport { parseEvmChainId } from './settle-received-claims.js';\n\n/** Why a claim was rejected at receipt time. Codes are stable API. */\nexport type ReceivedClaimRejectionCode =\n | 'CHAIN_MISMATCH'\n | 'RECIPIENT_MISMATCH'\n | 'SWAP_SIGNER_MISMATCH'\n | 'SIGNER_MISMATCH'\n | 'SIGNATURE_INVALID'\n | 'MINA_VERIFICATION_UNSUPPORTED'\n | 'UNSUPPORTED_CHAIN'\n | 'NON_MONOTONIC_NONCE'\n | 'NON_MONOTONIC_CUMULATIVE'\n | 'CUMULATIVE_SHORTFALL'\n | 'MISSING_CHAIN_CONFIG'\n | 'MALFORMED_METADATA';\n\nexport interface ReceivedClaimRejection {\n claim: AccumulatedClaim;\n code: ReceivedClaimRejectionCode;\n message: string;\n}\n\nexport interface VerifiedReceivedClaim {\n claim: AccumulatedClaim;\n /** How far this claim advanced the persisted cumulative watermark. */\n watermarkAdvance: bigint;\n}\n\nexport interface IngestReceivedClaimsParams {\n /** Accumulated claims off a swap stream (`streamSwap().claims`), in order. */\n claims: readonly AccumulatedClaim[];\n /** The session's target chain (`pair.to.chain` of the requested swap). */\n expectedChain: string;\n /** The session's payout address on `expectedChain`. */\n chainRecipient: string;\n /**\n * The maker's ADVERTISED on-chain signer address for `expectedChain`\n * (kind:10032 discovery or operator-supplied). When set, a claim whose\n * self-reported `swapSignerAddress` differs is rejected with\n * `SWAP_SIGNER_MISMATCH` and the signature is verified against THIS address,\n * never the claim's own.\n */\n expectedSignerAddress?: string;\n /**\n * Per-chain settlement contract addresses (the deployed `RollingSwapChannel`\n * / `verifyingContract`), keyed by the FULL chain key (e.g. `evm:base:8453`).\n * Matches the daemon config's `tokenNetworks` map and what\n * `buildSwapSettlements` already threads on the submit side.\n *\n * REQUIRED for EVM claims under the v2 EIP-712 digest (connector#324 finding\n * #1): the claim signature is domain-separated over `(chainId,\n * verifyingContract)`, so an EVM claim whose chain key lacks a `tokenNetworks`\n * entry (or a numeric chain id) is rejected `MISSING_CHAIN_CONFIG` — it cannot\n * be verified fail-closed without the domain. Supplied by the connector/swap\n * session context (the RollingSwapChannel the client settles against). Unused\n * for Solana/Mina claims, which fold their domain into the message itself.\n */\n tokenNetworks?: Record<string, string>;\n /** Durable watermark store; verified claims are persisted here. */\n store: ReceivedClaimStore;\n /** Pre-loaded `mina-signer` client — required to verify `mina:*` claims. */\n minaSignerClient?: MinaSignerClientLike;\n /** Clock seam for tests. */\n now?: () => number;\n}\n\nexport interface IngestReceivedClaimsResult {\n /** Claims that passed every check and advanced a persisted watermark. */\n verified: VerifiedReceivedClaim[];\n /** Claims that failed verification. NEVER counted as value received. */\n rejected: ReceivedClaimRejection[];\n /**\n * Claims missing settlement metadata (pre-rename / legacy swap peer, #349).\n * Not verified, not persisted, surfaced through the existing swap-time\n * warning — behavior for legacy no-metadata swaps is unchanged.\n */\n legacy: AccumulatedClaim[];\n /** Total watermark advance across verified claims (target micro-units). */\n valueReceived: bigint;\n}\n\n/** True when the claim carries every settlement-context field. */\nexport function hasSettlementMetadata(\n claim: AccumulatedClaim\n): claim is AccumulatedClaim &\n Required<\n Pick<\n AccumulatedClaim,\n | 'channelId'\n | 'nonce'\n | 'cumulativeAmount'\n | 'recipient'\n | 'swapSignerAddress'\n >\n > {\n return (\n claim.channelId !== undefined &&\n claim.nonce !== undefined &&\n claim.cumulativeAmount !== undefined &&\n claim.recipient !== undefined &&\n claim.swapSignerAddress !== undefined\n );\n}\n\n/** EVM addresses compare case-insensitively; other chains byte-exact. */\nfunction sameAddress(chain: string, a: string, b: string): boolean {\n return chain.startsWith('evm')\n ? a.toLowerCase() === b.toLowerCase()\n : a === b;\n}\n\n/** Map a `verifyAccumulatedClaim` reason string onto a stable rejection code. */\nfunction signatureRejectionCode(reason: string): ReceivedClaimRejectionCode {\n if (reason.startsWith('SIGNER_MISMATCH')) return 'SIGNER_MISMATCH';\n if (reason.startsWith('MINA_VERIFICATION_UNSUPPORTED'))\n return 'MINA_VERIFICATION_UNSUPPORTED';\n if (reason.startsWith('UNSUPPORTED_CHAIN')) return 'UNSUPPORTED_CHAIN';\n return 'SIGNATURE_INVALID';\n}\n\n/**\n * Verify a batch of received chain-B claims and persist the winning watermark\n * per `(chain, channelId)`. See the module doc for the check ladder.\n *\n * Result-shaped: never throws on a bad claim — it lands in `rejected` with a\n * stable code, and later claims are still processed (a channel's watermark\n * only advances through claims that verified).\n */\nexport function ingestReceivedClaims(\n params: IngestReceivedClaimsParams\n): IngestReceivedClaimsResult {\n const now = params.now ?? Date.now;\n const verified: VerifiedReceivedClaim[] = [];\n const rejected: ReceivedClaimRejection[] = [];\n const legacy: AccumulatedClaim[] = [];\n let valueReceived = 0n;\n\n // Session-local watermarks layered over the store so a multi-packet stream\n // is checked claim-against-claim without re-reading the file per packet.\n const watermarks = new Map<string, ReceivedClaimEntry>();\n const reject = (\n claim: AccumulatedClaim,\n code: ReceivedClaimRejectionCode,\n message: string\n ): void => {\n rejected.push({ claim, code, message });\n };\n\n for (const claim of params.claims) {\n if (!hasSettlementMetadata(claim)) {\n legacy.push(claim);\n continue;\n }\n const chain = claim.pair.to.chain;\n if (chain !== params.expectedChain) {\n reject(\n claim,\n 'CHAIN_MISMATCH',\n `claim settles on \"${chain}\", session expected \"${params.expectedChain}\"`\n );\n continue;\n }\n if (!sameAddress(chain, claim.recipient, params.chainRecipient)) {\n reject(\n claim,\n 'RECIPIENT_MISMATCH',\n `claim recipient \"${claim.recipient}\" is not the session chainRecipient \"${params.chainRecipient}\"`\n );\n continue;\n }\n if (\n params.expectedSignerAddress !== undefined &&\n !sameAddress(chain, claim.swapSignerAddress, params.expectedSignerAddress)\n ) {\n reject(\n claim,\n 'SWAP_SIGNER_MISMATCH',\n `claim swapSignerAddress \"${claim.swapSignerAddress}\" does not match the maker's advertised signer \"${params.expectedSignerAddress}\"`\n );\n continue;\n }\n const expectedSigner =\n params.expectedSignerAddress ?? claim.swapSignerAddress;\n // Signature check. EVM uses the v2 EIP-712 domain-separated digest\n // (connector#324 finding #1): the digest binds `chainId` +\n // `verifyingContract`, so the recovered signer is only valid for the exact\n // (chain, deployment) the claim settles against — closing cross-chain /\n // cross-deployment replay. Solana/Mina fold their domain into the message\n // itself and stay on the sdk `verifyAccumulatedClaim` path.\n let sig: { valid: true } | { valid: false; reason: string };\n if (chain.startsWith('evm')) {\n const chainId = parseEvmChainId(chain);\n const verifyingContract = params.tokenNetworks?.[chain];\n if (chainId === undefined || !verifyingContract) {\n reject(\n claim,\n 'MISSING_CHAIN_CONFIG',\n `EVM v2 balance-proof verification for ${chain} needs a numeric chain id in the ` +\n `chain key AND tokenNetworks[\"${chain}\"] (the RollingSwapChannel / verifyingContract) ` +\n `to reconstruct the EIP-712 domain; supply it from the connector/swap session context.`\n );\n continue;\n }\n let msgNonce: bigint;\n let msgCumulative: bigint;\n try {\n msgNonce = BigInt(claim.nonce);\n msgCumulative = BigInt(claim.cumulativeAmount);\n } catch {\n reject(\n claim,\n 'MALFORMED_METADATA',\n `nonce \"${claim.nonce}\" / cumulativeAmount \"${claim.cumulativeAmount}\" are not decimal integers`\n );\n continue;\n }\n sig = verifyEvmClaimSignature({\n ctx: { chainId, verifyingContract },\n message: {\n channelId: claim.channelId,\n cumulativeAmount: msgCumulative,\n nonce: msgNonce,\n recipient: claim.recipient,\n },\n signature: claim.claimBytes,\n expectedSigner,\n });\n } else {\n sig = verifyAccumulatedClaim(\n claim,\n { address: expectedSigner },\n params.minaSignerClient\n );\n }\n if (!sig.valid) {\n reject(claim, signatureRejectionCode(sig.reason), sig.reason);\n continue;\n }\n\n let nonce: bigint;\n let cumulativeAmount: bigint;\n try {\n nonce = BigInt(claim.nonce);\n cumulativeAmount = BigInt(claim.cumulativeAmount);\n } catch {\n reject(\n claim,\n 'MALFORMED_METADATA',\n `nonce \"${claim.nonce}\" / cumulativeAmount \"${claim.cumulativeAmount}\" are not decimal integers`\n );\n continue;\n }\n\n const wmKey = `${chain}|${claim.channelId}`;\n const watermark =\n watermarks.get(wmKey) ?? params.store.load(chain, claim.channelId);\n\n if (watermark) {\n if (!sameAddress(chain, watermark.swapSignerAddress, expectedSigner)) {\n reject(\n claim,\n 'SWAP_SIGNER_MISMATCH',\n `channel ${claim.channelId} watermark was signed by \"${watermark.swapSignerAddress}\"; a claim signed by \"${expectedSigner}\" may not rotate it`\n );\n continue;\n }\n if (nonce <= watermark.nonce) {\n reject(\n claim,\n 'NON_MONOTONIC_NONCE',\n `nonce ${nonce} does not advance the persisted watermark nonce ${watermark.nonce} for channel ${claim.channelId}`\n );\n continue;\n }\n if (cumulativeAmount <= watermark.cumulativeAmount) {\n reject(\n claim,\n 'NON_MONOTONIC_CUMULATIVE',\n `cumulativeAmount ${cumulativeAmount} does not advance the persisted watermark ${watermark.cumulativeAmount} for channel ${claim.channelId}`\n );\n continue;\n }\n }\n\n // The watermark advance is the value this claim actually adds. It must\n // cover the packet's expected targetAmount — a smaller advance means the\n // maker short-paid the packet (e.g. re-signed value we already held).\n const advance = cumulativeAmount - (watermark?.cumulativeAmount ?? 0n);\n if (advance < claim.targetAmount) {\n reject(\n claim,\n 'CUMULATIVE_SHORTFALL',\n `cumulative advance ${advance} is less than the packet's targetAmount ${claim.targetAmount} for channel ${claim.channelId}`\n );\n continue;\n }\n\n const entry: ReceivedClaimEntry = {\n chain,\n channelId: claim.channelId,\n nonce,\n cumulativeAmount,\n recipient: claim.recipient,\n swapSignerAddress: expectedSigner,\n claimBytes: claim.claimBytes,\n ...(claim.claimId !== undefined ? { claimId: claim.claimId } : {}),\n pair: claim.pair,\n receivedAt: claim.receivedAt,\n updatedAt: now(),\n // Settlement bookkeeping survives watermark advances.\n ...(watermark?.settledAt !== undefined\n ? { settledAt: watermark.settledAt }\n : {}),\n ...(watermark?.settledNonce !== undefined\n ? { settledNonce: watermark.settledNonce }\n : {}),\n ...(watermark?.settleTxHash !== undefined\n ? { settleTxHash: watermark.settleTxHash }\n : {}),\n };\n params.store.save(entry);\n watermarks.set(wmKey, entry);\n verified.push({ claim, watermarkAdvance: advance });\n valueReceived += advance;\n }\n\n return { verified, rejected, legacy, valueReceived };\n}\n","/**\n * EVM rolling-swap **v2** balance-proof claim digest (EIP-712 domain-separated).\n *\n * Refs connector#324 **finding #1** / connector#325 (canonical spec:\n * `docs/rolling-swap-v2-digest-spec.md`). This is the client's byte-for-byte\n * conformance anchor for the v2 migration.\n *\n * ## Why this exists in the client\n *\n * The v1 digest that shipped in `@toon-protocol/core` `balanceProofHashEvm`\n * (imported transitively by the sdk's `verifyAccumulatedClaim` /\n * `buildSettlementTx`, which is what this repo used to lean on) was\n *\n * keccak256( channelId(32) || cumulativeAmount(32BE)\n * || nonce(32BE) || recipient(20) )\n *\n * — it bound **neither** `chainId` **nor** the settling contract address, so a\n * signer-signed claim redeemed on one (chain, deployment) could be replayed\n * verbatim on another for the same tuple (cross-chain / cross-deployment\n * replay). v2 folds `chainId` **and** `verifyingContract` into the signed\n * preimage via a standard **EIP-712** typed-data domain, so a signature is\n * valid on **exactly one `(chainId, contract)` pair**, and the `version=\"2\"`\n * string makes the cutover fail-closed (a v1 raw-keccak sig can never validate\n * as v2 and vice-versa).\n *\n * ## Lockstep dependency\n *\n * The canonical v2 digest util lives in `@toon-protocol/core`\n * (`balanceProofHashEvm` → EIP-712) + `@toon-protocol/sdk`\n * (`verifyAccumulatedClaim` / `buildSettlementTx`). Those packages migrate in\n * lockstep (connector#324 release order: core/sdk → swap → client). Until a v2\n * core/sdk is published, this module is the client's own v2 digest so the\n * receive-side verify (see {@link file://./received-claims.ts}) is already\n * domain-separated and the golden-vector conformance test\n * (`evm-claim-digest.test.ts`) pins the exact literals from the spec. When the\n * v2 core/sdk ships, the recompute here should delegate to it (or be asserted\n * byte-identical to it) — the golden-vector test stays as the shared fixture.\n *\n * The signer leg (`swap` `EvmPaymentChannelSigner.signBalanceProof`) MUST also\n * move to this same EIP-712 preimage and now REQUIRES `chainId` +\n * `verifyingContract` inputs it did not take before.\n */\n\nimport {\n hashTypedData,\n type Hex,\n type Address,\n type TypedDataDomain,\n} from 'viem';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { keccak_256 } from '@noble/hashes/sha3.js';\nimport { hexToBytes, bytesToHex } from '@noble/hashes/utils.js';\n\n/** EIP-712 domain `name` for the RollingSwapChannel (spec §2.1). */\nexport const ROLLING_SWAP_DOMAIN_NAME = 'RollingSwapChannel' as const;\n/** EIP-712 domain `version` — `\"2\"` is the domain-separated migration. */\nexport const ROLLING_SWAP_DOMAIN_VERSION = '2' as const;\n\n/**\n * `keccak256(\"ClaimBalanceProof(bytes32 channelId,uint256 cumulativeAmount,uint256 nonce,address recipient)\")`.\n * Pinned from the spec; asserted in `evm-claim-digest.test.ts`.\n */\nexport const CLAIM_TYPEHASH =\n '0xa0c8262c1a8615f7674d3af796b14d19672d3634f89c6093502ab35c0afe2d91' as const;\n/**\n * `keccak256(\"CooperativeClose(bytes32 channelId,uint256 cumulativeAmount,uint256 nonce)\")`.\n * Pinned from the spec; asserted in `evm-claim-digest.test.ts`.\n */\nexport const COOP_CLOSE_TYPEHASH =\n '0xa5753389755fea51cd5016d7b02b508ac03f2e822d9a7ee345ec45b36574ff9f' as const;\n\nconst CLAIM_TYPES = {\n ClaimBalanceProof: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'cumulativeAmount', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'recipient', type: 'address' },\n ],\n} as const;\n\nconst COOP_CLOSE_TYPES = {\n CooperativeClose: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'cumulativeAmount', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n ],\n} as const;\n\n/** The two chain-context inputs v2 adds over v1 (the domain binding). */\nexport interface EvmClaimDomainContext {\n /** Settlement chain id (`block.chainid` on-chain). e.g. `8453` for Base. */\n chainId: number;\n /** Deployed `RollingSwapChannel` address (`address(this)` / EIP-712 `verifyingContract`). */\n verifyingContract: string;\n}\n\n/** Fields of the `ClaimBalanceProof` message (the balance-proof claim leg). */\nexport interface EvmClaimMessage {\n /** Channel id, 0x-prefixed 32-byte hex. */\n channelId: string;\n /** Cumulative transferred amount (target micro-units). */\n cumulativeAmount: bigint;\n /** Monotonic balance-proof nonce. */\n nonce: bigint;\n /** Recipient (the claim payout address), 0x-prefixed 20-byte hex. */\n recipient: string;\n}\n\n/** Fields of the `CooperativeClose` message (recipient close-ack leg). */\nexport interface EvmCooperativeCloseMessage {\n channelId: string;\n cumulativeAmount: bigint;\n nonce: bigint;\n}\n\n/**\n * viem validates EIP-712 `address` fields against their checksum; the wire\n * carries non-checksummed hex (e.g. an all-lowercase or all-uppercase\n * recipient). The address BYTES are what EIP-712 encodes, so lowercasing is a\n * no-op on the digest while side-stepping the checksum guard.\n */\nfunction normalizeAddress(addr: string): Address {\n return addr.toLowerCase() as Address;\n}\n\nfunction domainOf(ctx: EvmClaimDomainContext): TypedDataDomain {\n return {\n name: ROLLING_SWAP_DOMAIN_NAME,\n version: ROLLING_SWAP_DOMAIN_VERSION,\n chainId: ctx.chainId,\n verifyingContract: normalizeAddress(ctx.verifyingContract),\n };\n}\n\n/**\n * The v2 EIP-712 claim digest — `keccak256(0x1901 || domainSeparator ||\n * hashStruct(ClaimBalanceProof))` — that the on-chain `updateBalance` verifier\n * (and the swap signer) produce. This is what a received claim's signature must\n * recover against.\n */\nexport function evmClaimDigest(\n ctx: EvmClaimDomainContext,\n message: EvmClaimMessage\n): Hex {\n return hashTypedData({\n domain: domainOf(ctx),\n types: CLAIM_TYPES,\n primaryType: 'ClaimBalanceProof',\n message: {\n channelId: message.channelId as Hex,\n cumulativeAmount: message.cumulativeAmount,\n nonce: message.nonce,\n recipient: normalizeAddress(message.recipient),\n },\n });\n}\n\n/**\n * The v2 EIP-712 cooperative-close digest — same domain as the claim, distinct\n * type hash — that a recipient's close-ack signature must recover against.\n */\nexport function evmCooperativeCloseDigest(\n ctx: EvmClaimDomainContext,\n message: EvmCooperativeCloseMessage\n): Hex {\n return hashTypedData({\n domain: domainOf(ctx),\n types: COOP_CLOSE_TYPES,\n primaryType: 'CooperativeClose',\n message: {\n channelId: message.channelId as Hex,\n cumulativeAmount: message.cumulativeAmount,\n nonce: message.nonce,\n },\n });\n}\n\n/** A 65-byte `r || s || v` signature, as 0x-hex or raw bytes. */\nexport type ClaimSignature = Hex | Uint8Array;\n\n/** Byte length of a raw `r||s||v` signature. */\nconst SIG_BYTES = 65;\n\nfunction signatureToBytes(sig: ClaimSignature): Uint8Array {\n if (typeof sig !== 'string') return sig;\n const hex = sig.startsWith('0x') ? sig.slice(2) : sig;\n return hexToBytes(hex);\n}\n\n/**\n * Recover the EVM address that signed a v2 claim digest. Uses the same\n * `@noble/curves` secp256k1 recovery + keccak address derivation as the sdk's\n * on-chain-matching `recoverEvmSignerAddress`, over the **v2** EIP-712 digest.\n * Enforces the same 65-byte `r||s||v`, `v ∈ {27,28}` envelope the on-chain OZ\n * `ECDSA.recover` accepts (fail-closed on a malformed signature).\n *\n * @returns the recovered address (lowercase 0x-hex).\n * @throws if the signature is not 65 bytes or `v` is not 27/28.\n */\nexport function recoverEvmClaimSigner(\n ctx: EvmClaimDomainContext,\n message: EvmClaimMessage,\n signature: ClaimSignature\n): Address {\n const bytes = signatureToBytes(signature);\n if (bytes.length !== SIG_BYTES) {\n throw new Error(\n `EVM signature must be 65 bytes (r||s||v), got ${bytes.length}`\n );\n }\n const v = bytes[64];\n if (v !== 27 && v !== 28) {\n throw new Error(`EVM signature v must be 27 or 28, got ${v}`);\n }\n const digest = evmClaimDigest(ctx, message).slice(2);\n const recovered = secp256k1.Signature.fromBytes(bytes.slice(0, 64), 'compact')\n .addRecoveryBit(v - 27)\n .recoverPublicKey(hexToBytes(digest));\n const uncompressed = recovered.toBytes(false);\n const addrHash = keccak_256(uncompressed.slice(1));\n return `0x${bytesToHex(addrHash.slice(-20))}` as Address;\n}\n\n/** Result of {@link verifyEvmClaimSignature}. Mirrors the sdk verify shape. */\nexport type EvmClaimVerifyResult =\n | { valid: true; recovered: Address }\n | { valid: false; reason: string };\n\n/**\n * Verify a received EVM balance-proof claim: recover the v2-digest signer and\n * check it equals `expectedSigner` (case-insensitive, per EVM address rules).\n *\n * Result-shaped — never throws; a malformed signature or a mismatch is a\n * `{ valid: false, reason }` so the receive ladder can bucket it fail-closed.\n */\nexport function verifyEvmClaimSignature(params: {\n ctx: EvmClaimDomainContext;\n message: EvmClaimMessage;\n signature: ClaimSignature;\n expectedSigner: string;\n}): EvmClaimVerifyResult {\n let recovered: Address;\n try {\n recovered = recoverEvmClaimSigner(\n params.ctx,\n params.message,\n params.signature\n );\n } catch (err) {\n return {\n valid: false,\n reason: `SIGNATURE_INVALID: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n if (recovered.toLowerCase() !== params.expectedSigner.toLowerCase()) {\n return {\n valid: false,\n reason: `SIGNER_MISMATCH: recovered ${recovered}, expected ${params.expectedSigner}`,\n };\n }\n return { valid: true, recovered };\n}\n","/**\n * Per-packet preimage retention (toon-client#360, rolling-swap epic\n * toon-meta#145 — spec `docs/rolling-swap.md` §3 R1 / §3.2 leg-B reveal).\n *\n * `withSenderConditions` (toon-client#354) mints a fresh 32-byte preimage\n * `P_i` per fill packet, sets `C_i = sha256(P_i)` on the leg-A PREPARE, and —\n * before this module — DISCARDED `P_i`. Leg-B reveal (spec §3.2) is the commit\n * act: the sender reveals `P_i` only AFTER verifying the leg-B claim, so the\n * daemon must retain each `P_i` from mint time until the reveal step consumes\n * it. This is that retention seam.\n *\n * Keyed by `packetIndex` — the 0-indexed position in the swap's packet stream.\n * `packetIndex` is the one identifier shared between the send side (the wrapper\n * mints one condition per `sendSwapPacket` call, which `streamSwap` issues in\n * strictly increasing `packetIndex` order) and the receive side\n * (`AccumulatedClaim.packetIndex`), so it correlates a retained preimage to the\n * claim whose reveal will consume it.\n *\n * Reveal is single-use: {@link PreimageRetentionStore.take} removes the entry\n * so a preimage is never revealed twice (spec R1 — a reused preimage lets an\n * observer of packet *i* fulfill packet *i+1* without the sender's consent).\n *\n * Session-scoped and in-memory by design: a preimage is only meaningful within\n * the swap stream that minted it (a fresh stream mints fresh preimages), and a\n * preimage revealed after a crash would commit leg A for a leg-B claim the\n * restarted daemon can no longer verify. Durability lives on the *watermark*\n * (`ReceivedClaimStore`), not here.\n */\n\n/** A retained per-packet hashlock secret awaiting (or past) its leg-B reveal. */\nexport interface RetainedPreimage {\n /** 0-indexed position in the swap's packet stream; the correlation key. */\n packetIndex: number;\n /** The 32-byte preimage `P_i` — revealed to commit leg A (spec R6). */\n preimage: Uint8Array;\n /** `C_i = sha256(P_i)` — what went on the leg-A PREPARE (kept for auditing). */\n condition: Uint8Array;\n /** Unix ms the preimage was minted/retained. */\n retainedAt: number;\n}\n\n/**\n * Retention interface for per-packet preimages, keyed by `packetIndex`. Mirrors\n * the sync surface of the daemon's other stores ({@link ReceivedClaimStore}).\n */\nexport interface PreimageRetentionStore {\n /** Retain `entry`, replacing any prior entry for the same `packetIndex`. */\n retain(entry: RetainedPreimage): void;\n /** Peek the retained preimage for `packetIndex` without consuming it. */\n get(packetIndex: number): RetainedPreimage | undefined;\n /** Consume (return AND remove) the preimage — single-use reveal (spec R1). */\n take(packetIndex: number): RetainedPreimage | undefined;\n /** Number of preimages still retained (awaiting reveal). */\n size(): number;\n /** Drop every retained preimage — call when the session ends. */\n clear(): void;\n}\n\n/** Defensive copy so a retained preimage cannot be mutated after the fact. */\nfunction copy(entry: RetainedPreimage): RetainedPreimage {\n return {\n packetIndex: entry.packetIndex,\n preimage: Uint8Array.from(entry.preimage),\n condition: Uint8Array.from(entry.condition),\n retainedAt: entry.retainedAt,\n };\n}\n\n/**\n * In-memory {@link PreimageRetentionStore}. The only implementation: preimages\n * are session-scoped secrets that MUST NOT outlive their stream (see the module\n * doc), so there is deliberately no file-backed variant.\n */\nexport class InMemoryPreimageRetentionStore implements PreimageRetentionStore {\n private readonly entries = new Map<number, RetainedPreimage>();\n\n retain(entry: RetainedPreimage): void {\n this.entries.set(entry.packetIndex, copy(entry));\n }\n\n get(packetIndex: number): RetainedPreimage | undefined {\n const entry = this.entries.get(packetIndex);\n return entry ? copy(entry) : undefined;\n }\n\n take(packetIndex: number): RetainedPreimage | undefined {\n const entry = this.entries.get(packetIndex);\n if (!entry) return undefined;\n this.entries.delete(packetIndex);\n return copy(entry);\n }\n\n size(): number {\n return this.entries.size;\n }\n\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Atomic verify -> persist -> reveal composition (toon-client#360, rolling-swap\n * epic toon-meta#145 — spec `docs/rolling-swap.md` §3 R5/R8, §3.2 leg-B reveal).\n *\n * {@link ingestReceivedClaims} (toon-client#358) verifies a received chain-B\n * claim and persists its watermark AT VERIFY TIME. But verification is not the\n * commit: leg-B reveal is (spec R5 — the sender reveals `P_i` only after the\n * claim verifies). A daemon that verifies a claim, advances the watermark, and\n * then WITHHOLDS or FAILS the reveal has advanced a watermark for value it never\n * committed to. Left there, engine rule R8 bites: after the maker rolls its own\n * side back it REUSES the rolled-back nonce for the next fill, and the client's\n * monotonicity check (`nonce <= watermark.nonce -> NON_MONOTONIC_NONCE`) would\n * falsely reject that legitimate re-fill.\n *\n * So verify/persist/reveal must compose as ONE unit whose durable effect is\n * \"watermark advanced iff the reveal committed\":\n *\n * 1. snapshot the prior watermark for the claim's `(chain, channelId)`;\n * 2. verify + persist via {@link ingestReceivedClaims} (single claim);\n * 3. reveal the retained preimage `P_i` for `claim.packetIndex`;\n * 4. on `withheld` / thrown / preimage-missing -> COMPENSATING ROLLBACK:\n * restore the snapshot (or delete when there was none), so the watermark\n * tracks only ACCEPTED/REVEALED packets and R8's reused nonce is accepted.\n *\n * Claims are processed strictly in order and each claim's fate is decided\n * before the next is verified, so cross-claim monotonicity flows through the\n * durable store: a rolled-back claim leaves no trace for the next to trip over.\n * Legacy no-metadata claims (spec §349 path) and hard verification rejects\n * never reach a reveal and never touch a watermark — behavior unchanged.\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n ingestReceivedClaims,\n hasSettlementMetadata,\n type IngestReceivedClaimsParams,\n type ReceivedClaimRejection,\n} from './received-claims.js';\nimport type { ReceivedClaimEntry } from '../channel/ReceivedClaimStore.js';\nimport type {\n PreimageRetentionStore,\n RetainedPreimage,\n} from './preimage-retention.js';\n\n/** The sender's leg-B decision for a verified claim (spec R5). */\nexport type RevealDecision = 'revealed' | 'withheld';\n\nexport interface RevealResult {\n decision: RevealDecision;\n /** Human-readable detail, surfaced on a rolled-back record when withheld. */\n reason?: string;\n}\n\n/**\n * Reveal a verified claim's preimage to commit leg A, OR withhold it. Receives\n * the claim and the retained preimage for its `packetIndex` (`undefined` when\n * none was retained — e.g. a legacy zero-condition packet reaching this path).\n * Returning `withheld`, resolving to no decision, or THROWING all trigger the\n * compensating rollback; only `revealed` keeps the watermark advance.\n */\nexport type RevealFn = (\n claim: AccumulatedClaim,\n preimage: RetainedPreimage | undefined\n) => RevealResult | Promise<RevealResult>;\n\nexport interface IngestAndRevealParams extends IngestReceivedClaimsParams {\n /** Leg-B reveal decision, invoked once per VERIFIED claim (spec R5/R6). */\n reveal: RevealFn;\n /**\n * Retained per-packet preimages ({@link PreimageRetentionStore}). The reveal\n * for a verified claim CONSUMES (`take`) the preimage for its `packetIndex`,\n * so a preimage is never revealed twice (spec R1). Optional: without it the\n * reveal fn receives `undefined` and decides on its own.\n */\n preimages?: PreimageRetentionStore;\n}\n\nexport interface RevealedClaim {\n claim: AccumulatedClaim;\n /** How far the (now committed) watermark advanced. */\n watermarkAdvance: bigint;\n}\n\nexport interface RolledBackClaim {\n claim: AccumulatedClaim;\n /** The advance that was persisted then rolled back (never counted). */\n watermarkAdvance: bigint;\n /** Why the reveal did not commit (withheld reason, or the thrown error). */\n reason: string;\n}\n\nexport interface IngestAndRevealResult {\n /** Claims that verified AND revealed — the only ones whose value counts. */\n revealed: RevealedClaim[];\n /**\n * Claims that verified but whose reveal was withheld/failed: the watermark\n * advance was persisted then ROLLED BACK, so a subsequent re-fill reusing\n * the same nonce (engine R8) is accepted, not falsely rejected.\n */\n rolledBack: RolledBackClaim[];\n /** Claims that failed verification. NEVER revealed, NEVER persisted. */\n rejected: ReceivedClaimRejection[];\n /** Legacy no-metadata claims (spec §349). Unchanged: not verified/revealed. */\n legacy: AccumulatedClaim[];\n /** Total watermark advance across REVEALED claims only. */\n valueRevealed: bigint;\n}\n\n/**\n * Restore the watermark to `prior` (or delete it when the channel had none),\n * compensating a verify-time persist whose reveal did not commit.\n */\nfunction rollbackWatermark(\n store: IngestReceivedClaimsParams['store'],\n chain: string,\n channelId: string,\n prior: ReceivedClaimEntry | undefined\n): void {\n if (prior === undefined) {\n store.delete(chain, channelId);\n } else {\n store.save(prior);\n }\n}\n\n/**\n * Verify, persist, and reveal a batch of received chain-B claims atomically:\n * a verified claim's watermark advance survives iff its reveal commits, and is\n * rolled back otherwise (see the module doc for why R8 needs this).\n *\n * Never throws on a bad claim or a throwing reveal — both land in the result\n * (`rejected` / `rolledBack`) with the durable watermark left consistent.\n */\nexport async function ingestAndReveal(\n params: IngestAndRevealParams\n): Promise<IngestAndRevealResult> {\n const { reveal, preimages, claims, store, ...shared } = params;\n\n const revealed: RevealedClaim[] = [];\n const rolledBack: RolledBackClaim[] = [];\n const rejected: ReceivedClaimRejection[] = [];\n const legacy: AccumulatedClaim[] = [];\n let valueRevealed = 0n;\n\n for (const claim of claims) {\n // Verify + persist this one claim against the CURRENT durable watermark.\n // Single-claim so each claim's fate is sealed (revealed or rolled back)\n // before the next is checked — rollback leaves nothing for the next claim.\n //\n // A metadata-less (legacy) claim has no `(chain, channelId)` — and its\n // `pair.to` may be absent — so only snapshot when metadata is present, and\n // never dereference `pair.to.chain` before that guard.\n const hasMeta = hasSettlementMetadata(claim);\n const chain = hasMeta ? claim.pair.to.chain : undefined;\n const channelId = hasMeta ? claim.channelId : undefined;\n // Snapshot BEFORE persist so a withheld reveal can be compensated exactly.\n const prior =\n chain !== undefined && channelId !== undefined\n ? store.load(chain, channelId)\n : undefined;\n\n const ingest = ingestReceivedClaims({ ...shared, claims: [claim], store });\n\n if (ingest.legacy.length > 0) {\n legacy.push(claim);\n continue;\n }\n const rejection = ingest.rejected[0];\n if (rejection) {\n // Hard verification failure: nothing was persisted, nothing to reveal.\n rejected.push(rejection);\n continue;\n }\n\n const verified = ingest.verified[0];\n // A metadata-carrying claim that went neither legacy nor rejected verified\n // and was persisted, so `verified`, `chain`, and `channelId` are defined.\n // The guard is belt-and-suspenders for the type-checker and future changes.\n if (!verified || chain === undefined || channelId === undefined) continue;\n const advance = verified.watermarkAdvance;\n const preimage = preimages?.take(claim.packetIndex);\n\n let outcome: RevealResult;\n try {\n outcome = await reveal(claim, preimage);\n } catch (err) {\n outcome = {\n decision: 'withheld',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n if (outcome.decision === 'revealed') {\n revealed.push({ claim, watermarkAdvance: advance });\n valueRevealed += advance;\n continue;\n }\n\n // Withheld / failed: compensate the verify-time persist so the watermark\n // reflects only revealed packets (engine R8 — the maker reuses the nonce).\n rollbackWatermark(store, chain, channelId, prior);\n rolledBack.push({\n claim,\n watermarkAdvance: advance,\n reason: outcome.reason ?? 'reveal withheld',\n });\n }\n\n return { revealed, rolledBack, rejected, legacy, valueRevealed };\n}\n","/**\n * Devnet faucet helper.\n *\n * The deployed TOON devnet exposes a faucet that drips the settlement token\n * (USDC) to a given chain address so a client can open payment channels and pay\n * for writes. This helper hits the USDC-ONLY faucet legs — it funds USDC and\n * assumes the wallet already holds enough native gas to transact:\n *\n * EVM `POST {faucetUrl}/api/base-sepolia/request` body `{ address }` → USDC (Base Sepolia mint)\n * Solana `POST {faucetUrl}/api/solana/usdc-request` body `{ address }` → USDC (no SOL leg)\n * Mina `POST {faucetUrl}/api/mina/usdc-request` body `{ address }` → USDC (no MINA leg)\n *\n * Devnet edge (today): `https://faucet.devnet.toonprotocol.dev`.\n *\n * All three chains are live on the deployed faucet — the request shape is\n * identical (`{ address }`); only the path differs. (The EVM leg mints the\n * ungated mock USDC on Base Sepolia and best-effort tops up gas; the Solana and\n * Mina legs are strictly USDC-only and expect the address to already hold gas.)\n */\n\nimport { NetworkError } from './errors.js';\n\n/** Supported faucet chains. */\nexport type FaucetChain = 'evm' | 'solana' | 'mina';\n\n/** Result of a successful faucet drip. */\nexport interface FundWalletResult {\n /** The chain that was funded. */\n chain: FaucetChain;\n /** The funded address (echoed back). */\n address: string;\n /** Raw parsed JSON body from the faucet (shape is faucet-defined). */\n response: unknown;\n}\n\n/** Options for {@link fundWallet}. */\nexport interface FundWalletOptions {\n /** Custom fetch implementation (for testing / custom transports). */\n fetchImpl?: typeof fetch;\n /**\n * Request timeout in milliseconds. Defaults to {@link defaultFaucetTimeout}\n * for the chain (fast 30s for evm/solana, a longer 120s for the slow-settling\n * mina faucet).\n */\n timeout?: number;\n}\n\n/**\n * Default faucet request timeout (ms) for a chain.\n *\n * The EVM (Base Sepolia mint) and Solana USDC legs respond in a few seconds, so\n * 30s is plenty. The Mina USDC leg TRANSFERS the token via an o1js-proven\n * transaction on a chain that settles much more slowly: the drip routinely\n * succeeds server-side but takes well over 30s to answer the HTTP request, so a\n * flat 30s budget makes the client give up on a request that actually worked.\n * Give mina a much longer budget.\n */\nexport function defaultFaucetTimeout(chain: FaucetChain): number {\n return chain === 'mina' ? 120000 : 30000;\n}\n\n/**\n * Map a chain to its USDC-only faucet request path. Each leg funds USDC and\n * assumes the address already holds native gas (the EVM leg still best-effort\n * tops up Base Sepolia ETH, but does not depend on it).\n */\nfunction faucetPath(chain: FaucetChain): string {\n switch (chain) {\n case 'evm':\n return '/api/base-sepolia/request';\n case 'solana':\n return '/api/solana/usdc-request';\n case 'mina':\n return '/api/mina/usdc-request';\n }\n}\n\n/**\n * Drip test funds to `address` on `chain` from the devnet `faucetUrl`.\n *\n * @param faucetUrl - Faucet base URL, e.g. `https://faucet.devnet.toonprotocol.dev`.\n * A trailing `/` is tolerated.\n * @param address - The chain address to fund (EVM 0x address, Solana base58, etc).\n * @param chain - `'evm'` | `'solana'` | `'mina'` (all live on the devnet faucet).\n * @throws {Error} If `faucetUrl` or `address` is missing.\n * @throws {NetworkError} On transport failure or a non-2xx faucet response.\n */\nexport async function fundWallet(\n faucetUrl: string,\n address: string,\n chain: FaucetChain,\n options: FundWalletOptions = {}\n): Promise<FundWalletResult> {\n if (!faucetUrl) {\n throw new Error('fundWallet: faucetUrl is required');\n }\n if (!address) {\n throw new Error('fundWallet: address is required');\n }\n\n const base = faucetUrl.replace(/\\/+$/, '');\n const url = `${base}${faucetPath(chain)}`;\n const fetchImpl = options.fetchImpl ?? fetch;\n const timeout = options.timeout ?? defaultFaucetTimeout(chain);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ address }),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Faucet request timed out after ${timeout}ms (${url})`,\n error\n );\n }\n throw new NetworkError(\n `Faucet request failed (${url}): ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '');\n throw new NetworkError(\n `Faucet responded ${response.status} ${response.statusText}${\n detail ? `: ${detail}` : ''\n } (${url})`\n );\n }\n\n // The faucet returns JSON; tolerate an empty/non-JSON body (some faucets\n // return `204`/plain text on success).\n const body = await response.text().catch(() => '');\n let parsed: unknown = body;\n if (body) {\n try {\n parsed = JSON.parse(body);\n } catch {\n parsed = body;\n }\n }\n\n return { chain, address, response: parsed };\n}\n","import { finalizeEvent } from 'nostr-tools/pure';\nimport { nip19 } from 'nostr-tools';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { SolanaSigner } from '../signing/solana-signer.js';\nimport { MinaSigner } from '../signing/mina-signer.js';\nimport type {\n KeyManagerConfig,\n PasskeyInfo,\n ToonIdentity,\n VaultData,\n} from './types.js';\nimport {\n deriveFullIdentity,\n deriveFromNsec,\n generateMnemonic,\n validateMnemonic,\n} from './KeyDerivation.js';\nimport {\n registerPasskey,\n assertPasskey,\n hashCredentialId,\n isPrfSupported,\n} from './PasskeyAuth.js';\nimport {\n createVault,\n deriveKek,\n deriveKekFromPassword,\n unlockVault,\n addKekToVault,\n removeKekFromVault,\n addRecoveryCodeToVault,\n unlockVaultWithRecoveryCode,\n generateRecoveryCode as generateRecoveryCodeRaw,\n} from './KeyVault.js';\nimport {\n buildBackupEvent,\n publishBackupToRelays,\n fetchBackupFromRelays,\n} from './BackupService.js';\nimport { fromBase64, hexToBytes, bytesToHex } from './encoding.js';\n\n/**\n * KeyManager orchestrates the full key lifecycle:\n * generate, derive, store, backup, recover — gated by WebAuthn Passkeys.\n *\n * Usage:\n * const km = new KeyManager({ relayUrls: ['wss://relay.example'] });\n * const identity = await km.create();\n * // or: const identity = await km.recover();\n *\n * const client = new ToonClient({\n * secretKey: identity.nostr.secretKey,\n * // ...\n * });\n *\n * Security note: JavaScript strings (like mnemonics) are immutable and cannot be\n * zeroed from memory. Uint8Array key material is zeroed on lock(), but mnemonic\n * strings persist until garbage collected. This is a known JS platform limitation.\n */\nexport class KeyManager {\n private readonly config: Required<KeyManagerConfig>;\n private identity: ToonIdentity | null = null;\n private vault: VaultData | null = null;\n private activeCredentialIdHash: string | null = null;\n\n constructor(config: KeyManagerConfig) {\n if (!config.relayUrls || config.relayUrls.length === 0) {\n throw new Error('KeyManager requires at least one relay URL');\n }\n\n this.config = {\n relayUrls: config.relayUrls,\n rpId:\n config.rpId ??\n (typeof window !== 'undefined'\n ? window.location.hostname\n : 'localhost'),\n rpName: config.rpName ?? 'TOON Protocol',\n storageKey: config.storageKey ?? 'toon:keys',\n };\n }\n\n // --- Account Lifecycle ---\n\n /**\n * Create a new account: generate mnemonic, create Passkey, encrypt, backup.\n */\n async create(): Promise<ToonIdentity> {\n const mnemonic = generateMnemonic();\n const identity = await deriveFullIdentity(mnemonic);\n\n // Generate a unique PRF salt for this credential\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n\n // Convert pubkey hex to bytes for userHandle\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n // Register Passkey with PRF\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n // Derive KEK from PRF output\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n // Create encrypted vault\n this.vault = await createVault(mnemonic, kek, credIdHash, prfSalt);\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n // Persist to IndexedDB\n await this.saveToLocalStorage();\n\n // Backup to relay (best-effort)\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal — local vault is still available\n });\n\n return identity;\n }\n\n /**\n * Recover an account using a synced Passkey.\n * The Nostr pubkey is extracted from the Passkey's userHandle.\n *\n * Flow: single assertion → userHandle → fetch backup → derive KEK → unlock.\n * If the local vault is available (has the PRF salt), we use a single assertion\n * with the correct salt. Otherwise, we need the backup from relays first, which\n * requires a discovery assertion to get the pubkey.\n */\n async recover(): Promise<ToonIdentity> {\n // Check local vault first — if available, we can do a single-assertion unlock\n const localVault = await this.loadFromLocalStorage();\n if (localVault) {\n return this.unlockWithVault(localVault);\n }\n\n // No local vault — need to discover pubkey from Passkey userHandle,\n // fetch backup from relays, then do a second assertion with the correct salt.\n // This is the cross-device recovery path (two assertions unavoidable).\n const discovery = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: crypto.getRandomValues(new Uint8Array(32)), // Dummy salt for discovery\n });\n\n if (!discovery.userHandle || discovery.userHandle.length === 0) {\n throw new Error(\n 'Passkey did not return a userHandle. Cannot determine Nostr pubkey for recovery.'\n );\n }\n\n // Extract Nostr pubkey from userHandle\n const pubkey = bytesToHex(discovery.userHandle);\n\n // Fetch backup from relays\n const vault = await fetchBackupFromRelays(pubkey, this.config.relayUrls);\n if (!vault) {\n throw new Error(\n 'No backup found on configured relays for this identity. ' +\n 'Try importing with a mnemonic or nsec instead.'\n );\n }\n\n // Find the matching wrapped key entry for this credential\n const credIdHash = await hashCredentialId(discovery.credentialId);\n const entry = vault.wrappedKeys.find((e) => e.id === credIdHash);\n if (!entry) {\n throw new Error(\n 'This Passkey is not registered with the backup. ' +\n 'Try a different Passkey or use a recovery code.'\n );\n }\n\n // Re-assert with the correct PRF salt from the backup\n const saltBytes = fromBase64(entry.salt);\n const reassertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: saltBytes,\n allowCredentials: [discovery.credentialId],\n });\n\n // Derive KEK and unlock vault\n const kek = await deriveKek(reassertion.prfOutput);\n const mnemonic = await unlockVault(vault, kek, credIdHash);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n // Cache locally for future single-assertion unlocks\n await this.saveToLocalStorage();\n\n return identity;\n }\n\n /**\n * Import an existing BIP-39 mnemonic. Creates a Passkey and backup.\n */\n async importMnemonic(mnemonic: string): Promise<ToonIdentity> {\n if (!validateMnemonic(mnemonic)) {\n throw new Error('Invalid BIP-39 mnemonic phrase');\n }\n\n const identity = await deriveFullIdentity(mnemonic);\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n this.vault = await createVault(mnemonic, kek, credIdHash, prfSalt);\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n\n return identity;\n }\n\n /**\n * Import from an nsec (Nostr-only key).\n * Nostr + EVM are derived; Solana + Mina get fresh keys (not deterministically linked).\n */\n async importNsec(nsec: string): Promise<ToonIdentity> {\n const decoded = nip19.decode(nsec);\n if (decoded.type !== 'nsec') {\n throw new Error('Invalid nsec string');\n }\n const secretKey = decoded.data;\n const identity = deriveFromNsec(secretKey);\n\n if (isPrfSupported()) {\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n try {\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n // For nsec import without mnemonic, we store the hex-encoded secret key\n const hexKey = bytesToHex(secretKey);\n this.vault = await createVault(hexKey, kek, credIdHash, prfSalt);\n this.activeCredentialIdHash = credIdHash;\n\n await this.saveToLocalStorage();\n } catch {\n // PRF may be reported as supported but fail at registration time.\n // Proceed without vault — identity is still usable.\n }\n }\n\n this.identity = identity;\n return identity;\n }\n\n // --- Passkey Management ---\n\n /**\n * Register an additional Passkey for this identity.\n */\n async addPasskey(): Promise<void> {\n if (!this.identity || !this.vault || !this.activeCredentialIdHash) {\n throw new Error('No active identity — call create() or recover() first');\n }\n\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(this.identity.nostr.pubkey);\n\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${this.identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const newKek = await deriveKek(registration.prfOutput);\n const newCredIdHash = await hashCredentialId(registration.credentialId);\n\n // Re-assert the current Passkey to get KEK for unwrapping\n const currentEntry = this.vault.wrappedKeys.find(\n (e) => e.id === this.activeCredentialIdHash\n );\n if (!currentEntry) {\n throw new Error('Active credential not found in vault');\n }\n\n const currentSaltBytes = fromBase64(currentEntry.salt);\n const currentAssertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: currentSaltBytes,\n });\n const currentKek = await deriveKek(currentAssertion.prfOutput);\n\n this.vault = await addKekToVault(\n this.vault,\n currentKek,\n this.activeCredentialIdHash,\n newKek,\n newCredIdHash,\n prfSalt\n );\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n }\n\n /**\n * List registered Passkey credentials.\n */\n listPasskeys(): PasskeyInfo[] {\n if (!this.vault) return [];\n return this.vault.wrappedKeys.map((entry) => ({\n credentialIdHash: entry.id,\n createdAt: entry.created_at,\n }));\n }\n\n /**\n * Remove a Passkey from the vault. Cannot remove the last one.\n */\n async removePasskey(credentialIdHash: string): Promise<void> {\n if (!this.vault) {\n throw new Error('No active vault');\n }\n\n this.vault = removeKekFromVault(this.vault, credentialIdHash);\n\n // If we removed the active credential, switch to another\n if (this.activeCredentialIdHash === credentialIdHash) {\n const remaining = this.vault.wrappedKeys[0];\n this.activeCredentialIdHash = remaining ? remaining.id : null;\n }\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n }\n\n // --- Recovery ---\n\n /**\n * Generate a printable recovery code and add it to the vault.\n * The PBKDF2 salt is persisted alongside the wrapped DEK so the code\n * can be verified later without the original salt.\n *\n * @returns The recovery code — user must store it securely.\n */\n async generateRecoveryCode(): Promise<string> {\n if (!this.vault || !this.activeCredentialIdHash) {\n throw new Error('No active vault');\n }\n\n const code = generateRecoveryCodeRaw();\n\n // Generate and persist PBKDF2 salt for recovery code\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const recoveryKek = await deriveKekFromPassword(code, salt);\n\n // Get current KEK to unwrap DEK\n const currentEntry = this.vault.wrappedKeys.find(\n (e) => e.id === this.activeCredentialIdHash\n );\n if (!currentEntry) {\n throw new Error('Active credential not found in vault');\n }\n\n const currentSaltBytes = fromBase64(currentEntry.salt);\n const currentAssertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: currentSaltBytes,\n });\n const currentKek = await deriveKek(currentAssertion.prfOutput);\n\n this.vault = await addRecoveryCodeToVault(\n this.vault,\n currentKek,\n this.activeCredentialIdHash,\n recoveryKek,\n salt\n );\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n\n return code;\n }\n\n /**\n * Recover identity using a recovery code.\n * The PBKDF2 salt is read from the persisted vault data.\n */\n async recoverWithCode(code: string): Promise<ToonIdentity> {\n const vault = await this.loadFromLocalStorage();\n\n if (!vault) {\n throw new Error(\n 'No local vault found. Recovery code requires the encrypted vault. ' +\n 'If you have a Passkey, use recover() to fetch from relays first.'\n );\n }\n\n if (!vault.recoveryCodeWrappedDek || !vault.recoveryCodeSalt) {\n throw new Error('No recovery code configured for this vault');\n }\n\n // Use the persisted PBKDF2 salt to reproduce the exact KEK\n const salt = fromBase64(vault.recoveryCodeSalt);\n const recoveryKek = await deriveKekFromPassword(code, salt);\n\n const mnemonic = await unlockVaultWithRecoveryCode(vault, recoveryKek);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n\n return identity;\n }\n\n // --- Key Access ---\n\n /**\n * Get the current identity, or null if not unlocked.\n */\n getIdentity(): ToonIdentity | null {\n return this.identity;\n }\n\n /**\n * Get the Nostr secret key. Throws if not unlocked.\n */\n getNostrSecretKey(): Uint8Array {\n if (!this.identity) throw new Error('Identity not unlocked');\n return this.identity.nostr.secretKey;\n }\n\n /**\n * Get an EvmSigner instance. Throws if not unlocked.\n */\n getEvmSigner(): EvmSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n return new EvmSigner(this.identity.evm.privateKey);\n }\n\n /**\n * Get a SolanaSigner instance. Throws if not unlocked or Solana not derived.\n */\n getSolanaSigner(): SolanaSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n if (!this.identity.solana.publicKey) {\n throw new Error(\n 'Solana keys not available — was this imported from nsec?'\n );\n }\n return new SolanaSigner(this.identity.solana.secretKey);\n }\n\n /**\n * Get a MinaSigner instance. Throws if not unlocked or Mina not derived.\n */\n getMinaSigner(): MinaSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n if (!this.identity.mina.publicKey) {\n throw new Error('Mina keys not available — was this imported from nsec?');\n }\n return new MinaSigner(this.identity.mina.privateKey);\n }\n\n // --- Backup ---\n\n /**\n * Publish the current vault to configured relays as a kind:30078 event.\n */\n async backupToRelay(): Promise<void> {\n if (!this.identity || !this.vault) {\n throw new Error('No active identity or vault to backup');\n }\n\n const eventTemplate = buildBackupEvent(\n this.vault,\n this.identity.nostr.secretKey\n );\n\n // Sign with nostr-tools\n const signedEvent = finalizeEvent(\n eventTemplate,\n this.identity.nostr.secretKey\n );\n\n await publishBackupToRelays(signedEvent, this.config.relayUrls);\n }\n\n // --- Lock/Unlock ---\n\n /**\n * Clear keys from memory. The vault remains in IndexedDB.\n * Note: JavaScript strings (mnemonics) cannot be zeroed — only Uint8Array keys are cleared.\n */\n lock(): void {\n if (this.identity) {\n // Zero out sensitive Uint8Array key material\n this.identity.nostr.secretKey.fill(0);\n // evm.privateKey may be the same reference as nostr.secretKey — fill is idempotent\n this.identity.evm.privateKey.fill(0);\n this.identity.solana.secretKey.fill(0);\n }\n this.identity = null;\n }\n\n /**\n * Re-assert Passkey to decrypt local vault and restore identity.\n * Uses the local vault's stored PRF salt for a single biometric prompt.\n */\n async unlock(): Promise<ToonIdentity> {\n const vault = await this.loadFromLocalStorage();\n if (!vault) {\n throw new Error('No local vault found — use create() or recover()');\n }\n\n return this.unlockWithVault(vault);\n }\n\n // --- Private helpers ---\n\n /**\n * Unlock a vault with a single Passkey assertion using stored PRF salts.\n * If the vault has only one credential, uses allowCredentials to constrain.\n */\n private async unlockWithVault(vault: VaultData): Promise<ToonIdentity> {\n // We don't have the raw credential IDs (only hashes), so we can't constrain\n // allowCredentials. The user picks a credential, then we verify it matches.\n const firstEntry = vault.wrappedKeys[0];\n if (!firstEntry) {\n throw new Error('Vault has no registered credentials');\n }\n\n const assertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: fromBase64(firstEntry.salt),\n });\n\n const credIdHash = await hashCredentialId(assertion.credentialId);\n const matchingEntry = vault.wrappedKeys.find((e) => e.id === credIdHash);\n\n if (!matchingEntry) {\n throw new Error('This Passkey is not registered with the local vault');\n }\n\n // If the user picked the first credential, we already have the correct PRF output.\n // If they picked a different one, we need to re-assert with the correct salt.\n let prfOutput = assertion.prfOutput;\n if (matchingEntry.id !== firstEntry.id) {\n const correctSalt = fromBase64(matchingEntry.salt);\n const reassertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: correctSalt,\n allowCredentials: [assertion.credentialId],\n });\n prfOutput = reassertion.prfOutput;\n }\n\n const kek = await deriveKek(prfOutput);\n const mnemonic = await unlockVault(vault, kek, credIdHash);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n return identity;\n }\n\n // --- IndexedDB Persistence ---\n\n private async saveToLocalStorage(): Promise<void> {\n if (!this.vault) return;\n if (typeof indexedDB === 'undefined') return;\n\n const dbName = this.config.storageKey;\n const db = await openDb(dbName);\n const tx = db.transaction('vault', 'readwrite');\n const store = tx.objectStore('vault');\n store.put(JSON.stringify(this.vault), 'current');\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n db.close();\n }\n\n private async loadFromLocalStorage(): Promise<VaultData | null> {\n if (typeof indexedDB === 'undefined') return null;\n\n const dbName = this.config.storageKey;\n try {\n const db = await openDb(dbName);\n const tx = db.transaction('vault', 'readonly');\n const store = tx.objectStore('vault');\n const request = store.get('current');\n const result = await new Promise<string | undefined>(\n (resolve, reject) => {\n request.onsuccess = () =>\n resolve(request.result as string | undefined);\n request.onerror = () => reject(request.error);\n }\n );\n db.close();\n if (!result) return null;\n return JSON.parse(result) as VaultData;\n } catch {\n return null;\n }\n }\n}\n\n// --- Helpers ---\n\nfunction openDb(name: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, 1);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains('vault')) {\n db.createObjectStore('vault');\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n","import type {\n PasskeyAssertionResult,\n PasskeyRegistrationResult,\n} from './types.js';\n\n/**\n * WebAuthn Passkey authentication with PRF extension for key encryption.\n *\n * Handles credential registration (create) and assertion (get) with the\n * prf extension to derive a deterministic secret from the authenticator.\n * When PRF is unavailable, callers should fall back to password-based KEK.\n */\n\n/**\n * Register a new Passkey credential with PRF extension.\n *\n * @param rpId - Relying party identifier (e.g., \"example.com\")\n * @param rpName - Human-readable relying party name\n * @param userId - Raw user ID bytes (Nostr pubkey, 32 bytes)\n * @param userName - Display name for the credential\n * @param prfSalt - Random salt for the PRF evaluation\n * @returns Registration result with PRF output and credential ID\n */\nexport async function registerPasskey(params: {\n rpId: string;\n rpName: string;\n userId: Uint8Array;\n userName: string;\n prfSalt: Uint8Array;\n}): Promise<PasskeyRegistrationResult> {\n const { rpId, rpName, userId, userName, prfSalt } = params;\n\n const publicKeyOptions: PublicKeyCredentialCreationOptions = {\n rp: { id: rpId, name: rpName },\n user: {\n id: userId as unknown as BufferSource,\n name: userName,\n displayName: userName,\n },\n challenge: crypto.getRandomValues(\n new Uint8Array(32)\n ) as unknown as BufferSource,\n pubKeyCredParams: [\n { alg: -7, type: 'public-key' }, // ES256\n { alg: -257, type: 'public-key' }, // RS256\n ],\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'required',\n },\n extensions: {\n prf: {\n eval: {\n first: prfSalt as unknown as BufferSource,\n },\n },\n } as AuthenticationExtensionsClientInputs,\n };\n\n const credential = (await navigator.credentials.create({\n publicKey: publicKeyOptions,\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('Passkey registration was cancelled or failed');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const extensionResults = credential.getClientExtensionResults();\n\n const prfResults = (extensionResults as Record<string, unknown>)['prf'] as\n | { enabled?: boolean; results?: { first: ArrayBuffer } }\n | undefined;\n\n if (!prfResults?.results?.first) {\n throw new Error(\n 'PRF extension not supported by this authenticator. ' +\n 'Passkey was created but cannot be used for key encryption. ' +\n 'Use password-based encryption as fallback.'\n );\n }\n\n const credentialId = new Uint8Array(credential.rawId);\n\n // Verify attestation response is valid\n if (!response.attestationObject) {\n throw new Error('Invalid attestation response');\n }\n\n return {\n prfOutput: prfResults.results.first,\n credentialId,\n };\n}\n\n/**\n * Assert an existing Passkey credential with PRF extension.\n *\n * @param rpId - Relying party identifier\n * @param prfSalt - The same salt used during registration for this credential\n * @param allowCredentials - Optional list of credential IDs to filter\n * @returns Assertion result with PRF output, credential ID, and userHandle\n */\nexport async function assertPasskey(params: {\n rpId: string;\n prfSalt: Uint8Array;\n allowCredentials?: Uint8Array[];\n}): Promise<PasskeyAssertionResult> {\n const { rpId, prfSalt, allowCredentials } = params;\n\n const publicKeyOptions = {\n rpId,\n challenge: crypto.getRandomValues(\n new Uint8Array(32)\n ) as unknown as BufferSource,\n userVerification: 'required' as const,\n ...(allowCredentials && {\n allowCredentials: allowCredentials.map((id) => ({\n id: id as unknown as BufferSource,\n type: 'public-key' as const,\n })),\n }),\n extensions: {\n prf: {\n eval: {\n first: prfSalt as unknown as BufferSource,\n },\n },\n } as AuthenticationExtensionsClientInputs,\n } as PublicKeyCredentialRequestOptions;\n\n const credential = (await navigator.credentials.get({\n publicKey: publicKeyOptions,\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('Passkey assertion was cancelled or failed');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n const extensionResults = credential.getClientExtensionResults();\n\n const prfResults = (extensionResults as Record<string, unknown>)['prf'] as\n | { results?: { first: ArrayBuffer } }\n | undefined;\n\n if (!prfResults?.results?.first) {\n throw new Error(\n 'PRF extension did not return a result. ' +\n 'The authenticator may not support PRF.'\n );\n }\n\n return {\n prfOutput: prfResults.results.first,\n credentialId: new Uint8Array(credential.rawId),\n userHandle: response.userHandle\n ? new Uint8Array(response.userHandle)\n : null,\n };\n}\n\n/**\n * Check whether the current browser supports WebAuthn with PRF extension.\n * Returns false in Node.js or browsers without PublicKeyCredential.\n */\nexport function isPrfSupported(): boolean {\n if (typeof window === 'undefined') return false;\n if (typeof navigator === 'undefined') return false;\n if (!navigator.credentials) return false;\n if (typeof PublicKeyCredential === 'undefined') return false;\n // PRF support cannot be feature-detected without actually creating a credential,\n // so we return true if WebAuthn is available and let registration handle the error.\n return true;\n}\n\n/**\n * Compute SHA-256 hash of a credential ID for use as a lookup key.\n */\nexport async function hashCredentialId(\n credentialId: Uint8Array\n): Promise<string> {\n const arrayBuffer = credentialId.buffer.slice(\n credentialId.byteOffset,\n credentialId.byteOffset + credentialId.byteLength\n ) as ArrayBuffer;\n const hash = await crypto.subtle.digest('SHA-256', arrayBuffer);\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","/**\n * Browser-safe Base64 encoding/decoding utilities.\n * Accepts Uint8Array directly to avoid TypedArray .buffer offset issues.\n */\n\nexport function toBase64(data: Uint8Array | ArrayBuffer): string {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n let binary = '';\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary);\n}\n\nexport function fromBase64(b64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import type { VaultData, WrappedKeyEntry } from './types.js';\nimport { toBase64, fromBase64 } from './encoding.js';\n\n/**\n * Envelope encryption for mnemonic storage.\n *\n * Pattern: DEK encrypts mnemonic, KEK wraps DEK.\n * Multiple KEKs (Passkeys, recovery codes) can each wrap the same DEK independently.\n *\n * - DEK: random 256-bit AES key (Data Encryption Key)\n * - KEK: derived from Passkey PRF or recovery code (Key Encryption Key)\n * - Mnemonic encrypted with AES-256-GCM using DEK\n * - DEK wrapped with AES-KW using KEK\n */\n\n// --- DEK operations ---\n\n/**\n * Generate a random 256-bit Data Encryption Key.\n */\nexport async function generateDek(): Promise<CryptoKey> {\n return crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n true, // extractable — needed for AES-KW wrapping\n ['encrypt', 'decrypt']\n );\n}\n\n/**\n * Encrypt a mnemonic string with a DEK using AES-256-GCM.\n * @returns Base64-encoded ciphertext and IV\n */\nexport async function encryptMnemonic(\n dek: CryptoKey,\n mnemonic: string\n): Promise<{ encryptedMnemonic: string; iv: string }> {\n const encoder = new TextEncoder();\n const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit GCM nonce\n const ciphertext = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n dek,\n encoder.encode(mnemonic)\n );\n return {\n encryptedMnemonic: toBase64(ciphertext),\n iv: toBase64(iv),\n };\n}\n\n/**\n * Decrypt a mnemonic from its encrypted form using a DEK.\n */\nexport async function decryptMnemonic(\n dek: CryptoKey,\n encryptedMnemonic: string,\n iv: string\n): Promise<string> {\n const decoder = new TextDecoder();\n const plaintext = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: fromBase64(iv) },\n dek,\n fromBase64(encryptedMnemonic)\n );\n return decoder.decode(plaintext);\n}\n\n// --- KEK operations ---\n\n/**\n * Derive a KEK from a Passkey PRF output using HKDF.\n *\n * Flow: PRF(CredRandom, salt) → HKDF-SHA-256 → 256-bit AES-KW key\n */\nexport async function deriveKek(prfOutput: ArrayBuffer): Promise<CryptoKey> {\n // Import PRF output as HKDF key material\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n prfOutput,\n 'HKDF',\n false,\n ['deriveKey']\n );\n\n const encoder = new TextEncoder();\n return crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new Uint8Array(0), // PRF salt was already applied at the WebAuthn level\n info: encoder.encode('toon:kek'),\n },\n keyMaterial,\n { name: 'AES-KW', length: 256 },\n false, // not extractable\n ['wrapKey', 'unwrapKey']\n );\n}\n\n/**\n * Derive a KEK from a password string using PBKDF2.\n * Used as fallback when PRF is not available, or for recovery codes.\n */\nexport async function deriveKekFromPassword(\n password: string,\n salt: Uint8Array<ArrayBuffer>\n): Promise<CryptoKey> {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(password),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n hash: 'SHA-256',\n salt,\n iterations: 600_000, // OWASP 2023 recommendation for SHA-256\n },\n keyMaterial,\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey']\n );\n}\n\n// --- Wrap/Unwrap DEK ---\n\n/**\n * Wrap (encrypt) a DEK with a KEK using AES-KW.\n * @returns Base64-encoded wrapped DEK\n */\nexport async function wrapDek(kek: CryptoKey, dek: CryptoKey): Promise<string> {\n const wrapped = await crypto.subtle.wrapKey('raw', dek, kek, 'AES-KW');\n return toBase64(new Uint8Array(wrapped));\n}\n\n/**\n * Unwrap (decrypt) a DEK from its wrapped form using a KEK.\n * @returns The unwrapped DEK as a CryptoKey\n */\nexport async function unwrapDek(\n kek: CryptoKey,\n wrappedDek: string\n): Promise<CryptoKey> {\n return crypto.subtle.unwrapKey(\n 'raw',\n fromBase64(wrappedDek),\n kek,\n 'AES-KW',\n { name: 'AES-GCM', length: 256 },\n true, // extractable — needed for re-wrapping when adding new KEKs\n ['encrypt', 'decrypt']\n );\n}\n\n// --- High-level vault operations ---\n\n/**\n * Create a new vault: generate DEK, encrypt mnemonic, wrap DEK with initial KEK.\n */\nexport async function createVault(\n mnemonic: string,\n kek: CryptoKey,\n credentialIdHash: string,\n prfSalt: Uint8Array\n): Promise<VaultData> {\n const dek = await generateDek();\n const { encryptedMnemonic, iv } = await encryptMnemonic(dek, mnemonic);\n const wrappedDek = await wrapDek(kek, dek);\n\n const entry: WrappedKeyEntry = {\n id: credentialIdHash,\n wrapped_dek: wrappedDek,\n salt: toBase64(prfSalt),\n created_at: Math.floor(Date.now() / 1000),\n };\n\n return {\n encryptedMnemonic,\n iv,\n wrappedKeys: [entry],\n };\n}\n\n/**\n * Unlock a vault: unwrap DEK with KEK, decrypt mnemonic.\n */\nexport async function unlockVault(\n vault: VaultData,\n kek: CryptoKey,\n credentialIdHash: string\n): Promise<string> {\n const entry = vault.wrappedKeys.find((e) => e.id === credentialIdHash);\n if (!entry) {\n throw new Error(`No wrapped key found for credential ${credentialIdHash}`);\n }\n\n const dek = await unwrapDek(kek, entry.wrapped_dek);\n return decryptMnemonic(dek, vault.encryptedMnemonic, vault.iv);\n}\n\n/**\n * Add a new KEK (from a new Passkey or recovery code) to an existing vault.\n * Requires an existing KEK to unwrap the DEK first.\n */\nexport async function addKekToVault(\n vault: VaultData,\n existingKek: CryptoKey,\n existingCredentialIdHash: string,\n newKek: CryptoKey,\n newCredentialIdHash: string,\n newPrfSalt: Uint8Array\n): Promise<VaultData> {\n // Unwrap DEK with existing KEK\n const existingEntry = vault.wrappedKeys.find(\n (e) => e.id === existingCredentialIdHash\n );\n if (!existingEntry) {\n throw new Error(\n `No wrapped key found for credential ${existingCredentialIdHash}`\n );\n }\n const dek = await unwrapDek(existingKek, existingEntry.wrapped_dek);\n\n // Wrap DEK with new KEK\n const newWrappedDek = await wrapDek(newKek, dek);\n\n const newEntry: WrappedKeyEntry = {\n id: newCredentialIdHash,\n wrapped_dek: newWrappedDek,\n salt: toBase64(newPrfSalt),\n created_at: Math.floor(Date.now() / 1000),\n };\n\n return {\n ...vault,\n wrappedKeys: [...vault.wrappedKeys, newEntry],\n };\n}\n\n/**\n * Remove a KEK from a vault. Always requires at least one passkey KEK to remain.\n */\nexport function removeKekFromVault(\n vault: VaultData,\n credentialIdHash: string\n): VaultData {\n const remaining = vault.wrappedKeys.filter((e) => e.id !== credentialIdHash);\n\n if (remaining.length === 0) {\n throw new Error(\n 'Cannot remove the last passkey — at least one passkey must remain for vault access'\n );\n }\n\n return {\n ...vault,\n wrappedKeys: remaining,\n };\n}\n\n/**\n * Add a recovery code KEK to the vault.\n * The PBKDF2 salt is persisted in the vault so recoverWithCode can reproduce the KEK.\n */\nexport async function addRecoveryCodeToVault(\n vault: VaultData,\n existingKek: CryptoKey,\n existingCredentialIdHash: string,\n recoveryKek: CryptoKey,\n recoverySalt: Uint8Array\n): Promise<VaultData> {\n const existingEntry = vault.wrappedKeys.find(\n (e) => e.id === existingCredentialIdHash\n );\n if (!existingEntry) {\n throw new Error(\n `No wrapped key found for credential ${existingCredentialIdHash}`\n );\n }\n const dek = await unwrapDek(existingKek, existingEntry.wrapped_dek);\n const recoveryWrappedDek = await wrapDek(recoveryKek, dek);\n\n return {\n ...vault,\n recoveryCodeWrappedDek: recoveryWrappedDek,\n recoveryCodeSalt: toBase64(recoverySalt),\n };\n}\n\n/**\n * Unlock a vault using a recovery code.\n */\nexport async function unlockVaultWithRecoveryCode(\n vault: VaultData,\n recoveryKek: CryptoKey\n): Promise<string> {\n if (!vault.recoveryCodeWrappedDek) {\n throw new Error('No recovery code is configured for this vault');\n }\n\n const dek = await unwrapDek(recoveryKek, vault.recoveryCodeWrappedDek);\n return decryptMnemonic(dek, vault.encryptedMnemonic, vault.iv);\n}\n\n/**\n * Generate a human-readable recovery code (24 random hex chars with dashes).\n * Format: XXXX-XXXX-XXXX-XXXX-XXXX-XXXX (easy to write down).\n */\nexport function generateRecoveryCode(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(12));\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n const groups = hex.match(/.{4}/g) ?? [];\n return groups.join('-');\n}\n","import { getPublicKey } from 'nostr-tools/pure';\nimport type { BackupPayload, VaultData } from './types.js';\n\n/**\n * Relay-based encrypted backup service using kind:30078 (NIP-78 application-specific data).\n *\n * The backup event is a replaceable event keyed by `d: \"toon:identity-backup\"`.\n * Content is an encrypted payload — the relay cannot read the mnemonic.\n */\n\nconst BACKUP_KIND = 30078;\nconst BACKUP_D_TAG = 'toon:identity-backup';\nconst BACKUP_VERSION = '1';\n\n/**\n * Build a kind:30078 Nostr event for identity backup.\n * The event must be signed by the caller before publishing.\n *\n * @param vault - The encrypted vault data\n * @param secretKey - Nostr secret key for signing\n * @param chains - Comma-separated list of supported chains\n * @returns Unsigned Nostr event template\n */\nexport function buildBackupEvent(\n vault: VaultData,\n secretKey: Uint8Array,\n chains = 'nostr,evm,solana,mina'\n): {\n kind: number;\n pubkey: string;\n created_at: number;\n tags: string[][];\n content: string;\n} {\n const pubkey = getPublicKey(secretKey);\n\n const payload: BackupPayload = {\n encrypted_mnemonic: vault.encryptedMnemonic,\n wrapped_keys: vault.wrappedKeys,\n iv: vault.iv,\n ...(vault.recoveryCodeWrappedDek && {\n recovery_code_wrapped_dek: vault.recoveryCodeWrappedDek,\n }),\n ...(vault.recoveryCodeSalt && {\n recovery_code_salt: vault.recoveryCodeSalt,\n }),\n };\n\n return {\n kind: BACKUP_KIND,\n pubkey,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['d', BACKUP_D_TAG],\n ['v', BACKUP_VERSION],\n ['chains', chains],\n ],\n content: JSON.stringify(payload),\n };\n}\n\n/**\n * Build a relay filter to fetch the identity backup for a given pubkey.\n */\nexport function buildBackupFilter(pubkey: string): {\n kinds: number[];\n authors: string[];\n '#d': string[];\n} {\n return {\n kinds: [BACKUP_KIND],\n authors: [pubkey],\n '#d': [BACKUP_D_TAG],\n };\n}\n\n/**\n * Parse a backup event's content into VaultData.\n * Validates the structure before returning.\n */\nexport function parseBackupPayload(content: string): VaultData {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n throw new Error('Invalid backup event content: not valid JSON');\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Invalid backup event content: not an object');\n }\n\n const payload = parsed as Record<string, unknown>;\n\n if (typeof payload['encrypted_mnemonic'] !== 'string') {\n throw new Error('Invalid backup: missing encrypted_mnemonic');\n }\n if (typeof payload['iv'] !== 'string') {\n throw new Error('Invalid backup: missing iv');\n }\n if (!Array.isArray(payload['wrapped_keys'])) {\n throw new Error('Invalid backup: missing wrapped_keys array');\n }\n\n // Validate each wrapped key entry\n for (const entry of payload['wrapped_keys']) {\n if (typeof entry !== 'object' || entry === null) {\n throw new Error('Invalid backup: wrapped_keys entry is not an object');\n }\n const e = entry as Record<string, unknown>;\n if (typeof e['id'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing id');\n }\n if (typeof e['wrapped_dek'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing wrapped_dek');\n }\n if (typeof e['salt'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing salt');\n }\n if (typeof e['created_at'] !== 'number') {\n throw new Error(\n 'Invalid backup: wrapped key missing or invalid created_at'\n );\n }\n }\n\n return {\n encryptedMnemonic: payload['encrypted_mnemonic'] as string,\n iv: payload['iv'] as string,\n wrappedKeys: payload['wrapped_keys'] as VaultData['wrappedKeys'],\n ...(typeof payload['recovery_code_wrapped_dek'] === 'string' && {\n recoveryCodeWrappedDek: payload['recovery_code_wrapped_dek'],\n }),\n ...(typeof payload['recovery_code_salt'] === 'string' && {\n recoveryCodeSalt: payload['recovery_code_salt'],\n }),\n };\n}\n\n/**\n * Publish a backup event to one or more relays.\n *\n * Uses the SimplePool from nostr-tools for relay communication.\n * The event must be signed before calling this function.\n */\nexport async function publishBackupToRelays(\n signedEvent: {\n id: string;\n kind: number;\n pubkey: string;\n created_at: number;\n tags: string[][];\n content: string;\n sig: string;\n },\n relayUrls: string[]\n): Promise<void> {\n // Dynamic import to avoid pulling nostr-tools/pool into non-browser bundles\n const { SimplePool } = await import('nostr-tools/pool');\n const pool = new SimplePool();\n\n try {\n await Promise.allSettled(\n relayUrls.map((url) => pool.publish([url], signedEvent))\n );\n } finally {\n pool.close(relayUrls);\n }\n}\n\n/**\n * Fetch a backup event from relays for a given pubkey.\n * Returns the most recent backup event, or null if none found.\n */\nexport async function fetchBackupFromRelays(\n pubkey: string,\n relayUrls: string[]\n): Promise<VaultData | null> {\n const { SimplePool } = await import('nostr-tools/pool');\n const pool = new SimplePool();\n\n try {\n const filter = buildBackupFilter(pubkey);\n const events = await pool.querySync(relayUrls, filter);\n\n if (!events || events.length === 0) {\n return null;\n }\n\n // Sort by created_at descending, take most recent\n events.sort(\n (a: { created_at: number }, b: { created_at: number }) =>\n b.created_at - a.created_at\n );\n\n const latest = events[0];\n if (!latest) return null;\n return parseBackupPayload(latest.content);\n } finally {\n pool.close(relayUrls);\n }\n}\n","/**\n * Node-only encrypted mnemonic keystore for @toon-protocol/client.\n *\n * Mirrors the relay node wallet crypto (`packages/relay/src/wallet/\n * crypto.ts`): a BIP-39 mnemonic is encrypted at rest with scrypt (KDF) +\n * AES-256-GCM (authenticated encryption), serialized as JSON, and written to\n * disk with mode 0o600. Decryption requires the operator password; a wrong\n * password fails the GCM auth-tag verification and throws.\n *\n * This is the Node-side counterpart to the browser Passkey/IndexedDB\n * `KeyManager`/`KeyVault` flow — it does NOT touch those. It is guarded against\n * browser bundling: every entry point throws if `node:crypto`/`node:fs` are not\n * available (e.g. when accidentally imported in a browser bundle).\n *\n * @module\n */\n\nimport {\n scryptSync,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'node:crypto';\nimport { writeFileSync, readFileSync } from 'node:fs';\nimport {\n generateMnemonic as genMnemonic,\n validateMnemonic as isValidMnemonic,\n} from './KeyDerivation.js';\n\n/** scrypt parameters — N=2^17 (~0.5-1s on modern hardware), r=8, p=1. */\nconst SCRYPT_N = 2 ** 17;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SCRYPT_KEY_LEN = 32;\n/** maxmem for scrypt: N * r * 128 * 2 (with headroom for Node.js overhead). */\nconst SCRYPT_MAXMEM = SCRYPT_N * SCRYPT_R * 256 + 32 * 1024 * 1024;\n\n/** Salt length in bytes. */\nconst SALT_LEN = 32;\n/** AES-GCM IV length in bytes. */\nconst IV_LEN = 12;\n/** AES-GCM authentication tag length in bytes (128-bit). */\nconst AUTH_TAG_LEN = 16;\n\n/**\n * Encrypted keystore file format (JSON, all binary fields base64-encoded).\n * Wire-compatible with the relay node's `EncryptedWallet`.\n */\nexport interface EncryptedKeystore {\n /** scrypt salt (base64). */\n salt: string;\n /** AES-GCM initialization vector (base64). */\n iv: string;\n /** AES-256-GCM ciphertext (base64). */\n ciphertext: string;\n /** AES-GCM authentication tag (base64). */\n tag: string;\n /** Envelope version for forward-compat (currently 1). */\n version?: number;\n}\n\n/**\n * Throws if this module is running outside Node.js. The scrypt/AES-256-GCM\n * primitives and the 0o600 file write are Node-only — there is no browser\n * equivalent of `node:crypto`'s `scryptSync` or POSIX file modes, so we fail\n * loudly rather than silently bundling broken code into a browser build.\n */\nfunction assertNode(): void {\n // `process.versions.node` is present in Node and absent in browsers.\n const versions = (\n globalThis as { process?: { versions?: { node?: string } } }\n ).process?.versions;\n if (!versions?.node) {\n throw new Error(\n 'keystore-node is Node.js-only and cannot run in a browser. ' +\n 'Use the Passkey/IndexedDB KeyManager for browser key storage.'\n );\n }\n}\n\n/**\n * Encrypt a mnemonic with a password using scrypt + AES-256-GCM.\n * Returns the JSON-serializable encrypted envelope (does NOT write to disk).\n */\nexport function encryptMnemonic(\n mnemonic: string,\n password: string\n): EncryptedKeystore {\n assertNode();\n if (typeof mnemonic !== 'string' || mnemonic.length === 0) {\n throw new Error('encryptMnemonic: mnemonic must be a non-empty string');\n }\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('encryptMnemonic: password must be a non-empty string');\n }\n\n const salt = randomBytes(SALT_LEN);\n const iv = randomBytes(IV_LEN);\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const cipher = createCipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n const ciphertext = Buffer.concat([\n cipher.update(mnemonic, 'utf8'),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n\n return {\n salt: salt.toString('base64'),\n iv: iv.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n tag: tag.toString('base64'),\n version: 1,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Decrypt an encrypted keystore envelope with a password.\n * Throws on a wrong password (GCM auth-tag verification failure) or corruption.\n */\nexport function decryptMnemonic(\n encrypted: EncryptedKeystore,\n password: string\n): string {\n assertNode();\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('decryptMnemonic: password must be a non-empty string');\n }\n if (\n !encrypted ||\n typeof encrypted.salt !== 'string' ||\n typeof encrypted.iv !== 'string' ||\n typeof encrypted.ciphertext !== 'string' ||\n typeof encrypted.tag !== 'string'\n ) {\n throw new Error('decryptMnemonic: malformed keystore envelope');\n }\n\n const salt = Buffer.from(encrypted.salt, 'base64');\n const iv = Buffer.from(encrypted.iv, 'base64');\n const ciphertext = Buffer.from(encrypted.ciphertext, 'base64');\n const tag = Buffer.from(encrypted.tag, 'base64');\n\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const decipher = createDecipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n decipher.setAuthTag(tag);\n try {\n const plaintext = Buffer.concat([\n decipher.update(ciphertext),\n decipher.final(),\n ]);\n return plaintext.toString('utf8');\n } catch {\n throw new Error(\n 'Decryption failed: wrong password or corrupted keystore file'\n );\n }\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Generate a fresh 12-word BIP-39 mnemonic, encrypt it under `password`, and\n * write the encrypted keystore to `path` with mode 0o600.\n *\n * Returns the mnemonic (for one-time display/backup) alongside the encrypted\n * envelope. The caller is responsible for displaying the mnemonic securely and\n * NOT persisting it in plaintext.\n */\nexport function generateKeystore(\n path: string,\n password: string\n): { mnemonic: string; keystore: EncryptedKeystore } {\n assertNode();\n const mnemonic = genMnemonic();\n const keystore = encryptMnemonic(mnemonic, password);\n writeKeystoreFile(path, keystore);\n return { mnemonic, keystore };\n}\n\n/**\n * Import an existing BIP-39 mnemonic (12 or 24 words), encrypt it under\n * `password`, and write the encrypted keystore to `path` with mode 0o600.\n *\n * Throws if the mnemonic is not a valid BIP-39 phrase (wrong checksum/word\n * count) before any file is written.\n */\nexport function importKeystore(\n path: string,\n mnemonic: string,\n password: string\n): EncryptedKeystore {\n assertNode();\n if (!isValidMnemonic(mnemonic)) {\n throw new Error(\n 'Invalid BIP-39 mnemonic: checksum or word-list validation failed'\n );\n }\n const keystore = encryptMnemonic(mnemonic, password);\n writeKeystoreFile(path, keystore);\n return keystore;\n}\n\n/**\n * Load and decrypt a keystore file at `path` with `password`, returning the\n * plaintext mnemonic. Throws on a wrong password or corruption.\n */\nexport function loadKeystore(path: string, password: string): string {\n assertNode();\n const raw = readFileSync(path, 'utf8');\n let parsed: EncryptedKeystore;\n try {\n parsed = JSON.parse(raw) as EncryptedKeystore;\n } catch {\n throw new Error(`Keystore file at ${path} is not valid JSON`);\n }\n return decryptMnemonic(parsed, password);\n}\n\n/**\n * Serialize and write an encrypted keystore to disk with mode 0o600\n * (owner read/write only), mirroring the relay node wallet file permissions.\n */\nexport function writeKeystoreFile(\n path: string,\n keystore: EncryptedKeystore\n): void {\n assertNode();\n writeFileSync(path, JSON.stringify(keystore, null, 2), {\n encoding: 'utf8',\n mode: 0o600,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,qBAAAA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,OACK;;;ACJP,SAAS,qBAAAC,0BAAyB;AAClC;AAAA,EACE;AAAA,OAEK;;;ACDA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MAChB,OACA;AACA,UAAM,SAAS,EAAE,MAAM,CAAC;AAHR;AAIhB,SAAK,OAAO;AAAA,EACd;AAAA,EALkB;AAMpB;AAMO,IAAM,eAAN,cAA2B,gBAAgB;AAAA,EAChD,YAAY,SAAiB,OAAe;AAC1C,UAAM,SAAS,iBAAiB,KAAK;AACrC,SAAK,OAAO;AAAA,EACd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AU,QAAQ;AACnD,oBAAkB,MAAM,QAAQ;AAChC,SAAO;AACT;AAMO,SAAS,aAAa,MAAc,UAA0B;AACnE,aAAW;AACX,QAAM,MAAMI,cAAa,MAAM,MAAM;AACrC,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,UAAM,IAAI,MAAM,oBAAoB,IAAI,oBAAoB;AAAA,EAC9D;AACA,SAAOD,iBAAgB,QAAQ,QAAQ;AACzC;AAMO,SAAS,kBACd,MACA,UACM;AACN,aAAW;AACX,EAAAE,eAAc,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG;AAAA,IACrD,UAAU;AAAA,IACV,MAAM;AAAA,EACR,CAAC;AACH;","names":["generateSecretKey","getPublicKey","generateSecretKey","ed25519","key","generateSecretKey","toHex","key","OerErrorKind","EnvelopeErrorKind","GiftWrapErrorKind","concat","key","concat","encodeVarOctetString","decodeVarOctetString","textEncoder","sha256","randomBytes","require","http","ed25519","base58Encode","sha256","TOKEN_PROGRAM_ID","key","STATE_MAP","base58Encode","ed25519","ensureOwnedMinaZkApp","status","privateKeyToAccount","toHex","ed25519","base58Encode","ed25519","base58Encode","toHex","hexToMinaBase58PrivateKey","sha256","sha256","hexToMinaBase58PrivateKey","createPublicClient","http","defineChain","sha256","BASE58_ALPHABET","createPublicClient","defineChain","http","parseEvmChainId","hexToMinaBase58PrivateKey","hexToMinaBase58PrivateKey","generateSecretKey","getPublicKey","readFileSync","writeFileSync","existsSync","secp256k1","bytesToHex","parseEvmChainId","finalizeEvent","toBase64","fromBase64","hexToBytes","bytesToHex","toBase64","fromBase64","getPublicKey","hexToBytes","bytesToHex","fromBase64","finalizeEvent","randomBytes","writeFileSync","readFileSync","encryptMnemonic","randomBytes","key","decryptMnemonic","readFileSync","writeFileSync"]}
1
+ {"version":3,"sources":["../src/ToonClient.ts","../src/config.ts","../src/errors.ts","../src/keys/KeyDerivation.ts","../src/utils/binary.ts","../src/btp/protocol.ts","../src/adapters/ConnectorEdgeClient.ts","../src/wire/oer.ts","../src/wire/envelope.ts","../src/wire/giftwrap.ts","../src/wire/sealed-exchange.ts","../src/modes/http.ts","../src/utils/retry.ts","../src/adapters/HttpRuntimeClient.ts","../src/btp/IsomorphicBtpClient.ts","../src/utils/condition.ts","../src/adapters/ilp-send.ts","../src/adapters/BtpRuntimeClient.ts","../src/adapters/HttpIlpClient.ts","../src/adapters/selectIlpTransport.ts","../src/channel/OnChainChannelClient.ts","../src/channel/solana-payment-channel.ts","../src/signing/evm-signer.ts","../src/signing/solana-signer.ts","../src/signing/mina-signer.ts","../src/channel/mina-payment-channel.ts","../src/channel/mina-deposit.ts","../src/channel/ChannelManager.ts","../src/channel/ChannelStore.ts","../src/balance/WalletBalanceReader.ts","../src/blob-storage.ts","../src/adapters/Http402Client.ts","../src/swap/settle-received-claims.ts","../src/swap/mina-settlement.ts","../src/adapters/HttpConnectorAdmin.ts","../src/channel/ReceivedClaimStore.ts","../src/swap/received-claims.ts","../src/swap/evm-claim-digest.ts","../src/swap/preimage-retention.ts","../src/swap/atomic-reveal.ts","../src/faucet.ts","../src/keys/KeyManager.ts","../src/keys/PasskeyAuth.ts","../src/keys/encoding.ts","../src/keys/KeyVault.ts","../src/keys/BackupService.ts","../src/keys/keystore-node.ts"],"sourcesContent":["import {\n generateSecretKey,\n getPublicKey,\n finalizeEvent,\n} from 'nostr-tools/pure';\nimport type { NostrEvent, EventTemplate } from 'nostr-tools/pure';\nimport type {\n BootstrapService,\n DiscoveryTracker,\n IlpSendResult,\n IlpClient,\n} from '@toon-protocol/core';\nimport type { NetworkFamilyStatus } from '@toon-protocol/core';\nimport { validateConfig, applyDefaults, getNetworkStatus } from './config.js';\nimport {\n toBase64,\n fromBase64,\n encodeUtf8,\n decodeUtf8,\n} from './utils/binary.js';\nimport {\n ConnectorEdgeClient,\n connectorEdgeBaseUrl,\n type ConnectorSettlementTerms,\n type ConnectorSolanaSettlementTerms,\n} from './adapters/ConnectorEdgeClient.js';\nimport { readExchangeOutcome, sealExchange } from './wire/sealed-exchange.js';\nimport type { ResolvedConfig } from './config.js';\nimport { initializeHttpMode } from './modes/http.js';\nimport {\n ToonClientError,\n ChannelFundingError,\n isInsufficientGasError,\n} from './errors.js';\nimport { EvmSigner } from './signing/evm-signer.js';\nimport { SolanaSigner } from './signing/solana-signer.js';\nimport { MinaSigner } from './signing/mina-signer.js';\nimport { deriveFullIdentity } from './keys/KeyDerivation.js';\nimport {\n ChannelManager,\n type PeerNegotiation,\n} from './channel/ChannelManager.js';\nimport { JsonFileChannelStore } from './channel/ChannelStore.js';\nimport type { OnChainChannelClient } from './channel/OnChainChannelClient.js';\nimport {\n readEvmTokenBalance,\n readSolanaTokenBalance,\n readMinaBalance,\n readWalletBalances,\n type WalletBalance,\n type WalletBalanceSources,\n type WalletChainBalances,\n} from './balance/WalletBalanceReader.js';\nimport {\n requestBlobStorage,\n type RequestBlobStorageResult,\n} from './blob-storage.js';\nimport type { BtpRuntimeClient } from './adapters/BtpRuntimeClient.js';\nimport type { IlpSendParams } from './adapters/ilp-send.js';\nimport {\n Http402Client,\n type H402FetchOptions,\n} from './adapters/Http402Client.js';\nimport type { SettlementBundle } from '@toon-protocol/sdk';\nimport {\n submitEvmSettlement,\n type SubmitEvmSettlementResult,\n} from './swap/settle-received-claims.js';\nimport {\n submitMinaSettlement,\n type MinaSignaturePair,\n} from './swap/mina-settlement.js';\nimport type {\n ToonClientConfig,\n ToonStartResult,\n PublishEventResult,\n SignedBalanceProof,\n} from './types.js';\n\n/**\n * Validate an operator-supplied maker Mina co-signature (`{ r, s }` decimal\n * Field strings). Returns undefined for an absent/malformed entry so the\n * settlement path fails closed with `MINA_MAKER_COSIGN_REQUIRED` rather than\n * forwarding garbage into o1js.\n */\nfunction parseMakerMinaSignature(\n raw: { r: string; s: string } | undefined\n): MinaSignaturePair | undefined {\n if (\n raw &&\n typeof raw.r === 'string' &&\n raw.r.length > 0 &&\n typeof raw.s === 'string' &&\n raw.s.length > 0\n ) {\n return { r: raw.r, s: raw.s };\n }\n return undefined;\n}\n\n/**\n * Internal state for ToonClient after initialization.\n */\ninterface ToonClientState {\n bootstrapService: BootstrapService;\n discoveryTracker: DiscoveryTracker;\n runtimeClient: IlpClient;\n peersDiscovered: number;\n btpClient?: BtpRuntimeClient;\n}\n\n/**\n * ToonClient - High-level client for interacting with TOON network.\n *\n * This story implements HTTP mode only. Embedded mode will be added in a future epic.\n *\n * @example HTTP Mode\n * ```typescript\n * import { ToonClient } from '@toon-protocol/client';\n * import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';\n * import { encodeEvent, decodeEvent } from '@toon-protocol/relay';\n *\n * const secretKey = generateSecretKey();\n * const pubkey = getPublicKey(secretKey);\n *\n * const client = new ToonClient({\n * connectorUrl: 'http://localhost:8080',\n * secretKey,\n * ilpInfo: {\n * pubkey,\n * ilpAddress: `g.toon.${pubkey.slice(0, 8)}`,\n * btpEndpoint: 'ws://localhost:3000',\n * },\n * toonEncoder: encodeEvent,\n * toonDecoder: decodeEvent,\n * });\n *\n * await client.start(); // Bootstrap peers, start monitoring\n *\n * // Publish to default destination (from config)\n * await client.publishEvent(signedEvent);\n *\n * // Publish to specific destination (multi-hop routing)\n * await client.publishEvent(signedEvent, { destination: 'g.toon.peer1' });\n *\n * await client.stop(); // Cleanup\n * ```\n */\nexport class ToonClient {\n private readonly config: ResolvedConfig;\n private state: ToonClientState | null = null;\n private readonly evmSigner?: EvmSigner;\n private solanaSigner?: SolanaSigner;\n /**\n * Ed25519 signing seed (32 bytes) derived from the mnemonic for the Solana\n * identity. Retained so `start()` can inject it into the on-chain channel\n * client's Solana config (same key as `solanaSigner`).\n */\n private solanaSeed?: Uint8Array;\n private minaSigner?: MinaSigner;\n /**\n * Mina private key (big-endian hex scalar, as `deriveFullIdentity` emits)\n * derived from the mnemonic. Retained so `start()` can inject it into the\n * on-chain channel client's Mina config (same key as `minaSigner`).\n */\n private minaPrivateKey?: string;\n private channelManager?: ChannelManager;\n /** Concrete on-chain client, kept so deposit/withdraw can reach chain methods. */\n private onChainChannelClient?: OnChainChannelClient;\n private readonly peerNegotiations = new Map<string, PeerNegotiation>();\n /**\n * Peers whose x402 greeting advertised a Solana settlement leg that this\n * client could not weigh, because `config.solanaChannel` is unset and\n * {@link getBalances} therefore reports no Solana balance at all (issue\n * #474). The EVM leg was taken by default for these; if opening it then\n * fails for lack of funds, {@link withSolanaLegHint} says so.\n */\n private readonly unreadableSolanaLegs = new Set<string>();\n /**\n * Asks terminating connectors for their identity key, caching one per\n * client edge. A packet cannot be formed without the key of the connector\n * that terminates it (ADR 0018), so this is reached on every paid write.\n */\n private readonly connectorEdge = new ConnectorEdgeClient({\n // Resolve `fetch` per call rather than binding it once: a host that\n // installs its own global (and a test that swaps one in) must be the one\n // this reaches, whenever it is reached.\n fetch: (input, init) => globalThis.fetch(input, init),\n });\n\n /**\n * Creates a new ToonClient instance.\n *\n * @param config - Client configuration\n * @throws {ValidationError} If configuration is invalid\n */\n constructor(config: ToonClientConfig) {\n // Validate config (will reject embedded mode, require connectorUrl)\n validateConfig(config);\n\n // Apply defaults to optional fields (auto-generates secretKey if needed)\n this.config = applyDefaults(config);\n\n // Create EVM signer if private key provided\n if (this.config.evmPrivateKey) {\n this.evmSigner = new EvmSigner(this.config.evmPrivateKey);\n }\n }\n\n /**\n * Generates a new Nostr keypair.\n *\n * @returns Object with secretKey (Uint8Array) and pubkey (hex string)\n */\n static generateKeypair(): { secretKey: Uint8Array; pubkey: string } {\n const secretKey = generateSecretKey();\n const pubkey = getPublicKey(secretKey);\n return { secretKey, pubkey };\n }\n\n /**\n * Gets the Nostr public key derived from the secret key.\n * Works before start() is called.\n */\n getPublicKey(): string {\n return getPublicKey(this.config.secretKey);\n }\n\n /**\n * Sign an unsigned Nostr event template with the client's Nostr secret key,\n * returning a fully-signed event (id + pubkey + sig).\n *\n * This is the key primitive behind the daemon's sign-and-publish path: a UI\n * or agent supplies only `{ kind, content, tags, created_at }` and never holds\n * the private key — signing happens here, inside the key owner.\n */\n signEvent(template: EventTemplate): NostrEvent {\n return finalizeEvent(template, this.config.secretKey);\n }\n\n /**\n * Upload bytes to Arweave via the kind:5094 blob-storage DVM (single-packet),\n * signing the request with this client's Nostr key and paying through its\n * existing channel. Returns the Arweave tx id on success.\n *\n * Backs the daemon's `upload-media` path: the key and claim/channel plumbing\n * stay inside the client; callers pass only the bytes.\n */\n async uploadBlob(params: {\n blobData: Uint8Array;\n contentType?: string;\n bid?: string;\n destination?: string;\n ilpAmount?: bigint;\n }): Promise<RequestBlobStorageResult> {\n return requestBlobStorage(this, this.config.secretKey, params);\n }\n\n /**\n * Per-chain settlement readiness for the configured `network` tier, mirroring\n * the relay node's status. Returns `undefined` when no named `network` is\n * set (or `network: 'custom'`), since there is no preset tier to report on.\n */\n getNetworkStatus(): NetworkFamilyStatus | undefined {\n return getNetworkStatus(this.config);\n }\n\n /**\n * Gets the EVM address derived from the Nostr secret key (or explicit evmPrivateKey override).\n */\n getEvmAddress(): string | undefined {\n return this.evmSigner?.address;\n }\n\n /**\n * Gets the Solana (base58) address, when the client was constructed from a\n * `mnemonic`. Available only AFTER `start()` (Solana keys are derived\n * asynchronously). Returns undefined otherwise.\n */\n getSolanaAddress(): string | undefined {\n return this.solanaSigner?.signerIdentifier;\n }\n\n /**\n * Gets the Mina (base58) address, when the client was constructed from a\n * `mnemonic` AND `mina-signer` is installed. Available only AFTER `start()`.\n * Returns undefined otherwise.\n */\n getMinaAddress(): string | undefined {\n return this.minaSigner?.signerIdentifier;\n }\n\n /**\n * Derive the Solana/Mina keys from the mnemonic and register their signers on\n * the ChannelManager. Mirrors how the EVM signer is wired, but for the\n * non-secp256k1 chains. Skips any chain whose optional dependency is missing.\n */\n private async registerMnemonicChainSigners(\n mnemonic: string,\n accountIndex = 0\n ): Promise<void> {\n if (!this.channelManager) return;\n const identity = await deriveFullIdentity(mnemonic, accountIndex);\n\n // Solana: @noble/curves Ed25519 expects a 32-byte seed; deriveFullIdentity\n // returns a 64-byte keypair (seed||pubkey).\n if (identity.solana.publicKey) {\n const seed = identity.solana.secretKey.slice(0, 32);\n this.solanaSeed = seed;\n this.solanaSigner = new SolanaSigner(seed, identity.solana.publicKey);\n this.channelManager.registerChainSigner('solana', this.solanaSigner);\n }\n\n // Mina: only present when mina-signer is installed (optional dep).\n if (identity.mina.publicKey) {\n this.minaPrivateKey = identity.mina.privateKey;\n // Pass the configured GraphQL URL so the signer can read the channel's\n // on-chain `depositTotal` and bind the conserved `balanceB = depositTotal\n // − balanceA` commitment that a funded zkApp requires (connector#133);\n // without it Mina claims use the legacy balanceB=0 form and a funded zkApp\n // rejects them (F06 - Invalid zk-SNARK proof on claim).\n this.minaSigner = new MinaSigner(\n identity.mina.privateKey,\n identity.mina.publicKey,\n this.config.minaChannel?.graphqlUrl\n ? { graphqlUrl: this.config.minaChannel.graphqlUrl }\n : undefined\n );\n this.channelManager.registerChainSigner('mina', this.minaSigner);\n }\n }\n\n /**\n * Starts the ToonClient.\n *\n * This will:\n * 1. Initialize HTTP mode components (runtime client, admin client, bootstrap, monitor)\n * 2. Bootstrap the network (discover peers, register, and open channels)\n * 3. Start monitoring relay for new peers (kind:10032 events)\n *\n * @returns Result with number of peers discovered and mode\n * @throws {ToonClientError} If client is already started\n * @throws {ToonClientError} If initialization fails\n */\n async start(): Promise<ToonStartResult> {\n if (this.state !== null) {\n throw new ToonClientError('Client already started', 'INVALID_STATE');\n }\n\n try {\n // Create channel manager FIRST (before bootstrap) so it can sign claims during settlement\n if (this.evmSigner) {\n const store = this.config.channelStorePath\n ? new JsonFileChannelStore(this.config.channelStorePath)\n : undefined;\n // `initialDeposit`/`settlementTimeout` are documented ToonClientConfig\n // knobs; thread them through so the collateral an open locks is\n // configurable on every chain (they were previously accepted and\n // silently dropped, pinning every open to ChannelManager's defaults).\n this.channelManager = new ChannelManager(this.evmSigner, store, {\n ...(this.config.initialDeposit !== undefined\n ? { initialDeposit: this.config.initialDeposit }\n : {}),\n ...(this.config.settlementTimeout !== undefined\n ? { settlementTimeout: this.config.settlementTimeout }\n : {}),\n });\n\n // When constructed from a mnemonic, derive the non-secp256k1 keys\n // (Solana Ed25519, Mina Pallas) and register their signers so the\n // client can settle on those chains too. Derivation is async (dynamic\n // imports + optional deps), hence done here rather than in the\n // synchronous constructor. Gracefully skips a chain whose optional dep\n // is absent (e.g. mina-signer) — deriveFullIdentity leaves it empty.\n if (this.config.mnemonic) {\n await this.registerMnemonicChainSigners(\n this.config.mnemonic,\n this.config.mnemonicAccountIndex ?? 0\n );\n }\n }\n\n // Initialize HTTP mode components\n const initialization = await initializeHttpMode(this.config);\n\n const { bootstrapService, discoveryTracker, runtimeClient, btpClient } =\n initialization;\n\n // Wire claim signer to bootstrap service if we have channel manager\n if (this.channelManager) {\n const cm = this.channelManager;\n const nostrPubkey = this.getPublicKey();\n // Derive default chain context from config (first supported chain)\n const defaultChainCtx = this.getDefaultChainContext();\n bootstrapService.setClaimSigner(\n async (channelId: string, amount: bigint) => {\n // Track the channel if not already tracked\n if (!cm.isTracking(channelId)) {\n cm.trackChannel(channelId, defaultChainCtx);\n }\n // Sign balance proof and build full claim message with the\n // chain-appropriate signer (the channel is tracked above, so a\n // non-EVM channel yields its correct envelope, not an EVM claim).\n const proof = await cm.signBalanceProof(channelId, amount);\n const signer = cm.getSignerForChannel(channelId);\n return signer.buildClaimMessage(proof, nostrPubkey);\n }\n );\n }\n\n // Start bootstrap process (discover peers, register with settlement, announce)\n const bootstrapResults = await bootstrapService.bootstrap();\n\n // Store negotiation metadata from bootstrap results for lazy channel opening\n for (const result of bootstrapResults) {\n if (result.negotiatedChain && result.settlementAddress) {\n const chainType = result.negotiatedChain.split(':')[0] ?? 'evm';\n const parts = result.negotiatedChain.split(':');\n // Accept 3-part `evm:{network}:{chainId}` and 2-part `evm:{chainId}`.\n const chainId =\n parts.length >= 3\n ? parseInt(parts[2] ?? '0', 10)\n : parts.length >= 2\n ? parseInt(parts[1] ?? '0', 10)\n : 0;\n const r = result as typeof result & {\n tokenAddress?: string;\n tokenNetwork?: string;\n };\n this.peerNegotiations.set(result.registeredPeerId, {\n chain: result.negotiatedChain,\n chainType,\n chainId: isNaN(chainId) ? 0 : chainId,\n settlementAddress: result.settlementAddress,\n tokenAddress: r.tokenAddress,\n tokenNetwork: r.tokenNetwork,\n });\n } else if (\n result.registeredPeerId &&\n !this.peerNegotiations.has(result.registeredPeerId)\n ) {\n // Lightweight client fallback: bootstrap discovered the peer but didn't\n // negotiate a chain (no connector admin to register with). Extract the\n // peer's settlement info from their kind:10032 event data and match\n // against our supported chains.\n const peerInfo = result.peerInfo as typeof result.peerInfo & {\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n };\n const peerChains = peerInfo.supportedChains ?? [];\n const ourChains = this.config.supportedChains ?? [];\n // Find the first chain both sides support\n const matchedChain =\n ourChains.find((c) => peerChains.includes(c)) ?? ourChains[0];\n if (matchedChain) {\n const peerAddr = peerInfo.settlementAddresses?.[matchedChain];\n const parts = matchedChain.split(':');\n const chainId =\n parts.length >= 3\n ? parseInt(parts[2] ?? '0', 10)\n : parts.length >= 2\n ? parseInt(parts[1] ?? '0', 10)\n : 0;\n if (peerAddr) {\n this.peerNegotiations.set(result.registeredPeerId, {\n chain: matchedChain,\n chainType: parts[0] ?? 'evm',\n chainId: isNaN(chainId) ? 0 : chainId,\n settlementAddress: peerAddr,\n tokenAddress:\n peerInfo.preferredTokens?.[matchedChain] ??\n this.config.preferredTokens?.[matchedChain],\n tokenNetwork:\n peerInfo.tokenNetworks?.[matchedChain] ??\n this.config.tokenNetworks?.[matchedChain],\n });\n }\n }\n }\n // Track any pre-opened channels (backwards compat)\n if (\n this.channelManager &&\n result.channelId &&\n !this.channelManager.isTracking(result.channelId)\n ) {\n const chainCtx = this.getChainContext(result.negotiatedChain);\n this.channelManager.trackChannel(result.channelId, chainCtx);\n }\n }\n\n // Wire on-chain channel client into ChannelManager for lazy opens\n if (this.channelManager && initialization.onChainChannelClient) {\n this.onChainChannelClient = initialization.onChainChannelClient;\n this.channelManager.setChannelClient(\n initialization.onChainChannelClient\n );\n\n // Late-bind the Solana channel config: the program/RPC/token come from\n // config, the Ed25519 keypair from the mnemonic-derived Solana seed.\n // Requires both a Solana seed (mnemonic-derived) and explicit\n // solanaChannel config — otherwise the on-chain Solana opener has no\n // program/RPC and would throw at openChannel time.\n if (this.config.solanaChannel && this.solanaSeed) {\n initialization.onChainChannelClient.setSolanaConfig({\n rpcUrl: this.config.solanaChannel.rpcUrl,\n programId: this.config.solanaChannel.programId,\n tokenMint: this.config.solanaChannel.tokenMint,\n challengeDuration: this.config.solanaChannel.challengeDuration,\n deposit: this.config.solanaChannel.deposit,\n keypair: this.solanaSeed,\n });\n }\n\n // Late-bind the Mina channel config (parallel to Solana). The\n // graphqlUrl + zkAppAddress come from config; the Mina private key from\n // the mnemonic-derived Mina identity (same key as the registered Mina\n // signer). Requires both a Mina private key (mnemonic-derived, present\n // only when `mina-signer` is installed) and explicit minaChannel config.\n //\n // openMinaChannel now performs a REAL on-chain channel open\n // (initialize + optional deposit) on the deployed zkApp so the\n // connector's getChannelState reports `opened` and the claim verifies +\n // stores (parity with Solana). Full on-chain Mina SETTLE remains gated by\n // the connector-side settlement-executor (same blocker as Solana).\n if (this.config.minaChannel && this.minaPrivateKey) {\n initialization.onChainChannelClient.setMinaConfig({\n graphqlUrl: this.config.minaChannel.graphqlUrl,\n ...(this.config.minaChannel.zkAppAddress !== undefined\n ? { zkAppAddress: this.config.minaChannel.zkAppAddress }\n : {}),\n ...(this.config.minaChannel.autoDeploy !== undefined\n ? { autoDeploy: this.config.minaChannel.autoDeploy }\n : {}),\n privateKey: this.minaPrivateKey,\n ...(this.config.minaChannel.challengeDuration !== undefined\n ? { challengeDuration: this.config.minaChannel.challengeDuration }\n : {}),\n ...(this.config.minaChannel.tokenId !== undefined\n ? { tokenId: this.config.minaChannel.tokenId }\n : {}),\n ...(this.config.minaChannel.deposit !== undefined\n ? { deposit: this.config.minaChannel.deposit }\n : {}),\n ...(this.config.minaChannel.networkId !== undefined\n ? { networkId: this.config.minaChannel.networkId }\n : {}),\n });\n }\n }\n\n // Store state\n this.state = {\n bootstrapService,\n discoveryTracker,\n runtimeClient,\n peersDiscovered: bootstrapResults.length,\n btpClient: btpClient ?? undefined,\n };\n\n return {\n peersDiscovered: bootstrapResults.length,\n mode: 'http',\n };\n } catch (error) {\n throw new ToonClientError(\n 'Failed to start client',\n 'INITIALIZATION_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Publishes a Nostr event through the connector that terminates\n * `destination`, as a sealed, condition-bearing paid write (ADR 0018/0019).\n *\n * What crosses the wire, in order:\n *\n * 1. **The terminating connector's identity is fetched first.** `data` is\n * sealed to that key, so a packet cannot be formed without it — and\n * there is no default to fall back to, because sealing to the wrong key\n * is a confidentiality failure that merely presents as undeliverable.\n * 2. **The price is ASKED for, not computed.** ADR 0020 makes a price flat\n * per handler, so `GET /ilp/routes/price` — the same longest-prefix\n * lookup the claim gate charges against — is the only thing that can\n * state what this write costs. `options.ilpAmount` still overrides.\n * 3. **The event becomes an OER `EnvelopeRequest`** — `POST <proxyPath>`\n * carrying `{\"event\": …}` — never HTTP text.\n * 4. **The PREPARE carries a real execution condition**, minted as\n * `sha256` of the fulfilment derived from the secret sealed inside the\n * wrap. The transport verifies the returned preimage against it, so a\n * FULFILL nobody could have earned is counted failed rather than\n * accepted.\n * 5. **The answer is opened with that same secret.** A FULFILL carries a\n * sealed response envelope; a REJECT sealed at the termination means the\n * destination refused, and a plaintext one means somebody on the path\n * did. `refusedBy` keeps those apart.\n *\n * An HTTP status inside the response envelope is envelope CONTENT, not a\n * packet outcome (ADR 0020): a 404 rides home on a FULFILL and value moved.\n * This method still reports a non-2xx as `success: false` — the event did\n * not persist — but `response` is populated either way, so a caller can see\n * exactly what it paid for.\n *\n * @param event - Signed Nostr event to publish\n * @param options - Optional destination, claim, amount and request target\n * @throws {ToonClientError} If the client is not started, the terminating\n * connector's identity or route price cannot be obtained, or the send\n * fails outright.\n */\n async publishEvent(\n event: NostrEvent,\n options?: {\n destination?: string;\n claim?: SignedBalanceProof;\n ilpAmount?: bigint;\n /** Sub-path resolved strictly BENEATH the route's handler path (ADR\n * 0025). Default '' — the handler's own path, correct whenever the\n * destination terminates at exactly one endpoint. Never absolute:\n * a leading '/' is refused by the connector (F00). */\n proxyPath?: string;\n }\n ): Promise<PublishEventResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n try {\n const destination =\n options?.destination ?? this.config.destinationAddress;\n const edge = this.resolveClientEdgeEndpoint();\n\n // (1) The key first — no packet exists without it.\n const identity = await this.connectorEdge.getIdentity(edge);\n\n // (2) The price is ASKED for, not computed. ADR 0020 makes a price flat\n // per handler — the route table is the price list — so there is no\n // per-byte rate to multiply and nothing local that could disagree with\n // what the connector will actually charge. An explicit `ilpAmount`\n // still overrides, and never triggers the lookup.\n const amount =\n options?.ilpAmount !== undefined\n ? String(options.ilpAmount)\n : String(await this.routePriceFor(edge, destination));\n\n // (3)+(4) One call mints the envelope's seal and the condition that\n // matches it, so the two can never drift apart.\n const exchange = sealExchange(\n {\n method: 'POST',\n // ADR 0025 (connector #596): the envelope target is resolved\n // STRICTLY BENEATH the route's configured handler path — it can\n // extend that path, never replace it. '' means \"the handler's own\n // path\", which is the whole answer for a route that terminates at\n // exactly one endpoint (g.rust.relay → …/write, g.rust.store →\n // …/store): the DESTINATION picks the endpoint, not the target.\n // An absolute target like '/write' is refused as an escape\n // attempt (F00) before the app is ever reached.\n target: options?.proxyPath ?? '',\n headers: [['content-type', 'application/json']],\n body: encodeUtf8(JSON.stringify({ event })),\n },\n identity.publicKey\n );\n\n const transport = this.getClaimTransport();\n const claimMessage = await this.resolveClaimForDestination(\n destination,\n BigInt(amount),\n options?.claim\n );\n\n const response = await transport.sendIlpPacketWithClaim(\n {\n destination,\n amount,\n data: toBase64(exchange.data),\n executionCondition: exchange.condition,\n },\n claimMessage\n );\n\n // (5) Open the answer with the secret this packet sealed.\n const outcome = readExchangeOutcome(\n response,\n response.data === undefined ? undefined : fromBase64(response.data),\n exchange.sharedSecret\n );\n\n if (outcome.kind === 'destination-refused') {\n return {\n success: false,\n refusedBy: 'destination',\n code: outcome.code,\n error: `Destination refused the write: ${outcome.code} - ${outcome.message}`,\n };\n }\n if (outcome.kind === 'path-refused') {\n return {\n success: false,\n refusedBy: 'path',\n code: outcome.code,\n error: `A connector on the path refused the write: ${outcome.code} - ${outcome.message}`,\n };\n }\n\n const { response: answer } = outcome;\n if (answer.status < 200 || answer.status >= 300) {\n const detail =\n answer.body.length > 0 ? ` - ${decodeUtf8(answer.body)}` : '';\n return {\n success: false,\n response: answer,\n error: `Write failed: the destination answered HTTP ${answer.status}${detail}`,\n };\n }\n\n return { success: true, eventId: event.id, response: answer };\n } catch (error) {\n console.error(\n '[ToonClient.publishEvent] ROOT CAUSE:',\n String(error),\n error instanceof Error ? error.stack : ''\n );\n // These conditions are raised before any packet exists and name a thing\n // the caller can fix: the destination is not terminated here, there is\n // no client edge to ask at all, no channel negotiation exists AND the\n // greeting-based bootstrap (connector #617) found nothing to synthesize\n // one from, or the settlement wallet cannot fund the one-time on-chain\n // channel open (`CHANNEL_FUNDING` — which carries the wallet, the chain,\n // and, for an unreadable Solana leg, the missing config, see\n // {@link withSolanaLegHint}). Wrapping any of them in `PUBLISH_ERROR`\n // would hide the one fact worth surfacing behind the most generic code\n // this method has. Everything else — including a connector that will not\n // answer for its identity — keeps the existing wrapping, so\n // `PUBLISH_ERROR` still means \"the publish itself failed\".\n if (\n error instanceof ToonClientError &&\n (error.code === 'NO_TERMINATED_ROUTE' ||\n error.code === 'NO_CONNECTOR_EDGE' ||\n error.code === 'PEER_NOT_NEGOTIATED' ||\n error.code === 'CHANNEL_FUNDING')\n ) {\n throw error;\n }\n throw new ToonClientError(\n 'Failed to publish event',\n 'PUBLISH_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * What a destination costs, asked of the connector that terminates it —\n * `null` when it terminates no route matching it.\n *\n * The public form of the lookup `publishEvent` makes, for callers that need\n * a price BEFORE they build a packet: a pre-push estimate that must equal\n * what the push will actually pay, a fee quote shown to a user for consent.\n * Since ADR 0020 a price is flat per handler, so the figure is the whole\n * fee for one packet to that destination — there is nothing to multiply it\n * by. Cached per destination, so this is cheap to call repeatedly.\n *\n * @throws {ToonClientError} NO_CONNECTOR_EDGE when no client edge is known.\n * @throws {ConnectorEdgeError} when the connector cannot be asked.\n */\n async getRoutePrice(destination: string): Promise<bigint | null> {\n const price = await this.connectorEdge.getRoutePrice(\n this.resolveClientEdgeEndpoint(),\n destination\n );\n return price === null ? null : price.price;\n }\n\n /**\n * What this destination costs, from the connector that terminates it.\n *\n * ADR 0020 makes a price flat per handler: one handler, one price, and an\n * app that wants to charge differently exposes more handlers. There is\n * therefore nothing to compute — the route table IS the price list, and\n * `GET /ilp/routes/price` is the same longest-prefix lookup the claim gate\n * charges against, so it can never state a price a real request would not\n * be charged.\n *\n * Cached per (edge, destination) by {@link ConnectorEdgeClient}, so this is\n * one round trip per destination rather than one per packet.\n *\n * @throws {ToonClientError} NO_TERMINATED_ROUTE when the connector answers\n * `404` — it does not terminate this destination. That is a refusal to\n * guess, not a zero: pricing an unroutable write at 0 (or at some local\n * fallback rate) would send a packet certain to be rejected, and report\n * the wrong reason for it.\n */\n private async routePriceFor(\n edge: string,\n destination: string\n ): Promise<bigint> {\n const price = await this.connectorEdge.getRoutePrice(edge, destination);\n if (price === null) {\n throw new ToonClientError(\n `The connector at ${edge} terminates no route for \"${destination}\", so it ` +\n 'cannot say what a write there costs. Check the destination, or pass an ' +\n 'explicit `ilpAmount` to price it yourself.',\n 'NO_TERMINATED_ROUTE'\n );\n }\n return price.price;\n }\n\n /**\n * The client edge `/ilp/identity` and `/ilp/routes/price` hang off — the\n * same origin paid writes already POST `/ilp` to.\n *\n * Preferring the live transport's own endpoint over config is deliberate:\n * transport selection may have followed a discovered `httpEndpoint`, and\n * the identity must come from the connector actually being paid, not from\n * whatever URL was configured before discovery ran.\n *\n * @throws {ToonClientError} NO_CONNECTOR_EDGE when no origin is known.\n */\n private resolveClientEdgeEndpoint(): string {\n const runtime = this.state?.runtimeClient as\n | { clientEdgeEndpoint?: string }\n | undefined;\n const endpoint =\n runtime?.clientEdgeEndpoint ??\n this.config.proxyUrl ??\n this.config.connectorUrl;\n if (!endpoint) {\n throw new ToonClientError(\n 'No connector client edge to ask for an identity. Configure `proxyUrl` or ' +\n '`connectorUrl`; a payload cannot be sealed without the terminating ' +\n \"connector's key (ADR 0018).\",\n 'NO_CONNECTOR_EDGE'\n );\n }\n return connectorEdgeBaseUrl(endpoint);\n }\n\n /**\n * Payment-aware HTTP fetch over TOON (issue #50). A `fetch()`-like method that\n * makes paying for an HTTP resource transparent:\n *\n * 1. Issues the HTTP request to `url`.\n * 2. On `402`, parses the x402 `accepts` array and selects the\n * `toon-channel` entry (see {@link Http402Client} for the wire shape).\n * 3. Opens/reuses a payment channel for the entry's ILP destination (via\n * ChannelManager), signs a balance proof for the demanded price, and\n * re-sends the SAME HTTP request as a transparent HTTP-in-ILP packet to\n * the connector's `POST /ilp` (via {@link HttpIlpClient}), with the claim\n * in the `ILP-Payment-Channel-Claim` header.\n * 4. Reconstructs and returns a standard Web `Response` from the FULFILL\n * `data`. The caller never sees ILP.\n *\n * If the origin offers no `toon-channel` entry, the original `402` Response is\n * returned unchanged (the caller sees the vanilla x402 challenge).\n *\n * The channel/claim plumbing is wired to the live ChannelManager + per-chain\n * signer via `resolveClaimForDestination` — identical to `publishEvent`. The\n * `amount` paid comes from the selected x402 entry (the resource's price).\n *\n * @throws {ToonClientError} If the client is not started.\n * @throws {ConnectorError} If the connector rejects the payment or returns no\n * HTTP payload.\n */\n async h402Fetch(url: string, opts?: H402FetchOptions): Promise<Response> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n // Pay only when a channel manager is configured; otherwise the engine still\n // probes and transparently surfaces the vanilla 402 (no resolveClaim hook).\n const client = new Http402Client({\n // Share this client's identity cache rather than letting each per-call\n // engine fetch the same connector's key again: `h402Fetch` builds a\n // fresh Http402Client per call (below), and a paid request now needs a\n // terminating key.\n connectorEdge: this.connectorEdge,\n ...(this.channelManager\n ? {\n resolveClaim: (destination: string, amount: bigint) =>\n this.resolveClaimForDestination(destination, amount),\n }\n : {}),\n });\n\n return client.fetch(url, opts);\n }\n\n /**\n * Sends a raw swap ILP packet (Story 12.5) to a swap peer with an attached\n * balance-proof claim. This is a lower-level surface than `publishEvent`:\n * it forwards the raw `IlpSendResult` so the sender (`streamSwap()`) can\n * decode FULFILL metadata itself.\n *\n * Claim resolution mirrors `publishEvent`:\n * (a) explicit `params.claim` -> use it,\n * (b) `channelManager` present -> auto-open + auto-sign for the peer\n * matching `destination`,\n * (c) neither -> throw MISSING_CLAIM.\n *\n * A caller may supply a sender-chosen 32-byte `executionCondition`\n * (`C = sha256(P)`, one fresh preimage per packet — toon-client#350,\n * rolling-swap spec §3 R1/R2) and an explicit `expiresAt` (R7). Both are\n * set on the wire by either transport (HTTP `POST /ilp` and BTP), and on\n * FULFILL the transport verifies `sha256(fulfillment) == condition` —\n * a mismatch comes back as `accepted: false` (code F99), never a silent\n * accept. Omitting them keeps today's zero-condition legacy packet.\n *\n * @throws {ToonClientError} INVALID_STATE / NO_ILP_TRANSPORT / MISSING_CLAIM\n */\n async sendSwapPacket(params: {\n destination: string;\n amount: bigint;\n toonData: Uint8Array;\n timeout?: number;\n claim?: SignedBalanceProof;\n /** Sender-chosen 32-byte execution condition; absent/zero = legacy. */\n executionCondition?: Uint8Array;\n /** Explicit ILP expiry; defaults to `now + timeout` in the transport. */\n expiresAt?: Date;\n }): Promise<IlpSendResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n const transport = this.getClaimTransport();\n\n const claimMessage = await this.resolveClaimForDestination(\n params.destination,\n params.amount,\n params.claim\n );\n\n return transport.sendIlpPacketWithClaim(\n {\n destination: params.destination,\n amount: String(params.amount),\n data: toBase64(params.toonData),\n timeout: params.timeout ?? 30000,\n ...(params.executionCondition\n ? { executionCondition: params.executionCondition }\n : {}),\n ...(params.expiresAt ? { expiresAt: params.expiresAt } : {}),\n },\n claimMessage as unknown as Record<string, unknown>\n );\n }\n\n /**\n * Build a BTP claim message from a pre-signed balance proof using the\n * CHAIN-APPROPRIATE signer.\n *\n * The explicit-claim path (caller signs the balance proof, then passes\n * `{ claim }`) must wrap the proof with the signer matching the channel's\n * chain. Hardcoding `EvmSigner.buildClaimMessage` here produced an EVM\n * `BTPClaimMessage` for a Solana/Mina balance proof — no `blockchain`\n * discriminator and the base58 channel account placed in the EVM\n * `channelId` field — which the connector's inbound validator classifies\n * as EVM and rejects with F06 (`Invalid channelId format`).\n *\n * When the proof's `channelId` is tracked we use\n * `getSignerForChannel(channelId).buildClaimMessage`, which emits the\n * correct per-chain envelope (e.g. `blockchain:'solana'` + base58\n * `channelAccount`). When it is not tracked we fall back to the EVM signer\n * to preserve prior behavior for lightweight/EVM-only callers.\n *\n * EVM output is byte-identical to the previous hardcoded path (the EVM\n * adapter in `getSignerForChannel` delegates to the same\n * `EvmSigner.buildClaimMessage`).\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- claim message is opaque forwarded type\n private buildClaimMessageForProof(claim: SignedBalanceProof): any {\n if (this.channelManager?.isTracking(claim.channelId)) {\n const signer = this.channelManager.getSignerForChannel(claim.channelId);\n return signer.buildClaimMessage(claim, this.getPublicKey());\n }\n return EvmSigner.buildClaimMessage(claim, this.getPublicKey());\n }\n\n /**\n * Resolve the ILP transport for a paid (claim-bearing) write.\n *\n * The connector is a payment-proxy: paid writes carry an ILP PREPARE plus the\n * signed payment-channel claim. Either transport speaks the SAME claim\n * contract — the BTP `payment-channel-claim` protocolData entry and the\n * ILP-over-HTTP `ILP-Payment-Channel-Claim` header serialize the same claim\n * JSON — so we route through whichever transport is ACTIVE rather than\n * hard-requiring BTP.\n *\n * Selection (mirrors `modes/http.ts` runtime-client precedence):\n * 1. `runtimeClient` when it implements `sendIlpPacketWithClaim` — this is\n * the HttpIlpClient (proxy `POST /ilp`) when a `proxyUrl`/\n * `connectorHttpEndpoint` is configured, else the BtpRuntimeClient.\n * 2. `btpClient` as an explicit fallback (always present when `btpUrl` is set).\n *\n * The level-3 `HttpRuntimeClient` (connector-admin HTTP, no `btpUrl` AND no\n * proxy) does NOT implement `sendIlpPacketWithClaim`; in that case there is no\n * paid-write transport and we throw a clear, actionable error.\n *\n * @throws {ToonClientError} NO_ILP_TRANSPORT when no active transport can send\n * a packet+claim.\n */\n private getClaimTransport(): {\n // IlpSendParams: both built-in transports (HttpIlpClient / BtpRuntimeClient)\n // accept the sender-chosen `executionCondition` + explicit `expiresAt`\n // extensions (toon-client#350) and enforce FULFILL preimage verification.\n sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult>;\n } {\n const state = this.state;\n if (!state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n const candidates: (IlpClient | BtpRuntimeClient | undefined)[] = [\n state.runtimeClient,\n state.btpClient,\n ];\n for (const candidate of candidates) {\n if (\n candidate &&\n typeof (candidate as IlpClient).sendIlpPacketWithClaim === 'function'\n ) {\n return candidate as ReturnType<ToonClient['getClaimTransport']>;\n }\n }\n throw new ToonClientError(\n 'No ILP transport for paid writes. Configure `proxyUrl`/`connectorHttpEndpoint` ' +\n '(route through the connector proxy over ILP-over-HTTP) or `btpUrl` (BTP socket).',\n 'NO_ILP_TRANSPORT'\n );\n }\n\n /**\n * Shared claim-resolution logic used by `publishEvent` and `sendSwapPacket`.\n */\n private async resolveClaimForDestination(\n destination: string,\n amount: bigint,\n explicitClaim?: SignedBalanceProof\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- claim message is opaque forwarded type\n ): Promise<any> {\n if (explicitClaim) {\n return this.buildClaimMessageForProof(explicitClaim);\n }\n if (this.channelManager) {\n const peerId = this.peerIdForClaim(destination);\n const negotiation =\n this.peerNegotiations.get(peerId) ??\n (await this.negotiateFromGreeting(destination, peerId));\n if (!negotiation) {\n throw new ToonClientError(\n `No negotiation metadata for peer \"${peerId}\" — was bootstrap completed?` +\n \" (and the route's x402 greeting carried no settlement facts to bootstrap from)\",\n 'PEER_NOT_NEGOTIATED'\n );\n }\n let channelId: string;\n try {\n channelId = await this.channelManager.ensureChannel(\n peerId,\n negotiation\n );\n } catch (error) {\n throw this.withSolanaLegHint(peerId, error);\n }\n const proof = await this.channelManager.signBalanceProof(\n channelId,\n amount\n );\n const signer = this.channelManager.getSignerForChannel(channelId);\n return signer.buildClaimMessage(proof, this.getPublicKey());\n }\n throw new ToonClientError(\n 'No claim provided and no channel manager configured',\n 'MISSING_CLAIM'\n );\n }\n\n /**\n * Signs a balance proof for the given channel with the specified amount.\n * Delegates to ChannelManager which auto-increments nonce and tracks cumulative amount.\n *\n * @param channelId - Payment channel identifier\n * @param amount - Additional amount to add to cumulative transferred amount\n * @returns Signed balance proof\n * @throws {ToonClientError} If no EVM signer configured or channel not tracked\n */\n async signBalanceProof(\n channelId: string,\n amount: bigint\n ): Promise<SignedBalanceProof> {\n if (!this.channelManager) {\n throw new ToonClientError(\n 'No EVM signer configured. Provide evmPrivateKey in config.',\n 'NO_EVM_SIGNER'\n );\n }\n return this.channelManager.signBalanceProof(channelId, amount);\n }\n\n /**\n * Eagerly open (or return existing) payment channel for the given destination.\n *\n * Channels are normally opened lazily on the first `publishEvent()` /\n * `sendSwapPacket()` call. This method exposes the lazy-open path so\n * callers (and E2E tests) that need a tracked `channelId` BEFORE publishing\n * can force the open. Idempotent — returns the existing channel ID for the\n * peer if one is already open.\n *\n * @param destination - Optional ILP destination address. Defaults to\n * `config.destinationAddress`.\n * @returns The channel ID of the (now) open channel.\n * @throws {ToonClientError} If client not started, no channel manager\n * configured, or peer negotiation metadata missing.\n */\n async openChannel(destination?: string): Promise<string> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n if (!this.channelManager) {\n throw new ToonClientError(\n 'No channel manager configured. Provide evmPrivateKey in config.',\n 'NO_EVM_SIGNER'\n );\n }\n const dest = destination ?? this.config.destinationAddress;\n if (!dest) {\n throw new ToonClientError(\n 'No destination provided and no default destinationAddress configured.',\n 'NO_DESTINATION'\n );\n }\n const peerId = this.peerIdForClaim(dest);\n const negotiation =\n this.peerNegotiations.get(peerId) ??\n (await this.negotiateFromGreeting(dest, peerId));\n if (!negotiation) {\n throw new ToonClientError(\n `No negotiation metadata for peer \"${peerId}\" — was bootstrap completed?` +\n \" (and the route's x402 greeting carried no settlement facts to bootstrap from)\",\n 'PEER_NOT_NEGOTIATED'\n );\n }\n try {\n return await this.channelManager.ensureChannel(peerId, negotiation);\n } catch (error) {\n throw this.withSolanaLegHint(peerId, error);\n }\n }\n\n /**\n * Gets list of tracked payment channel IDs.\n */\n getTrackedChannels(): string[] {\n return this.channelManager?.getTrackedChannels() ?? [];\n }\n\n /**\n * Gets the current nonce for a tracked channel.\n */\n getChannelNonce(channelId: string): number {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getNonce(channelId);\n }\n\n /**\n * Gets the cumulative transferred amount for a tracked channel.\n */\n getChannelCumulativeAmount(channelId: string): bigint {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getCumulativeAmount(channelId);\n }\n\n /**\n * Gets the on-chain deposit total (locked collateral) for a tracked channel.\n * The available (spendable) balance is this minus the cumulative spent amount.\n */\n getChannelDepositTotal(channelId: string): bigint {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getDepositTotal(channelId);\n }\n\n /**\n * Deposit additional collateral into an open channel. `amount` is the delta to\n * add (base units, decimal string or bigint). The daemon signs its own tx; no\n * key material leaves the client. Reads the current tracked deposit, performs\n * the on-chain deposit, updates the tracked total, and returns the new total.\n * EVM is live; Solana/Mina deposit lands in a follow-up.\n */\n async depositToChannel(\n channelId: string,\n amount: string | bigint\n ): Promise<{ channelId: string; txHash?: string; depositTotal: string }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const delta = BigInt(amount);\n if (delta <= 0n) throw new Error('Deposit amount must be positive.');\n const currentDeposit = this.channelManager.getDepositTotal(channelId);\n const result = await this.onChainChannelClient.depositToChannel(\n channelId,\n delta,\n {\n currentDeposit,\n }\n );\n this.channelManager.setDepositTotal(channelId, result.depositTotal);\n return {\n channelId,\n ...(result.txHash ? { txHash: result.txHash } : {}),\n depositTotal: result.depositTotal.toString(),\n };\n }\n\n /**\n * Close a channel to begin the settlement grace period (first half of\n * withdraw). Records `closedAt`/`settleableAt` (unix seconds) on the tracked\n * channel — persisted, so the grace timer survives a daemon restart. Spends\n * on-chain. EVM today; Solana/Mina are follow-ups.\n */\n async closeChannel(channelId: string): Promise<{\n channelId: string;\n txHash?: string;\n closedAt: string;\n settleableAt: string;\n }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const r = await this.onChainChannelClient.closeChannel(channelId);\n this.channelManager.setChannelClosed(channelId, r.closedAt, r.settleableAt);\n return {\n channelId,\n ...(r.txHash ? { txHash: r.txHash } : {}),\n closedAt: r.closedAt.toString(),\n settleableAt: r.settleableAt.toString(),\n };\n }\n\n /**\n * Settle a closed channel to release collateral (second half of withdraw).\n * THE time guard: never settle before `settleableAt`. A too-early call throws\n * a retryable error (carrying the remaining seconds) BEFORE spending gas — the\n * contract would revert anyway. Spends on-chain. EVM today.\n */\n async settleChannel(\n channelId: string\n ): Promise<{ channelId: string; txHash?: string }> {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n if (!this.onChainChannelClient) {\n throw new Error(\n 'On-chain channel client not configured (no chainRpcUrls).'\n );\n }\n const settleableAt = this.channelManager.getSettleableAt(channelId);\n if (settleableAt === undefined) {\n throw new Error(\n `Channel \"${channelId}\" is not closed; call closeChannel first.`\n );\n }\n const nowSec = BigInt(Math.floor(Date.now() / 1000));\n if (nowSec < settleableAt) {\n const remaining = settleableAt - nowSec;\n throw Object.assign(\n new Error(\n `Channel \"${channelId}\" is not settleable yet — ${remaining}s remain (settleable at ${settleableAt}).`\n ),\n {\n name: 'SettleTooEarlyError',\n retryable: true,\n settleableAt: settleableAt.toString(),\n }\n );\n }\n const r = await this.onChainChannelClient.settleChannel(channelId);\n this.channelManager.setChannelSettled(channelId, nowSec);\n return { channelId, ...(r.txHash ? { txHash: r.txHash } : {}) };\n }\n\n /**\n * Submit a receive-side swap settlement bundle on-chain (toon-client#352).\n * The bundle comes from the sdk's `buildSettlementTx` over persisted,\n * verified chain-B claims (`buildSwapSettlements`); this signs it with the\n * client's EVM account (the claim recipient) and broadcasts it.\n *\n * Env-gated seam: EVM only, and only when `chainRpcUrls[bundle.chain]` is\n * configured — otherwise this throws a clear config error and callers\n * surface a built-not-submitted result. Solana submission and the Mina\n * receive-side co-sign path are explicit follow-ups (see\n * swap/settle-received-claims.ts module doc).\n */\n async settleSwapBundle(\n bundle: SettlementBundle\n ): Promise<SubmitEvmSettlementResult> {\n if (bundle.chainKind === 'mina') {\n // Mina receive-side redemption (#357): reads the live channel state,\n // produces the recipient's co-signature, and drives the dual-party\n // `claimFromChannel` (o1js proving). Config-gated on minaChannel.graphqlUrl\n // + a derived Mina key; fails closed (never a silent pass) with a stable\n // MinaSettlementError code that the daemon surfaces.\n if (!this.minaPrivateKey) {\n throw new Error(\n 'Mina signer not configured (no mnemonic / mina-signer) — cannot co-sign the receive-side claim.'\n );\n }\n const makerSignature = parseMakerMinaSignature(\n this.config.swapMinaMakerSignatures?.[bundle.channelId]\n );\n const { txHash } = await submitMinaSettlement(bundle, {\n recipientPrivateKey: this.minaPrivateKey,\n ...(this.config.minaChannel?.graphqlUrl\n ? { graphqlUrl: this.config.minaChannel.graphqlUrl }\n : {}),\n ...(makerSignature ? { makerSignature } : {}),\n });\n return { txHash };\n }\n if (bundle.chainKind !== 'evm') {\n throw new Error(\n `Swap settlement submission for ${bundle.chainKind} (${bundle.chain}) is not wired yet — EVM only today.`\n );\n }\n const rpcUrl = this.config.chainRpcUrls?.[bundle.chain];\n if (!rpcUrl) {\n throw new Error(\n `No RPC URL configured for chain \"${bundle.chain}\" — add it to chainRpcUrls to enable swap settlement submission.`\n );\n }\n if (!this.evmSigner) {\n throw new Error('EVM signer not configured (no evmPrivateKey/mnemonic).');\n }\n return submitEvmSettlement(bundle, {\n rpcUrl,\n account: this.evmSigner.account,\n });\n }\n\n /** Where a tracked channel sits in the withdraw journey. */\n getChannelCloseState(\n channelId: string\n ): 'open' | 'closing' | 'settleable' | 'settled' {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getChannelCloseState(channelId);\n }\n\n getSettleableAt(channelId: string): bigint | undefined {\n if (!this.channelManager) throw new Error('ChannelManager not initialized');\n return this.channelManager.getSettleableAt(channelId);\n }\n\n /**\n * Re-hydrate a RESUMED channel's on-chain deposit. Persisted channel state\n * omits `depositTotal`, so after a daemon restart the tracked deposit is `0`\n * and the wallet shows 0 spendable even though real collateral is locked\n * on-chain. Read the participant's `deposit` from the `participants` mapping\n * and update the tracked total so `depositTotal - cumulativeAmount` is right.\n * Best-effort by caller (await + catch); returns the on-chain deposit, or\n * `undefined` when it can't be read (no channel manager / on-chain client /\n * EVM address).\n */\n async rehydrateChannelDeposit(\n channelId: string,\n opts: { chain: string; tokenNetworkAddress: string }\n ): Promise<bigint | undefined> {\n if (!this.channelManager || !this.onChainChannelClient) return undefined;\n const participant = this.getEvmAddress();\n if (!participant) return undefined;\n const { deposit } = await this.onChainChannelClient.readEvmParticipantState(\n {\n chain: opts.chain,\n tokenNetworkAddress: opts.tokenNetworkAddress,\n channelId,\n participant,\n }\n );\n this.channelManager.setDepositTotal(channelId, deposit);\n return deposit;\n }\n\n /**\n * Read the on-chain settlement-token balance of this client's OWN wallet on\n * each configured chain (EVM token, Solana SPL, native MINA). A free read — no\n * signing, no payment. Best-effort per chain: a chain whose config is absent or\n * whose RPC read fails is omitted rather than failing the whole result, so the\n * wallet view degrades gracefully. Available after `start()` (Solana/Mina keys\n * are derived there).\n */\n async getBalances(): Promise<WalletBalance[]> {\n const out: WalletBalance[] = [];\n\n // EVM: read the settlement token (preferredTokens) for the client's\n // settlement chain. `supportedChains` is a union with the network PRESET\n // first (see applyDefaults), so the preset's primary EVM chain (e.g.\n // base-sepolia on devnet) sorts ahead of an explicitly-configured chain\n // like `evm:anvil:31337`. Picking the FIRST evm key would read the preset\n // chain's token — a different contract with a 0 balance — even though the\n // faucet funds, and channels live on, the settlement chain. So prefer the\n // evm key that is the actual settlement chain (present in\n // `settlementAddresses`), falling back to the first usable evm chain.\n const evmAddress = this.getEvmAddress();\n const rpcUrls = this.config.chainRpcUrls;\n const tokens = this.config.preferredTokens;\n if (evmAddress && rpcUrls && tokens) {\n const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);\n const usableEvm = (c: string): boolean =>\n c.startsWith('evm') && Boolean(rpcUrls[c]) && Boolean(tokens[c]);\n const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});\n const chainKey =\n settlementKeys.find((c) => usableEvm(c)) ?? chainKeys.find(usableEvm);\n const rpcUrl = chainKey ? rpcUrls[chainKey] : undefined;\n const tokenAddress = chainKey ? tokens[chainKey] : undefined;\n if (chainKey && rpcUrl && tokenAddress) {\n try {\n out.push(\n await readEvmTokenBalance({\n rpcUrl,\n chainKey,\n tokenAddress,\n owner: evmAddress,\n })\n );\n } catch {\n /* best-effort: drop EVM on read failure */\n }\n }\n }\n\n // Solana: SPL balance of the negotiated token mint.\n const solAddress = this.getSolanaAddress();\n const sol = this.config.solanaChannel;\n if (solAddress && sol?.rpcUrl && sol.tokenMint) {\n try {\n out.push(\n await readSolanaTokenBalance({\n rpcUrl: sol.rpcUrl,\n mint: sol.tokenMint,\n owner: solAddress,\n })\n );\n } catch {\n /* best-effort */\n }\n }\n\n // Mina: native MINA balance via GraphQL.\n const minaAddress = this.getMinaAddress();\n const mina = this.config.minaChannel;\n if (minaAddress && mina?.graphqlUrl) {\n try {\n out.push(\n await readMinaBalance({\n graphqlUrl: mina.graphqlUrl,\n owner: minaAddress,\n })\n );\n } catch {\n /* best-effort */\n }\n }\n\n return out;\n }\n\n /**\n * The FULL multi-chain wallet view (#299): for every chain the identity is\n * configured for, the native coin (ETH / SOL / MINA) AND every configured\n * token (USDC), grouped per chain with the identity's address on that chain.\n * A superset of {@link getBalances} — which stays scoped to the channel's\n * settlement token — kept as a separate reader so channel-settlement callers\n * are unaffected.\n *\n * FREE: read-only RPC, no signing, no payment. Works on an UNSTARTED client:\n * the Solana/Mina addresses (which the signers only register during\n * `start()`) are derived on demand from the retained mnemonic — the SAME keys\n * `start()` would register and that `rig fund` prints — so all configured\n * chains appear even before a start. Best-effort per chain: an unreachable\n * RPC yields `{ unreadable: true }` for that chain, never failing the others.\n *\n * `fallback` supplies Solana/Mina channel params (RPC/GraphQL + token) to use\n * ONLY when `config.solanaChannel`/`config.minaChannel` are unset — a\n * wallet-view-only default (e.g. the network preset's public RPC) that lets a\n * caller show all three chains, reading 0 for a not-yet-on-chain account,\n * WITHOUT injecting those channels into the client's settlement config (which\n * would change chain negotiation). Explicit config wins.\n */\n async getWalletBalances(fallback?: {\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n }): Promise<WalletChainBalances[]> {\n const sources: WalletBalanceSources = {};\n\n // Solana/Mina keys are only registered as signers during start(); derive\n // them from the retained mnemonic on demand so an unstarted client (e.g.\n // `rig balance`) still reports every configured chain. Derived once, lazily.\n let derived: Awaited<ReturnType<typeof deriveFullIdentity>> | undefined;\n let derivedTried = false;\n const ensureDerived = async (): Promise<typeof derived> => {\n if (derivedTried) return derived;\n derivedTried = true;\n if (this.config.mnemonic) {\n derived = await deriveFullIdentity(\n this.config.mnemonic,\n this.config.mnemonicAccountIndex ?? 0\n );\n }\n return derived;\n };\n\n // EVM: native ETH + settlement USDC. Pick the settlement chain key the same\n // way getBalances does (settlement chain wins over the preset primary).\n const evmAddress = this.getEvmAddress();\n const rpcUrls = this.config.chainRpcUrls;\n const tokens = this.config.preferredTokens;\n if (evmAddress && rpcUrls) {\n const usableEvm = (c: string): boolean =>\n c.startsWith('evm') && Boolean(rpcUrls[c]);\n const settlementKeys = Object.keys(this.config.settlementAddresses ?? {});\n const chainKeys = this.config.supportedChains ?? Object.keys(rpcUrls);\n const chainKey =\n settlementKeys.find(usableEvm) ?? chainKeys.find(usableEvm);\n if (chainKey && rpcUrls[chainKey]) {\n sources.evm = {\n chainKey,\n rpcUrl: rpcUrls[chainKey],\n owner: evmAddress,\n ...(tokens?.[chainKey] ? { tokenAddress: tokens[chainKey] } : {}),\n };\n }\n }\n\n // Solana: native SOL + SPL USDC (the negotiated mint). Explicit config\n // wins; else the caller's wallet-view fallback (e.g. network preset RPC).\n const sol = this.config.solanaChannel ?? fallback?.solanaChannel;\n if (sol?.rpcUrl) {\n const solAddress =\n this.getSolanaAddress() ?? (await ensureDerived())?.solana.publicKey;\n if (solAddress) {\n sources.solana = {\n chainKey: 'solana',\n rpcUrl: sol.rpcUrl,\n owner: solAddress,\n ...(sol.tokenMint ? { tokenMint: sol.tokenMint } : {}),\n };\n }\n }\n\n // Mina: native MINA plus, when the deployment settles a custom token, that\n // token's balance (USDC) — read via the derived/explicit `minaChannel.tokenId`\n // (core preset or announce, see resolveNetworkTopology/deriveMinaChannel). A\n // fresh client with no explicit `config.minaChannel` still gets both.\n // Explicit config wins; else the caller's wallet-view fallback.\n const mina = this.config.minaChannel ?? fallback?.minaChannel;\n if (mina?.graphqlUrl) {\n const minaAddress =\n this.getMinaAddress() ?? (await ensureDerived())?.mina.publicKey;\n if (minaAddress) {\n sources.mina = {\n chainKey: 'mina',\n graphqlUrl: mina.graphqlUrl,\n owner: minaAddress,\n ...(mina.tokenId ? { tokenId: mina.tokenId } : {}),\n };\n }\n }\n\n return readWalletBalances(sources);\n }\n\n /**\n * Resolves an ILP destination address to a peer ID.\n * Convention: destination \"g.toon.peer1\" → peerId \"peer1\" (last segment).\n * Falls back to first known peer if no match.\n */\n /**\n * The peer id a claim for `destination` accounts under. Normally\n * `resolvePeerId` — but where that throws `PEER_NOT_FOUND` (an empty\n * negotiation map: nothing announced, nothing registered), the\n * destination itself is the key, so the announce-less greeting bootstrap\n * (connector #617) has a stable identity to remember its synthesized\n * negotiation under.\n */\n private peerIdForClaim(destination: string): string {\n try {\n return this.resolvePeerId(destination);\n } catch {\n return destination;\n }\n }\n\n /**\n * The announce-less channel bootstrap (connector #617): when nothing has\n * negotiated with this destination's peer — no kind:10032 announce, no\n * connector-admin registration — ask the route itself. A settling\n * connector's x402 greeting carries the channel-opening facts, and ADR\n * 0022 makes the greeting the ONLY place the Rust fleet will ever state\n * them. Synthesizes a {@link PeerNegotiation} from those facts, remembers\n * it, and returns it; `undefined` when there is no edge to ask or the\n * greeting carries no settlement facts this client can open a channel on.\n *\n * A two-chain greeting (connector #632's `extra.settlements`) prefers EVM\n * — the long-standing default — UNLESS the wallet holds Solana\n * settlement-token funds and holds none on EVM (issue #470), in which case\n * it opens the Solana leg instead: a wallet funded only with Solana devnet\n * assets can bootstrap exactly as an EVM one does. A Solana-only greeting\n * (no EVM leg at all) always opens Solana — there is nothing to compare\n * funds against.\n *\n * That comparison is only as good as what {@link getBalances} can SEE: with\n * no `solanaChannel` config it cannot read the Solana side at all, so a\n * Solana-funded client silently looks broke and takes the EVM leg (issue\n * #474). We cannot fix the read here — the config genuinely isn't there —\n * but we remember the peer so the resulting EVM funding failure names the\n * missing config instead of reading as a plain \"fund your wallet\".\n *\n * Never throws: this is a fallback on a path that already has a precise\n * error (`PEER_NOT_NEGOTIATED`), and a transport failure while ASKING\n * must not mask it.\n */\n private async negotiateFromGreeting(\n destination: string,\n peerId: string\n ): Promise<PeerNegotiation | undefined> {\n let edge: string;\n try {\n edge = this.resolveClientEdgeEndpoint();\n } catch {\n return undefined;\n }\n try {\n const terms = await this.connectorEdge.getRouteTerms(edge, destination);\n const evmSettlement = terms?.settlement;\n const solanaSettlement = terms?.settlements?.find(\n (entry) => entry.kind === 'solana'\n );\n if (!evmSettlement && !solanaSettlement) return undefined;\n\n let negotiation: PeerNegotiation | undefined;\n if (\n solanaSettlement &&\n (!evmSettlement || (await this.walletPrefersSolana()))\n ) {\n negotiation = this.solanaNegotiationFromSettlement(solanaSettlement);\n } else if (evmSettlement) {\n negotiation = this.evmNegotiationFromSettlement(evmSettlement);\n // EVM chosen while the greeting also offered Solana we could not read.\n if (solanaSettlement && !this.canReadSolanaBalance()) {\n this.unreadableSolanaLegs.add(peerId);\n }\n }\n if (!negotiation) return undefined;\n\n this.peerNegotiations.set(peerId, negotiation);\n return negotiation;\n } catch (error) {\n console.warn(\n '[ToonClient] channel bootstrap from the x402 greeting failed:',\n String(error)\n );\n return undefined;\n }\n }\n\n /**\n * Build the EVM {@link PeerNegotiation} from the greeting's legacy\n * `settlement` object (connector #617). `undefined` when `chain` is not\n * the documented `evm:<chainId>` shape — the greeting is malformed rather\n * than a chain this client cannot open, so bootstrap declines instead of\n * opening against unverified facts.\n */\n private evmNegotiationFromSettlement(\n settlement: ConnectorSettlementTerms\n ): PeerNegotiation | undefined {\n const [chainType, chainIdText] = settlement.chain.split(':');\n const chainId = Number(chainIdText);\n if (chainType !== 'evm' || !Number.isFinite(chainId)) return undefined;\n return {\n chain: settlement.chain,\n chainType,\n chainId,\n settlementAddress: settlement.settlementAddress,\n tokenAddress: settlement.tokenAddress,\n tokenNetwork: settlement.tokenNetwork,\n };\n }\n\n /**\n * Build the Solana {@link PeerNegotiation} from a `settlements` entry\n * (connector #632). Unlike the EVM leg there is no numeric chain id to\n * parse or validate — `chain` is always the literal `'solana'` — so,\n * unlike {@link evmNegotiationFromSettlement}, this cannot fail.\n */\n private solanaNegotiationFromSettlement(\n settlement: ConnectorSolanaSettlementTerms\n ): PeerNegotiation {\n return {\n chain: 'solana',\n chainType: 'solana',\n chainId: 'solana',\n settlementAddress: settlement.settlementAddress,\n tokenAddress: settlement.tokenAddress,\n tokenNetwork: settlement.programId,\n };\n }\n\n /**\n * Whether a two-chain greeting-bootstrap should open the Solana leg\n * instead of the default EVM one (issue #470): the wallet holds Solana\n * SETTLEMENT-TOKEN funds and holds none on EVM.\n *\n * Reads {@link getBalances}, which reports one balance per chain — the SPL\n * settlement token on Solana, NOT native SOL (issue #474). That is\n * deliberate: SOL alone cannot collateralize a channel, so a SOL-only\n * wallet must not steer the negotiation to Solana. The native SOL a fresh\n * open needs for rent + fees is checked separately, at open time, by the\n * Solana opener's funding preflight.\n *\n * `getBalances` is itself best-effort per chain (a missing config or failed\n * RPC read just omits that chain) — this never throws, degrading to \"prefer\n * EVM\" (the pre-existing default) on any read failure. When Solana is\n * omitted because `solanaChannel` is unset, see\n * {@link canReadSolanaBalance} / {@link unreadableSolanaLegs}.\n */\n private async walletPrefersSolana(): Promise<boolean> {\n try {\n const balances = await this.getBalances();\n const hasFunds = (chain: 'evm' | 'solana'): boolean =>\n balances.some((b) => b.chain === chain && BigInt(b.amount) > 0n);\n return hasFunds('solana') && !hasFunds('evm');\n } catch {\n return false;\n }\n }\n\n /**\n * Whether {@link getBalances} can report a Solana balance at all — the exact\n * condition that reader gates on. False means a Solana-funded wallet reads\n * as empty, so `walletPrefersSolana` cannot see its funds.\n */\n private canReadSolanaBalance(): boolean {\n const sol = this.config.solanaChannel;\n return Boolean(this.getSolanaAddress() && sol?.rpcUrl && sol.tokenMint);\n }\n\n /**\n * Re-throw a channel-open failure with the missing-`solanaChannel` diagnosis\n * attached (issue #474).\n *\n * When the peer's greeting advertised a Solana leg this client could not\n * evaluate, \"the EVM wallet has no funds/gas\" is a symptom, not the cause:\n * the funds may be sitting on Solana, invisible because `solanaChannel` is\n * unconfigured. Only funding failures are rewritten — every other error is\n * returned untouched, since a transport/RPC/contract fault has nothing to do\n * with which chain was picked.\n */\n private withSolanaLegHint(peerId: string, error: unknown): unknown {\n if (!this.unreadableSolanaLegs.has(peerId)) return error;\n const isFunding =\n error instanceof ChannelFundingError || isInsufficientGasError(error);\n if (!isFunding) return error;\n const detail = error instanceof Error ? error.message : String(error);\n return new ChannelFundingError(\n `${detail} NOTE: the route also offered a Solana settlement leg, but this ` +\n `client has no \\`solanaChannel\\` config (rpcUrl + tokenMint), so its Solana ` +\n `balance could not be read and the EVM leg was chosen by default. If the ` +\n `wallet is funded on Solana, configure \\`solanaChannel\\` and retry.`,\n error instanceof Error ? error : undefined\n );\n }\n\n private resolvePeerId(destination: string): string {\n // Check if destination matches a known peer's ILP address pattern\n const segments = destination.split('.');\n const lastSegment = segments[segments.length - 1] ?? '';\n\n // Direct match against peerNegotiations keys\n if (lastSegment && this.peerNegotiations.has(lastSegment)) {\n return lastSegment;\n }\n\n // Try \"nostr-\" prefixed peer IDs (convention: nostr-{pubkey_prefix})\n for (const peerId of this.peerNegotiations.keys()) {\n if (\n destination.endsWith(`.${peerId}`) ||\n destination.endsWith(`.${peerId.replace('nostr-', '')}`)\n ) {\n return peerId;\n }\n }\n\n // Fallback: return first peer\n const firstPeerResult = this.peerNegotiations.keys().next();\n if (!firstPeerResult.done && firstPeerResult.value)\n return firstPeerResult.value;\n\n throw new ToonClientError(\n `Cannot resolve peer for destination: ${destination}`,\n 'PEER_NOT_FOUND'\n );\n }\n\n /**\n * Extracts chain context (chainId + tokenNetworkAddress) from a chain key like 'evm:base:421614'.\n */\n private getChainContext(\n negotiatedChain?: string\n ):\n | { chainId: number; tokenNetworkAddress: string; tokenAddress?: string }\n | undefined {\n if (!negotiatedChain) return undefined;\n const parts = negotiatedChain.split(':');\n // Accept 3-part `evm:{network}:{chainId}` and 2-part `evm:{chainId}`.\n const chainIdPart =\n parts.length >= 3 ? parts[2] : parts.length >= 2 ? parts[1] : undefined;\n const numericChainId =\n chainIdPart !== undefined ? parseInt(chainIdPart, 10) : NaN;\n if (isNaN(numericChainId)) return undefined;\n const tokenNetworkAddress = this.config.tokenNetworks?.[negotiatedChain];\n if (!tokenNetworkAddress) return undefined;\n const tokenAddress = this.config.preferredTokens?.[negotiatedChain];\n return { chainId: numericChainId, tokenNetworkAddress, tokenAddress };\n }\n\n /**\n * Gets the default chain context from the first supported chain in config.\n */\n private getDefaultChainContext():\n | { chainId: number; tokenNetworkAddress: string; tokenAddress?: string }\n | undefined {\n const chains = this.config.supportedChains;\n if (!chains?.length) return undefined;\n return this.getChainContext(chains[0]);\n }\n\n /**\n * Sends an ILP payment, optionally with a balance proof claim via BTP.\n *\n * @param params - Payment parameters\n * @returns ILP send result\n * @throws {ToonClientError} If client is not started\n */\n async sendPayment(params: {\n destination: string;\n amount: string;\n data?: string;\n claim?: SignedBalanceProof;\n }): Promise<IlpSendResult> {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n const ilpParams = {\n destination: params.destination,\n amount: params.amount,\n data: params.data ?? '',\n };\n\n // Require claim + BTP — plain sendIlpPacket is only valid for\n // node-to-node forwarding (relay.ts), not client-to-node.\n if (!params.claim) {\n throw new ToonClientError(\n 'Signed balance proof required. Call signBalanceProof() first.',\n 'MISSING_CLAIM'\n );\n }\n const transport = this.getClaimTransport();\n\n const claimMessage = this.buildClaimMessageForProof(params.claim);\n return transport.sendIlpPacketWithClaim(\n ilpParams,\n claimMessage as unknown as Record<string, unknown>\n );\n }\n\n /**\n * Stops the ToonClient and cleans up resources.\n *\n * This will:\n * 1. Disconnect BTP client if connected\n * 2. Clear internal state\n *\n * @throws {ToonClientError} If client is not started\n */\n async stop(): Promise<void> {\n if (!this.state) {\n throw new ToonClientError('Client not started', 'INVALID_STATE');\n }\n\n try {\n // Disconnect BTP client if connected\n if (this.state.btpClient) {\n await this.state.btpClient.disconnect();\n }\n\n // Clear state\n this.state = null;\n } catch (error) {\n throw new ToonClientError(\n 'Failed to stop client',\n 'STOP_ERROR',\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Returns true if the client is currently started.\n */\n isStarted(): boolean {\n return this.state !== null;\n }\n\n /**\n * Gets the number of peers discovered during bootstrap.\n *\n * @returns Number of peers discovered\n * @throws {ToonClientError} If client is not started\n */\n getPeersCount(): number {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n return this.state.peersDiscovered;\n }\n\n /**\n * Gets the list of peers discovered by the relay monitor.\n *\n * @returns Array of discovered peer objects\n * @throws {ToonClientError} If client is not started\n */\n getDiscoveredPeers() {\n if (!this.state) {\n throw new ToonClientError(\n 'Client not started. Call start() first.',\n 'INVALID_STATE'\n );\n }\n\n return this.state.discoveryTracker.getDiscoveredPeers();\n }\n}\n","import { generateSecretKey } from 'nostr-tools/pure';\nimport {\n resolveClientNetwork,\n type NetworkFamilyStatus,\n} from '@toon-protocol/core';\nimport { ValidationError } from './errors.js';\nimport {\n validateMnemonic,\n deriveNostrKeyFromMnemonic,\n} from './keys/KeyDerivation.js';\nimport type { ToonClientConfig } from './types.js';\n\n/**\n * Settlement info produced by buildSettlementInfo().\n * Extends the core SettlementConfig shape with ilpAddress for client use.\n */\nexport interface ClientSettlementInfo {\n ilpAddress?: string;\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n}\n\n/**\n * Applies named-network preset defaults to a client config.\n *\n * When `config.network` is set and != `'custom'`, the settlement-related\n * fields are defaulted from the shared core presets (`resolveClientNetwork`):\n * RPC/GraphQL URLs, supported chain identifiers, preferred tokens, EVM\n * TokenNetwork addresses, and the Solana/Mina channel params. Any explicit\n * per-chain field on `config` OVERRIDES the preset (explicit always wins).\n *\n * `'custom'` and the unset case both pass `config` through untouched, keeping\n * the fully-manual path and full backward compatibility.\n *\n * @returns A shallow copy with preset defaults merged in (never mutates input).\n */\nexport function applyNetworkPresets(\n config: ToonClientConfig\n): ToonClientConfig {\n const { network } = config;\n if (!network || network === 'custom') return config;\n\n const presets = resolveClientNetwork(network);\n\n // Merge a preset record under an explicit one (explicit keys win).\n const mergeRecord = (\n explicit: Record<string, string> | undefined,\n preset: Record<string, string>\n ): Record<string, string> => ({ ...preset, ...explicit });\n\n // supportedChains: union (preset first), preserving any explicit extras.\n const supportedChains = config.supportedChains\n ? Array.from(\n new Set([...presets.supportedChains, ...config.supportedChains])\n )\n : presets.supportedChains;\n\n return {\n ...config,\n supportedChains,\n chainRpcUrls: mergeRecord(config.chainRpcUrls, presets.chainRpcUrls),\n preferredTokens: mergeRecord(\n config.preferredTokens,\n presets.preferredTokens\n ),\n tokenNetworks: mergeRecord(config.tokenNetworks, presets.tokenNetworks),\n // settlementAddresses are identity-derived (per-client), so they have no\n // preset; pass any explicit value through unchanged.\n ...(config.settlementAddresses && {\n settlementAddresses: config.settlementAddresses,\n }),\n // Channel params: preset fills the deployed programId/zkApp + URLs unless\n // the caller supplied their own (explicit object wins wholesale).\n ...(presets.solanaChannel && {\n solanaChannel: config.solanaChannel ?? presets.solanaChannel,\n }),\n ...(presets.minaChannel && {\n minaChannel: config.minaChannel ?? presets.minaChannel,\n }),\n };\n}\n\n/**\n * Returns per-chain settlement readiness for the configured `network` tier,\n * mirroring the relay node's status. Returns `undefined` when `network` is\n * unset or `'custom'` (no preset tier to report on).\n */\nexport function getNetworkStatus(\n config: ToonClientConfig\n): NetworkFamilyStatus | undefined {\n const { network } = config;\n if (!network || network === 'custom') return undefined;\n return resolveClientNetwork(network).status;\n}\n\n/**\n * Normalize a connector-proxy base URL into its `POST /ilp` endpoint.\n *\n * `https://proxy.devnet.toonprotocol.dev` → `https://proxy.devnet.toonprotocol.dev/ilp`\n * `https://proxy.devnet.toonprotocol.dev/ilp` → unchanged (idempotent)\n * `https://proxy.devnet.toonprotocol.dev/` → `https://proxy.devnet.toonprotocol.dev/ilp`\n *\n * Returns `undefined` for an empty/falsy input so callers can `??`-chain it.\n */\nexport function proxyIlpEndpoint(proxyUrl: string | undefined): string | undefined {\n if (!proxyUrl) return undefined;\n const trimmed = proxyUrl.replace(/\\/+$/, '');\n return /\\/ilp$/i.test(trimmed) ? trimmed : `${trimmed}/ilp`;\n}\n\n/**\n * Validates ToonClient configuration.\n *\n * This story implements HTTP mode only. Embedded mode validation will be added in a future epic.\n *\n * @throws {ValidationError} If configuration is invalid\n */\nexport function validateConfig(config: ToonClientConfig): void {\n // Reject embedded mode (not implemented in this story)\n if (config.connector !== undefined) {\n throw new ValidationError(\n 'Embedded mode not yet implemented in ToonClient. Use connectorUrl for HTTP mode.'\n );\n }\n\n // Require an HTTP edge for HTTP mode — either an explicit `connectorUrl` or a\n // connector-`proxyUrl` (the devnet payment-proxy). `applyDefaults` derives\n // `connectorUrl` from `proxyUrl` when only the proxy is given.\n if (!config.connectorUrl && !config.proxyUrl) {\n throw new ValidationError(\n 'connectorUrl (or proxyUrl) is required for HTTP mode. Example: \"http://localhost:8080\"'\n );\n }\n\n // Validate connectorUrl format\n if (config.connectorUrl) {\n try {\n const url = new URL(config.connectorUrl);\n if (!url.protocol.startsWith('http')) {\n throw new Error('Must be HTTP or HTTPS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid connectorUrl: must be a valid HTTP/HTTPS URL (e.g., \"http://localhost:8080\"). ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate proxyUrl / faucetUrl format when provided (both are HTTP(S) URLs).\n for (const [field, value] of [\n ['proxyUrl', config.proxyUrl],\n ['faucetUrl', config.faucetUrl],\n ] as const) {\n if (value === undefined) continue;\n try {\n const url = new URL(value);\n if (!url.protocol.startsWith('http')) {\n throw new Error('Must be HTTP or HTTPS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid ${field}: must be a valid HTTP/HTTPS URL. ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate secretKey only when provided\n if (config.secretKey !== undefined) {\n if (!config.secretKey || config.secretKey.length !== 32) {\n throw new ValidationError(\n 'secretKey must be 32 bytes (Nostr private key)'\n );\n }\n }\n\n // Validate mnemonic when provided. The mnemonic derives the Nostr/EVM +\n // Solana/Mina identity, so it cannot coexist with an explicit secretKey\n // (that would split the Nostr identity from the Solana/Mina identity). An\n // explicit evmPrivateKey override IS allowed (documented hardware-wallet case).\n if (config.mnemonic !== undefined) {\n if (config.secretKey !== undefined) {\n throw new ValidationError(\n 'Provide either `mnemonic` or `secretKey`, not both — the mnemonic ' +\n 'derives the Nostr key, so a separate secretKey would yield an ' +\n 'inconsistent cross-chain identity. (An `evmPrivateKey` override is allowed.)'\n );\n }\n if (\n typeof config.mnemonic !== 'string' ||\n !validateMnemonic(config.mnemonic)\n ) {\n throw new ValidationError('mnemonic must be a valid BIP-39 phrase');\n }\n }\n\n // Validate mnemonicAccountIndex when provided (must be a non-negative\n // integer within the BIP-32 non-hardened range, matching the SDK guard).\n if (config.mnemonicAccountIndex !== undefined) {\n const idx = config.mnemonicAccountIndex;\n if (!Number.isInteger(idx) || idx < 0 || idx > 0x7fffffff) {\n throw new ValidationError(\n 'mnemonicAccountIndex must be a non-negative integer (0 to 2147483647)'\n );\n }\n }\n\n if (!config.ilpInfo?.ilpAddress) {\n throw new ValidationError('ilpInfo.ilpAddress is required');\n }\n\n if (!config.toonEncoder || typeof config.toonEncoder !== 'function') {\n throw new ValidationError('toonEncoder function is required');\n }\n\n if (!config.toonDecoder || typeof config.toonDecoder !== 'function') {\n throw new ValidationError('toonDecoder function is required');\n }\n\n // Validate evmPrivateKey format when provided\n if (config.evmPrivateKey !== undefined) {\n if (config.evmPrivateKey instanceof Uint8Array) {\n if (config.evmPrivateKey.length !== 32) {\n throw new ValidationError('evmPrivateKey must be 32 bytes');\n }\n } else if (typeof config.evmPrivateKey === 'string') {\n const hex = config.evmPrivateKey.startsWith('0x')\n ? config.evmPrivateKey.slice(2)\n : config.evmPrivateKey;\n if (!/^[0-9a-fA-F]{64}$/.test(hex)) {\n throw new ValidationError('evmPrivateKey must be a 32-byte hex string');\n }\n } else {\n throw new ValidationError(\n 'evmPrivateKey must be a hex string or Uint8Array'\n );\n }\n }\n\n // Validate btpUrl when provided\n if (config.btpUrl !== undefined) {\n try {\n const url = new URL(config.btpUrl);\n if (!url.protocol.startsWith('ws')) {\n throw new Error('Must be WS or WSS');\n }\n } catch (error) {\n throw new ValidationError(\n `Invalid btpUrl: must be a valid WebSocket URL (e.g., \"ws://localhost:3000\"). ` +\n `Error: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n\n // Validate chainRpcUrls keys match supportedChains when both present\n if (config.chainRpcUrls && config.supportedChains) {\n for (const chain of Object.keys(config.chainRpcUrls)) {\n if (!config.supportedChains.includes(chain)) {\n throw new ValidationError(\n `chainRpcUrls key \"${chain}\" is not in supportedChains`\n );\n }\n }\n }\n}\n\n/**\n * The resolved config type after defaults are applied.\n * secretKey is guaranteed to be present (auto-generated if omitted).\n */\nexport type ResolvedConfig = Required<\n Omit<\n ToonClientConfig,\n | 'connector'\n | 'mnemonic'\n | 'mnemonicAccountIndex'\n | 'evmPrivateKey'\n | 'network'\n | 'supportedChains'\n | 'settlementAddresses'\n | 'preferredTokens'\n | 'tokenNetworks'\n | 'btpUrl'\n | 'btpAuthToken'\n | 'btpPeerId'\n | 'connectorHttpEndpoint'\n | 'proxyUrl'\n | 'faucetUrl'\n | 'connectorSupportsUpgrade'\n | 'chainRpcUrls'\n | 'initialDeposit'\n | 'settlementTimeout'\n | 'solanaChannel'\n | 'minaChannel'\n | 'swapMinaMakerSignatures'\n | 'channelStorePath'\n | 'knownPeers'\n | 'destinationAddress'\n >\n> & {\n connector?: unknown;\n /** Always present after applyDefaults() — derived from secretKey if not explicitly provided */\n evmPrivateKey: string | Uint8Array;\n /**\n * BIP-39 phrase retained so `ToonClient.start()` can derive the Solana/Mina\n * keys asynchronously and register the corresponding signers. The Nostr/EVM\n * keys are already resolved synchronously into `secretKey`/`evmPrivateKey`.\n */\n mnemonic?: string;\n /**\n * BIP-44 account index for mnemonic-based derivation (defaults to 0).\n * Retained so `ToonClient.start()` derives the Solana/Mina signers at the\n * same index as the synchronously-resolved Nostr/EVM keys.\n */\n mnemonicAccountIndex?: number;\n /** Named network tier, retained for `getNetworkStatus()`. */\n network?: ToonClientConfig['network'];\n supportedChains?: string[];\n settlementAddresses?: Record<string, string>;\n preferredTokens?: Record<string, string>;\n tokenNetworks?: Record<string, string>;\n btpUrl?: string;\n btpAuthToken?: string;\n btpPeerId?: string;\n connectorHttpEndpoint?: string;\n proxyUrl?: string;\n faucetUrl?: string;\n connectorSupportsUpgrade?: boolean;\n chainRpcUrls?: Record<string, string>;\n initialDeposit?: string;\n settlementTimeout?: number;\n solanaChannel?: ToonClientConfig['solanaChannel'];\n minaChannel?: ToonClientConfig['minaChannel'];\n swapMinaMakerSignatures?: ToonClientConfig['swapMinaMakerSignatures'];\n channelStorePath?: string;\n knownPeers?: {\n pubkey: string;\n relayUrl: string;\n btpEndpoint?: string;\n }[];\n destinationAddress: string;\n};\n\n/**\n * Applies default values to optional configuration fields.\n * Auto-generates a Nostr keypair when secretKey is omitted.\n * Derives btpUrl from connectorUrl when not provided.\n */\nexport function applyDefaults(rawConfig: ToonClientConfig): ResolvedConfig {\n // Fill settlement-related defaults from the named-network presets first\n // (explicit per-chain fields always win). No-op for unset/`custom`.\n const config = applyNetworkPresets(rawConfig);\n\n // Resolve the Nostr secret key. Precedence:\n // 1. explicit secretKey\n // 2. derived from mnemonic (Nostr/EVM only — Solana/Mina are derived\n // asynchronously in start(), which is why the mnemonic is retained)\n // 3. auto-generated ephemeral key\n const secretKey =\n config.secretKey ??\n (config.mnemonic\n ? deriveNostrKeyFromMnemonic(\n config.mnemonic,\n config.mnemonicAccountIndex ?? 0\n ).secretKey\n : generateSecretKey());\n\n // Derive the connector-proxy `POST /ilp` endpoint from `proxyUrl` (unless an\n // explicit `connectorHttpEndpoint` was given — explicit always wins). When set\n // this makes `selectIlpTransport` prefer the stateless HttpIlpClient transport\n // for one-shot writes, routing through the devnet payment-proxy.\n const connectorHttpEndpoint =\n config.connectorHttpEndpoint ?? proxyIlpEndpoint(config.proxyUrl);\n\n // `connectorUrl` is required by validateConfig but can be satisfied by\n // `proxyUrl`; fall back to the proxy base so downstream code (HttpRuntimeClient\n // fallback, destination derivation) always has an HTTP edge URL.\n const connectorUrl =\n config.connectorUrl ?? config.proxyUrl?.replace(/\\/+$/, '');\n\n // Derive btpUrl from connectorUrl when not explicitly provided\n // http://host:8080 → ws://host:3000.\n // SKIP this auto-derivation when an HTTP/proxy transport is configured: the\n // proxy edge serves ILP-over-HTTP and may not expose BTP, so we must not open\n // (or require) a BTP socket. Writes route through HttpIlpClient instead.\n let btpUrl = config.btpUrl;\n if (!btpUrl && connectorUrl && !connectorHttpEndpoint) {\n try {\n const url = new URL(connectorUrl);\n const wsProtocol = url.protocol === 'https:' ? 'wss:' : 'ws:';\n btpUrl = `${wsProtocol}//${url.hostname}:3000`;\n } catch {\n // connectorUrl already validated, this shouldn't happen\n }\n }\n\n // Derive destinationAddress from connectorUrl port when not explicitly provided\n // This provides sensible defaults for local development:\n // - http://localhost:8080 → g.toon.genesis (genesis node)\n // - http://localhost:8090 → g.toon.peer1 (peer1 node)\n // For production, explicitly set destinationAddress in config\n let destinationAddress = config.destinationAddress;\n if (!destinationAddress && connectorUrl) {\n try {\n const url = new URL(connectorUrl);\n if (url.hostname === 'localhost' || url.hostname === '127.0.0.1') {\n // Map common local ports to known nodes\n if (url.port === '8080') {\n destinationAddress = 'g.toon.genesis';\n } else if (url.port === '8090') {\n destinationAddress = 'g.toon.peer1';\n } else if (url.port === '8100') {\n destinationAddress = 'g.toon.peer2';\n } else {\n // Fallback: use ilpInfo.ilpAddress if available\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n } else {\n // Production: default to ilpInfo.ilpAddress\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n } catch {\n destinationAddress = config.ilpInfo?.ilpAddress || 'g.toon.relay';\n }\n }\n\n // Derive EVM private key from Nostr secret key when not explicitly provided.\n // Both Nostr and EVM use secp256k1, so a single 32-byte key works for both.\n const evmPrivateKey = config.evmPrivateKey ?? secretKey;\n\n return {\n ...config,\n secretKey,\n evmPrivateKey,\n // Satisfied by connectorUrl OR proxyUrl (validateConfig enforced one of them).\n connectorUrl: connectorUrl as string,\n // Surface the derived `POST /ilp` endpoint so HTTP mode selects HttpIlpClient.\n ...(connectorHttpEndpoint ? { connectorHttpEndpoint } : {}),\n // Last-resort relay default. An explicit `config.relayUrl` always wins;\n // `applyNetworkPresets` does not set a per-network relay, so this fallback\n // points at the public devnet relay rather than a dead localhost socket.\n relayUrl: config.relayUrl ?? 'wss://relay-ws.devnet.toonprotocol.dev',\n queryTimeout: config.queryTimeout ?? 30000,\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n btpUrl,\n destinationAddress: destinationAddress as string, // Always set by logic above\n };\n}\n\n/**\n * Builds SettlementConfig from client config.\n * Returns undefined if no settlement-related config is present.\n */\nexport function buildSettlementInfo(\n rawConfig: ToonClientConfig\n): ClientSettlementInfo | undefined {\n // Resolve named-network preset defaults so a `network`-only config still\n // produces settlement info (explicit fields win; no-op for unset/`custom`).\n const config = applyNetworkPresets(rawConfig);\n\n if (\n !config.supportedChains?.length &&\n !config.settlementAddresses &&\n !config.preferredTokens &&\n !config.tokenNetworks\n ) {\n return undefined;\n }\n\n return {\n ilpAddress: config.ilpInfo?.ilpAddress,\n supportedChains: config.supportedChains,\n settlementAddresses: config.settlementAddresses,\n preferredTokens: config.preferredTokens,\n tokenNetworks: config.tokenNetworks,\n };\n}\n","/**\n * Base error class for all TOON client errors.\n */\nexport class ToonClientError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n cause?: Error\n ) {\n super(message, { cause });\n this.name = 'ToonClientError';\n }\n}\n\n/**\n * Network error for connection failures (ECONNREFUSED, ETIMEDOUT).\n * These errors trigger retry logic with exponential backoff.\n */\nexport class NetworkError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Connector error for 5xx server errors.\n * These errors indicate the connector is unavailable or malfunctioning.\n */\nexport class ConnectorError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'CONNECTOR_ERROR', cause);\n this.name = 'ConnectorError';\n }\n}\n\n/**\n * Validation error for invalid input parameters.\n * These errors are thrown before making any HTTP requests.\n */\nexport class ValidationError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'VALIDATION_ERROR', cause);\n this.name = 'ValidationError';\n }\n}\n\n/**\n * Unauthorized error for 401 responses from connector admin API.\n * Indicates missing or invalid authentication credentials.\n */\nexport class UnauthorizedError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'UNAUTHORIZED', cause);\n this.name = 'UnauthorizedError';\n }\n}\n\n/**\n * Peer not found error for 404 responses when removing a peer.\n * Indicates the specified peer ID does not exist in the connector.\n */\nexport class PeerNotFoundError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'PEER_NOT_FOUND', cause);\n this.name = 'PeerNotFoundError';\n }\n}\n\n/**\n * Peer already exists error for 409 responses when adding a peer.\n * Indicates a peer with the same ID already exists in the connector.\n */\nexport class PeerAlreadyExistsError extends ToonClientError {\n constructor(message: string, cause?: Error) {\n super(message, 'PEER_ALREADY_EXISTS', cause);\n this.name = 'PeerAlreadyExistsError';\n }\n}\n\n/**\n * Thrown when the one-time on-chain payment-channel OPEN reverts because the\n * local settlement wallet has no native gas to pay for its own\n * approve/openChannel/setTotalDeposit transactions. This is the channel OPEN\n * only — per-write settlement rides ILP-over-HTTP and never spends gas. We\n * remap ONLY this case so callers get an actionable message (fund the wallet)\n * instead of the raw viem \"...exceeds the balance of the account\" string\n * (toon-meta#65). Retryable once the wallet is funded; the underlying viem/RPC\n * error is preserved as `cause`.\n */\nexport class ChannelFundingError extends ToonClientError {\n readonly retryable = true;\n constructor(message: string, cause?: Error) {\n super(message, 'CHANNEL_FUNDING', cause);\n this.name = 'ChannelFundingError';\n }\n}\n\n/**\n * Substrings that mark an insufficient-native-gas revert from an on-chain\n * channel-open tx. viem surfaces the node's message verbatim and the exact\n * phrasing varies by RPC (anvil/geth/hardhat), so we match a set of known\n * markers case-insensitively.\n */\nconst INSUFFICIENT_GAS_MARKERS = [\n 'exceeds the balance of the account',\n 'insufficient funds for gas',\n 'insufficient funds for intrinsic transaction cost',\n 'insufficient funds for transfer',\n];\n\n/**\n * True when `err` (or any error in its nested `cause` chain) is an\n * insufficient-native-gas revert. viem wraps the node error one or more levels\n * deep, so the whole chain is flattened and scanned.\n */\nexport function isInsufficientGasError(err: unknown): boolean {\n const parts: string[] = [];\n let cur: unknown = err;\n for (let i = 0; i < 10 && cur != null; i++) {\n parts.push(cur instanceof Error ? cur.message : String(cur));\n cur = cur instanceof Error ? (cur as { cause?: unknown }).cause : undefined;\n }\n const text = parts.join(' | ').toLowerCase();\n return INSUFFICIENT_GAS_MARKERS.some((m) => text.includes(m));\n}\n","import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';\nimport { privateKeyToAccount } from 'viem/accounts';\nimport { toHex } from 'viem';\nimport {\n generateMnemonic as _genMnemonic,\n validateMnemonic as _validateMnemonic,\n mnemonicToSeedSync,\n} from '@scure/bip39';\nimport { wordlist as english } from '@scure/bip39/wordlists/english';\nimport { HDKey } from '@scure/bip32';\nimport { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport type { ToonIdentity } from './types.js';\n\n/**\n * Generate a new 12-word BIP-39 mnemonic.\n */\nexport function generateMnemonic(): string {\n return _genMnemonic(english, 128);\n}\n\n/**\n * Validate a BIP-39 mnemonic phrase.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return _validateMnemonic(mnemonic, english);\n}\n\n/**\n * Maximum valid BIP-32 non-hardened child index (2^31 - 1).\n * Values at or above 2^31 are reserved for hardened derivation.\n */\nconst MAX_BIP32_INDEX = 0x7fffffff;\n\n/**\n * Validate a BIP-44 account index. Mirrors the SDK's `fromMnemonic` guard so\n * the client and SDK reject the same out-of-range indices.\n */\nfunction assertValidAccountIndex(accountIndex: number): void {\n if (\n !Number.isInteger(accountIndex) ||\n accountIndex < 0 ||\n accountIndex > MAX_BIP32_INDEX\n ) {\n throw new Error(\n `Invalid accountIndex: expected a non-negative integer (0 to ${MAX_BIP32_INDEX}), got ${String(accountIndex)}`\n );\n }\n}\n\n/**\n * Derive the Nostr secp256k1 key from mnemonic using NIP-06 path:\n * m/44'/1237'/0'/0/{accountIndex}. At accountIndex 0 this is the canonical\n * m/44'/1237'/0'/0/0, matching the SDK's `fromMnemonic`/`fromMnemonicFull`.\n */\nfunction deriveNostrKey(\n seed: Uint8Array,\n accountIndex = 0\n): {\n secretKey: Uint8Array;\n pubkey: string;\n} {\n const master = HDKey.fromMasterSeed(seed);\n const child = master.derive(`m/44'/1237'/0'/0/${accountIndex}`);\n if (!child.privateKey) {\n throw new Error('Failed to derive Nostr private key from seed');\n }\n const secretKey = new Uint8Array(child.privateKey);\n const pubkey = getPublicKey(secretKey);\n return { secretKey, pubkey };\n}\n\n/**\n * Derive the EVM address from the same secp256k1 key (shares curve with Nostr).\n */\nfunction deriveEvmIdentity(secretKey: Uint8Array): {\n privateKey: Uint8Array;\n address: string;\n} {\n const account = privateKeyToAccount(toHex(secretKey));\n return {\n privateKey: secretKey,\n address: account.address,\n };\n}\n\n/**\n * Derive Solana Ed25519 keypair using SLIP-0010 path:\n * m/44'/501'/{accountIndex}'/0' (all hardened). At accountIndex 0 this is the\n * canonical m/44'/501'/0'/0', matching the SDK's `deriveSolanaIdentity`.\n * Dynamically imports @noble/curves for Ed25519 operations.\n */\nasync function deriveSolanaKey(\n seed: Uint8Array,\n accountIndex = 0\n): Promise<{\n secretKey: Uint8Array;\n publicKey: string;\n}> {\n // SLIP-0010 Ed25519 derivation (hardened only)\n // Uses HMAC-SHA512 with \"ed25519 seed\" as key\n const { hmac } = await import('@noble/hashes/hmac');\n const { sha512 } = await import('@noble/hashes/sha512');\n const { ed25519 } = await import('@noble/curves/ed25519.js');\n\n // SLIP-0010 master key derivation for ed25519\n const encoder = new TextEncoder();\n let I = hmac(sha512, encoder.encode('ed25519 seed'), seed);\n let key = I.slice(0, 32);\n let chainCode = I.slice(32);\n\n // Derive path: m/44'/501'/{accountIndex}'/0' (all hardened)\n const indices = [\n 0x8000002c, // 44'\n 0x800001f5, // 501'\n (0x80000000 + accountIndex) >>> 0, // {accountIndex}'\n 0x80000000, // 0'\n ];\n\n for (const index of indices) {\n const data = new Uint8Array(37);\n data[0] = 0x00;\n data.set(key, 1);\n // Write index as big-endian uint32\n data[33] = (index >>> 24) & 0xff;\n data[34] = (index >>> 16) & 0xff;\n data[35] = (index >>> 8) & 0xff;\n data[36] = index & 0xff;\n\n I = hmac(sha512, chainCode, data);\n key = I.slice(0, 32);\n chainCode = I.slice(32);\n }\n\n const publicKeyBytes: Uint8Array = ed25519.getPublicKey(key);\n\n // Solana keypair = 32-byte private key + 32-byte public key = 64 bytes\n const keypair = new Uint8Array(64);\n keypair.set(key, 0);\n keypair.set(publicKeyBytes, 32);\n\n // Base58 encode the public key\n const publicKey = toBase58(publicKeyBytes);\n\n return { secretKey: keypair, publicKey };\n}\n\n/**\n * Derive Mina Pallas key using path: m/44'/12586'/{accountIndex}'/0/0. At\n * accountIndex 0 this is the canonical m/44'/12586'/0'/0/0, matching the SDK's\n * `deriveMinaIdentity`.\n * Dynamically imports mina-signer.\n */\nasync function deriveMinaKey(\n seed: Uint8Array,\n accountIndex = 0\n): Promise<{\n privateKey: string;\n publicKey: string;\n}> {\n const master = HDKey.fromMasterSeed(seed);\n // Mina coin type = 12586 (0x312A)\n const child = master.derive(`m/44'/12586'/${accountIndex}'/0/0`);\n if (!child.privateKey) {\n throw new Error('Failed to derive Mina private key from seed');\n }\n const keyBytes = new Uint8Array(child.privateKey);\n\n // Clamp the top 2 bits so the scalar is within the Pallas base-field order\n // (matches @toon-protocol/swap's `deriveSwapKeys`). Without this, the raw\n // BIP-32 child scalar can exceed the field order and mina-signer rejects it.\n keyBytes[0] = (keyBytes[0] ?? 0) & 0x3f;\n\n // mina-signer needs the Mina base58check (`EK…`) private-key format, NOT a\n // raw hex scalar (raw hex fails with \"invalid checksum\"). Convert via the\n // shared @toon-protocol/core helper before deriving the public key.\n try {\n const MinaSignerLib = await import('mina-signer');\n const Client =\n 'default' in MinaSignerLib ? MinaSignerLib.default : MinaSignerLib;\n const client = new Client({ network: 'mainnet' });\n\n const hexKey = Array.from(keyBytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n const minaPrivateKey = hexToMinaBase58PrivateKey(hexKey);\n const publicKey = client.derivePublicKey(minaPrivateKey);\n return {\n // Store the clamped big-endian hex scalar; consumers (e.g. the client's\n // MinaSigner) re-convert to base58check via hexToMinaBase58PrivateKey.\n privateKey: hexKey,\n publicKey,\n };\n } catch {\n throw new Error(\n 'mina-signer is required for Mina key derivation. Install it as an optional dependency.'\n );\n }\n}\n\n/**\n * Synchronously derive ONLY the Nostr secp256k1 key (NIP-06) from a mnemonic.\n *\n * The EVM key shares this same secp256k1 key. Solana (Ed25519) and Mina\n * (Pallas) require async dynamic imports — use {@link deriveFullIdentity} for\n * those. This sync subset exists so `ToonClient`'s synchronous constructor can\n * resolve the Nostr/EVM identity from a `mnemonic` config field without an\n * async factory; the client derives Solana/Mina lazily in `start()`.\n */\nexport function deriveNostrKeyFromMnemonic(\n mnemonic: string,\n accountIndex = 0\n): {\n secretKey: Uint8Array;\n pubkey: string;\n} {\n assertValidAccountIndex(accountIndex);\n const seed = mnemonicToSeedSync(mnemonic);\n const result = deriveNostrKey(seed, accountIndex);\n seed.fill(0); // Zero seed after derivation (F7 fix)\n return result;\n}\n\n/**\n * Derive a full multi-chain ToonIdentity from a BIP-39 mnemonic.\n *\n * All four chains vary by `accountIndex` (default 0), matching the SDK's\n * {@link https://www.npmjs.com/package/@toon-protocol/sdk `fromMnemonicFull`}\n * path-per-index scheme so a non-zero index produces the SAME addresses as\n * `fromMnemonicFull(mnemonic, { accountIndex })`. Index 0 is unchanged from the\n * historical fixed paths (back-compat).\n *\n * Chains derived:\n * - Nostr (secp256k1): m/44'/1237'/0'/0/{accountIndex}\n * - EVM (secp256k1): same key as Nostr\n * - Solana (Ed25519): m/44'/501'/{accountIndex}'/0' (SLIP-0010)\n * - Mina (Pallas): m/44'/12586'/{accountIndex}'/0/0\n *\n * @param mnemonic - A valid BIP-39 mnemonic (12 or 24 words).\n * @param accountIndex - BIP-44 account index (default 0).\n */\nexport async function deriveFullIdentity(\n mnemonic: string,\n accountIndex = 0\n): Promise<ToonIdentity> {\n assertValidAccountIndex(accountIndex);\n const seed = mnemonicToSeedSync(mnemonic);\n\n const nostr = deriveNostrKey(seed, accountIndex);\n const evm = deriveEvmIdentity(nostr.secretKey);\n\n // Solana and Mina can fail if optional deps are missing — derive independently\n let solana: ToonIdentity['solana'];\n try {\n solana = await deriveSolanaKey(seed, accountIndex);\n } catch {\n solana = { secretKey: new Uint8Array(64), publicKey: '' };\n }\n\n let mina: ToonIdentity['mina'];\n try {\n mina = await deriveMinaKey(seed, accountIndex);\n } catch {\n mina = { privateKey: '', publicKey: '' };\n }\n\n // Zero seed after derivation (F7 fix)\n seed.fill(0);\n\n return { nostr, evm, solana, mina };\n}\n\n/**\n * Derive a partial identity from an nsec (Nostr-only private key).\n * Nostr + EVM share the same secp256k1 key.\n * Solana and Mina get empty placeholders (not deterministically linked).\n */\nexport function deriveFromNsec(secretKey: Uint8Array): ToonIdentity {\n // Copy input to avoid caller mutation corrupting identity keys\n const keyCopy = new Uint8Array(secretKey);\n const pubkey = getPublicKey(keyCopy);\n const evm = deriveEvmIdentity(keyCopy);\n\n return {\n nostr: { secretKey: keyCopy, pubkey },\n evm,\n solana: { secretKey: new Uint8Array(64), publicKey: '' },\n mina: { privateKey: '', publicKey: '' },\n };\n}\n\n/**\n * Generate a random identity (no mnemonic — for testing or ephemeral use).\n */\nexport function generateRandomIdentity(): ToonIdentity {\n const secretKey = generateSecretKey();\n return deriveFromNsec(secretKey);\n}\n\n// --- Utility ---\n\nconst BASE58_ALPHABET =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\nfunction toBase58(bytes: Uint8Array): string {\n let num = BigInt(0);\n for (const b of bytes) num = num * 256n + BigInt(b);\n let result = '';\n while (num > 0n) {\n result = BASE58_ALPHABET[Number(num % 58n)] + result;\n num = num / 58n;\n }\n for (const b of bytes) {\n if (b === 0) result = '1' + result;\n else break;\n }\n return result;\n}\n","/**\n * Isomorphic binary helpers — works in both Node.js and browser\n * without requiring Buffer polyfills.\n *\n * These replace Buffer usage throughout the client package so that\n * browser consumers (e.g. ditto) don't need the `buffer` npm polyfill.\n */\n\n/** Convert a Uint8Array to a base64 string (browser + Node compatible). */\nexport function toBase64(bytes: Uint8Array): string {\n // Node.js Buffer is a Uint8Array subclass and has toString('base64')\n if (typeof Buffer !== 'undefined' && Buffer.isBuffer(bytes)) {\n return (bytes as Buffer).toString('base64');\n }\n // Browser path: use btoa with binary string\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/** Convert a base64 string to a Uint8Array (browser + Node compatible). */\nexport function fromBase64(base64: string): Uint8Array {\n if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {\n return new Uint8Array(Buffer.from(base64, 'base64'));\n }\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/** Convert a Uint8Array to a hex string. */\nexport function toHex(bytes: Uint8Array): string {\n let hex = '';\n for (const byte of bytes) {\n hex += byte.toString(16).padStart(2, '0');\n }\n return hex;\n}\n\n/** Convert a hex string to a Uint8Array. */\nexport function fromHex(hex: string): Uint8Array {\n const clean = hex.startsWith('0x') ? hex.slice(2) : hex;\n const bytes = new Uint8Array(clean.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);\n }\n return bytes;\n}\n\n/** Convert a UTF-8 string to Uint8Array. */\nexport function encodeUtf8(str: string): Uint8Array {\n return new TextEncoder().encode(str);\n}\n\n/** Convert a Uint8Array to a UTF-8 string. */\nexport function decodeUtf8(bytes: Uint8Array): string {\n return new TextDecoder().decode(bytes);\n}\n\n/** Check if a string is valid base64. */\nexport function isBase64(str: string): boolean {\n return /^[A-Za-z0-9+/]*={0,2}$/.test(str);\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- bounds-checked binary parsing */\n/**\n * Isomorphic BTP + ILP binary protocol.\n * Uses Uint8Array and DataView — no Buffer, no Node.js dependencies.\n *\n * BTP (Bilateral Transfer Protocol) message format:\n * 1 byte — message type\n * 4 bytes — request ID (uint32 BE)\n * variable — payload (MESSAGE data or ERROR data)\n *\n * ILP (Interledger Protocol) OER-encoded packets:\n * PREPARE (type 12), FULFILL (type 13), REJECT (type 14)\n */\n\n// ─── Text codec (isomorphic) ────────────────────────────────────────────────\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\n// ─── BTP types ──────────────────────────────────────────────────────────────\n\nexport const BTPMessageType = {\n RESPONSE: 1,\n ERROR: 2,\n MESSAGE: 6,\n} as const;\n\nexport const ILPPacketType = {\n PREPARE: 12,\n FULFILL: 13,\n REJECT: 14,\n} as const;\n\nexport interface BTPProtocolData {\n protocolName: string;\n contentType: number;\n data: Uint8Array;\n}\n\nexport interface BTPMessageData {\n protocolData: BTPProtocolData[];\n ilpPacket?: Uint8Array;\n}\n\nexport interface BTPMessage {\n type: number;\n requestId: number;\n data: BTPMessageData | BTPErrorData;\n}\n\nexport interface BTPErrorData {\n code: string;\n name: string;\n triggeredAt: string;\n /** The trailing `data` octet string decoded as UTF-8 — the human-readable error text. */\n message: string;\n data: Uint8Array;\n}\n\nexport interface ILPPreparePacket {\n type: typeof ILPPacketType.PREPARE;\n amount: bigint;\n destination: string;\n executionCondition: Uint8Array;\n expiresAt: Date;\n data: Uint8Array;\n}\n\nexport interface ILPFulfillPacket {\n type: typeof ILPPacketType.FULFILL;\n /**\n * The 32-byte fulfillment preimage from the wire. All-zero on legacy\n * (zero-condition) packets; on sender-chosen conditions (toon-client#350)\n * the transport verifies `sha256(fulfillment) == executionCondition`.\n */\n fulfillment: Uint8Array;\n data: Uint8Array;\n}\n\nexport interface ILPRejectPacket {\n type: typeof ILPPacketType.REJECT;\n code: string;\n message: string;\n data: Uint8Array;\n}\n\nexport type ILPResponsePacket = ILPFulfillPacket | ILPRejectPacket;\n\n// ─── Byte helpers ───────────────────────────────────────────────────────────\n\nfunction concat(...arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, a) => sum + a.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const a of arrays) {\n result.set(a, offset);\n offset += a.length;\n }\n return result;\n}\n\nfunction readUint8(buf: Uint8Array, offset: number): number {\n if (offset >= buf.length) throw new Error('Buffer underflow reading uint8');\n return buf[offset]!;\n}\n\nfunction readUint16BE(buf: Uint8Array, offset: number): number {\n if (offset + 2 > buf.length)\n throw new Error('Buffer underflow reading uint16');\n return (buf[offset]! << 8) | buf[offset + 1]!;\n}\n\nfunction readUint32BE(buf: Uint8Array, offset: number): number {\n if (offset + 4 > buf.length)\n throw new Error('Buffer underflow reading uint32');\n return (\n ((buf[offset]! << 24) |\n (buf[offset + 1]! << 16) |\n (buf[offset + 2]! << 8) |\n buf[offset + 3]!) >>>\n 0\n );\n}\n\nfunction writeUint8(value: number): Uint8Array {\n return new Uint8Array([value]);\n}\n\nfunction writeUint16BE(value: number): Uint8Array {\n return new Uint8Array([(value >> 8) & 0xff, value & 0xff]);\n}\n\nfunction writeUint32BE(value: number): Uint8Array {\n return new Uint8Array([\n (value >> 24) & 0xff,\n (value >> 16) & 0xff,\n (value >> 8) & 0xff,\n value & 0xff,\n ]);\n}\n\nfunction sliceUtf8(buf: Uint8Array, offset: number, length: number): string {\n return textDecoder.decode(buf.slice(offset, offset + length));\n}\n\n// ─── OER encoding (ILP wire format) ─────────────────────────────────────────\n\nfunction encodeVarUInt(value: bigint): Uint8Array {\n if (value >= 0n && value <= 127n) {\n return new Uint8Array([Number(value)]);\n }\n const bytes: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n bytes.unshift(Number(remaining & 0xffn));\n remaining = remaining >> 8n;\n }\n return new Uint8Array([0x80 | bytes.length, ...bytes]);\n}\n\nfunction decodeVarUInt(\n buf: Uint8Array,\n offset: number\n): { value: bigint; bytesRead: number } {\n const firstByte = readUint8(buf, offset);\n if (firstByte <= 127) {\n return { value: BigInt(firstByte), bytesRead: 1 };\n }\n const length = firstByte & 0x7f;\n if (offset + 1 + length > buf.length)\n throw new Error('VarUInt buffer underflow');\n let value = 0n;\n for (let i = 0; i < length; i++) {\n value = (value << 8n) | BigInt(buf[offset + 1 + i]!);\n }\n return { value, bytesRead: 1 + length };\n}\n\nfunction encodeVarOctetString(data: Uint8Array): Uint8Array {\n return concat(encodeVarUInt(BigInt(data.length)), data);\n}\n\nfunction decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; bytesRead: number } {\n const { value: length, bytesRead: lenBytes } = decodeVarUInt(buf, offset);\n const dataLen = Number(length);\n const start = offset + lenBytes;\n if (start + dataLen > buf.length)\n throw new Error('VarOctetString buffer underflow');\n return {\n value: buf.slice(start, start + dataLen),\n bytesRead: lenBytes + dataLen,\n };\n}\n\nfunction encodeGeneralizedTime(date: Date): Uint8Array {\n const y = date.getUTCFullYear().toString().padStart(4, '0');\n const mo = (date.getUTCMonth() + 1).toString().padStart(2, '0');\n const d = date.getUTCDate().toString().padStart(2, '0');\n const h = date.getUTCHours().toString().padStart(2, '0');\n const mi = date.getUTCMinutes().toString().padStart(2, '0');\n const s = date.getUTCSeconds().toString().padStart(2, '0');\n const ms = date.getUTCMilliseconds().toString().padStart(3, '0');\n return textEncoder.encode(`${y}${mo}${d}${h}${mi}${s}.${ms}Z`);\n}\n\n// ─── ILP packet serialization ───────────────────────────────────────────────\n\nexport function serializeIlpPrepare(packet: ILPPreparePacket): Uint8Array {\n const condition =\n packet.executionCondition.length === 32\n ? packet.executionCondition\n : new Uint8Array(32);\n return concat(\n writeUint8(ILPPacketType.PREPARE),\n encodeVarUInt(packet.amount),\n encodeGeneralizedTime(packet.expiresAt),\n condition,\n encodeVarOctetString(textEncoder.encode(packet.destination)),\n encodeVarOctetString(packet.data)\n );\n}\n\nexport function deserializeIlpPacket(buf: Uint8Array): ILPResponsePacket {\n if (buf.length === 0) throw new Error('Empty ILP packet');\n const type = buf[0]!;\n if (type === ILPPacketType.FULFILL) return deserializeIlpFulfill(buf);\n if (type === ILPPacketType.REJECT) return deserializeIlpReject(buf);\n throw new Error(`Unknown ILP packet type: ${type}`);\n}\n\nfunction deserializeIlpFulfill(buf: Uint8Array): ILPFulfillPacket {\n let offset = 1; // skip type byte\n // 32-byte fulfillment preimage. Was skipped (\"unused in TOON\") before\n // sender-chosen execution conditions (toon-client#350) made it load-bearing.\n if (buf.length < offset + 32) {\n throw new Error('Buffer underflow reading FULFILL fulfillment');\n }\n const fulfillment = buf.slice(offset, offset + 32);\n offset += 32;\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.FULFILL, fulfillment, data };\n}\n\nfunction deserializeIlpReject(buf: Uint8Array): ILPRejectPacket {\n let offset = 1; // skip type byte\n // 3-byte error code\n const code = sliceUtf8(buf, offset, 3);\n offset += 3;\n // triggeredBy (skip)\n const { bytesRead: tbBytes } = decodeVarOctetString(buf, offset);\n offset += tbBytes;\n // message\n const { value: msgBuf, bytesRead: msgBytes } = decodeVarOctetString(\n buf,\n offset\n );\n offset += msgBytes;\n const message = textDecoder.decode(msgBuf);\n // data\n const { value: data } = decodeVarOctetString(buf, offset);\n return { type: ILPPacketType.REJECT, code, message, data };\n}\n\n// ─── BTP message serialization ──────────────────────────────────────────────\n\nexport function serializeBtpMessage(message: BTPMessage): Uint8Array {\n const parts: Uint8Array[] = [\n writeUint8(message.type),\n writeUint32BE(message.requestId),\n ];\n\n const data = message.data as BTPMessageData;\n const protocolData = data.protocolData ?? [];\n\n // Protocol data count\n parts.push(writeUint8(protocolData.length));\n\n // Each protocol data entry\n for (const pd of protocolData) {\n const nameBytes = textEncoder.encode(pd.protocolName);\n parts.push(writeUint8(nameBytes.length));\n parts.push(nameBytes);\n parts.push(writeUint16BE(pd.contentType));\n parts.push(writeUint32BE(pd.data.length));\n if (pd.data.length > 0) parts.push(pd.data);\n }\n\n // ILP packet\n const ilpPacket = data.ilpPacket ?? new Uint8Array(0);\n parts.push(writeUint32BE(ilpPacket.length));\n if (ilpPacket.length > 0) parts.push(ilpPacket);\n\n return concat(...parts);\n}\n\nexport function parseBtpMessage(buf: Uint8Array): BTPMessage {\n if (buf.length < 5) throw new Error('BTP message too short');\n let offset = 0;\n\n const type = readUint8(buf, offset);\n offset += 1;\n const requestId = readUint32BE(buf, offset);\n offset += 4;\n\n if (type === BTPMessageType.ERROR) {\n // code\n const codeLen = readUint8(buf, offset);\n offset += 1;\n const code = sliceUtf8(buf, offset, codeLen);\n offset += codeLen;\n // name\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const name = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n // triggeredAt\n const taLen = readUint8(buf, offset);\n offset += 1;\n const triggeredAt = sliceUtf8(buf, offset, taLen);\n offset += taLen;\n // data\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n const message = textDecoder.decode(data);\n return {\n type,\n requestId,\n data: { code, name, triggeredAt, message, data },\n };\n }\n\n // MESSAGE or RESPONSE\n const pdCount = readUint8(buf, offset);\n offset += 1;\n const protocolData: BTPProtocolData[] = [];\n for (let i = 0; i < pdCount; i++) {\n const nameLen = readUint8(buf, offset);\n offset += 1;\n const protocolName = sliceUtf8(buf, offset, nameLen);\n offset += nameLen;\n const contentType = readUint16BE(buf, offset);\n offset += 2;\n const dataLen = readUint32BE(buf, offset);\n offset += 4;\n const data = buf.slice(offset, offset + dataLen);\n offset += dataLen;\n protocolData.push({ protocolName, contentType, data });\n }\n\n let ilpPacket: Uint8Array | undefined;\n if (offset + 4 <= buf.length) {\n const ilpLen = readUint32BE(buf, offset);\n offset += 4;\n if (ilpLen > 0 && offset + ilpLen <= buf.length) {\n ilpPacket = buf.slice(offset, offset + ilpLen);\n }\n }\n\n return { type, requestId, data: { protocolData, ilpPacket } };\n}\n","/**\n * Ask a terminating connector who it is and what it charges — the step that\n * has to happen BEFORE a packet can be formed at all.\n *\n * ADR 0018 makes holding the terminating connector's public key a\n * precondition of forming a packet: `Prepare.data` is sealed to that key, and\n * sealing to the wrong one is a confidentiality failure, not a delivery\n * failure. ADR 0022 says the connector *answers* — it never announces — so\n * both facts are fetched from the connector's own client edge, on the same\n * origin this client already POSTs `/ilp` to\n * (`docs/protocol/client-edge-spec.md` §1.7):\n *\n * - `GET /ilp/identity` → `{ \"keyId\": \"...\", \"publicKey\": \"0x04...\" }` — the\n * uncompressed secp256k1 key, 65 bytes, `0x`-prefixed hex.\n * - `GET /ilp/routes/price?destination=<ILP address>` →\n * `{ \"destination\": \"...\", \"price\": 100 }`, or `404` when no\n * locally-terminated route matches.\n *\n * Both are unauthenticated and neither changes state.\n *\n * ─── What this module refuses to do ────────────────────────────────────────\n * Unlike the 402-challenge parser next door (which degrades gracefully so an\n * unrecognised connector shape falls back to the vanilla 402), an identity is\n * parsed STRICTLY. A key that is the wrong length, not `0x04`-prefixed, or not\n * valid hex is refused with a distinguishable error rather than carried\n * forward: a half-understood key would be sealed to, and the failure would be\n * silent. There is no \"best effort\" reading of a public key.\n *\n * Pure transport + parsing: no keys are held, nothing is signed, and the only\n * state is the identity cache.\n */\n\nimport { NetworkError, ToonClientError } from '../errors.js';\nimport { ILPPacketType, serializeIlpPrepare } from '../btp/protocol.js';\n\n// ─── Identity ───────────────────────────────────────────────────────────────\n\n/** The terminating connector's own identity, as reported by `GET /ilp/identity`. */\nexport interface ConnectorIdentity {\n /** The key id identifying the key (opaque to this client). */\n keyId: string;\n /** The uncompressed secp256k1 public key — exactly 65 raw bytes, leading `0x04`. */\n publicKey: Uint8Array;\n /** The key exactly as reported, `0x`-prefixed lowercase hex (65 bytes → 132 chars). */\n publicKeyHex: string;\n /** The normalized client-edge base URL this identity was read from. */\n endpoint: string;\n}\n\n/**\n * The channel-opening facts a settling connector carries in its x402\n * greeting (connector #617): everything a buyer needs to OPEN a channel\n * with the node, learned by ASKING (ADR 0022) rather than from a\n * kind:10032 announce the Rust fleet never makes.\n */\nexport interface ConnectorSettlementTerms {\n /** `evm:<chainId>` — the chain the node's settlement backend runs on. */\n chain: string;\n /** The on-chain counterparty a buyer opens a channel WITH. */\n settlementAddress: string;\n /** The stable TokenNetworkRegistry factory address. */\n tokenNetworkRegistry: string;\n /** The resolved TokenNetwork — the EIP-712 verifyingContract. */\n tokenNetwork: string;\n tokenAddress: string;\n /** Informational; claims are already in base units. */\n decimals: number;\n}\n\n/**\n * The Solana twin of {@link ConnectorSettlementTerms} (connector #632): what\n * an unaffiliated buyer needs to open a channel against a Solana settlement\n * backend's deployed `payment-channel` program instance.\n */\nexport interface ConnectorSolanaSettlementTerms {\n /** Always `'solana'` — unlike EVM there is no chain id to append. */\n chain: string;\n /** The on-chain counterparty a buyer opens a channel WITH, base58. */\n settlementAddress: string;\n /** The deployed `payment-channel` program instance, base58. */\n programId: string;\n /** The SPL mint every channel this backend opens settles in, base58. */\n tokenAddress: string;\n /** Informational; claims are already in base units. */\n decimals: number;\n}\n\n/**\n * One chain's entry in the x402 greeting's per-chain `settlements` list\n * (connector #632). `kind` is added by this parser, not present on the wire\n * — the wire is untagged, disambiguated structurally (`tokenNetworkRegistry`\n * names EVM, `programId` names Solana).\n */\nexport type ConnectorChainSettlementTerms =\n | ({ kind: 'evm' } & ConnectorSettlementTerms)\n | ({ kind: 'solana' } & ConnectorSolanaSettlementTerms);\n\n/**\n * A route's terms as the x402 greeting states them: the price, plus (from a\n * settling node) the channel-opening facts. `settlement` is absent exactly\n * when the node has no settlement backend — the wire's own shape. `settlements`\n * is the additive per-chain list (connector #632): one entry per chain the\n * node settles on, including the same EVM entry `settlement` already carries.\n * Absent — not an empty array — on a node with no settlement backend, or one\n * still answering the pre-#632 greeting shape.\n */\nexport interface ConnectorRouteTerms {\n destination: string;\n price: string;\n settlement?: ConnectorSettlementTerms;\n settlements?: ConnectorChainSettlementTerms[];\n}\n\n/** What a locally-terminated route costs, as reported by `GET /ilp/routes/price`. */\nexport interface ConnectorRoutePrice {\n /** The ILP destination that was asked about (echoed by the connector). */\n destination: string;\n /** The price in ILP base units of the route `destination` matched. */\n price: bigint;\n}\n\n/**\n * Every distinguishable way asking a connector for its identity or terms can\n * fail. Each code names exactly one cause; there is no catch-all, because the\n * caller's next move differs per cause (retry a transport failure; never\n * retry a malformed key).\n */\nexport type ConnectorEdgeErrorCode =\n /** Non-2xx from `GET /ilp/identity`. */\n | 'IDENTITY_HTTP_STATUS'\n /** `GET /ilp/identity` answered 2xx with a body that is not the documented object. */\n | 'IDENTITY_MALFORMED'\n /** `publicKey` is present but is not `0x`-prefixed even-length hex. */\n | 'IDENTITY_KEY_NOT_HEX'\n /** `publicKey` decodes, but not to exactly 65 bytes. */\n | 'IDENTITY_KEY_LENGTH'\n /** `publicKey` is 65 bytes but does not start with the SEC1 uncompressed tag `0x04`. */\n | 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n /** Non-2xx, non-404 from `GET /ilp/routes/price` (404 is not an error — see below). */\n | 'ROUTE_PRICE_HTTP_STATUS'\n /** `GET /ilp/routes/price` answered 2xx with a body that is not the documented object. */\n | 'ROUTE_PRICE_MALFORMED'\n /** A destination that cannot be put in a query string was asked about. */\n | 'INVALID_DESTINATION'\n /** A 402 greeting whose body is not the documented x402 shape (or whose\n * optional `settlement` facts are present but malformed — refused rather\n * than silently dropped, since they would be opened AGAINST). */\n | 'TERMS_MALFORMED';\n\n/**\n * A refusal to carry a connector's answer forward. Distinct from\n * {@link NetworkError} (which this module throws for a transport failure), so\n * \"the connector is unreachable\" and \"the connector answered something I will\n * not seal to\" are never confused.\n */\nexport class ConnectorEdgeError extends ToonClientError {\n /** Narrowed from `ToonClientError`'s `string`; type-only, no runtime field. */\n declare readonly code: ConnectorEdgeErrorCode;\n\n constructor(message: string, code: ConnectorEdgeErrorCode, cause?: Error) {\n super(message, code, cause);\n this.name = 'ConnectorEdgeError';\n }\n}\n\n// ─── URL handling ───────────────────────────────────────────────────────────\n\n/**\n * Normalize any client-edge URL a caller already holds into the base the\n * `/ilp/*` routes hang off.\n *\n * Callers reach this module holding whatever the x402 offer or their config\n * gave them — `https://apex.example`, `https://apex.example/`, or the\n * `POST /ilp` endpoint `https://apex.example/ilp` itself. All three name the\n * same client edge, so all three normalize to `https://apex.example`.\n */\nexport function connectorEdgeBaseUrl(endpoint: string): string {\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch (error) {\n throw new ConnectorEdgeError(\n `not a valid connector endpoint URL: ${endpoint}`,\n 'IDENTITY_MALFORMED',\n error instanceof Error ? error : undefined\n );\n }\n // Drop a trailing `/ilp` (the POST endpoint) and any trailing slashes.\n let path = url.pathname.replace(/\\/+$/, '');\n if (path.endsWith('/ilp')) path = path.slice(0, -'/ilp'.length);\n url.pathname = path;\n url.search = '';\n url.hash = '';\n return url.toString().replace(/\\/+$/, '');\n}\n\n// ─── Parsing (pure, exported so the wire shape is testable without a server) ─\n\nconst UNCOMPRESSED_KEY_BYTES = 65;\nconst SEC1_UNCOMPRESSED_TAG = 0x04;\n\n/**\n * Decode a `0x`-prefixed hex public key into its 65 raw bytes, refusing\n * anything that is not exactly one uncompressed secp256k1 key.\n */\nexport function decodeConnectorPublicKey(publicKeyHex: string): Uint8Array {\n const trimmed = publicKeyHex.trim();\n if (!/^0x[0-9a-fA-F]*$/.test(trimmed) || trimmed.length % 2 !== 0) {\n throw new ConnectorEdgeError(\n `connector publicKey is not 0x-prefixed hex: ${publicKeyHex}`,\n 'IDENTITY_KEY_NOT_HEX'\n );\n }\n const hex = trimmed.slice(2);\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n }\n if (bytes.length !== UNCOMPRESSED_KEY_BYTES) {\n throw new ConnectorEdgeError(\n `connector publicKey must be ${UNCOMPRESSED_KEY_BYTES} bytes, got ${bytes.length}`,\n 'IDENTITY_KEY_LENGTH'\n );\n }\n const tag = bytes[0] ?? 0;\n if (tag !== SEC1_UNCOMPRESSED_TAG) {\n throw new ConnectorEdgeError(\n `connector publicKey must be SEC1-uncompressed (0x04 prefix), got 0x${tag.toString(16).padStart(2, '0')}`,\n 'IDENTITY_KEY_NOT_UNCOMPRESSED'\n );\n }\n return bytes;\n}\n\n/**\n * Parse an already-decoded `GET /ilp/identity` body. Exported so the shape the\n * connector actually emits can be pinned without standing up a server.\n */\nexport function parseConnectorIdentity(\n body: unknown,\n endpoint: string\n): ConnectorIdentity {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity did not answer a JSON object',\n 'IDENTITY_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const keyId = record['keyId'];\n const publicKeyHex = record['publicKey'];\n if (typeof keyId !== 'string' || keyId.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a keyId',\n 'IDENTITY_MALFORMED'\n );\n }\n if (typeof publicKeyHex !== 'string' || publicKeyHex.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/identity answered without a publicKey',\n 'IDENTITY_MALFORMED'\n );\n }\n return {\n keyId,\n publicKey: decodeConnectorPublicKey(publicKeyHex),\n publicKeyHex: publicKeyHex.trim().toLowerCase(),\n endpoint,\n };\n}\n\n/** Parse an already-decoded `GET /ilp/routes/price` 200 body. */\nexport function parseConnectorRoutePrice(body: unknown): ConnectorRoutePrice {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price did not answer a JSON object',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n const record = body as Record<string, unknown>;\n const destination = record['destination'];\n const price = record['price'];\n if (typeof destination !== 'string' || destination.length === 0) {\n throw new ConnectorEdgeError(\n 'GET /ilp/routes/price answered without a destination',\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n if (\n typeof price !== 'number' ||\n !Number.isFinite(price) ||\n !Number.isInteger(price) ||\n price < 0\n ) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered a non-integer price: ${String(price)}`,\n 'ROUTE_PRICE_MALFORMED'\n );\n }\n return { destination, price: BigInt(price) };\n}\n\n// ─── Client ─────────────────────────────────────────────────────────────────\n\nexport interface ConnectorEdgeClientConfig {\n /** HTTP fetch implementation. Default: global `fetch`. Injectable for tests. */\n fetch?: typeof fetch;\n /** Per-request timeout in milliseconds. Default 10_000. */\n timeout?: number;\n}\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/**\n * Separator between a client-edge base URL and an ILP destination in a price\n * cache key. NUL can appear in neither, so no pair can be spelled two ways\n * and no two pairs can collide.\n */\nconst PRICE_KEY_SEPARATOR = '\\u0000';\n\n/** Cache key for one (client edge, destination) pair. */\nfunction priceCacheKey(base: string, destination: string): string {\n return `${base}${PRICE_KEY_SEPARATOR}${destination}`;\n}\n\n/**\n * The prefix every key for `base` shares — `priceCacheKey`'s own output for\n * an empty destination, so the two cannot drift into disagreeing about the\n * separator. They once did, and the endpoint-wide invalidation below then\n * silently matched nothing.\n */\nfunction priceCacheKeyPrefix(base: string): string {\n return priceCacheKey(base, '');\n}\n\n/**\n * Asks connectors for their identity and their terms, caching each identity\n * per client-edge endpoint and each route price per (endpoint, destination).\n *\n * The cache is per endpoint rather than per client instance because a sender\n * routinely speaks to several connectors, and re-fetching a key per packet\n * would put a network round trip in front of every send. Nothing here expires\n * on a timer: an operator key rotation, or a route being repriced, is a\n * deliberate event, so {@link invalidateIdentity} / {@link invalidateRoutePrice}\n * are how a stale answer is dropped.\n *\n * A price is cached the same way and for the same reason (toon-client#452):\n * under ADR 0020 a route's price is FLAT — one handler, one price — so it does\n * not vary with what is being sent, and asking again per packet would buy\n * nothing but latency.\n */\nexport class ConnectorEdgeClient {\n private readonly fetchImpl: typeof fetch;\n private readonly timeout: number;\n private readonly identities = new Map<string, Promise<ConnectorIdentity>>();\n private readonly prices = new Map<\n string,\n Promise<ConnectorRoutePrice | null>\n >();\n\n constructor(config: ConnectorEdgeClientConfig = {}) {\n this.fetchImpl = config.fetch ?? globalThis.fetch.bind(globalThis);\n this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;\n }\n\n /**\n * The terminating connector's public key, fetched once per endpoint.\n *\n * @param endpoint any client-edge URL (`https://apex`, `https://apex/ilp`).\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getIdentity(\n endpoint: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorIdentity> {\n const base = connectorEdgeBaseUrl(endpoint);\n if (options.forceRefresh) this.identities.delete(base);\n\n const cached = this.identities.get(base);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever.\n const inFlight = this.fetchIdentity(base).catch((error: unknown) => {\n this.identities.delete(base);\n throw error;\n });\n this.identities.set(base, inFlight);\n return inFlight;\n }\n\n /**\n * Drop a cached identity — one endpoint's, or every endpoint's when\n * `endpoint` is omitted. The way to react to a key rotation.\n */\n invalidateIdentity(endpoint?: string): void {\n if (endpoint === undefined) {\n this.identities.clear();\n return;\n }\n this.identities.delete(connectorEdgeBaseUrl(endpoint));\n }\n\n /** Whether an identity for `endpoint` is already held (no request is made). */\n hasCachedIdentity(endpoint: string): boolean {\n return this.identities.has(connectorEdgeBaseUrl(endpoint));\n }\n\n /**\n * What `destination` costs at this connector, or `null` when the connector\n * answers `404` — no locally-terminated route matches it.\n *\n * `null` is the answer to \"you do not terminate this\", which is information;\n * a transport failure throws {@link NetworkError} instead, so a caller can\n * always tell \"not mine\" from \"could not ask\".\n *\n * Fetched once per (endpoint, destination) and reused. ADR 0020 makes a\n * price flat per handler, so it does not vary with the packet — a route\n * being repriced is an operator event, and {@link invalidateRoutePrice} is\n * how a caller reacts to one.\n *\n * @param options `forceRefresh` bypasses (and replaces) the cache entry.\n */\n async getRoutePrice(\n endpoint: string,\n destination: string,\n options: { forceRefresh?: boolean } = {}\n ): Promise<ConnectorRoutePrice | null> {\n if (typeof destination !== 'string' || destination.trim().length === 0) {\n throw new ConnectorEdgeError(\n 'a route price needs a non-empty ILP destination',\n 'INVALID_DESTINATION'\n );\n }\n const base = connectorEdgeBaseUrl(endpoint);\n const key = priceCacheKey(base, destination);\n if (options.forceRefresh) this.prices.delete(key);\n\n const cached = this.prices.get(key);\n if (cached) return cached;\n\n // Cache the in-flight promise so concurrent senders share one round trip;\n // drop it again on failure so a transient error is not cached forever. A\n // `404` IS cached: \"this connector does not terminate that\" is an answer.\n const inFlight = this.fetchRoutePrice(base, destination).catch(\n (error: unknown) => {\n this.prices.delete(key);\n throw error;\n }\n );\n this.prices.set(key, inFlight);\n return inFlight;\n }\n\n /**\n * Ask a route for its full x402 terms — the greeting a claimless PREPARE\n * is answered with (client-edge-spec.md §1.4) — including, from a settling\n * node, the channel-opening facts (connector #617).\n *\n * This is a real `POST /ilp` carrying a minimal PREPARE with no claim\n * header. It is free by the wire's own contract: an unpaid request to a\n * priced route is answered with terms instead of performed, and nothing\n * is charged for asking. `null` when the connector does not price the\n * destination (the request would be routed or refused, not greeted) —\n * mapped from anything other than a 402 answer.\n */\n async getRouteTerms(\n endpoint: string,\n destination: string\n ): Promise<ConnectorRouteTerms | null> {\n if (typeof destination !== 'string' || destination.trim().length === 0) {\n throw new ConnectorEdgeError(\n 'route terms need a non-empty ILP destination',\n 'INVALID_DESTINATION'\n );\n }\n const base = connectorEdgeBaseUrl(endpoint);\n // A syntactically complete PREPARE the greeting gate answers before the\n // packet is ever routed: a non-zero condition (an all-zero one is F01),\n // a near-term expiry, no data. Amount is irrelevant to the greeting.\n const condition = new Uint8Array(32);\n condition[0] = 1;\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: 0n,\n destination,\n executionCondition: condition,\n expiresAt: new Date(Date.now() + 30_000),\n data: new Uint8Array(0),\n });\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n let response: Response;\n try {\n response = await this.fetchImpl(`${base}/ilp`, {\n method: 'POST',\n headers: { 'content-type': 'application/octet-stream' },\n body: prepare.slice(),\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${base}/ilp`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n\n if (response.status !== 402) return null;\n let body: unknown;\n try {\n body = await response.json();\n } catch (error) {\n throw new ConnectorEdgeError(\n 'connector answered 402 with a body that is not JSON',\n 'TERMS_MALFORMED',\n error instanceof Error ? error : undefined\n );\n }\n return parseConnectorRouteTerms(body);\n }\n\n /**\n * Drop a cached route price — one (endpoint, destination)'s, every\n * destination's at one endpoint when `destination` is omitted, or all of\n * them when both are. The way to react to a route being repriced.\n */\n invalidateRoutePrice(endpoint?: string, destination?: string): void {\n if (endpoint === undefined) {\n this.prices.clear();\n return;\n }\n const base = connectorEdgeBaseUrl(endpoint);\n if (destination !== undefined) {\n this.prices.delete(priceCacheKey(base, destination));\n return;\n }\n const prefix = priceCacheKeyPrefix(base);\n for (const key of this.prices.keys()) {\n if (key.startsWith(prefix)) this.prices.delete(key);\n }\n }\n\n /**\n * Whether a price for `(endpoint, destination)` is already held (no request\n * is made).\n */\n hasCachedRoutePrice(endpoint: string, destination: string): boolean {\n return this.prices.has(\n priceCacheKey(connectorEdgeBaseUrl(endpoint), destination)\n );\n }\n\n private async fetchRoutePrice(\n base: string,\n destination: string\n ): Promise<ConnectorRoutePrice | null> {\n const url = `${base}/ilp/routes/price?destination=${encodeURIComponent(destination)}`;\n const response = await this.get(url);\n\n if (response.status === 404) return null;\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/routes/price answered ${response.status}`,\n 'ROUTE_PRICE_HTTP_STATUS'\n );\n }\n return parseConnectorRoutePrice(\n await this.readJson(response, 'ROUTE_PRICE_MALFORMED')\n );\n }\n\n private async fetchIdentity(base: string): Promise<ConnectorIdentity> {\n const response = await this.get(`${base}/ilp/identity`);\n if (!response.ok) {\n throw new ConnectorEdgeError(\n `GET /ilp/identity answered ${response.status}`,\n 'IDENTITY_HTTP_STATUS'\n );\n }\n return parseConnectorIdentity(\n await this.readJson(response, 'IDENTITY_MALFORMED'),\n base\n );\n }\n\n private async readJson(\n response: Response,\n code: ConnectorEdgeErrorCode\n ): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new ConnectorEdgeError(\n 'connector answered a body that is not JSON',\n code,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /** GET with a timeout, mapping any transport failure onto {@link NetworkError}. */\n private async get(url: string): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeout);\n try {\n return await this.fetchImpl(url, {\n method: 'GET',\n headers: { accept: 'application/json' },\n signal: controller.signal,\n });\n } catch (error) {\n throw new NetworkError(\n `could not reach the connector client edge at ${url}`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timer);\n }\n }\n}\n\n/** A required-string reader over a raw settlement-facts record, refusing a missing/empty field. */\nfunction settlementStr(s: Record<string, unknown>, key: string): string {\n const value = s[key];\n if (typeof value !== 'string' || value.length === 0) {\n throw new ConnectorEdgeError(\n `x402 greeting settlement facts lack '${key}'`,\n 'TERMS_MALFORMED'\n );\n }\n return value;\n}\n\n/** A required-`decimals` reader, shared by every chain's settlement-facts shape. */\nfunction settlementDecimals(s: Record<string, unknown>): number {\n const decimals = s['decimals'];\n if (typeof decimals !== 'number') {\n throw new ConnectorEdgeError(\n \"x402 greeting settlement facts lack 'decimals'\",\n 'TERMS_MALFORMED'\n );\n }\n return decimals;\n}\n\n/** Parse one already-object-checked EVM settlement-facts record (legacy `settlement` shape). */\nfunction parseEvmSettlementTerms(\n s: Record<string, unknown>\n): ConnectorSettlementTerms {\n return {\n chain: settlementStr(s, 'chain'),\n settlementAddress: settlementStr(s, 'settlementAddress'),\n tokenNetworkRegistry: settlementStr(s, 'tokenNetworkRegistry'),\n tokenNetwork: settlementStr(s, 'tokenNetwork'),\n tokenAddress: settlementStr(s, 'tokenAddress'),\n decimals: settlementDecimals(s),\n };\n}\n\n/** Parse one already-object-checked Solana settlement-facts record (connector #632). */\nfunction parseSolanaSettlementTerms(\n s: Record<string, unknown>\n): ConnectorSolanaSettlementTerms {\n return {\n chain: settlementStr(s, 'chain'),\n settlementAddress: settlementStr(s, 'settlementAddress'),\n programId: settlementStr(s, 'programId'),\n tokenAddress: settlementStr(s, 'tokenAddress'),\n decimals: settlementDecimals(s),\n };\n}\n\n/**\n * Parse one entry of the greeting's `extra.settlements` list (connector\n * #632). The wire is untagged — serde on the connector side, and this parser\n * on the client side, both disambiguate structurally: `programId` names a\n * Solana entry, `tokenNetworkRegistry` names an EVM one. Anything else (both\n * fields present, neither present, or a field of the wrong shape) is refused\n * rather than guessed at.\n */\nfunction parseChainSettlementEntry(\n raw: unknown\n): ConnectorChainSettlementTerms {\n if (typeof raw !== 'object' || raw === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlements entry is not an object',\n 'TERMS_MALFORMED'\n );\n }\n const s = raw as Record<string, unknown>;\n if (typeof s['programId'] === 'string') {\n return { kind: 'solana', ...parseSolanaSettlementTerms(s) };\n }\n if (typeof s['tokenNetworkRegistry'] === 'string') {\n return { kind: 'evm', ...parseEvmSettlementTerms(s) };\n }\n throw new ConnectorEdgeError(\n \"x402 greeting settlements entry names neither an EVM ('tokenNetworkRegistry') nor a Solana ('programId') chain\",\n 'TERMS_MALFORMED'\n );\n}\n\n/**\n * Parse an x402 v2 greeting body into {@link ConnectorRouteTerms}. Pure and\n * exported so the wire shape is testable without a server. Refuses a body\n * that is not the documented greeting; a malformed OPTIONAL `settlement`\n * object (or `settlements` entry) is also a refusal rather than a silent\n * drop — half-understood channel-opening facts would be opened AGAINST.\n */\nexport function parseConnectorRouteTerms(body: unknown): ConnectorRouteTerms {\n if (typeof body !== 'object' || body === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting is not an object',\n 'TERMS_MALFORMED'\n );\n }\n const greeting = body as {\n resource?: { url?: unknown };\n accepts?: unknown;\n };\n const accepts = Array.isArray(greeting.accepts) ? greeting.accepts : [];\n const option = accepts.find(\n (entry): entry is Record<string, unknown> =>\n typeof entry === 'object' &&\n entry !== null &&\n (entry as { scheme?: unknown }).scheme === 'toon-channel'\n );\n if (!option || typeof option['amount'] !== 'string') {\n throw new ConnectorEdgeError(\n 'x402 greeting carries no toon-channel option',\n 'TERMS_MALFORMED'\n );\n }\n const destination =\n typeof greeting.resource?.url === 'string' ? greeting.resource.url : '';\n const extra = option['extra'] as\n | { settlement?: unknown; settlements?: unknown }\n | undefined;\n\n const rawSettlements = extra?.settlements;\n let settlements: ConnectorChainSettlementTerms[] | undefined;\n if (rawSettlements !== undefined) {\n if (!Array.isArray(rawSettlements)) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlements is not an array',\n 'TERMS_MALFORMED'\n );\n }\n settlements = rawSettlements.map(parseChainSettlementEntry);\n }\n\n const rawSettlement = extra?.settlement;\n if (rawSettlement === undefined) {\n return {\n destination,\n price: option['amount'],\n ...(settlements ? { settlements } : {}),\n };\n }\n if (typeof rawSettlement !== 'object' || rawSettlement === null) {\n throw new ConnectorEdgeError(\n 'x402 greeting settlement facts are malformed',\n 'TERMS_MALFORMED'\n );\n }\n return {\n destination,\n price: option['amount'],\n settlement: parseEvmSettlementTerms(\n rawSettlement as Record<string, unknown>\n ),\n ...(settlements ? { settlements } : {}),\n };\n}\n","/**\n * Canonical OER length primitives (RFC-0030), ported byte-for-byte from\n * `connector_domain::oer` so the Rust and TypeScript fleets agree on the wire.\n *\n * \"Canonical\" is the whole point (ADR 0023): every value has exactly ONE\n * encoding, and a decoder that quietly accepts a second spelling of the same\n * value is a decoder two implementations can disagree through. So a\n * determinant is refused unless the bytes it introduces are exactly what\n * {@link encodeVarUint} would have produced:\n *\n * - `0x81 0x03` — a long form for `3`, which `0x03` already encodes — is\n * {@link OerErrorKind.NonCanonicalLength}, not `3`.\n * - `0x80` — a zero-byte long form aliasing `0x00` — is\n * {@link OerErrorKind.NonCanonicalLength}, not `0`.\n * - `0x89 …` — nine length bytes, which cannot fit a `u64` without silently\n * discarding the high-order ones — is\n * {@link OerErrorKind.LengthDeterminantOverflow}, not a truncated read.\n *\n * Values are `bigint` because the wire type is `u64` and `number` cannot hold\n * one; the caller narrows.\n *\n * Pure: no I/O, no keys, no clock.\n */\n\n/** The three, and only three, ways a length determinant can be refused. */\nexport enum OerErrorKind {\n /** The buffer ends before the field it declares does. */\n BufferUnderflow = 'buffer_underflow',\n /** A determinant that is not the minimal encoding of its own value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A determinant wider than eight bytes (cannot be a `u64`). */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n}\n\n/** A refusal from the length primitives, carrying which of the three it is. */\nexport class OerError extends Error {\n constructor(readonly kind: OerErrorKind) {\n super(OER_ERROR_MESSAGES[kind]);\n this.name = 'OerError';\n }\n}\n\nconst OER_ERROR_MESSAGES: Record<OerErrorKind, string> = {\n [OerErrorKind.BufferUnderflow]: 'buffer underflow: the value is truncated',\n [OerErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [OerErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n};\n\nconst MAX_DETERMINANT_BYTES = 8;\n\n/** Encode a VarUInt: `0..=127` as one byte, `128+` as a length-prefixed BE value. */\nexport function encodeVarUint(value: bigint): Uint8Array {\n if (value < 0n)\n throw new RangeError('VarUInt cannot encode a negative value');\n if (value <= 127n) return Uint8Array.of(Number(value));\n\n const body: number[] = [];\n let remaining = value;\n while (remaining > 0n) {\n body.unshift(Number(remaining & 0xffn));\n remaining >>= 8n;\n }\n if (body.length > MAX_DETERMINANT_BYTES) {\n throw new RangeError('VarUInt cannot encode a value wider than 8 bytes');\n }\n return Uint8Array.from([0x80 | body.length, ...body]);\n}\n\n/** A decoded field: its value, and how many bytes it consumed. */\nexport interface Decoded<T> {\n value: T;\n consumed: number;\n}\n\n/**\n * Decode a VarUInt at `offset`, refusing any non-canonical spelling.\n *\n * @throws {OerError} and nothing else — arbitrary bytes never produce a\n * `RangeError`, a `TypeError`, or a plausible-but-wrong value.\n */\nexport function decodeVarUint(\n buf: Uint8Array,\n offset: number\n): Decoded<bigint> {\n const first = buf[offset];\n if (first === undefined) throw new OerError(OerErrorKind.BufferUnderflow);\n if (first <= 127) return { value: BigInt(first), consumed: 1 };\n\n const length = first & 0x7f;\n if (length > MAX_DETERMINANT_BYTES) {\n throw new OerError(OerErrorKind.LengthDeterminantOverflow);\n }\n const start = offset + 1;\n const end = start + length;\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n let value = 0n;\n for (let i = start; i < end; i++) {\n value = (value << 8n) | BigInt(buf[i] as number);\n }\n const consumed = 1 + length;\n\n // The canonicality test, exactly as `connector_domain::oer` states it:\n // re-encode and demand the same bytes back. This is what rejects the\n // non-minimal long form and the zero-length alias in one check.\n const canonical = encodeVarUint(value);\n if (\n canonical.length !== consumed ||\n !canonical.every((byte, i) => byte === buf[offset + i])\n ) {\n throw new OerError(OerErrorKind.NonCanonicalLength);\n }\n return { value, consumed };\n}\n\n/** Encode a VarOctetString: a VarUInt length prefix followed by the bytes. */\nexport function encodeVarOctetString(data: Uint8Array): Uint8Array {\n const prefix = encodeVarUint(BigInt(data.length));\n const out = new Uint8Array(prefix.length + data.length);\n out.set(prefix, 0);\n out.set(data, prefix.length);\n return out;\n}\n\n/**\n * Decode a VarOctetString at `offset`.\n *\n * @throws {OerError} and nothing else.\n */\nexport function decodeVarOctetString(\n buf: Uint8Array,\n offset: number\n): Decoded<Uint8Array> {\n const { value: length, consumed: lengthBytes } = decodeVarUint(buf, offset);\n\n // A declared length larger than the whole buffer is underflow, checked in\n // `bigint` BEFORE any `Number` conversion so a `u64`-scale length can never\n // wrap into a plausible small one.\n if (length > BigInt(buf.length)) {\n throw new OerError(OerErrorKind.BufferUnderflow);\n }\n const start = offset + lengthBytes;\n const end = start + Number(length);\n if (end > buf.length) throw new OerError(OerErrorKind.BufferUnderflow);\n\n // A copy, not a view: a decoded body that aliases the input buffer would\n // change under a caller who reuses that buffer.\n return {\n value: buf.slice(start, end),\n consumed: lengthBytes + Number(length),\n };\n}\n","/**\n * The structured envelope (ADR 0018): what a packet carries between a\n * connector and the app behind it, encoded with the same OER primitives an ILP\n * packet already uses rather than as HTTP text.\n *\n * A faithful port of `connector_domain::envelope`\n * (`crates/connector-domain/src/envelope.rs`) — a method, target, ordered\n * headers and body going in; a two-byte big-endian status, headers and body\n * coming back. `vectors/wire-vectors.json` is the contract this is checked\n * against, and `wire-vectors.test.ts` is where that check happens; the prose\n * here describes the same thing but the bytes decide.\n *\n * ─── Why not HTTP text ─────────────────────────────────────────────────────\n * `utils/store-envelope.ts` builds latin1 HTTP/1.1 request text and\n * `utils/fulfill-http.ts` hand-parses a status line and scans for `\\r\\n\\r\\n`,\n * which is how they acquired leniencies nobody chose: a missing header/body\n * separator yielding an empty body, blank header lines skipped, spaces\n * tolerated inside the target. A structured encoding has exactly one\n * representation per message and nothing to smuggle. This module lands BESIDE\n * those two rather than replacing them — the swap is a later child — so it can\n * be reviewed against the vectors in isolation.\n *\n * ─── Headers are a list, not a map ─────────────────────────────────────────\n * A count prefix then `(name, value)` pairs in order. Both header ORDER and\n * DUPLICATE NAMES are meaningful on this wire and both survive a round trip; a\n * `Record<string, string>` would silently destroy each.\n *\n * Pure: no keys, no I/O, no clock. `@noble/*` is not involved.\n */\n\nimport {\n OerError,\n OerErrorKind,\n decodeVarOctetString,\n decodeVarUint,\n encodeVarOctetString,\n encodeVarUint,\n} from './oer.js';\n\nconst TYPE_ENVELOPE_REQUEST = 1;\nconst TYPE_ENVELOPE_RESPONSE = 2;\n\n/**\n * Every distinguishable way an envelope can fail to decode. These strings are\n * the vector file's `expected_error` values verbatim — the same names\n * `EnvelopeError` uses in `connector-domain` — so a replay compares reasons,\n * not just \"it threw\".\n *\n * There is deliberately no catch-all: a decoder with an `Invalid` bucket is a\n * decoder that can be lenient without anyone noticing.\n */\nexport enum EnvelopeErrorKind {\n /** The buffer ends before the envelope does. */\n BufferUnderflow = 'buffer_underflow',\n /** A length determinant that is not the minimal encoding of its value. */\n NonCanonicalLength = 'non_canonical_length',\n /** A length determinant wider than eight bytes. */\n LengthDeterminantOverflow = 'length_determinant_overflow',\n /** The type byte is not the one the requested direction requires. */\n InvalidType = 'invalid_type',\n /** A field that must be UTF-8 is not. */\n InvalidUtf8 = 'invalid_utf8',\n /** Bytes remain after a fully decoded envelope. */\n TrailingBytes = 'trailing_bytes',\n}\n\n/**\n * A refusal to decode. `kind` is the machine-readable reason; `field` names\n * the offending field for {@link EnvelopeErrorKind.InvalidUtf8}, matching\n * `EnvelopeError::InvalidUtf8(&'static str)` on the Rust side.\n */\nexport class EnvelopeError extends Error {\n constructor(\n readonly kind: EnvelopeErrorKind,\n readonly field?: string\n ) {\n super(\n field === undefined\n ? ENVELOPE_ERROR_MESSAGES[kind]\n : `${ENVELOPE_ERROR_MESSAGES[kind]} (field '${field}')`\n );\n this.name = 'EnvelopeError';\n }\n}\n\nconst ENVELOPE_ERROR_MESSAGES: Record<EnvelopeErrorKind, string> = {\n [EnvelopeErrorKind.BufferUnderflow]:\n 'buffer underflow: envelope is truncated',\n [EnvelopeErrorKind.NonCanonicalLength]:\n 'non-canonical OER length determinant: not the minimal encoding of its value',\n [EnvelopeErrorKind.LengthDeterminantOverflow]:\n 'OER length determinant wider than 8 bytes',\n [EnvelopeErrorKind.InvalidType]:\n 'invalid envelope type byte: expected 1 (REQUEST) or 2 (RESPONSE)',\n [EnvelopeErrorKind.InvalidUtf8]: 'invalid UTF-8 in envelope field',\n [EnvelopeErrorKind.TrailingBytes]:\n 'trailing bytes after a fully decoded envelope',\n};\n\n/** One `(name, value)` header, in wire order. Duplicates are legal. */\nexport type EnvelopeHeader = readonly [name: string, value: string];\n\n/** The request a connector is to make of the app behind a terminated route. */\nexport interface EnvelopeRequest {\n method: string;\n target: string;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** The app's response back to the connector. */\nexport interface EnvelopeResponse {\n /** HTTP status, two bytes big-endian on the wire (`0..=65535`). */\n status: number;\n headers: readonly EnvelopeHeader[];\n body: Uint8Array;\n}\n\n/** Either direction, tagged — the shape the vector file's `decoded` carries. */\nexport type Envelope =\n | ({ direction: 'request' } & EnvelopeRequest)\n | ({ direction: 'response' } & EnvelopeResponse);\n\n// ─── Shared helpers ─────────────────────────────────────────────────────────\n\nconst UTF8_ENCODER = new TextEncoder();\n/** `fatal` is load-bearing: a lenient decoder would turn bad bytes into U+FFFD. */\nconst UTF8_DECODER = new TextDecoder('utf-8', { fatal: true });\n\n/** Map an {@link OerError} onto its envelope-level counterpart, 1:1. */\nfunction fromOerError(error: unknown): EnvelopeError {\n if (error instanceof OerError) {\n switch (error.kind) {\n case OerErrorKind.BufferUnderflow:\n return new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n case OerErrorKind.NonCanonicalLength:\n return new EnvelopeError(EnvelopeErrorKind.NonCanonicalLength);\n case OerErrorKind.LengthDeterminantOverflow:\n return new EnvelopeError(EnvelopeErrorKind.LengthDeterminantOverflow);\n }\n }\n throw error;\n}\n\nfunction decodeOctets(\n buf: Uint8Array,\n offset: number\n): { value: Uint8Array; consumed: number } {\n try {\n return decodeVarOctetString(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\nfunction decodeCount(\n buf: Uint8Array,\n offset: number\n): {\n value: bigint;\n consumed: number;\n} {\n try {\n return decodeVarUint(buf, offset);\n } catch (error) {\n throw fromOerError(error);\n }\n}\n\n/** Decode a VarOctetString and validate it as UTF-8 in one step. */\nfunction decodeStringField(\n buf: Uint8Array,\n offset: number,\n field: string\n): { value: string; consumed: number } {\n const { value: bytes, consumed } = decodeOctets(buf, offset);\n try {\n return { value: UTF8_DECODER.decode(bytes), consumed };\n } catch {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidUtf8, field);\n }\n}\n\nfunction checkTypeByte(buf: Uint8Array, expected: number): number {\n const typeByte = buf[0];\n if (typeByte === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n if (typeByte !== expected) {\n throw new EnvelopeError(EnvelopeErrorKind.InvalidType);\n }\n return 1;\n}\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\nfunction encodeHeaders(headers: readonly EnvelopeHeader[]): Uint8Array {\n const parts: Uint8Array[] = [encodeVarUint(BigInt(headers.length))];\n for (const [name, value] of headers) {\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(name)));\n parts.push(encodeVarOctetString(UTF8_ENCODER.encode(value)));\n }\n return concat(parts);\n}\n\nfunction decodeHeaders(\n buf: Uint8Array,\n offset: number\n): { value: EnvelopeHeader[]; consumed: number } {\n const { value: count, consumed: countBytes } = decodeCount(buf, offset);\n\n // Every header costs at least two bytes, so a count exceeding what remains\n // cannot be honoured. Checked in `bigint`, before any loop, so a `u64`-scale\n // count is refused as underflow instead of spinning.\n if (count * 2n > BigInt(buf.length - offset - countBytes)) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n\n let consumed = countBytes;\n const headers: EnvelopeHeader[] = [];\n for (let i = 0n; i < count; i++) {\n const name = decodeStringField(buf, offset + consumed, 'header name');\n consumed += name.consumed;\n const value = decodeStringField(buf, offset + consumed, 'header value');\n consumed += value.consumed;\n headers.push([name.value, value.value]);\n }\n return { value: headers, consumed };\n}\n\n// ─── Request ────────────────────────────────────────────────────────────────\n\n/** Encode a request envelope. The inverse of {@link decodeEnvelopeRequest}. */\nexport function encodeEnvelopeRequest(request: EnvelopeRequest): Uint8Array {\n return concat([\n Uint8Array.of(TYPE_ENVELOPE_REQUEST),\n encodeVarOctetString(UTF8_ENCODER.encode(request.method)),\n encodeVarOctetString(UTF8_ENCODER.encode(request.target)),\n encodeHeaders(request.headers),\n encodeVarOctetString(request.body),\n ]);\n}\n\n/**\n * Decode a request envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeRequest(buf: Uint8Array): EnvelopeRequest {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_REQUEST);\n\n const method = decodeStringField(buf, offset, 'method');\n offset += method.consumed;\n\n const target = decodeStringField(buf, offset, 'target');\n offset += target.consumed;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return {\n method: method.value,\n target: target.value,\n headers: headers.value,\n body: body.value,\n };\n}\n\n// ─── Response ───────────────────────────────────────────────────────────────\n\n/** Encode a response envelope. The inverse of {@link decodeEnvelopeResponse}. */\nexport function encodeEnvelopeResponse(response: EnvelopeResponse): Uint8Array {\n if (\n !Number.isInteger(response.status) ||\n response.status < 0 ||\n response.status > 0xffff\n ) {\n throw new RangeError(\n `envelope status must fit two bytes, got ${response.status}`\n );\n }\n return concat([\n Uint8Array.of(\n TYPE_ENVELOPE_RESPONSE,\n (response.status >> 8) & 0xff,\n response.status & 0xff\n ),\n encodeHeaders(response.headers),\n encodeVarOctetString(response.body),\n ]);\n}\n\n/**\n * Decode a response envelope, consuming the WHOLE buffer.\n *\n * @throws {EnvelopeError} and nothing else, for any input whatsoever.\n */\nexport function decodeEnvelopeResponse(buf: Uint8Array): EnvelopeResponse {\n let offset = checkTypeByte(buf, TYPE_ENVELOPE_RESPONSE);\n\n const high = buf[offset];\n const low = buf[offset + 1];\n if (high === undefined || low === undefined) {\n throw new EnvelopeError(EnvelopeErrorKind.BufferUnderflow);\n }\n const status = (high << 8) | low;\n offset += 2;\n\n const headers = decodeHeaders(buf, offset);\n offset += headers.consumed;\n\n const body = decodeOctets(buf, offset);\n offset += body.consumed;\n\n if (offset !== buf.length) {\n throw new EnvelopeError(EnvelopeErrorKind.TrailingBytes);\n }\n return { status, headers: headers.value, body: body.value };\n}\n\n// ─── Direction-tagged façade ────────────────────────────────────────────────\n\n/** Encode either direction from its tagged form. */\nexport function encodeEnvelope(envelope: Envelope): Uint8Array {\n return envelope.direction === 'request'\n ? encodeEnvelopeRequest(envelope)\n : encodeEnvelopeResponse(envelope);\n}\n\n/**\n * Decode as the named direction. The direction is an INPUT, never guessed from\n * the type byte: a caller that asked for a request and got a response has been\n * handed the wrong bytes, and `invalid_type` is the honest answer.\n */\nexport function decodeEnvelope(\n buf: Uint8Array,\n direction: 'request' | 'response'\n): Envelope {\n return direction === 'request'\n ? { direction, ...decodeEnvelopeRequest(buf) }\n : { direction, ...decodeEnvelopeResponse(buf) };\n}\n","/**\n * The gift wrap (ADR 0018) and the fulfilment a shared secret derives (ADR\n * 0019): the seal around the {@link ./envelope.js | envelope}, so a packet\n * payload is readable only by the connector that terminates it and the\n * preimage that pays for it needs no app participation.\n *\n * A faithful port of `connector_signer::giftwrap`\n * (`crates/connector-signer/src/giftwrap.rs` on toon-protocol/connector `main`)\n * and of `connector_domain::condition::derive_condition`\n * (`crates/connector-domain/src/condition.rs:27`). `vectors/wire-vectors.json`'s\n * `giftwrap` and `fulfilment` sections are the contract, replayed byte-for-byte\n * in `wire-vectors.test.ts`; the prose here describes the same thing but the\n * bytes decide.\n *\n * ─── The mechanism, as read off the Rust ────────────────────────────────────\n * Recorded here because it cannot be inferred from the vector file's field\n * names, and because the acceptance criterion for toon-client#449 asks for it\n * in writing. Every line below is cited to\n * `crates/connector-signer/src/giftwrap.rs` unless stated otherwise.\n *\n * - **Curve and ECDH.** The receiver's identity key is secp256k1; the value a\n * real connector reports from `GET /ilp/identity` is its 65-byte\n * uncompressed form (`0x04 ‖ X ‖ Y`). The sender ECDHs a fresh, per-packet\n * ephemeral key against it and uses the **raw X-coordinate** of the\n * resulting point — `crypto.rs`'s `ecdh_x_coordinate` does\n * `tweak_mul_assign` then `serialize_compressed()[1..]`, deliberately *not*\n * `libsecp256k1::SharedSecret`'s digest-mixing variant. So: not hashed, and\n * not the 33-byte compressed point.\n * - **Key derivation.** `HKDF-SHA256`, **no salt** (`Hkdf::new(None, ikm)`,\n * i.e. HKDF-Extract with an all-zero salt), expanded to 32 bytes under one\n * of three fixed ASCII `info` strings — `giftwrap.rs`'s `hkdf_key`:\n * - `toon-giftwrap-request` — the request AEAD key, over the ECDH X.\n * - `toon-giftwrap-response` — the response AEAD key, over the shared secret.\n * - `toon-giftwrap-fulfillment` — the fulfilment, over the shared secret.\n * (American spelling on the wire; the vector *section* is `fulfilment`.)\n * These three strings are the only domain separation between two AEAD keys\n * and a payment preimage all derived from the same input, so one wrong\n * character silently yields bytes that decrypt nothing and satisfy no\n * condition.\n * - **AEAD.** ChaCha20-Poly1305 (RFC 8439), 12-byte nonce, **no** additional\n * authenticated data.\n * - **Request framing.** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖\n * ciphertext`, where the encrypted plaintext is `shared_secret(32) ‖\n * encoded_envelope`. The secret rides *inside* the sealed request, which is\n * what lets the response be sealed with no second key exchange.\n * - **Response framing.** `0x02 ‖ nonce(12) ‖ ciphertext`, the plaintext being\n * just the encoded envelope. Sealed directly with the request's shared\n * secret.\n * - **Fulfilment and condition.** `fulfilment = HKDF-SHA256(shared_secret,\n * \"toon-giftwrap-fulfillment\")`; the condition a sender mints is\n * `sha256(fulfilment)` — `condition.rs`'s `derive_condition`. A sender knows\n * the secret before it seals, so it can mint the condition first; the\n * terminating connector recovers the secret by opening the wrap and derives\n * the preimage without asking the app anything.\n * - **Telling a sealed reject from a plaintext one.** The leading type byte,\n * and only that (`looks_like_sealed_response`). A reject raised short of the\n * termination shares no secret with the sender and carries empty `data`; an\n * empty `data` is never sealed, so a sealed reject is positive proof that\n * the destination itself said no.\n *\n * ─── Two failure modes, two types ───────────────────────────────────────────\n * A wrap that cannot be OPENED throws {@link GiftWrapError}. A wrap that opens\n * cleanly but whose recovered plaintext is not a valid envelope throws\n * `EnvelopeError`, from `envelope.ts` — a different class entirely, raised\n * above this module rather than by it. The Rust keeps the same separation\n * (`GiftWrapError` vs `connector_domain::EnvelopeError`) for the same reason:\n * \"I could not read this\" and \"I read this and it was malformed\" are different\n * facts about a peer, and collapsing them loses the distinction at every call\n * site.\n *\n * ─── Additive ───────────────────────────────────────────────────────────────\n * Nothing in this client's live send path calls this yet — `publishEvent` is\n * still the latin1 HTTP framing in `utils/store-envelope.ts`. Rewiring it is a\n * later child (toon-client#450).\n */\n\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { chacha20poly1305 } from '@noble/ciphers/chacha.js';\nimport { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\n\n// ─── Constants (giftwrap.rs:36-46) ──────────────────────────────────────────\n\n/** ChaCha20-Poly1305 nonce length. */\nexport const GIFTWRAP_NONCE_LENGTH = 12;\n/** The shared secret carried inside a sealed request, and the fulfilment. */\nexport const GIFTWRAP_SECRET_LENGTH = 32;\n/** The uncompressed secp256k1 public key a sealed request carries. */\nexport const GIFTWRAP_PUBLIC_KEY_LENGTH = 65;\n\nconst REQUEST_INFO = 'toon-giftwrap-request';\nconst RESPONSE_INFO = 'toon-giftwrap-response';\nconst FULFILLMENT_INFO = 'toon-giftwrap-fulfillment';\n\n/** `TYPE_GIFTWRAP_REQUEST` — the leading byte of a sealed request. */\nexport const GIFTWRAP_TYPE_REQUEST = 1;\n/** `TYPE_GIFTWRAP_RESPONSE` — the leading byte of a sealed response. */\nexport const GIFTWRAP_TYPE_RESPONSE = 2;\n\n/** Poly1305 tag length — the minimum a non-empty ciphertext can be. */\nconst TAG_LENGTH = 16;\n\n// ─── Errors ─────────────────────────────────────────────────────────────────\n\n/**\n * Every distinguishable way a wrap can fail to open — the four variants of\n * `GiftWrapError` in `giftwrap.rs:57-71`, named the same way. There is\n * deliberately no catch-all: this module must never be able to fail \"somehow\".\n *\n * None of these ever carries decrypted plaintext, matching the Rust's own\n * guarantee.\n */\nexport enum GiftWrapErrorKind {\n /** The leading byte is not the one this direction requires. */\n InvalidType = 'invalid_type',\n /** The bytes end before the framing does. */\n Truncated = 'truncated',\n /** An ephemeral or receiver public key that is not a usable curve point. */\n InvalidKey = 'invalid_key',\n /** The AEAD refused: wrong key, wrong nonce, or a tampered ciphertext. */\n OpenFailed = 'open_failed',\n}\n\nconst GIFTWRAP_ERROR_MESSAGES: Record<GiftWrapErrorKind, string> = {\n [GiftWrapErrorKind.InvalidType]: 'invalid gift wrap type byte',\n [GiftWrapErrorKind.Truncated]: 'gift wrap is truncated',\n [GiftWrapErrorKind.InvalidKey]: 'invalid ephemeral or peer public key',\n [GiftWrapErrorKind.OpenFailed]: 'gift wrap failed to decrypt',\n};\n\n/**\n * A refusal to open a wrap. `kind` is the machine-readable reason;\n * `expectedType` names the type byte that was required, for\n * {@link GiftWrapErrorKind.InvalidType} — mirroring\n * `GiftWrapError::InvalidType(u8)`.\n */\nexport class GiftWrapError extends Error {\n constructor(\n readonly kind: GiftWrapErrorKind,\n readonly expectedType?: number\n ) {\n super(\n expectedType === undefined\n ? GIFTWRAP_ERROR_MESSAGES[kind]\n : `${GIFTWRAP_ERROR_MESSAGES[kind]}: expected ${expectedType}`\n );\n this.name = 'GiftWrapError';\n }\n}\n\n// ─── Shapes ─────────────────────────────────────────────────────────────────\n\n/**\n * What sealing a request produces: the bytes to carry as `Prepare.data`, and\n * the shared secret that both derives this packet's fulfilment and opens the\n * answer. The sender must keep the secret — it is the only thing that opens\n * the response, and the only thing that proves the fulfilment it is paid\n * against was earned rather than guessed.\n */\nexport interface SealedRequest {\n /** `0x01 ‖ ephemeral_public(65) ‖ nonce(12) ‖ ciphertext`. */\n readonly wrapped: Uint8Array;\n /** The 32 random bytes sealed inside `wrapped`. */\n readonly sharedSecret: Uint8Array;\n}\n\n/** What opening a sealed request recovers. */\nexport interface OpenedRequest {\n /** The encoded envelope — feed to `decodeEnvelopeRequest`. */\n readonly envelopeBytes: Uint8Array;\n /** The 32-byte secret the sender chose, for the fulfilment and the answer. */\n readonly sharedSecret: Uint8Array;\n}\n\n/**\n * A key agreement that never hands out secret key material — the TypeScript\n * counterpart of `giftwrap.rs`'s dependency on `Signer::ecdh`, and the reason\n * {@link openRequest} takes this rather than a raw private key: a remote or\n * hardware-backed identity can open a wrap without its key leaving its own\n * boundary.\n *\n * Returns the raw 32-byte ECDH X-coordinate, or throws.\n */\nexport interface GiftWrapEcdh {\n ecdh(ephemeralPublicKey: Uint8Array): Uint8Array;\n}\n\n// ─── Primitives ─────────────────────────────────────────────────────────────\n\nfunction concat(parts: readonly Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, part) => sum + part.length, 0);\n const out = new Uint8Array(total);\n let offset = 0;\n for (const part of parts) {\n out.set(part, offset);\n offset += part.length;\n }\n return out;\n}\n\n/**\n * `HKDF-SHA256(ikm, salt = none, info, L = 32)` — `giftwrap.rs`'s `hkdf_key`.\n * The absent salt is load-bearing: HKDF-Extract runs with an all-zero salt, so\n * passing a salt of any kind produces a different, silently-wrong key.\n */\nfunction hkdfKey(ikm: Uint8Array, info: string): Uint8Array {\n return hkdf(sha256, ikm, undefined, info, 32);\n}\n\n/** `giftwrap.rs`'s `encrypt_with_nonce`: `nonce ‖ ciphertext`. */\nfunction encryptWithNonce(\n key: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n return concat([nonce, chacha20poly1305(key, nonce).encrypt(plaintext)]);\n}\n\n/** `giftwrap.rs`'s `decrypt`: splits `nonce ‖ ciphertext` and opens it. */\nfunction decrypt(key: Uint8Array, nonceAndCiphertext: Uint8Array): Uint8Array {\n if (nonceAndCiphertext.length < GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n const nonce = nonceAndCiphertext.subarray(0, GIFTWRAP_NONCE_LENGTH);\n const ciphertext = nonceAndCiphertext.subarray(GIFTWRAP_NONCE_LENGTH);\n // A ciphertext shorter than the Poly1305 tag cannot be an AEAD output at\n // all. `@noble/ciphers` throws a plain `Error` for that rather than failing\n // the tag check, so classify it here instead of letting a foreign error type\n // escape this module.\n if (ciphertext.length < TAG_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n try {\n return chacha20poly1305(key, nonce).decrypt(ciphertext);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.OpenFailed);\n }\n}\n\n/**\n * The raw ECDH X-coordinate of `secret * public` — `crypto.rs`'s\n * `ecdh_x_coordinate`. `@noble/curves` returns the compressed point, whose\n * bytes `1..33` are exactly the `serialize_compressed()[1..]` the Rust takes.\n */\nfunction ecdhXCoordinate(\n secretKey: Uint8Array,\n publicKey: Uint8Array\n): Uint8Array {\n let compressed: Uint8Array;\n try {\n compressed = secp256k1.getSharedSecret(secretKey, publicKey, true);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n return compressed.slice(1);\n}\n\n/**\n * The ordinary local case of {@link GiftWrapEcdh}: a 32-byte secp256k1 secret\n * key held in this process. `openRequest` accepts a bare key too and wraps it\n * in this.\n */\nexport function localGiftWrapEcdh(secretKey: Uint8Array): GiftWrapEcdh {\n return {\n ecdh: (ephemeralPublicKey) =>\n ecdhXCoordinate(secretKey, ephemeralPublicKey),\n };\n}\n\n// ─── Request direction ──────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealRequest}, parameterized on every value\n * a real seal draws at random — the counterpart of the Rust's\n * `seal_request_with_randomness`, which that crate gates behind a `test-util`\n * feature for a reason worth repeating: **reusing a (key, nonce) pair under\n * ChaCha20-Poly1305 is catastrophic**, so caller-supplied randomness is a\n * footgun, not a convenience. Use {@link sealRequest} unless you are replaying\n * a fixed vector.\n *\n * `receiverPublicKey` may be the 65-byte uncompressed form a connector's\n * `GET /ilp/identity` reports, or the 33-byte compressed form; the ECDH result\n * is the same point either way. The ephemeral key is always emitted\n * uncompressed, because that is what the framing pins.\n */\nexport function sealRequestWithRandomness(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array,\n ephemeralSecretKey: Uint8Array,\n sharedSecret: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n let ephemeralPublicKey: Uint8Array;\n try {\n ephemeralPublicKey = secp256k1.getPublicKey(ephemeralSecretKey, false);\n } catch {\n throw new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const aeadKey = hkdfKey(\n ecdhXCoordinate(ephemeralSecretKey, receiverPublicKey),\n REQUEST_INFO\n );\n const inner = concat([sharedSecret, plaintext]);\n\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_REQUEST),\n ephemeralPublicKey,\n encryptWithNonce(aeadKey, inner, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` (an encoded envelope) to `receiverPublicKey`. A fresh\n * ephemeral key pair, shared secret and nonce are drawn for this call alone,\n * so no two sealed requests — even to the same receiver, even with the same\n * plaintext — share any of the three.\n *\n * Returns the wire bytes and the shared secret. Mint the packet's execution\n * condition as {@link deriveCondition}({@link deriveFulfillment}(secret))\n * before sending: the terminating connector recovers the same secret by\n * opening this wrap, so the preimage it is paid against is one it derived, not\n * one anybody handed it.\n */\nexport function sealRequest(\n plaintext: Uint8Array,\n receiverPublicKey: Uint8Array\n): SealedRequest {\n const ephemeralSecretKey = secp256k1.utils.randomSecretKey();\n const sharedSecret = randomBytes(GIFTWRAP_SECRET_LENGTH);\n const nonce = randomBytes(GIFTWRAP_NONCE_LENGTH);\n\n return {\n wrapped: sealRequestWithRandomness(\n plaintext,\n receiverPublicKey,\n ephemeralSecretKey,\n sharedSecret,\n nonce\n ),\n sharedSecret,\n };\n}\n\n/**\n * Open a sealed request addressed to `identity`, recovering the encoded\n * envelope and the shared secret carried alongside it.\n *\n * `identity` is either a 32-byte secp256k1 secret key or a {@link GiftWrapEcdh}\n * that never exposes one. Nothing in this client terminates packets today, so\n * this exists to make the seal testable from both ends — and to make the\n * vectors' \"opening it with the fixture's secret key must recover the envelope\n * and the secret exactly\" a check this repo can actually run.\n */\nexport function openRequest(\n bytes: Uint8Array,\n identity: Uint8Array | GiftWrapEcdh\n): OpenedRequest {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_REQUEST) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_REQUEST\n );\n }\n if (bytes.length < 1 + GIFTWRAP_PUBLIC_KEY_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n const ephemeralPublicKey = bytes.slice(1, 1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n const ciphertext = bytes.subarray(1 + GIFTWRAP_PUBLIC_KEY_LENGTH);\n\n const agreement =\n identity instanceof Uint8Array ? localGiftWrapEcdh(identity) : identity;\n let ecdhSecret: Uint8Array;\n try {\n ecdhSecret = agreement.ecdh(ephemeralPublicKey);\n } catch (error) {\n throw error instanceof GiftWrapError\n ? error\n : new GiftWrapError(GiftWrapErrorKind.InvalidKey);\n }\n\n const plaintext = decrypt(hkdfKey(ecdhSecret, REQUEST_INFO), ciphertext);\n if (plaintext.length < GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n\n return {\n envelopeBytes: plaintext.slice(GIFTWRAP_SECRET_LENGTH),\n sharedSecret: plaintext.slice(0, GIFTWRAP_SECRET_LENGTH),\n };\n}\n\n// ─── Response direction ─────────────────────────────────────────────────────\n\n/**\n * The deterministic core of {@link sealResponse}, parameterized on the nonce.\n * Same footgun, same warning as {@link sealRequestWithRandomness}: a nonce\n * reused under one shared secret destroys the confidentiality of both\n * responses sealed with it.\n */\nexport function sealResponseWithRandomness(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array,\n nonce: Uint8Array\n): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (nonce.length !== GIFTWRAP_NONCE_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return concat([\n Uint8Array.of(GIFTWRAP_TYPE_RESPONSE),\n encryptWithNonce(hkdfKey(sharedSecret, RESPONSE_INFO), plaintext, nonce),\n ]);\n}\n\n/**\n * Seal `plaintext` — an encoded response envelope, or a reject's diagnostic\n * bytes — with the request's own `sharedSecret`. No second key exchange: the\n * secret is bidirectional by construction, which is also why a sealed reject\n * can only have come from the termination.\n */\nexport function sealResponse(\n sharedSecret: Uint8Array,\n plaintext: Uint8Array\n): Uint8Array {\n return sealResponseWithRandomness(\n sharedSecret,\n plaintext,\n randomBytes(GIFTWRAP_NONCE_LENGTH)\n );\n}\n\n/**\n * Open a sealed response with the shared secret {@link sealRequest} returned\n * for the request it answers. No signer, no key exchange, no identity key.\n */\nexport function openResponse(\n sharedSecret: Uint8Array,\n bytes: Uint8Array\n): Uint8Array {\n if (bytes.length === 0) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n if (bytes[0] !== GIFTWRAP_TYPE_RESPONSE) {\n throw new GiftWrapError(\n GiftWrapErrorKind.InvalidType,\n GIFTWRAP_TYPE_RESPONSE\n );\n }\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return decrypt(hkdfKey(sharedSecret, RESPONSE_INFO), bytes.subarray(1));\n}\n\n/**\n * Whether `bytes` is shaped like a sealed response — the leading type byte and\n * nothing else, exactly as `looks_like_sealed_response` does it. This is how a\n * sender tells a reject raised BY the destination from one raised on the way\n * to it, without holding the secret to try opening it.\n *\n * Empty `data`, which every reject raised short of a termination carries, is\n * never sealed.\n */\nexport function looksLikeSealedResponse(bytes: Uint8Array): boolean {\n return bytes.length > 0 && bytes[0] === GIFTWRAP_TYPE_RESPONSE;\n}\n\n// ─── Fulfilment and condition ───────────────────────────────────────────────\n\n/**\n * The fulfilment a request's shared secret derives (ADR 0019):\n * `HKDF-SHA256(shared_secret, \"toon-giftwrap-fulfillment\")`, 32 bytes.\n * Domain-separated by its own `info` string from both AEAD keys the same\n * secret also derives, so it can never collide with either.\n */\nexport function deriveFulfillment(sharedSecret: Uint8Array): Uint8Array {\n if (sharedSecret.length !== GIFTWRAP_SECRET_LENGTH) {\n throw new GiftWrapError(GiftWrapErrorKind.Truncated);\n }\n return hkdfKey(sharedSecret, FULFILLMENT_INFO);\n}\n\n/**\n * The condition a `fulfillment` satisfies: `sha256(fulfillment)` —\n * `connector_domain::condition::derive_condition`. Hashing only ever runs in\n * this direction; there is deliberately no function here that goes from a\n * condition back to a fulfilment.\n *\n * The hash is the same one `utils/condition.ts` already uses; what ADR 0019\n * changes is where the preimage comes from. `mintExecutionCondition` there\n * draws a random preimage the sender must then carry to the FULFILL itself;\n * here the preimage is DERIVED from the secret sealed inside the packet, so\n * the terminating connector can produce it without the sender or the app\n * handing it over. Checking a returned fulfilment against a condition is\n * unchanged either way — use `fulfillmentMatchesCondition` from\n * `utils/condition.ts` for that rather than a second copy of it here.\n */\nexport function deriveCondition(fulfillment: Uint8Array): Uint8Array {\n return sha256(fulfillment);\n}\n","/**\n * One sealed request/answer exchange with a terminating connector (ADR 0018,\n * ADR 0019, ADR 0020) — the whole shape of a packet's payload, from the\n * envelope going out to the answer coming back, behind two functions.\n *\n * A sender's obligations on this wire are not independent of one another, and\n * getting any of them separately wrong is silent:\n *\n * - The `data` is a gift wrap addressed to the connector that TERMINATES the\n * route, around an OER envelope — never HTTP text, never a bare payload.\n * - The execution condition is `sha256` of the fulfilment DERIVED from the\n * very secret that wrap carries. A random condition would never be\n * fulfilled; an all-zero one is refused outright by the connector\n * (`connector-domain`'s `condition_is_present`), which is why the publish\n * path could not work against it at all before this module existed.\n * - The answer is sealed with that same secret, so opening it requires having\n * kept it from the seal.\n *\n * {@link sealExchange} produces all three from one call so they cannot drift\n * apart, and {@link readExchangeOutcome} is the only thing that reads the\n * answer. The secret is the token joining them.\n *\n * ─── Why the outcome is a tagged union ─────────────────────────────────────\n * ADR 0018 gives a sender something it never had: a REJECT sealed with the\n * request's own secret can ONLY have come from the termination, because only\n * the termination could recover that secret. A reject raised short of it is\n * necessarily plaintext — an intermediate hop shares no secret and cannot\n * seal. So \"the destination said no\" and \"somebody on the path said no\" are\n * now genuinely different facts, and flattening both into one error string\n * would throw away the distinction the seal was introduced to create.\n *\n * ADR 0020 draws the other line this union encodes: an HTTP status inside a\n * response envelope is envelope CONTENT, not a packet outcome. A 404 arrives\n * on a FULFILL and value moved. {@link ExchangeOutcome.Answered} therefore\n * carries any status at all, and it is the caller's business — not this\n * module's — whether a given status means its own operation succeeded.\n *\n * Pure: no I/O, no clock, no network. Randomness only through\n * {@link sealRequest}.\n */\n\nimport {\n decodeEnvelopeResponse,\n encodeEnvelopeRequest,\n EnvelopeError,\n type EnvelopeRequest,\n type EnvelopeResponse,\n} from './envelope.js';\nimport {\n deriveCondition,\n deriveFulfillment,\n GiftWrapError,\n looksLikeSealedResponse,\n openResponse,\n sealRequest,\n} from './giftwrap.js';\n\n/**\n * A sealed request, ready to become a PREPARE: what goes in `data`, what goes\n * on `executionCondition`, and the secret needed to read the answer.\n *\n * The three are produced together and belong together. Sending `data` under a\n * condition minted any other way produces a packet no honest connector can\n * fulfil; opening the answer with any other secret fails.\n */\nexport interface SealedExchange {\n /** The gift wrap to carry as the PREPARE's `data`. */\n readonly data: Uint8Array;\n /**\n * The PREPARE's `executionCondition`: `sha256(deriveFulfillment(secret))`.\n * Derived, never random and never caller-supplied — the terminating\n * connector recovers the same secret and derives the same fulfilment\n * without the app participating (ADR 0019).\n */\n readonly condition: Uint8Array;\n /**\n * The 32-byte secret sealed inside the wrap. Keep it until the answer is\n * read; it is the only thing that opens the response. Never send it\n * anywhere else, and never reuse it for a second packet.\n */\n readonly sharedSecret: Uint8Array;\n /**\n * The fulfilment the terminating connector will return. Held so a caller\n * can check the FULFILL preimage it actually got, rather than only that it\n * hashes to the condition.\n */\n readonly fulfillment: Uint8Array;\n}\n\n/**\n * How an exchange ended. Three outcomes, deliberately not two: a refusal's\n * ORIGIN is the fact ADR 0018 makes knowable for the first time.\n */\nexport type ExchangeOutcome =\n /**\n * The termination answered. `response` is whatever it said, at whatever\n * status — a non-2xx here is a real answer that was paid for (ADR 0020),\n * not a failure of the packet.\n */\n | { readonly kind: 'answered'; readonly response: EnvelopeResponse }\n /**\n * The DESTINATION refused, provably: the reject's `data` was sealed with\n * this exchange's own secret, which only the terminating connector could\n * hold. `detail` is whatever it sealed alongside (often empty).\n */\n | {\n readonly kind: 'destination-refused';\n readonly code: string;\n readonly message: string;\n readonly detail: Uint8Array;\n }\n /**\n * Somebody ON THE PATH refused — no route, expiry, a ceiling, a rejected\n * claim — short of the termination, so nothing was sealed. Unauthenticated\n * by construction: any hop can produce this, and it should be read as a\n * hint, not a verdict from the destination.\n */\n | {\n readonly kind: 'path-refused';\n readonly code: string;\n readonly message: string;\n };\n\n/**\n * Why an answer that arrived could not be read. Distinct from an\n * {@link ExchangeOutcome}: these are not the destination's answer at all, but\n * bytes that failed to be one.\n */\nexport type SealedResponseErrorKind =\n /** A FULFILL whose `data` is absent, or does not begin with the sealed-response type byte. */\n | 'not-sealed'\n /** The wrap is shaped right but does not open under this exchange's secret. */\n | 'unopenable'\n /** It opened, and what came out is not a response envelope. */\n | 'malformed-envelope';\n\n/** A refusal to read an answer. Never carries recovered plaintext. */\nexport class SealedResponseError extends Error {\n constructor(\n readonly kind: SealedResponseErrorKind,\n message: string,\n override readonly cause?: Error\n ) {\n super(message);\n this.name = 'SealedResponseError';\n }\n}\n\n/**\n * Seal `request` to `connectorPublicKey` — the identity of the connector that\n * TERMINATES the destination, as read from its own client edge\n * (`ConnectorEdgeClient`). Sealing to any other key is a confidentiality\n * failure that presents as an undeliverable packet.\n *\n * @param request the envelope to seal.\n * @param connectorPublicKey the terminating connector's 65-byte uncompressed\n * secp256k1 identity key.\n */\nexport function sealExchange(\n request: EnvelopeRequest,\n connectorPublicKey: Uint8Array\n): SealedExchange {\n const { wrapped, sharedSecret } = sealRequest(\n encodeEnvelopeRequest(request),\n connectorPublicKey\n );\n const fulfillment = deriveFulfillment(sharedSecret);\n return {\n data: wrapped,\n condition: deriveCondition(fulfillment),\n sharedSecret,\n fulfillment,\n };\n}\n\n/**\n * Read what came back.\n *\n * `accepted` distinguishes a FULFILL from a REJECT; `data` is the packet's\n * payload bytes, absent when it carried none. Both come straight off the\n * transport's result, so this stays testable without a socket.\n *\n * A FULFILL must be sealed and must decode: value moved, so bytes that are\n * neither are a broken counterparty, and this throws rather than inventing an\n * outcome. A REJECT is classified instead of thrown on — an unopenable one is\n * simply a path reject that happened to carry bytes.\n *\n * @throws {SealedResponseError} for a FULFILL that is not a readable sealed\n * response envelope.\n */\nexport function readExchangeOutcome(\n result: { accepted: boolean; code?: string; message?: string },\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): ExchangeOutcome {\n if (result.accepted) {\n return { kind: 'answered', response: openAnswer(data, sharedSecret) };\n }\n\n const code = result.code ?? 'F00';\n const message = result.message ?? '';\n\n // Only the termination could have sealed this, so only a wrap that actually\n // OPENS proves the destination refused. A leading type byte alone is a\n // claim, not evidence — an intermediary can write one byte.\n if (data !== undefined && looksLikeSealedResponse(data)) {\n try {\n return {\n kind: 'destination-refused',\n code,\n message,\n detail: openResponse(sharedSecret, data),\n };\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n // Fall through: bytes that pose as sealed but do not open are not the\n // destination's word, and must not be reported as if they were.\n }\n }\n\n return { kind: 'path-refused', code, message };\n}\n\nfunction openAnswer(\n data: Uint8Array | undefined,\n sharedSecret: Uint8Array\n): EnvelopeResponse {\n if (data === undefined || data.length === 0) {\n throw new SealedResponseError(\n 'not-sealed',\n 'FULFILL carried no data; a terminated route always seals a response envelope'\n );\n }\n if (!looksLikeSealedResponse(data)) {\n throw new SealedResponseError(\n 'not-sealed',\n `FULFILL data is not a sealed response (leading byte 0x${(data[0] ?? 0)\n .toString(16)\n .padStart(2, '0')}, expected 0x02)`\n );\n }\n\n let opened: Uint8Array;\n try {\n opened = openResponse(sharedSecret, data);\n } catch (error) {\n if (!(error instanceof GiftWrapError)) throw error;\n throw new SealedResponseError(\n 'unopenable',\n 'FULFILL data did not open under this packet\\'s shared secret',\n error\n );\n }\n\n try {\n return decodeEnvelopeResponse(opened);\n } catch (error) {\n if (!(error instanceof EnvelopeError)) throw error;\n throw new SealedResponseError(\n 'malformed-envelope',\n `sealed answer opened but did not decode as a response envelope: ${error.message}`,\n error\n );\n }\n}\n\n/** Read a response header, case-insensitively; the first match wins. */\nexport function envelopeHeader(\n response: EnvelopeResponse,\n name: string\n): string | undefined {\n const wanted = name.toLowerCase();\n for (const [header, value] of response.headers) {\n if (header.toLowerCase() === wanted) return value;\n }\n return undefined;\n}\n","import { BootstrapService, createDiscoveryTracker } from '@toon-protocol/core';\nimport type { BootstrapServiceConfig } from '@toon-protocol/core';\nimport { HttpRuntimeClient } from '../adapters/HttpRuntimeClient.js';\nimport { BtpRuntimeClient } from '../adapters/BtpRuntimeClient.js';\nimport { HttpIlpClient } from '../adapters/HttpIlpClient.js';\nimport {\n selectIlpTransport,\n readDiscoveredIlpPeer,\n} from '../adapters/selectIlpTransport.js';\nimport { OnChainChannelClient } from '../channel/OnChainChannelClient.js';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { buildSettlementInfo } from '../config.js';\nimport type { ResolvedConfig } from '../config.js';\nimport type { HttpModeInitialization } from './types.js';\n\n/**\n * Initializes HTTP mode for ToonClient.\n *\n * HTTP mode uses external connector service via HTTP/WebSocket.\n * This function creates all necessary clients and services for operating in HTTP mode.\n *\n * @param config - ToonClient configuration (must have connectorUrl)\n * @returns Initialized HTTP mode components\n */\nexport async function initializeHttpMode(\n config: ResolvedConfig\n): Promise<HttpModeInitialization> {\n const effectiveBtpUrl = config.btpUrl;\n const effectiveConnectorUrl = config.connectorUrl;\n\n // Build settlement info from config\n const settlementInfo = buildSettlementInfo(config);\n\n // Select the ILP transport for the uplink connector.\n //\n // The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port\n // (connector PR #181). A peer advertises the `POST /ilp` URL in discovery via\n // `IlpPeerInfo.httpEndpoint` (+ `supportsUpgrade`) added in toon PR #29.\n //\n // The client SDK's only \"peer\" at init time is its uplink connector, so we\n // build a DiscoveredIlpPeer from the connector endpoints we know: the derived\n // BTP WebSocket URL plus an optional explicit `connectorHttpEndpoint` (which\n // mirrors the on-wire `httpEndpoint`). `readDiscoveredIlpPeer` reads those\n // fields defensively so this stays compatible with the installed\n // @toon-protocol/core 1.4.2 (pre-PR-#29).\n //\n // NOTE(dep): once a @toon-protocol/core release with the PR-#29\n // `httpEndpoint`/`supportsUpgrade` IlpPeerInfo fields is published (latest on\n // npm is still 1.4.2), bump the dep and feed real discovered peer info here\n // instead of (or in addition to) the explicit config field.\n //\n // FALLBACK GUARANTEE: when no `httpEndpoint` is present (the default — no\n // connector advertises one yet, and `connectorHttpEndpoint` is unset),\n // `selectIlpTransport` returns `{ kind: 'btp' }`, which is exactly the prior\n // behavior. Existing BTP-only flows are unchanged.\n const discoveredPeer = readDiscoveredIlpPeer({\n btpEndpoint: effectiveBtpUrl,\n httpEndpoint: config.connectorHttpEndpoint,\n supportsUpgrade: config.connectorSupportsUpgrade,\n });\n\n // The client SDK's runtime client is a one-shot consumer (it sends ILP\n // packets and reads the synchronous FULFILL/REJECT). It does not need a duplex\n // session at the transport-selection layer, so `needsDuplex` stays false and\n // HTTP is preferred when advertised. A `btpEndpoint` is always present when\n // `btpUrl` is configured, so HTTP is only ever selected when an httpEndpoint\n // is explicitly available.\n const transportChoice =\n discoveredPeer.httpEndpoint || discoveredPeer.btpEndpoint\n ? selectIlpTransport(discoveredPeer, { needsDuplex: false })\n : null;\n\n // Create BTP runtime client — the duplex transport for the client SDK.\n // The client connects to the connector via BTP WebSocket to send ILP packets\n // AND to receive server-initiated packets / act as a peer. We always open it\n // when a btpUrl is configured (publishing, swaps and payments require it), so\n // ToonClient's `btpClient`-gated paths keep working even when one-shot writes\n // go over HTTP.\n let btpClient: BtpRuntimeClient | null = null;\n if (effectiveBtpUrl) {\n btpClient = new BtpRuntimeClient({\n btpUrl: effectiveBtpUrl,\n peerId: config.btpPeerId ?? `client`,\n authToken: config.btpAuthToken ?? '',\n });\n await btpClient.connect();\n }\n\n // Build the HTTP one-shot client when the transport policy selected it.\n let httpIlpClient: HttpIlpClient | null = null;\n if (\n transportChoice &&\n (transportChoice.kind === 'http' ||\n transportChoice.kind === 'http-upgradable')\n ) {\n httpIlpClient = new HttpIlpClient({\n httpEndpoint: transportChoice.httpEndpoint,\n ...(config.btpPeerId !== undefined ? { peerId: config.btpPeerId } : {}),\n ...(config.btpAuthToken !== undefined\n ? { authToken: config.btpAuthToken }\n : {}),\n timeout: config.queryTimeout,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n });\n }\n\n // Runtime client precedence for sending ILP packets:\n // 1. HttpIlpClient — when the connector advertises an httpEndpoint (PR #29).\n // 2. BtpRuntimeClient — the BTP WebSocket (existing default; FALLBACK).\n // 3. HttpRuntimeClient — connector-admin-style HTTP when no btpUrl at all.\n const runtimeClient =\n httpIlpClient ??\n btpClient ??\n new HttpRuntimeClient({\n connectorUrl: effectiveConnectorUrl,\n timeout: config.queryTimeout,\n maxRetries: config.maxRetries,\n retryDelay: config.retryDelay,\n });\n\n // Create on-chain channel client when chain RPC URLs are configured.\n // evmPrivateKey is always present (derived from secretKey by default).\n let onChainChannelClient: OnChainChannelClient | null = null;\n if (config.chainRpcUrls) {\n const evmSigner = new EvmSigner(config.evmPrivateKey);\n onChainChannelClient = new OnChainChannelClient({\n evmSigner,\n chainRpcUrls: config.chainRpcUrls,\n });\n }\n\n // Create BootstrapService\n const bootstrapConfig: BootstrapServiceConfig = {\n knownPeers: (config.knownPeers || []).map((p) => ({\n pubkey: p.pubkey,\n relayUrl: p.relayUrl,\n btpEndpoint: p.btpEndpoint ?? '',\n })),\n queryTimeout: config.queryTimeout,\n ardriveEnabled: true,\n defaultRelayUrl: config.relayUrl,\n settlementInfo,\n ownIlpAddress: config.ilpInfo.ilpAddress,\n toonEncoder: config.toonEncoder,\n toonDecoder: config.toonDecoder,\n // No `basePricePerByte`: ADR 0020 removed per-byte pricing, and a packet's\n // amount now comes from `GET /ilp/routes/price` at the terminating\n // connector (toon-client#452). Nothing here may state a local rate.\n };\n\n const bootstrapService = new BootstrapService(\n bootstrapConfig,\n config.secretKey,\n config.ilpInfo\n );\n\n // Wire ILP client into bootstrap service\n bootstrapService.setIlpClient(runtimeClient);\n\n // Wire on-chain channel client if available\n if (onChainChannelClient) {\n bootstrapService.setChannelClient(onChainChannelClient);\n }\n\n // Do NOT wire ConnectorAdmin — addPeer() at line 472 is skipped when connectorAdmin is null\n // This is intentional: the client is a standalone peer, not an admin interface\n\n // Create DiscoveryTracker\n const discoveryTracker = createDiscoveryTracker({\n secretKey: config.secretKey,\n settlementInfo,\n });\n\n return {\n bootstrapService,\n discoveryTracker,\n runtimeClient,\n adminClient: null,\n btpClient,\n onChainChannelClient,\n };\n}\n","/**\n * Configuration options for retry behavior with exponential backoff.\n */\nexport interface RetryOptions {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n /** Initial delay in milliseconds between retries (default: 1000) */\n retryDelay: number;\n /** Use exponential backoff for delays (default: true) */\n exponentialBackoff?: boolean;\n /** Maximum delay cap in milliseconds (default: 30000) */\n maxDelay?: number;\n /** Custom predicate to determine if an error should trigger a retry */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Executes an async operation with retry logic and exponential backoff.\n *\n * @param operation - The async function to execute\n * @param options - Retry configuration options\n * @returns The result of the successful operation\n * @throws The last error if all retries are exhausted\n *\n * @example\n * ```typescript\n * const result = await withRetry(\n * async () => fetchData(),\n * {\n * maxRetries: 3,\n * retryDelay: 1000,\n * shouldRetry: (err) => err.name === 'NetworkError'\n * }\n * );\n * ```\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n options: RetryOptions\n): Promise<T> {\n const {\n maxRetries,\n retryDelay,\n exponentialBackoff = true,\n maxDelay = 30000,\n shouldRetry,\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if we should retry this error\n if (shouldRetry && !shouldRetry(lastError)) {\n throw lastError;\n }\n\n // If this was the last attempt, throw the error\n if (attempt === maxRetries) {\n throw lastError;\n }\n\n // Calculate delay with exponential backoff\n const currentDelay = exponentialBackoff\n ? Math.min(retryDelay * Math.pow(2, attempt), maxDelay)\n : retryDelay;\n\n // Wait before retrying\n await new Promise((resolve) => setTimeout(resolve, currentDelay));\n }\n }\n\n // This should never be reached, but TypeScript needs it\n throw lastError ?? new Error('Unknown error during retry');\n}\n","import type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport { NetworkError, ConnectorError, ValidationError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { isBase64 } from '../utils/binary.js';\n\n/**\n * Configuration options for HttpRuntimeClient.\n */\nexport interface HttpRuntimeClientConfig {\n /** Connector runtime API base URL (e.g., 'http://localhost:8080') */\n connectorUrl: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts for network failures (default: 3) */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** HTTP client implementation (for testing) */\n httpClient?: typeof fetch;\n}\n\n/**\n * HTTP client for sending ILP packets to an external connector runtime API.\n *\n * Implements the IlpClient interface for use with TOON agents\n * that need to send ILP packets without embedding a full connector.\n *\n * Features:\n * - Request validation (destination, amount, data)\n * - Retry logic with exponential backoff for transient network failures\n * - Typed error handling (NetworkError, ConnectorError, ValidationError)\n * - Connection pooling and keep-alive (via Node.js fetch)\n *\n * @example\n * ```typescript\n * const client = new HttpRuntimeClient({\n * connectorUrl: 'http://localhost:8080'\n * });\n *\n * const result = await client.sendIlpPacket({\n * destination: 'g.toon.alice',\n * amount: '1000',\n * data: 'base64EncodedToonData==',\n * });\n *\n * if (result.accepted) {\n * console.log('Payment accepted');\n * } else {\n * console.error('Payment rejected:', result.code, result.message);\n * }\n * ```\n */\nexport class HttpRuntimeClient implements IlpClient {\n private readonly connectorUrl: string;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n\n constructor(config: HttpRuntimeClientConfig) {\n // Normalize connector URL (remove trailing slash)\n this.connectorUrl = config.connectorUrl.replace(/\\/$/, '');\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n }\n\n /**\n * Send an ILP packet to the connector runtime API.\n *\n * @param params - ILP packet parameters\n * @returns ILP packet response with acceptance status\n * @throws {ValidationError} If request parameters are invalid\n * @throws {NetworkError} If network connection fails after retries\n * @throws {ConnectorError} If connector returns 5xx server error\n */\n async sendIlpPacket(params: {\n destination: string;\n amount: string;\n data: string;\n timeout?: number;\n }): Promise<IlpSendResult> {\n // Validate request parameters\n this.validateRequest(params);\n\n // Wrap HTTP request with retry logic\n return withRetry(async () => this.sendHttpRequest(params), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors (ECONNREFUSED, ETIMEDOUT)\n // Do not retry on validation errors, 4xx, or 5xx errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Validate ILP packet request parameters.\n *\n * @throws {ValidationError} If any parameter is invalid\n */\n private validateRequest(params: {\n destination: string;\n amount: string;\n data: string;\n }): void {\n // Validate destination: non-empty, valid ILP address format\n if (!params.destination || params.destination.trim() === '') {\n throw new ValidationError('Destination cannot be empty');\n }\n if (!params.destination.startsWith('g.')) {\n throw new ValidationError(\n `Invalid ILP address format: \"${params.destination}\" (must start with \"g.\")`\n );\n }\n\n // Validate amount: non-empty, parseable as bigint, positive\n if (!params.amount || params.amount.trim() === '') {\n throw new ValidationError('Amount cannot be empty');\n }\n try {\n const amountBigInt = BigInt(params.amount);\n if (amountBigInt <= 0n) {\n throw new ValidationError(\n `Amount must be positive: \"${params.amount}\"`\n );\n }\n } catch (error) {\n if (error instanceof ValidationError) throw error;\n throw new ValidationError(\n `Amount must be a valid integer: \"${params.amount}\"`,\n error instanceof Error ? error : undefined\n );\n }\n\n // Validate data: non-empty, valid Base64 encoding\n if (!params.data || params.data.trim() === '') {\n throw new ValidationError('Data cannot be empty');\n }\n try {\n if (!isBase64(params.data)) {\n throw new ValidationError(\n `Data must be valid Base64 encoding: \"${params.data}\"`\n );\n }\n } catch (error) {\n if (error instanceof ValidationError) throw error;\n throw new ValidationError(\n `Data must be valid Base64 encoding: \"${params.data}\"`,\n error instanceof Error ? error : undefined\n );\n }\n }\n\n /**\n * Send HTTP POST request to connector runtime API.\n *\n * @throws {NetworkError} On connection failures (ECONNREFUSED, ETIMEDOUT)\n * @throws {ConnectorError} On 5xx server errors\n * @returns IlpSendResult with acceptance status\n */\n private async sendHttpRequest(params: {\n destination: string;\n amount: string;\n data: string;\n timeout?: number;\n }): Promise<IlpSendResult> {\n const requestTimeout = params.timeout ?? this.timeout;\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), requestTimeout);\n\n try {\n // NOTE: Using admin endpoint /admin/ilp/send since connector doesn't have public /ilp endpoint yet\n const response = await this.httpClient(\n `${this.connectorUrl}/admin/ilp/send`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n destination: params.destination,\n amount: params.amount,\n data: params.data,\n }),\n signal: controller.signal,\n }\n );\n\n clearTimeout(timeoutId);\n\n // Handle response by status code\n if (response.ok) {\n // 200 OK: Parse response as IlpSendResult\n const result = (await response.json()) as Record<string, unknown>;\n return {\n accepted: (result['accepted'] as boolean) ?? false,\n data: result['data'] as string | undefined,\n code: result['code'] as string | undefined,\n message: result['message'] as string | undefined,\n };\n } else if (response.status >= 400 && response.status < 500) {\n // 4xx: Client error - return as failed ILP response (no retry)\n const errorBody = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n return {\n accepted: false,\n code: `HTTP_${response.status}`,\n message:\n (errorBody['message'] as string) ??\n (errorBody['error'] as string) ??\n response.statusText,\n };\n } else if (response.status >= 500 && response.status < 600) {\n // 5xx: Server error - throw ConnectorError (no retry)\n const errorBody = (await response.json().catch(() => ({}))) as Record<\n string,\n unknown\n >;\n throw new ConnectorError(\n `Connector server error (${response.status}): ${\n (errorBody['message'] as string) ??\n (errorBody['error'] as string) ??\n response.statusText\n }`\n );\n }\n\n // Unexpected status code (not 2xx, 4xx, or 5xx)\n throw new ConnectorError(\n `Unexpected HTTP status: ${response.status} ${response.statusText}`\n );\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Handle AbortController timeout\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request timeout after ${requestTimeout}ms`,\n error\n );\n }\n\n // Handle network errors (ECONNREFUSED, ETIMEDOUT, etc.)\n if (\n error instanceof TypeError &&\n (error.message.includes('fetch failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('network'))\n ) {\n throw new NetworkError(\n `Network connection failed: ${error.message}`,\n error\n );\n }\n\n // Re-throw known error types\n if (\n error instanceof NetworkError ||\n error instanceof ConnectorError ||\n error instanceof ValidationError\n ) {\n throw error;\n }\n\n // Unknown error\n throw new ConnectorError(\n `Unexpected error during HTTP request: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : undefined\n );\n }\n }\n}\n","/* eslint-disable @typescript-eslint/no-non-null-assertion -- ws is guaranteed non-null when _isConnected */\n/**\n * Isomorphic BTP client — works in both browser and Node.js.\n * Uses native WebSocket (browser) or globalThis.WebSocket (Node 21+).\n * No dependency on `ws`, `events`, or `Buffer`.\n *\n * Replaces the @toon-protocol/connector BTPClient for the client SDK.\n */\n\nimport {\n BTPMessageType,\n ILPPacketType,\n serializeBtpMessage,\n serializeIlpPrepare,\n parseBtpMessage,\n deserializeIlpPacket,\n type BTPProtocolData,\n type BTPMessageData,\n type BTPErrorData,\n type ILPPreparePacket,\n type ILPResponsePacket,\n} from './protocol.js';\n\nconst textEncoder = new TextEncoder();\n\nexport interface IsomorphicBtpClientConfig {\n url: string;\n peerId: string;\n authToken: string;\n sendTimeoutMs?: number;\n authTimeoutMs?: number;\n /** Custom WebSocket constructor (e.g., the Node `ws` package, or for testing). */\n createWebSocket?: (url: string) => WebSocket;\n}\n\ninterface PendingRequest {\n resolve: (packet: ILPResponsePacket) => void;\n reject: (error: Error) => void;\n timeoutId: ReturnType<typeof setTimeout>;\n}\n\nexport class BtpConnectionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpConnectionError';\n }\n}\n\nexport class BtpAuthError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BtpAuthError';\n }\n}\n\n/**\n * Lightweight BTP client that speaks the BTP binary protocol over WebSocket.\n * Handles: connect → authenticate → send ILP packets → receive responses.\n */\nexport class IsomorphicBtpClient {\n private ws: WebSocket | null = null;\n private _isConnected = false;\n private requestIdCounter = 0;\n private readonly pendingRequests = new Map<number, PendingRequest>();\n private readonly config: Required<\n Omit<IsomorphicBtpClientConfig, 'createWebSocket'>\n > &\n Pick<IsomorphicBtpClientConfig, 'createWebSocket'>;\n\n constructor(config: IsomorphicBtpClientConfig) {\n this.config = {\n sendTimeoutMs: 30_000,\n authTimeoutMs: 5_000,\n ...config,\n };\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n async connect(): Promise<void> {\n if (this._isConnected) return;\n\n return new Promise<void>((resolve, reject) => {\n try {\n this.ws = this.config.createWebSocket\n ? this.config.createWebSocket(this.config.url)\n : new WebSocket(this.config.url);\n this.ws.binaryType = 'arraybuffer';\n } catch (err) {\n reject(\n new BtpConnectionError(\n `Failed to create WebSocket: ${err instanceof Error ? err.message : String(err)}`\n )\n );\n return;\n }\n\n this.ws.onopen = async () => {\n try {\n await this.authenticate();\n this._isConnected = true;\n resolve();\n } catch (err) {\n this._isConnected = false;\n this.ws?.close();\n reject(err);\n }\n };\n\n this.ws.onmessage = (event: MessageEvent) => {\n this.handleMessage(event.data);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.ws.onerror = (event: any) => {\n const underlying = event?.error ?? event?.message;\n const detail =\n underlying instanceof Error\n ? underlying.message\n : typeof underlying === 'string'\n ? underlying\n : null;\n reject(\n new BtpConnectionError(\n detail\n ? `WebSocket connection error: ${detail}`\n : 'WebSocket connection error'\n )\n );\n };\n\n this.ws.onclose = () => {\n this._isConnected = false;\n // Reject all pending requests\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Connection closed'));\n this.pendingRequests.delete(id);\n }\n };\n });\n }\n\n async disconnect(): Promise<void> {\n this._isConnected = false;\n if (this.ws) {\n this.ws.close();\n this.ws = null;\n }\n for (const [id, pending] of this.pendingRequests) {\n clearTimeout(pending.timeoutId);\n pending.reject(new BtpConnectionError('Disconnected'));\n this.pendingRequests.delete(id);\n }\n }\n\n /**\n * Send an ILP PREPARE packet, optionally with protocol data (e.g. payment channel claim).\n * Returns the ILP response (FULFILL or REJECT).\n */\n async sendPacket(\n packet: ILPPreparePacket,\n protocolData?: BTPProtocolData[]\n ): Promise<ILPResponsePacket> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const serializedIlp = serializeIlpPrepare(packet);\n const requestId = this.nextRequestId();\n\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: protocolData ?? [],\n ilpPacket: serializedIlp,\n },\n });\n\n this.ws.send(btpMessage);\n\n // Calculate timeout from packet expiry or default\n let timeoutMs = this.config.sendTimeoutMs;\n if (packet.expiresAt) {\n const remaining = packet.expiresAt.getTime() - Date.now();\n timeoutMs = Math.max(remaining - 500, 1000);\n }\n\n return new Promise<ILPResponsePacket>((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(requestId);\n reject(new BtpConnectionError(`Packet send timeout (${timeoutMs}ms)`));\n }, timeoutMs);\n\n this.pendingRequests.set(requestId, { resolve, reject, timeoutId });\n });\n }\n\n /**\n * Send a fire-and-forget BTP MESSAGE carrying only protocol data (no ILP\n * packet). Used for out-of-band claim notifications that the connector's\n * ClaimReceiver consumes via `handleClaimMessage` — there is no RESPONSE\n * frame, so we resolve immediately after the WebSocket buffers the bytes.\n *\n * Mirrors `sendPacket` wire-format construction but uses an empty ILP\n * payload and does not enroll a pending request.\n */\n async sendProtocolData(\n protocolName: string,\n contentType: number,\n data: Uint8Array\n ): Promise<void> {\n if (!this._isConnected || !this.ws) {\n throw new BtpConnectionError('Not connected');\n }\n\n const requestId = this.nextRequestId();\n const btpMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [{ protocolName, contentType, data }],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n this.ws.send(btpMessage);\n }\n\n // ─── Private ────────────────────────────────────────────────────────────\n\n private async authenticate(): Promise<void> {\n if (!this.ws) throw new BtpAuthError('WebSocket not connected');\n\n const authData = JSON.stringify({\n peerId: this.config.peerId,\n secret: this.config.authToken,\n });\n\n const requestId = this.nextRequestId();\n const authMessage = serializeBtpMessage({\n type: BTPMessageType.MESSAGE,\n requestId,\n data: {\n protocolData: [\n {\n protocolName: 'auth',\n contentType: 0,\n data: textEncoder.encode(authData),\n },\n ],\n ilpPacket: new Uint8Array(0),\n },\n });\n\n return new Promise<void>((resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new BtpAuthError('Authentication timeout'));\n }, this.config.authTimeoutMs);\n\n // Temporarily intercept messages for auth response\n const originalHandler = this.ws!.onmessage;\n this.ws!.onmessage = (event: MessageEvent) => {\n try {\n const data = this.toUint8Array(event.data);\n\n // Try JSON parse first (server may respond with JSON)\n try {\n const jsonStr = new TextDecoder().decode(data);\n if (jsonStr.startsWith('{')) {\n // JSON response — not a BTP binary auth response, ignore\n }\n } catch {\n /* not JSON */\n }\n\n // Parse as BTP binary\n const message = parseBtpMessage(data);\n if (message.requestId === requestId) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n reject(\n new BtpAuthError(\n `Authentication failed: ${errData.code} msg=${errData.message ?? ''} trigger=${errData.triggeredAt ?? ''}`\n )\n );\n } else if (message.type === BTPMessageType.RESPONSE) {\n resolve();\n }\n }\n } catch (err) {\n clearTimeout(timeout);\n this.ws!.onmessage = originalHandler;\n reject(\n new BtpAuthError(err instanceof Error ? err.message : String(err))\n );\n }\n };\n\n this.ws!.send(authMessage);\n });\n }\n\n private handleMessage(raw: unknown): void {\n // Try JSON first (server can send JSON FULFILL/REJECT responses)\n try {\n const data = this.toUint8Array(raw);\n const jsonStr = new TextDecoder().decode(data);\n if (jsonStr.startsWith('{')) {\n const json = JSON.parse(jsonStr) as Record<string, unknown>;\n if (json['type'] === 'FULFILL' || json['type'] === 'REJECT') {\n const first = this.pendingRequests.entries().next();\n if (!first.done) {\n const [id, pending] = first.value;\n clearTimeout(pending.timeoutId);\n this.pendingRequests.delete(id);\n\n if (json['type'] === 'FULFILL') {\n const responseData = json['data']\n ? this.base64ToUint8Array(json['data'] as string)\n : new Uint8Array(0);\n // JSON FULFILLs may carry the fulfillment preimage as base64;\n // absent means all-zero (legacy). A sender-chosen condition\n // (toon-client#350) then fails verification — fail-closed.\n const fulfillment = json['fulfillment']\n ? this.base64ToUint8Array(json['fulfillment'] as string)\n : new Uint8Array(32);\n pending.resolve({\n type: ILPPacketType.FULFILL,\n fulfillment,\n data: responseData,\n });\n } else {\n pending.resolve({\n type: ILPPacketType.REJECT,\n code: (json['code'] as string) || 'F00',\n message: (json['message'] as string) || 'Unknown error',\n data: json['data']\n ? this.base64ToUint8Array(json['data'] as string)\n : new Uint8Array(0),\n });\n }\n }\n return;\n }\n }\n } catch {\n /* not JSON, try BTP binary */\n }\n\n // BTP binary response\n try {\n const data = this.toUint8Array(raw);\n const message = parseBtpMessage(data);\n\n if (\n message.type === BTPMessageType.RESPONSE ||\n message.type === BTPMessageType.ERROR\n ) {\n const pending = this.pendingRequests.get(message.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timeoutId);\n this.pendingRequests.delete(message.requestId);\n\n if (message.type === BTPMessageType.ERROR) {\n const errData = message.data as BTPErrorData;\n pending.reject(\n new BtpConnectionError(`BTP error: ${errData.code} ${errData.name}`)\n );\n return;\n }\n\n const msgData = message.data as BTPMessageData;\n if (msgData.ilpPacket && msgData.ilpPacket.length > 0) {\n const ilpResponse = deserializeIlpPacket(msgData.ilpPacket);\n pending.resolve(ilpResponse);\n }\n }\n } catch {\n // Unparseable message — ignore\n }\n }\n\n private toUint8Array(data: unknown): Uint8Array {\n if (data instanceof ArrayBuffer) return new Uint8Array(data);\n if (data instanceof Uint8Array) return data;\n if (typeof data === 'string') return textEncoder.encode(data);\n throw new Error(`Unexpected WebSocket data type: ${typeof data}`);\n }\n\n private base64ToUint8Array(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n }\n\n private nextRequestId(): number {\n this.requestIdCounter = (this.requestIdCounter + 1) & 0xffffffff;\n return this.requestIdCounter;\n }\n}\n","/**\n * Sender-chosen ILP execution conditions (toon-client#350, rolling-swap\n * prerequisite — toon-meta#145 §3 R1/R2).\n *\n * Contract (normative: connector `docs/local-delivery-fulfillment-contract.md`,\n * connector#309):\n * - An ABSENT or ALL-ZERO (32×0x00) `executionCondition` is the LEGACY\n * class: no hashlock, no verification — today's publish/upload writes.\n * - Any NON-ZERO condition is SENDER-CHOSEN: the sender mints a fresh\n * random 32-byte preimage `P` per packet, sets `C = sha256(P)` on the\n * PREPARE, and on FULFILL MUST verify that the returned fulfillment\n * hashes back to `C` — a missing/malformed/mismatching fulfillment is a\n * hard failure (the packet is counted failed, never silently accepted).\n *\n * Isomorphic: @noble/hashes only (no Buffer, no node:crypto).\n */\n\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\n\n/** Exact byte length of an ILP execution condition / fulfillment preimage. */\nexport const CONDITION_LENGTH = 32;\n\n/** A freshly minted per-packet hashlock: `condition = sha256(preimage)`. */\nexport interface ExecutionConditionPair {\n /** Random 32-byte preimage `P` — reveal is the commit act; never reuse. */\n preimage: Uint8Array;\n /** `C = sha256(P)` — goes on the PREPARE's `executionCondition`. */\n condition: Uint8Array;\n}\n\n/**\n * Mint a fresh random 32-byte preimage and its sha256 condition (spec R1).\n * Mint one PER PACKET: a reused preimage lets any observer of packet *i*\n * fulfill packet *i+1* without the sender's consent.\n */\nexport function mintExecutionCondition(): ExecutionConditionPair {\n const preimage = randomBytes(CONDITION_LENGTH);\n return { preimage, condition: sha256(preimage) };\n}\n\n/**\n * True when `condition` selects the LEGACY (unverified) class: absent or\n * all-zero. The OER wire treats absent and 32×0x00 identically.\n */\nexport function isZeroCondition(condition: Uint8Array | undefined): boolean {\n if (condition === undefined) return true;\n for (const byte of condition) {\n if (byte !== 0) return false;\n }\n return true;\n}\n\n/**\n * Validate a caller-supplied execution condition before it goes on the wire.\n * @throws {Error} When the condition is not exactly 32 bytes — the OER\n * serializer would otherwise silently zero-fill it, downgrading a\n * sender-chosen packet to the legacy unverified class.\n */\nexport function assertValidCondition(condition: Uint8Array): void {\n if (condition.length !== CONDITION_LENGTH) {\n throw new Error(\n `executionCondition must be exactly ${CONDITION_LENGTH} bytes, got ${condition.length}`\n );\n }\n}\n\n/**\n * True iff `fulfillment` is exactly 32 bytes and `sha256(fulfillment)`\n * equals `condition` — the sender-side FULFILL check (spec R6's mirror).\n * Fail-closed: an undefined/short/long fulfillment never matches.\n */\nexport function fulfillmentMatchesCondition(\n fulfillment: Uint8Array | undefined,\n condition: Uint8Array\n): boolean {\n if (fulfillment === undefined || fulfillment.length !== CONDITION_LENGTH) {\n return false;\n }\n const digest = sha256(fulfillment);\n // Plain comparison is fine: both operands are locally computed/received\n // values on the sender; there is no secret to protect from timing here.\n for (let i = 0; i < CONDITION_LENGTH; i++) {\n if (digest[i] !== condition[i]) return false;\n }\n return true;\n}\n","/**\n * Shared sender-side plumbing for sender-chosen execution conditions\n * (toon-client#350; contract: connector `docs/local-delivery-fulfillment-contract.md`,\n * connector#309; spec: toon-meta `docs/rolling-swap.md` §3).\n *\n * Both ILP transports (HTTP `POST /ilp` and BTP) take the SAME extended send\n * params and map FULFILL/REJECT responses through the SAME verifier so the\n * two paths cannot drift:\n *\n * - absent/all-zero `executionCondition` → legacy class: today's behavior,\n * byte-for-byte (zero condition on the wire, no FULFILL verification);\n * - non-zero `executionCondition` → sender-chosen: the condition goes on\n * the PREPARE verbatim and the FULFILL's 32-byte fulfillment MUST hash\n * back to it — a missing/malformed/mismatching preimage is surfaced as a\n * FAILED result (never a silent accept, never retried).\n */\n\nimport type { IlpSendResult } from '@toon-protocol/core';\nimport { ILPPacketType, type ILPResponsePacket } from '../btp/protocol.js';\nimport { toBase64 } from '../utils/binary.js';\nimport {\n fulfillmentMatchesCondition,\n isZeroCondition,\n} from '../utils/condition.js';\n\n/**\n * Send parameters accepted by both ILP transports. Extends the\n * `@toon-protocol/core` `IlpClient` param shape with the sender-chosen\n * condition and an explicit expiry — plain `IlpClient` callers keep working\n * unchanged (both extras are optional; omitting them is the legacy path).\n */\nexport interface IlpSendParams {\n destination: string;\n amount: string;\n /** Base64 ILP `data` payload. */\n data: string;\n /** Transport timeout in ms; also the default expiry window. */\n timeout?: number;\n /**\n * Sender-chosen 32-byte execution condition `C = sha256(P)` (spec R2).\n * Absent or all-zero = legacy unverified packet (default — ordinary\n * publish/upload writes MUST keep this default).\n */\n executionCondition?: Uint8Array;\n /**\n * Explicit PREPARE `expiresAt` (spec R7). Defaults to `now + timeout`,\n * preserving pre-#350 behavior. Accepts a `Date` or an ISO 8601 string —\n * `@toon-protocol/core` ≥2.1.0's `IlpClient` passes the string form.\n */\n expiresAt?: Date | string;\n}\n\n/** Normalize an `IlpSendParams.expiresAt` to a `Date` (default: now + timeout). */\nexport function resolveExpiresAt(\n expiresAt: Date | string | undefined,\n timeoutMs: number\n): Date {\n if (expiresAt === undefined) return new Date(Date.now() + timeoutMs);\n return expiresAt instanceof Date ? new Date(expiresAt.getTime()) : new Date(expiresAt);\n}\n\n/**\n * `IlpSendResult` plus the FULFILL preimage when a sender-chosen condition\n * was verified. Only populated on the sender-chosen path so legacy result\n * objects stay byte-identical.\n */\nexport interface IlpSendResultWithFulfillment extends IlpSendResult {\n /** Base64 32-byte fulfillment preimage (verified: sha256 == condition). */\n fulfillment?: string;\n}\n\n/** ILP code used for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_CODE = 'F99';\n\n/** Message for a client-side fulfillment-verification failure. */\nexport const FULFILLMENT_MISMATCH_MESSAGE =\n 'FULFILL fulfillment does not match execution condition ' +\n '(sha256(fulfillment) != executionCondition) — packet counted failed';\n\n/**\n * Map a parsed ILP response packet to an `IlpSendResult`, enforcing the\n * sender-chosen condition when one was sent.\n *\n * Verification is fail-closed: when `sentCondition` is non-zero, a FULFILL\n * whose fulfillment is absent, not exactly 32 bytes, or does not sha256-hash\n * to the condition yields `accepted: false` (code F99). The result shape —\n * not a thrown error — is deliberate: transports only retry thrown\n * `NetworkError`s, so a forged/wrong FULFILL is never retried (re-sending\n * would re-spend the attached claim), and packet counters (`streamSwap`\n * rejections) count it failed.\n */\nexport function mapIlpResponse(\n packet: ILPResponsePacket,\n sentCondition?: Uint8Array\n): IlpSendResultWithFulfillment {\n if (packet.type === ILPPacketType.FULFILL) {\n const dataField =\n packet.data.length > 0 ? { data: toBase64(packet.data) } : {};\n\n // Legacy class: absent/all-zero condition → accept without verification\n // (pre-#350 behavior, byte-for-byte).\n if (sentCondition === undefined || isZeroCondition(sentCondition)) {\n return { accepted: true, ...dataField };\n }\n\n // Sender-chosen class: the FULFILL preimage MUST hash to the condition.\n if (!fulfillmentMatchesCondition(packet.fulfillment, sentCondition)) {\n return {\n accepted: false,\n code: FULFILLMENT_MISMATCH_CODE,\n message: FULFILLMENT_MISMATCH_MESSAGE,\n ...dataField,\n };\n }\n\n return {\n accepted: true,\n fulfillment: toBase64(packet.fulfillment),\n ...dataField,\n };\n }\n\n // REJECT\n return {\n accepted: false,\n code: packet.code,\n message: packet.message,\n ...(packet.data.length > 0 ? { data: toBase64(packet.data) } : {}),\n };\n}\n","import {\n IsomorphicBtpClient,\n BtpConnectionError,\n} from '../btp/IsomorphicBtpClient.js';\nimport { type BTPProtocolData } from '../btp/protocol.js';\nimport type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport { withRetry } from '../utils/retry.js';\nimport { fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport { mapIlpResponse, resolveExpiresAt, type IlpSendParams } from './ilp-send.js';\nimport { assertValidCondition, isZeroCondition } from '../utils/condition.js';\n\nexport interface BtpRuntimeClientConfig {\n btpUrl: string;\n peerId: string;\n authToken: string;\n /** Max reconnection attempts on send failure (default: 3) */\n maxRetries?: number;\n /** Delay between reconnection attempts in ms (default: 1000) */\n retryDelay?: number;\n /** Custom WebSocket constructor (for testing / custom transports). */\n createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * Returns true if the error is a connection-level error worth retrying.\n * ILP application-level rejects (F02, T01, etc.) are NOT retried.\n */\nfunction isConnectionError(error: Error): boolean {\n const msg = error.message.toLowerCase();\n return (\n msg.includes('not connected') ||\n msg.includes('connection') ||\n msg.includes('websocket') ||\n msg.includes('econnrefused') ||\n msg.includes('econnreset') ||\n msg.includes('socket hang up') ||\n msg.includes('timeout')\n );\n}\n\n/**\n * BTP transport implementing IlpClient.\n * Uses IsomorphicBtpClient (browser-native, no Node.js dependencies).\n */\nexport class BtpRuntimeClient implements IlpClient {\n private btpClient: IsomorphicBtpClient | null = null;\n private readonly config: BtpRuntimeClientConfig;\n private _isConnected = false;\n\n constructor(config: BtpRuntimeClientConfig) {\n this.config = config;\n }\n\n /**\n * Connects to the BTP peer via WebSocket.\n */\n async connect(): Promise<void> {\n this.btpClient = new IsomorphicBtpClient({\n url: this.config.btpUrl,\n peerId: this.config.peerId,\n authToken: this.config.authToken,\n createWebSocket: this.config.createWebSocket,\n });\n\n await this.btpClient.connect();\n this._isConnected = true;\n }\n\n /**\n * Attempts to reconnect by creating a fresh client and connecting.\n */\n async reconnect(): Promise<void> {\n if (this.btpClient) {\n try {\n await this.btpClient.disconnect();\n } catch {\n // Ignore disconnect errors during reconnect\n }\n this.btpClient = null;\n this._isConnected = false;\n }\n\n await this.connect();\n }\n\n /**\n * Disconnects from the BTP peer.\n */\n async disconnect(): Promise<void> {\n if (this.btpClient) {\n await this.btpClient.disconnect();\n this._isConnected = false;\n this.btpClient = null;\n }\n }\n\n get isConnected(): boolean {\n return this._isConnected;\n }\n\n /**\n * Sends an ILP packet via BTP with auto-reconnect on connection errors.\n * Satisfies IlpClient interface.\n *\n * `params` may carry a sender-chosen `executionCondition` and an explicit\n * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition\n * path, unchanged. With a non-zero condition the FULFILL preimage is\n * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced\n * as a failed result — see `mapIlpResponse`.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketOnce(params), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Sends a balance proof claim via BTP protocol data, then sends an ILP packet.\n * Auto-reconnects on connection errors.\n *\n * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are\n * identical to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n return withRetry(() => this._sendIlpPacketWithClaimOnce(params, claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n /**\n * Send a standalone `payment-channel-claim` BTP MESSAGE (no ILP packet\n * attached). The connector's ClaimReceiver consumes this fire-and-forget\n * to register cumulative claim state independently of the per-packet\n * forwarding path. Auto-reconnects on connection errors.\n */\n async sendClaimMessage(claim: Record<string, unknown>): Promise<void> {\n return withRetry(() => this._sendClaimMessageOnce(claim), {\n maxRetries: this.config.maxRetries ?? 3,\n retryDelay: this.config.retryDelay ?? 1000,\n shouldRetry: (error) => {\n if (!isConnectionError(error)) return false;\n this._isConnected = false;\n return true;\n },\n });\n }\n\n private async _sendClaimMessageOnce(\n claim: Record<string, unknown>\n ): Promise<void> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n await this.btpClient.sendProtocolData(\n 'payment-channel-claim',\n 1,\n encodeUtf8(JSON.stringify(claim))\n );\n }\n\n /**\n * Build the ILP PREPARE for a send, applying the sender-chosen condition /\n * explicit expiry when provided (toon-client#350) and validating that a\n * non-zero condition is exactly 32 bytes (the OER serializer would\n * otherwise silently zero-fill it, downgrading the packet to the legacy\n * unverified class).\n */\n private buildPrepare(params: IlpSendParams): {\n prepare: {\n type: 12;\n amount: bigint;\n destination: string;\n executionCondition: Uint8Array;\n expiresAt: Date;\n data: Uint8Array;\n };\n condition: Uint8Array | undefined;\n } {\n const condition = params.executionCondition;\n if (condition !== undefined && !isZeroCondition(condition)) {\n assertValidCondition(condition);\n }\n return {\n prepare: {\n type: 12 as const,\n amount: BigInt(params.amount),\n destination: params.destination,\n executionCondition: condition ?? new Uint8Array(32),\n expiresAt: resolveExpiresAt(params.expiresAt, params.timeout ?? 30000),\n data: fromBase64(params.data),\n },\n condition,\n };\n }\n\n /**\n * Single-attempt ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketOnce(\n params: IlpSendParams\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n const { prepare, condition } = this.buildPrepare(params);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- guaranteed by reconnect() above\n const response = await this.btpClient!.sendPacket(prepare);\n\n return mapIlpResponse(response, condition);\n }\n\n /**\n * Single-attempt claim + ILP packet send. Reconnects if not connected.\n */\n private async _sendIlpPacketWithClaimOnce(\n params: IlpSendParams,\n claim: Record<string, unknown>\n ): Promise<IlpSendResult> {\n if (!this._isConnected) {\n await this.reconnect();\n }\n\n if (!this.btpClient) {\n throw new BtpConnectionError('BTP client not connected');\n }\n\n const protocolData: BTPProtocolData[] = [\n {\n protocolName: 'payment-channel-claim',\n contentType: 1,\n data: encodeUtf8(JSON.stringify(claim)),\n },\n ];\n\n const { prepare, condition } = this.buildPrepare(params);\n const response = await this.btpClient.sendPacket(prepare, protocolData);\n\n return mapIlpResponse(response, condition);\n }\n}\n","/**\n * ILP-over-HTTP (RFC-0035) transport for the TOON client.\n *\n * The connector now serves ILP-over-HTTP on the SAME port as BTP (connector\n * PR #181). This adapter lets a client do stateless one-shot writes over HTTP\n * (`POST /ilp`) and upgrade to a duplex BTP session when it needs to receive\n * server-initiated packets or act as a peer.\n *\n * Wire contract (targets connector PR #181's `/ilp`):\n * - One-shot write: `POST /ilp`\n * body: OER-encoded ILP PREPARE (`application/octet-stream`)\n * header: `ILP-Payment-Channel-Claim: base64(JSON of the claim)` — the\n * SAME claim JSON the BTP path attaches as the\n * `payment-channel-claim` protocolData entry.\n * optional: `ILP-Peer-Id` + `Authorization: Bearer <secret>` identity.\n * response: `200 OK` with an OER FULFILL or REJECT body. HTTP non-2xx is\n * reserved for TRANSPORT errors (400/401/413/5xx); ILP-level\n * rejects come back as a 200 + REJECT body.\n * - Upgrade to BTP: standard HTTP `Upgrade` with `Sec-WebSocket-Protocol: btp`\n * plus the same `ILP-Peer-Id` + `Authorization` headers. The connector\n * pre-authenticates the BTP session from those headers (continuity), so\n * after `101` we send BTP frames WITHOUT a separate in-band auth frame.\n * Omitting the auth headers falls back to the normal BTP auth-frame flow.\n *\n * Reuses `serializeIlpPrepare`/`deserializeIlpPacket` from `btp/protocol.ts` —\n * the SAME OER codec the BTP path uses. Claim signing/construction is owned by\n * the caller (BootstrapService); this transport never builds or signs claims.\n */\n\nimport type { IlpClient, IlpSendResult } from '@toon-protocol/core';\nimport type WSModule from 'ws';\nimport {\n ILPPacketType,\n serializeIlpPrepare,\n deserializeIlpPacket,\n} from '../btp/protocol.js';\nimport { BtpRuntimeClient } from './BtpRuntimeClient.js';\nimport { NetworkError, ConnectorError } from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\nimport { toBase64, fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport { mapIlpResponse, resolveExpiresAt, type IlpSendParams } from './ilp-send.js';\nimport { assertValidCondition, isZeroCondition } from '../utils/condition.js';\n\n/** Header carrying the base64(JSON) payment-channel claim. */\nexport const ILP_CLAIM_HEADER = 'ILP-Payment-Channel-Claim';\n/** Header carrying the peer identity. */\nexport const ILP_PEER_ID_HEADER = 'ILP-Peer-Id';\n\nexport interface HttpIlpClientConfig {\n /** The peer's `POST /ilp` URL (the `httpEndpoint` from discovery). */\n httpEndpoint: string;\n /**\n * Optional peer identity. With no `peerId`/`authToken` the connector treats\n * the request as an anonymous no-auth peer (permissionless default) and\n * derives an ephemeral id from the claim signer.\n */\n peerId?: string;\n /** Bearer secret for `Authorization`. Omit for the no-auth peer path. */\n authToken?: string;\n /** Request timeout in milliseconds (default: 30000). */\n timeout?: number;\n /** Max retry attempts for transport-level network failures (default: 3). */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000). */\n retryDelay?: number;\n /** Custom fetch implementation (for testing / custom transports). */\n httpClient?: typeof fetch;\n /**\n * Custom WebSocket constructor for the BTP upgrade path (for testing /\n * custom transports). Forwarded to the underlying BtpRuntimeClient.\n */\n createWebSocket?: (url: string) => WebSocket;\n}\n\n/**\n * Stateless ILP-over-HTTP transport implementing `IlpClient`.\n *\n * Use this for pure one-shot consumers (publish-and-forget writes). When the\n * client needs a duplex session — to receive server-initiated packets or to act\n * as a peer — call {@link upgradeToBtp} to obtain a connected BtpRuntimeClient\n * that reuses the existing BTP code path.\n */\nexport class HttpIlpClient implements IlpClient {\n private readonly httpEndpoint: string;\n private readonly peerId: string | undefined;\n private readonly authToken: string | undefined;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n private readonly createWebSocket: ((url: string) => WebSocket) | undefined;\n\n constructor(config: HttpIlpClientConfig) {\n this.httpEndpoint = config.httpEndpoint;\n this.peerId = config.peerId;\n this.authToken = config.authToken;\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n this.createWebSocket = config.createWebSocket;\n }\n\n /**\n * The client edge this transport pays — the origin `GET /ilp/identity` and\n * `GET /ilp/routes/price` hang off (`ConnectorEdgeClient` normalizes the\n * trailing `/ilp` away). Exposed because a sealed write must ask the\n * connector it is ACTUALLY paying for its key, not a configured guess.\n */\n get clientEdgeEndpoint(): string {\n return this.httpEndpoint;\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` WITHOUT a claim. The connector accepts\n * this only on free/zero-amount routes; paid writes must use\n * {@link sendIlpPacketWithClaim}. Satisfies the IlpClient interface.\n *\n * `params` may carry a sender-chosen `executionCondition` and an explicit\n * `expiresAt` (toon-client#350); omitting both is the legacy zero-condition\n * path, unchanged. With a non-zero condition the FULFILL preimage is\n * verified (`sha256(fulfillment) == condition`) and a mismatch is surfaced\n * as a failed result — see {@link mapIlpResponse}.\n */\n async sendIlpPacket(params: IlpSendParams): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Send an ILP PREPARE via `POST /ilp` with the payment-channel claim attached\n * as the `ILP-Payment-Channel-Claim` header. `claim` is the SAME JSON object\n * the BTP path attaches as the `payment-channel-claim` protocolData entry —\n * we base64(JSON.stringify(claim)) it, byte-for-byte identical to BTP.\n *\n * Sender-chosen `executionCondition` / explicit `expiresAt` semantics are\n * identical to {@link sendIlpPacket}.\n */\n async sendIlpPacketWithClaim(\n params: IlpSendParams,\n claim: unknown\n ): Promise<IlpSendResult> {\n return withRetry(() => this.postPrepare(params, claim), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => error instanceof NetworkError,\n });\n }\n\n /**\n * Upgrade to a duplex BTP session over the SAME endpoint.\n *\n * Derives the `ws(s)://` URL from `httpEndpoint`, opens a WebSocket with\n * `Sec-WebSocket-Protocol: btp` and the same `ILP-Peer-Id` + `Authorization`\n * headers, and returns a connected {@link BtpRuntimeClient}. When auth headers\n * are present the connector pre-authenticates the session (no in-band auth\n * frame); without them the BtpRuntimeClient falls back to the normal BTP\n * auth-frame flow.\n *\n * NOTE: passing per-connection headers + a subprotocol to a WebSocket is\n * Node-only (the `ws` package). Browsers cannot set arbitrary request headers\n * on a WebSocket handshake, so a browser consumer must use the gateway\n * transport or BTP-with-auth-frame instead.\n */\n async upgradeToBtp(): Promise<BtpRuntimeClient> {\n const btpUrl = httpEndpointToBtpUrl(this.httpEndpoint);\n\n // Default WS factory negotiates `btp` + carries the auth headers so the\n // connector pre-authenticates. Built lazily (Node-only) — browsers must\n // pass an explicit `createWebSocket` (they can't set handshake headers).\n const createWebSocket =\n this.createWebSocket ?? (await makeBtpWebSocketFactory(this.authHeaders()));\n\n const client = new BtpRuntimeClient({\n btpUrl,\n // BtpRuntimeClient sends an auth frame using these; when the connector\n // pre-authenticated via Upgrade headers it accepts the (redundant) frame.\n peerId: this.peerId ?? 'client',\n authToken: this.authToken ?? '',\n createWebSocket,\n });\n await client.connect();\n return client;\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n private authHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n if (this.peerId) headers[ILP_PEER_ID_HEADER] = this.peerId;\n if (this.authToken) headers['Authorization'] = `Bearer ${this.authToken}`;\n return headers;\n }\n\n /**\n * Single attempt: serialize the PREPARE, POST it, and map the response.\n * @throws {NetworkError} On connection/timeout failures (retried).\n * @throws {ConnectorError} On non-retryable transport errors (5xx / unexpected).\n */\n private async postPrepare(\n params: IlpSendParams,\n claim?: unknown\n ): Promise<IlpSendResult> {\n const requestTimeout = params.timeout ?? this.timeout;\n\n // Sender-chosen condition (toon-client#350): validate length up front so\n // the OER serializer can never silently zero-fill a malformed condition\n // and downgrade the packet to the legacy unverified class.\n const condition = params.executionCondition;\n if (condition !== undefined && !isZeroCondition(condition)) {\n assertValidCondition(condition);\n }\n\n const prepare = serializeIlpPrepare({\n type: ILPPacketType.PREPARE,\n amount: BigInt(params.amount),\n destination: params.destination,\n executionCondition: condition ?? new Uint8Array(32),\n expiresAt: resolveExpiresAt(params.expiresAt, requestTimeout),\n data: fromBase64(params.data),\n });\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/octet-stream',\n ...this.authHeaders(),\n };\n if (claim !== undefined) {\n headers[ILP_CLAIM_HEADER] = toBase64(\n encodeUtf8(JSON.stringify(claim))\n );\n }\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), requestTimeout);\n\n try {\n const response = await this.httpClient(this.httpEndpoint, {\n method: 'POST',\n headers,\n // Copy into a fresh ArrayBuffer so fetch sees a clean body, not a view.\n body: prepare.slice(),\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n return await this.mapResponse(response, condition);\n } catch (error) {\n clearTimeout(timeoutId);\n throw this.mapTransportError(error, requestTimeout);\n }\n }\n\n /**\n * Map a `200 OK` body (OER FULFILL/REJECT) to an IlpSendResult; map a non-2xx\n * to a transport error. Per the wire contract, ILP-level rejects arrive as a\n * 200 + REJECT body — only HTTP non-2xx means a transport-layer failure.\n *\n * When `sentCondition` is non-zero the FULFILL preimage is verified against\n * it; a mismatch yields `accepted: false` (shared `mapIlpResponse` logic,\n * identical to the BTP path).\n */\n private async mapResponse(\n response: Response,\n sentCondition?: Uint8Array\n ): Promise<IlpSendResult> {\n if (response.ok) {\n const buf = new Uint8Array(await response.arrayBuffer());\n if (buf.length === 0) {\n throw new ConnectorError('Empty 200 body from /ilp (expected OER ILP response)');\n }\n return mapIlpResponse(deserializeIlpPacket(buf), sentCondition);\n }\n\n // Transport-level error (400 malformed, 401 auth, 413 too large, 5xx).\n const body = await response.text().catch(() => '');\n const detail = body ? `: ${body}` : '';\n if (response.status >= 500) {\n throw new ConnectorError(\n `Connector transport error (${response.status} ${response.statusText})${detail}`\n );\n }\n // 4xx — non-retryable client/transport error.\n throw new ConnectorError(\n `ILP-over-HTTP request rejected (${response.status} ${response.statusText})${detail}`\n );\n }\n\n private mapTransportError(error: unknown, requestTimeout: number): Error {\n if (error instanceof ConnectorError || error instanceof NetworkError) {\n return error;\n }\n if (error instanceof Error && error.name === 'AbortError') {\n return new NetworkError(`Request timeout after ${requestTimeout}ms`, error);\n }\n if (\n error instanceof TypeError &&\n (error.message.includes('fetch failed') ||\n error.message.includes('ECONNREFUSED') ||\n error.message.includes('ECONNRESET') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('network'))\n ) {\n return new NetworkError(`Network connection failed: ${error.message}`, error);\n }\n return new ConnectorError(\n `Unexpected error during ILP-over-HTTP request: ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n }\n}\n\n/**\n * Derive the BTP WebSocket URL from a `POST /ilp` HTTP endpoint. The connector\n * serves BTP on the SAME path, so we only swap the scheme (http→ws, https→wss).\n */\nexport function httpEndpointToBtpUrl(httpEndpoint: string): string {\n return httpEndpoint\n .replace(/^https:\\/\\//i, 'wss://')\n .replace(/^http:\\/\\//i, 'ws://');\n}\n\n/**\n * Build a WebSocket factory that opens the BTP upgrade with a `btp` subprotocol\n * and the given handshake headers. Node-only — lazily loads the `ws` package via\n * a dynamically-imported `createRequire` so the node-only `node:module`/`ws`\n * deps never enter a browser bundle (per-connection headers aren't settable on\n * the browser WebSocket anyway).\n */\nasync function makeBtpWebSocketFactory(\n headers: Record<string, string>\n): Promise<(url: string) => WebSocket> {\n const { createRequire } = await import('node:module');\n const require = createRequire(import.meta.url);\n const WS = require('ws') as typeof WSModule;\n\n // CJS/ESM interop: walk the constructor ladder (class / .default / .WebSocket)\n // so this works under any loader.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const ws = WS as any;\n const WSClass = (typeof ws === 'function'\n ? ws\n : typeof ws.default === 'function'\n ? ws.default\n : typeof ws.WebSocket === 'function'\n ? ws.WebSocket\n : null) as unknown as typeof WSModule.prototype.constructor;\n if (WSClass === null) {\n throw new Error(\n \"makeBtpWebSocketFactory: require('ws') did not yield a constructor on .default, .WebSocket, or the module root.\"\n );\n }\n\n // `ws` accepts (url, protocols, options); the connector negotiates `btp` and\n // pre-authenticates the session from the `ILP-Peer-Id`/`Authorization` headers.\n return (url: string): WebSocket =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new (WSClass as any)(url, 'btp', { headers }) as unknown as WebSocket;\n}\n","/**\n * Transport selection policy for the client ILP layer.\n *\n * The connector serves ILP-over-HTTP (`POST /ilp`) and BTP on the SAME port\n * (connector PR #181). A peer advertises this in discovery via the toon-core\n * `IlpPeerInfo` fields added in toon PR #29:\n * - `httpEndpoint?: string` — the `POST /ilp` URL.\n * - `supportsUpgrade?: boolean` — whether the host accepts the BTP upgrade.\n *\n * Those fields may not yet exist on the installed `@toon-protocol/core`\n * `IlpPeerInfo` type, so we read them defensively here (see `DiscoveredIlpPeer`).\n *\n * Policy:\n * - Pure one-shot consumers (`needsDuplex: false`) prefer HTTP when the peer\n * advertises an `httpEndpoint` — stateless, no persistent socket.\n * - Clients that must receive server-initiated packets or act as a peer\n * (`needsDuplex: true`) use BTP. If the peer only exposes `httpEndpoint`\n * and `supportsUpgrade` is true, we go HTTP-then-upgrade; otherwise we\n * connect to the BTP endpoint directly.\n */\n\n/**\n * The subset of discovery fields this policy reads. Structurally compatible with\n * core's `IlpPeerInfo`; `httpEndpoint`/`supportsUpgrade` are optional so a\n * pre-PR-#29 `IlpPeerInfo` can be passed through a cast.\n */\nexport interface DiscoveredIlpPeer {\n /** BTP WebSocket endpoint (always present on a TOON peer). */\n btpEndpoint?: string;\n /** `POST /ilp` URL (toon PR #29). */\n httpEndpoint?: string;\n /** Whether the host accepts the BTP upgrade over the HTTP endpoint (toon PR #29). */\n supportsUpgrade?: boolean;\n}\n\nexport type IlpTransportChoice =\n /** Stateless one-shot writes via `POST /ilp`. */\n | { kind: 'http'; httpEndpoint: string; canUpgrade: boolean }\n /** Duplex BTP session via the WebSocket endpoint. */\n | { kind: 'btp'; btpEndpoint: string }\n /**\n * Open HTTP first (one-shot writes) but upgrade to BTP when duplex is needed.\n * Only chosen when the peer exposes `httpEndpoint` + `supportsUpgrade` and no\n * separate `btpEndpoint`.\n */\n | { kind: 'http-upgradable'; httpEndpoint: string };\n\nexport interface SelectIlpTransportOptions {\n /**\n * Whether the client needs a duplex session (receive server-initiated\n * packets / act as a peer). Default: false (pure one-shot consumer).\n */\n needsDuplex?: boolean;\n}\n\n/**\n * Read discovery fields defensively from a (possibly pre-PR-#29) peer info\n * object. Accepts core's `IlpPeerInfo` or any structurally-compatible shape.\n */\nexport function readDiscoveredIlpPeer(peer: unknown): DiscoveredIlpPeer {\n const p = (peer ?? {}) as Record<string, unknown>;\n return {\n btpEndpoint:\n typeof p['btpEndpoint'] === 'string' ? (p['btpEndpoint'] as string) : undefined,\n httpEndpoint:\n typeof p['httpEndpoint'] === 'string'\n ? (p['httpEndpoint'] as string)\n : undefined,\n supportsUpgrade:\n typeof p['supportsUpgrade'] === 'boolean'\n ? (p['supportsUpgrade'] as boolean)\n : undefined,\n };\n}\n\n/**\n * Choose the ILP transport for a discovered peer given the consumer's needs.\n *\n * @throws {Error} If the peer advertises no usable endpoint at all.\n */\nexport function selectIlpTransport(\n peer: DiscoveredIlpPeer,\n options: SelectIlpTransportOptions = {}\n): IlpTransportChoice {\n const needsDuplex = options.needsDuplex ?? false;\n const http = peer.httpEndpoint?.trim() || undefined;\n const btp = peer.btpEndpoint?.trim() || undefined;\n const canUpgrade = peer.supportsUpgrade === true;\n\n if (needsDuplex) {\n // Duplex consumers prefer a real BTP endpoint; fall back to HTTP-upgrade\n // only when the host advertises it.\n if (btp) return { kind: 'btp', btpEndpoint: btp };\n if (http && canUpgrade) return { kind: 'http-upgradable', httpEndpoint: http };\n throw new Error(\n 'Duplex transport required but peer exposes neither a btpEndpoint nor an upgradable httpEndpoint'\n );\n }\n\n // One-shot consumers prefer stateless HTTP when available.\n if (http) return { kind: 'http', httpEndpoint: http, canUpgrade };\n if (btp) return { kind: 'btp', btpEndpoint: btp };\n throw new Error('Peer exposes neither an httpEndpoint nor a btpEndpoint');\n}\n","import {\n createPublicClient,\n createWalletClient,\n http,\n maxUint256,\n decodeEventLog,\n defineChain,\n type Hex,\n type TransactionReceipt,\n} from 'viem';\nimport type {\n ConnectorChannelClient,\n OpenChannelParams,\n OpenChannelResult,\n ChannelState,\n} from '@toon-protocol/core';\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode } from '@toon-protocol/core';\nimport type { EvmSigner } from '../signing/evm-signer.js';\nimport { ChannelFundingError, isInsufficientGasError } from '../errors.js';\nimport {\n openSolanaChannel as openSolanaChannelOnChain,\n getChannelAccountState as getSolanaChannelAccountState,\n depositSolanaChannel,\n deriveAssociatedTokenAccount,\n} from './solana-payment-channel.js';\nimport { openMinaChannelOnChain } from './mina-channel-open.js';\n\n// TokenNetwork ABI — only the functions we need\nconst TOKEN_NETWORK_ABI = [\n {\n name: 'openChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'participant2', type: 'address' },\n { name: 'settlementTimeout', type: 'uint256' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'setTotalDeposit',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'participant', type: 'address' },\n { name: 'totalDeposit', type: 'uint256' },\n ],\n outputs: [],\n },\n {\n name: 'closeChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'settleChannel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ name: 'channelId', type: 'bytes32' }],\n outputs: [],\n },\n {\n name: 'channels',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }],\n outputs: [\n { name: 'settlementTimeout', type: 'uint256' },\n { name: 'state', type: 'uint8' },\n { name: 'closedAt', type: 'uint256' },\n { name: 'openedAt', type: 'uint256' },\n { name: 'participant1', type: 'address' },\n { name: 'participant2', type: 'address' },\n ],\n },\n {\n name: 'participants',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32' }, { type: 'address' }],\n outputs: [\n { name: 'deposit', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n ],\n },\n {\n name: 'ChannelOpened',\n type: 'event',\n inputs: [\n { name: 'channelId', type: 'bytes32', indexed: true },\n { name: 'participant1', type: 'address', indexed: true },\n { name: 'participant2', type: 'address', indexed: true },\n { name: 'settlementTimeout', type: 'uint256', indexed: false },\n ],\n },\n] as const;\n\n// ERC20 ABI — only approve and allowance\nconst ERC20_ABI = [\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { name: 'spender', type: 'address' },\n { name: 'amount', type: 'uint256' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'owner', type: 'address' },\n { name: 'spender', type: 'address' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n] as const;\n\n/** Maps on-chain state uint8 to ChannelState status */\nconst STATE_MAP: Record<number, ChannelState['status']> = {\n 0: 'settled',\n 1: 'open',\n 2: 'closed',\n 3: 'settled',\n};\n\nexport interface SolanaChannelConfig {\n rpcUrl: string;\n /**\n * Ed25519 keypair material. Accepts either a 32-byte seed or a 64-byte\n * `secretKey` (seed || pubkey, as produced by `deriveFullIdentity`). The first\n * 32 bytes are the signing seed; the public key is derived from it.\n */\n keypair: Uint8Array;\n /**\n * DEFAULT payment-channel program id (base58). The per-channel negotiated\n * program (`OpenChannelParams.tokenNetwork`, i.e. the greeting's `programId`)\n * takes precedence when present — see {@link SolanaChannelConfig.tokenMint},\n * which works the same way.\n */\n programId: string;\n /**\n * SPL token mint (base58) for PDA derivation. Optional — the per-channel\n * negotiated token (`OpenChannelParams.token`) takes precedence when present.\n */\n tokenMint?: string;\n /**\n * Challenge-period duration in seconds for `initialize_channel`. Defaults to\n * `OpenChannelParams.settlementTimeout` or 86400.\n */\n challengeDuration?: number;\n /**\n * OVERRIDE for the on-chain deposit made at open time: `amount` in base units\n * and/or `payerTokenAccount`, the payer's funded SPL token account (ATA,\n * base58; derived from owner+mint when left empty).\n *\n * Normally left unset — the open deposits `OpenChannelParams.initialDeposit`,\n * the same negotiated amount the EVM opener locks. Set this only to pin a\n * different amount or a non-ATA source account. A 0 amount opts out of the\n * deposit entirely and leaves the channel UNCOLLATERALIZED: the connector\n * accepts claims on channel `opened` status + participant membership, but\n * those claims cannot be redeemed for value on-chain (connector#646).\n */\n deposit?: { amount: string; payerTokenAccount: string };\n}\n\nexport interface MinaChannelConfig {\n graphqlUrl: string;\n privateKey: string;\n /**\n * Deployed payment-channel zkApp address (B62). Optional when `autoDeploy`\n * is set — the open path then resolves (or deploys) a pair-owned zkApp\n * itself; see `mina-channel-deploy.ts`.\n */\n zkAppAddress?: string;\n /**\n * Per-pair zkApp auto-deploy (the Mina `PaymentChannel` zkApp is\n * single-pair: one deployment serves exactly one client↔connector pair).\n * When set, `openMinaChannel` first resolves a zkApp that is provably OURS\n * — the recorded `deployed` one, or `zkAppAddress` when its on-chain\n * channelHash matches this pair — and deploys a fresh one otherwise\n * (compile ≈1-3 min; inclusion ≈3-6 min; costs ~1.1 MINA + fees).\n * Without it, behavior is exactly the pre-autoDeploy contract: the\n * configured `zkAppAddress` is required and used verbatim.\n */\n autoDeploy?: {\n /** A previously recorded own deployment for this identity, if any. */\n deployed?: { zkAppAddress: string; zkAppPrivateKey: string };\n /**\n * Persist hook — called with the zkApp address + key BEFORE the deploy tx\n * is sent (and before the circuit compiles), so a crash between send and\n * on-chain confirmation reuses the SAME zkApp next run instead of\n * deploying (and paying ~1.1 MINA for) a second one.\n */\n onDeploying?: (record: {\n zkAppAddress: string;\n zkAppPrivateKey: string;\n feePayer: string;\n }) => void | Promise<void>;\n /** Persist hook — called BEFORE the open proceeds on a fresh deploy. */\n onDeployed?: (record: {\n zkAppAddress: string;\n zkAppPrivateKey: string;\n feePayer: string;\n deployTxHash?: string;\n vkHash?: string;\n }) => void | Promise<void>;\n /** Progress lines (compile/deploy/inclusion phases take minutes). */\n onProgress?: (line: string) => void;\n };\n /**\n * Channel settlement timeout in slots for `initializeChannel`. Defaults to\n * `OpenChannelParams.settlementTimeout` or 86400.\n */\n challengeDuration?: number;\n /**\n * Mina token id field (decimal string) for `initializeChannel`. Default '1'\n * (native MINA). The connector reads this only as on-chain channel metadata.\n */\n tokenId?: string;\n /**\n * Optional on-chain deposit (base units, string) submitted after the channel\n * is initialized. When omitted, the channel is opened (OPEN state) without a\n * deposit — the connector accepts the claim on `opened` status; deposit is\n * only consumed at on-chain settle time.\n */\n deposit?: { amount: string };\n /** Mina network id for the account/Schnorr prefix. Default 'devnet'. */\n networkId?: 'devnet' | 'mainnet';\n}\n\nexport interface OnChainChannelClientConfig {\n evmSigner: EvmSigner;\n chainRpcUrls: Record<string, string>;\n solanaConfig?: SolanaChannelConfig;\n minaConfig?: MinaChannelConfig;\n}\n\n/**\n * Implements ConnectorChannelClient using viem for direct on-chain\n * interaction with TokenNetwork smart contract.\n *\n * Fully non-custodial — the client deposits its own funds on-chain.\n */\nexport class OnChainChannelClient implements ConnectorChannelClient {\n private readonly evmSigner: EvmSigner;\n private readonly chainRpcUrls: Record<string, string>;\n private solanaConfig?: SolanaChannelConfig;\n private minaConfig?: MinaChannelConfig;\n private readonly channelContext = new Map<\n string,\n { chain: string; tokenNetworkAddress: string; tokenAddress?: string }\n >();\n\n constructor(config: OnChainChannelClientConfig) {\n this.evmSigner = config.evmSigner;\n this.chainRpcUrls = config.chainRpcUrls;\n this.solanaConfig = config.solanaConfig;\n this.minaConfig = config.minaConfig;\n }\n\n /**\n * Late-binds the Solana channel config.\n *\n * `ToonClient.start()` derives the Solana Ed25519 keypair from the client's\n * mnemonic asynchronously (after this client is constructed), so the keypair\n * is injected here rather than at construction. Same keypair as the\n * registered Solana signer — guarantees the channel-open key and the\n * claim-signing key match.\n */\n setSolanaConfig(config: SolanaChannelConfig): void {\n this.solanaConfig = config;\n }\n\n /**\n * Late-binds the Mina channel config.\n *\n * Parallel to `setSolanaConfig`: `ToonClient.start()` derives the Mina private\n * key from the client's mnemonic asynchronously (after this client is\n * constructed), so the key is injected here rather than at construction. Same\n * key as the registered Mina signer.\n */\n setMinaConfig(config: MinaChannelConfig): void {\n this.minaConfig = config;\n }\n\n /**\n * Parse chain identifier to extract chainId.\n * Format: \"evm:{network}:{chainId}\" e.g., \"evm:anvil:31337\"\n */\n private parseChainId(chain: string): number {\n const parts = chain.split(':');\n if (parts.length < 2) {\n throw new Error(\n `Invalid chain format: \"${chain}\". Expected \"evm:{network}:{chainId}\" or \"evm:{chainId}\".`\n );\n }\n // Accept both the canonical 3-part `evm:{network}:{chainId}` and the 2-part\n // `evm:{chainId}` form some connectors advertise (e.g. `evm:31337`).\n const chainIdStr = parts.length >= 3 ? parts[2] : parts[1];\n if (!chainIdStr) {\n throw new Error(\n `Invalid chain format: \"${chain}\". Expected \"evm:{network}:{chainId}\".`\n );\n }\n const chainId = parseInt(chainIdStr, 10);\n if (isNaN(chainId)) {\n throw new Error(`Invalid chainId in chain \"${chain}\".`);\n }\n return chainId;\n }\n\n /**\n * Create viem clients for a given chain.\n */\n private createClients(chain: string) {\n const rpcUrl = this.chainRpcUrls[chain];\n if (!rpcUrl) {\n throw new Error(\n `No RPC URL configured for chain \"${chain}\". Available: ${Object.keys(this.chainRpcUrls).join(', ')}`\n );\n }\n\n const chainId = this.parseChainId(chain);\n\n const viemChain = defineChain({\n id: chainId,\n name: chain,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [rpcUrl] } },\n });\n\n const publicClient = createPublicClient({\n transport: http(rpcUrl),\n chain: viemChain,\n });\n\n const walletClient = createWalletClient({\n account: this.evmSigner.account,\n transport: http(rpcUrl),\n chain: viemChain,\n });\n\n return { publicClient, walletClient };\n }\n\n /**\n * Opens a new payment channel on-chain.\n *\n * 1. Approve token spend if needed\n * 2. Call TokenNetwork.openChannel()\n * 3. Extract channelId from ChannelOpened event\n * 4. Deposit initial funds if specified\n */\n async openChannel(params: OpenChannelParams): Promise<OpenChannelResult> {\n const chainPrefix = params.chain.split(':')[0];\n\n // Dispatch to chain-specific opener\n if (chainPrefix === 'solana') return this.openSolanaChannel(params);\n if (chainPrefix === 'mina') return this.openMinaChannel(params);\n\n // EVM path (default)\n return this.openEvmChannel(params);\n }\n\n /**\n * Deposit additional collateral into an already-open channel. `amount` is the\n * DELTA to add (base units). Dispatches by the channel's cached chain context;\n * `currentDeposit` is the channel's current locked total (tracked off-chain by\n * the caller) — required for EVM, whose `setTotalDeposit` takes the new\n * cumulative total, not a delta. Returns the new on-chain deposit total.\n *\n * Non-custodial: the client deposits its OWN funds and signs its OWN tx.\n * EVM is live; Solana/Mina deposit extraction is a follow-up (PR B.1).\n */\n async depositToChannel(\n channelId: string,\n amount: bigint,\n opts: { currentDeposit: bigint }\n ): Promise<{ txHash?: string; depositTotal: bigint }> {\n if (amount <= 0n) throw new Error('Deposit amount must be positive.');\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana') {\n // Both PDA seeds come from the channel's own context, never from config:\n // `tokenNetworkAddress` is the program the channel was OPENED on (the\n // greeting's, when it named one — the only program whose vault PDA holds\n // this collateral), and `tokenAddress` is the mint the open derived the\n // payer ATA from. Reading either from config would re-open the #473 split.\n return this.depositSolana(channelId, amount, opts.currentDeposit, {\n programId: ctx.tokenNetworkAddress,\n ...(ctx.tokenAddress ? { tokenMint: ctx.tokenAddress } : {}),\n });\n }\n if (chainPrefix === 'mina') {\n throw new Error(\n 'Deposit on mina is not yet supported (EVM + Solana today; Mina follow-up).'\n );\n }\n return this.depositEvm(channelId, amount, opts.currentDeposit, ctx);\n }\n\n /**\n * Solana deposit: fire the standalone `deposit` instruction against the channel\n * vault. Incremental on-chain (the program adds `amount`), so the new total is\n * the caller-tracked current plus the delta. Requires the funded payer token\n * account (the funded ATA) from the Solana channel config.\n *\n * `channel` carries the program and mint the channel was actually OPENED\n * with (the greeting's, when it named them — see\n * {@link OnChainChannelClient.openSolanaChannel}), NOT\n * `solanaConfig.programId`/`tokenMint`. Both PDAs this deposit addresses are\n * derived from those: the vault from the program, the payer ATA from the mint.\n */\n private async depositSolana(\n channelId: string,\n amount: bigint,\n currentDeposit: bigint,\n channel: { programId: string; tokenMint?: string }\n ): Promise<{ txHash: string; depositTotal: bigint }> {\n if (!this.solanaConfig) {\n throw new Error('Solana channel config not set — cannot deposit.');\n }\n const cfg = this.solanaConfig;\n const payerSeed = cfg.keypair.slice(0, 32);\n const payerPubkey = base58Encode(\n new Uint8Array(ed25519.getPublicKey(payerSeed))\n );\n // The funded token account is deterministically the payer's ATA for THIS\n // CHANNEL's mint, so derive it when the caller didn't pass one explicitly\n // (config need not carry payerTokenAccount — it's owner+mint, both known here).\n const tokenMint = channel.tokenMint ?? cfg.tokenMint;\n let payerTokenAccount = cfg.deposit?.payerTokenAccount;\n if (!payerTokenAccount) {\n if (!tokenMint) {\n throw new Error(\n 'Solana deposit requires solanaConfig.deposit.payerTokenAccount or a known channel mint to derive the payer ATA.'\n );\n }\n payerTokenAccount = deriveAssociatedTokenAccount(payerPubkey, tokenMint);\n }\n const { depositTxSignature } = await depositSolanaChannel({\n rpcUrl: cfg.rpcUrl,\n programId: channel.programId,\n channelPDA: channelId,\n payerSeed,\n payerPubkey,\n payerTokenAccount,\n amount,\n });\n return {\n txHash: depositTxSignature,\n depositTotal: currentDeposit + amount,\n };\n }\n\n /**\n * EVM deposit: approve the token-network for the delta if the allowance is\n * short, then `setTotalDeposit(channelId, participant, current + delta)` —\n * the contract takes the new cumulative total, so we add the delta to the\n * caller-supplied current locked amount.\n */\n private async depositEvm(\n channelId: string,\n amount: bigint,\n currentDeposit: bigint,\n ctx: { chain: string; tokenNetworkAddress: string; tokenAddress?: string }\n ): Promise<{ txHash: string; depositTotal: bigint }> {\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const tokenNetworkAddr = ctx.tokenNetworkAddress as Hex;\n const myAddress = this.evmSigner.address as Hex;\n const newTotal = currentDeposit + amount;\n\n // Approve the additional collateral if the current allowance can't cover it.\n if (ctx.tokenAddress) {\n const tokenAddr = ctx.tokenAddress as Hex;\n const allowance = await publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [myAddress, tokenNetworkAddr],\n });\n if ((allowance as bigint) < amount) {\n const approveHash = await walletClient.writeContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [tokenNetworkAddr, maxUint256],\n });\n await publicClient.waitForTransactionReceipt({ hash: approveHash });\n }\n }\n\n const depositHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, myAddress, newTotal],\n });\n await publicClient.waitForTransactionReceipt({ hash: depositHash });\n return { txHash: depositHash, depositTotal: newTotal };\n }\n\n /**\n * Close a channel to begin the settlement grace period. Dispatches by the\n * channel's cached chain context. EVM `closeChannel` is unilateral (channelId\n * only); after it confirms we read the `channels()` view for the AUTHORITATIVE\n * `closedAt` + `settlementTimeout` (block-timestamp seconds) and compute\n * `settleableAt = closedAt + settlementTimeout`. Solana/Mina are follow-ups.\n */\n async closeChannel(channelId: string): Promise<{\n txHash?: string;\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `Close on ${chainPrefix} is not yet supported (EVM today; Solana/Mina follow-up).`\n );\n }\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const tokenNetworkAddr = ctx.tokenNetworkAddress as Hex;\n const closeHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'closeChannel',\n args: [channelId as Hex],\n });\n await publicClient.waitForTransactionReceipt({ hash: closeHash });\n\n const info = await this.readEvmChannel(\n publicClient,\n tokenNetworkAddr,\n channelId\n );\n return {\n txHash: closeHash,\n closedAt: info.closedAt,\n settlementTimeout: info.settlementTimeout,\n settleableAt: info.closedAt + info.settlementTimeout,\n };\n }\n\n /**\n * Settle a closed channel after its grace period to release collateral. EVM\n * `settleChannel` is unilateral (channelId only); the contract itself reverts\n * before `closedAt + settlementTimeout`, so an early call surfaces as a tx\n * revert here — but the caller (ToonClient/daemon) enforces the time guard\n * BEFORE spending gas. Solana/Mina are follow-ups.\n */\n async settleChannel(channelId: string): Promise<{ txHash?: string }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx) {\n throw new Error(\n `No on-chain context for channel \"${channelId}\" — it must be opened by this client first.`\n );\n }\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `Settle on ${chainPrefix} is not yet supported (EVM today; Solana/Mina follow-up).`\n );\n }\n const { publicClient, walletClient } = this.createClients(ctx.chain);\n const settleHash = await walletClient.writeContract({\n address: ctx.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'settleChannel',\n args: [channelId as Hex],\n });\n await publicClient.waitForTransactionReceipt({ hash: settleHash });\n return { txHash: settleHash };\n }\n\n /**\n * Read the EVM channel's close-relevant fields so a restarted daemon can\n * recompute the grace timer from chain (chain is authoritative). EVM-only.\n */\n async getChannelCloseInfo(channelId: string): Promise<{\n status: ChannelState['status'];\n closedAt: bigint;\n settlementTimeout: bigint;\n settleableAt: bigint;\n }> {\n const ctx = this.channelContext.get(channelId);\n if (!ctx)\n throw new Error(`No on-chain context for channel \"${channelId}\".`);\n const chainPrefix = ctx.chain.split(':')[0];\n if (chainPrefix === 'solana' || chainPrefix === 'mina') {\n throw new Error(\n `getChannelCloseInfo on ${chainPrefix} is not supported.`\n );\n }\n const { publicClient } = this.createClients(ctx.chain);\n const info = await this.readEvmChannel(\n publicClient,\n ctx.tokenNetworkAddress as Hex,\n channelId\n );\n return {\n status: STATE_MAP[info.state] ?? 'open',\n closedAt: info.closedAt,\n settlementTimeout: info.settlementTimeout,\n settleableAt: info.closedAt + info.settlementTimeout,\n };\n }\n\n /** Read + destructure the EVM `channels(bytes32)` view. */\n private async readEvmChannel(\n publicClient: ReturnType<\n OnChainChannelClient['createClients']\n >['publicClient'],\n tokenNetworkAddr: Hex,\n channelId: string\n ): Promise<{ settlementTimeout: bigint; state: number; closedAt: bigint }> {\n const res = (await publicClient.readContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channels',\n args: [channelId as Hex],\n })) as readonly [bigint, number, bigint, bigint, string, string];\n return {\n settlementTimeout: res[0],\n state: Number(res[1]),\n closedAt: res[2],\n };\n }\n\n /**\n * Read a participant's on-chain channel state — `deposit` (locked collateral),\n * `nonce`, and `transferredAmount` — straight from the `participants` mapping.\n * Takes the chain + token-network explicitly so it works for a channel that\n * was RESUMED from disk (no in-memory `channelContext` yet), which is exactly\n * when the daemon needs to re-hydrate the deposit it doesn't persist.\n */\n async readEvmParticipantState(opts: {\n chain: string;\n tokenNetworkAddress: string;\n channelId: string;\n participant: string;\n }): Promise<{ deposit: bigint; nonce: bigint; transferredAmount: bigint }> {\n const { publicClient } = this.createClients(opts.chain);\n const res = (await publicClient.readContract({\n address: opts.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'participants',\n args: [opts.channelId as Hex, opts.participant as Hex],\n })) as readonly [bigint, bigint, bigint];\n return { deposit: res[0], nonce: res[1], transferredAmount: res[2] };\n }\n\n /**\n * Opens a REAL on-chain Solana payment channel.\n *\n * Derives the connector-parity channel PDA\n * (`[b\"channel\", min_pubkey, max_pubkey, token_mint]`), submits the\n * `initialize_channel` instruction plus the `deposit` that collateralizes the\n * channel, and returns the base58 PDA as the channel id. That\n * PDA is what the claim carries as `channelAccount`, and the on-chain channel\n * is what the connector's `verifySolanaClaim` reads via\n * `provider.getChannelState` before accepting the claim.\n *\n * Both PDA seeds are NEGOTIATED, not configured: the mint is\n * `OpenChannelParams.token` and the program is `OpenChannelParams.tokenNetwork`\n * — the greeting's `tokenAddress`/`programId` as threaded through by\n * `ChannelManager.ensureChannel` — each falling back to the `solanaConfig`\n * default only when the negotiation named none. That is what keeps the channel\n * this opens and the channel the signed claim asserts the same object (#473).\n *\n * Mirrors `openEvmChannel`'s open(+deposit) structure. Idempotent: if the\n * channel account already exists on-chain, returns its PDA without\n * re-initializing.\n */\n private async openSolanaChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n if (!this.solanaConfig) {\n throw new Error(\n 'Solana channel config not provided — cannot open Solana channel'\n );\n }\n\n const cfg = this.solanaConfig;\n // First 32 bytes are the Ed25519 signing seed (config may pass a 64-byte\n // secretKey of seed||pubkey, or a bare 32-byte seed).\n const payerSeed = cfg.keypair.slice(0, 32);\n const payerPubkey = base58Encode(\n new Uint8Array(ed25519.getPublicKey(payerSeed))\n );\n\n // PDA mint: per-channel negotiated token takes precedence over config default.\n const tokenMint = params.token ?? cfg.tokenMint;\n if (!tokenMint) {\n throw new Error(\n 'Solana channel requires a token mint (OpenChannelParams.token or solanaConfig.tokenMint)'\n );\n }\n // PDA program: the negotiated program (the greeting's `programId`, which\n // `ChannelManager` threads through as `tokenNetwork`) takes precedence over\n // the config default — exactly as the negotiated mint already does (#473).\n // The claim's metadata reports this negotiated program, so opening against\n // anything else would open on one program and assert another; ADR 0022\n // makes the greeting the authoritative source of settlement facts, and a\n // stale client preset must not silently override it.\n const programId = params.tokenNetwork ?? cfg.programId;\n if (!params.peerAddress) {\n throw new Error(\n 'Solana channel requires peerAddress (apex settlement pubkey, base58)'\n );\n }\n\n const challengeDuration = BigInt(\n cfg.challengeDuration ?? params.settlementTimeout ?? 86400\n );\n\n // Deposit amount — the SAME policy the EVM opener uses (connector#646):\n // `OpenChannelParams.initialDeposit`, which `ChannelManager.ensureChannel`\n // fills from `negotiation.initialDeposit ?? ChannelManagerConfig.initialDeposit`.\n // Before this, the Solana branch consulted ONLY `solanaConfig.deposit` — an\n // operator-only field nothing on the rig/daemon/preset path ever sets — so\n // every negotiated open silently skipped the `deposit` instruction and left\n // the vault at 0, making accepted claims uncollateralized. `solanaConfig.deposit`\n // remains an explicit override of the amount and/or the funded token account.\n const depositAmount = BigInt(\n cfg.deposit?.amount ?? params.initialDeposit ?? '0'\n );\n const deposit =\n depositAmount > 0n\n ? {\n amount: depositAmount,\n // Derive the payer ATA (owner + channel mint) when not supplied — it is\n // deterministic, so the caller need not thread payerTokenAccount through.\n payerTokenAccount:\n cfg.deposit?.payerTokenAccount ||\n deriveAssociatedTokenAccount(payerPubkey, tokenMint),\n }\n : undefined;\n\n const { channelPDA, depositTotal } = await openSolanaChannelOnChain({\n rpcUrl: cfg.rpcUrl,\n programId,\n tokenMint,\n payerSeed,\n payerPubkey,\n peerPubkey: params.peerAddress,\n challengeDuration,\n deposit,\n });\n\n // Cache context (PDA is the channel id / channelAccount). Record BOTH seeds\n // the channel was actually opened with — program and mint — so a later\n // deposit addresses this channel's vault and this channel's payer ATA,\n // rather than re-deriving either from config (#473).\n this.channelContext.set(channelPDA, {\n chain: params.chain,\n tokenNetworkAddress: programId,\n tokenAddress: tokenMint,\n });\n\n return {\n channelId: channelPDA,\n status: 'opening',\n // Report the collateral now in the vault, when this call established it\n // (locked here on a fresh open, read from chain on a top-up). Reporting\n // only — no spend decision reads it; it exists so callers can show and\n // log real collateral instead of 0.\n ...(depositTotal !== undefined ? { depositTotal } : {}),\n };\n }\n\n /**\n * Opens a REAL on-chain Mina payment channel on the deployed `PaymentChannel`\n * zkApp.\n *\n * The zkApp is deployed out-of-band (the operator/e2e harness deploys it\n * deterministically and advertises its B62 address). This client then calls\n * `initializeChannel` on that zkApp so its on-chain `channelState` becomes\n * `OPEN` — which is what the connector's `MinaPaymentChannelSDK.getChannelState`\n * reads to return status `'opened'` (claim verification otherwise fails with\n * `mina_claim_verification_failed`). The deployed zkApp address IS the channel\n * id: `MinaClaimMessage.zkAppAddress` is both the claim's channel identifier\n * AND the channel-hash preimage the off-chain proof binds to (see\n * `mina-payment-channel.ts`), so the channel-open id and the claim's channel id\n * are guaranteed identical.\n *\n * This is the Mina analog of `openSolanaChannel` (connector#105): the client\n * opens its own per-channel on-chain state (initialize + optional deposit). The\n * heavyweight o1js + `@toon-protocol/mina-zkapp` proof work is lazily imported\n * inside `openMinaChannelOnChain` so npm consumers who never open a Mina\n * channel don't pay the o1js cost.\n *\n * Idempotent: if the on-chain channel is already `OPEN`, the opener returns\n * without re-initializing.\n *\n * NOTE: full on-chain Mina SETTLE remains gated by the connector-side\n * settlement-executor (the same blocker that stops the Solana SETTLE); reaching\n * `opened` + a stored claim is parity with Solana.\n */\n private async openMinaChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n if (!this.minaConfig) {\n throw new Error(\n 'Mina channel config not provided — cannot open Mina channel'\n );\n }\n // The apex's Mina settlement B62 (participantB) is REQUIRED so the channel is\n // opened TWO-party. The off-chain claim is signed in participant form\n // (`Poseidon([client.x, apex.x, 0])`); without participantB the on-chain\n // channel records empty/duplicate participants and the connector's\n // participant-form verification fails on settle (`Invalid balance proof\n // signature`, `participants:[\"\",\"\"]`). Mirrors the Solana peerAddress guard.\n // (Checked before auto-deploy too — the pair hash needs participantB.)\n if (!params.peerAddress) {\n throw new Error(\n 'Mina channel requires peerAddress (apex Mina settlement B62) so the ' +\n 'on-chain channel is opened two-party — the participant-form claim ' +\n 'cannot settle against a single-party channel'\n );\n }\n // The deployed zkApp address IS the channel id (claim `zkAppAddress`).\n // With autoDeploy, resolve a zkApp that is provably OURS for this pair\n // (reusing the recorded/configured one when its on-chain channelHash\n // matches; deploying a dedicated one otherwise) — the Mina PaymentChannel\n // zkApp is single-pair, so a shared/announced address can never serve a\n // second identity. Lazily imported: only autoDeploy users pay the cost.\n let zkAppAddress = this.minaConfig.zkAppAddress;\n if (this.minaConfig.autoDeploy) {\n const { ensureOwnedMinaZkApp } = await import('./mina-channel-deploy.js');\n const ensured = await ensureOwnedMinaZkApp({\n graphqlUrl: this.minaConfig.graphqlUrl,\n payerPrivateKey: this.minaConfig.privateKey,\n peerPublicKey: params.peerAddress,\n ...(this.minaConfig.autoDeploy.deployed\n ? { deployed: this.minaConfig.autoDeploy.deployed }\n : {}),\n ...(zkAppAddress ? { candidateZkAppAddress: zkAppAddress } : {}),\n ...(this.minaConfig.autoDeploy.onDeploying\n ? { onDeploying: this.minaConfig.autoDeploy.onDeploying }\n : {}),\n ...(this.minaConfig.autoDeploy.onDeployed\n ? { onDeployed: this.minaConfig.autoDeploy.onDeployed }\n : {}),\n ...(this.minaConfig.autoDeploy.onProgress\n ? { onProgress: this.minaConfig.autoDeploy.onProgress }\n : {}),\n });\n zkAppAddress = ensured.zkAppAddress;\n }\n if (!zkAppAddress) {\n throw new Error(\n 'Mina channel requires a deployed zkAppAddress (minaConfig.zkAppAddress)'\n );\n }\n\n const timeout = BigInt(\n this.minaConfig.challengeDuration ?? params.settlementTimeout ?? 86400\n );\n const deposit = this.minaConfig.deposit\n ? { amount: BigInt(this.minaConfig.deposit.amount) }\n : undefined;\n\n const openResult = await openMinaChannelOnChain({\n graphqlUrl: this.minaConfig.graphqlUrl,\n zkAppAddress,\n payerPrivateKey: this.minaConfig.privateKey,\n // params.peerAddress is the apex Mina settlement B62 pubkey (participantB).\n peerPublicKey: params.peerAddress,\n timeout,\n tokenId: this.minaConfig.tokenId,\n deposit,\n networkId: this.minaConfig.networkId,\n });\n\n // The deployed zkApp address IS the channel id (claim `zkAppAddress`).\n this.channelContext.set(zkAppAddress, {\n chain: params.chain,\n tokenNetworkAddress: zkAppAddress,\n });\n\n // Surface the CURRENT on-chain depositTotal so the Mina signer can bind\n // `balanceB = depositTotal − balanceA` (connector#133). Read at open time so\n // a re-deposited channel signs against the live value, not a stale config.\n return {\n channelId: zkAppAddress,\n status: 'opening',\n depositTotal: openResult.depositTotal,\n };\n }\n\n /**\n * Opens an EVM payment channel on-chain, remapping the one-time\n * insufficient-native-gas revert into an actionable {@link ChannelFundingError}\n * so callers surface \"fund the wallet\" instead of the raw viem\n * \"...exceeds the balance of the account\" string (toon-meta#65). Only the gas\n * case is remapped; every other error propagates unchanged.\n */\n private async openEvmChannel(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n try {\n return await this.openEvmChannelUnchecked(params);\n } catch (err) {\n if (!isInsufficientGasError(err)) throw err;\n // `chain` is a CAIP-ish id (e.g. \"evm:anvil:31337\"); surface just the\n // family so the remedy reads \"no gas on evm\", not the full slug.\n const chainFamily = params.chain.split(':')[0] || params.chain;\n throw new ChannelFundingError(\n `Settlement wallet ${this.evmSigner.address} has no gas on ` +\n `${chainFamily} to open a payment channel. Run toon_fund_wallet ` +\n `(or fund the wallet) and retry.`,\n err instanceof Error ? err : undefined\n );\n }\n }\n\n /**\n * Raw EVM channel-open (no gas-error remapping — see {@link openEvmChannel}).\n *\n * 1. Approve token spend if needed\n * 2. Call TokenNetwork.openChannel()\n * 3. Extract channelId from ChannelOpened event\n * 4. Deposit initial funds if specified\n */\n private async openEvmChannelUnchecked(\n params: OpenChannelParams\n ): Promise<OpenChannelResult> {\n const {\n chain,\n tokenNetwork,\n peerAddress,\n initialDeposit,\n settlementTimeout,\n } = params;\n\n if (!tokenNetwork) {\n throw new Error(\n 'tokenNetwork address is required for on-chain channel opening'\n );\n }\n\n const { publicClient, walletClient } = this.createClients(chain);\n const tokenNetworkAddr = tokenNetwork as Hex;\n const deposit = initialDeposit ? BigInt(initialDeposit) : 0n;\n\n // If deposit > 0, ensure token approval\n if (deposit > 0n && params.token) {\n const tokenAddr = params.token as Hex;\n const myAddress = this.evmSigner.address as Hex;\n\n const currentAllowance = await publicClient.readContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [myAddress, tokenNetworkAddr],\n });\n\n if ((currentAllowance as bigint) < deposit) {\n const approveHash = await walletClient.writeContract({\n address: tokenAddr,\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [tokenNetworkAddr, maxUint256],\n });\n await publicClient.waitForTransactionReceipt({ hash: approveHash });\n }\n }\n\n // Open channel\n const timeout = BigInt(settlementTimeout ?? 86400);\n const openHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'openChannel',\n args: [peerAddress as Hex, timeout],\n });\n\n const receipt: TransactionReceipt =\n await publicClient.waitForTransactionReceipt({ hash: openHash });\n\n // Extract channelId from ChannelOpened event\n let channelId: string | undefined;\n for (const log of receipt.logs) {\n try {\n const decoded = decodeEventLog({\n abi: TOKEN_NETWORK_ABI,\n data: log.data,\n topics: log.topics,\n });\n if (decoded.eventName === 'ChannelOpened') {\n channelId = (decoded.args as Record<string, unknown>)[\n 'channelId'\n ] as string;\n break;\n }\n } catch {\n // Not our event, skip\n }\n }\n\n if (!channelId) {\n throw new Error('Failed to extract channelId from ChannelOpened event');\n }\n\n // Cache context for getChannelState + later deposits (the token address is\n // needed to approve additional collateral on a standalone deposit).\n this.channelContext.set(channelId, {\n chain,\n tokenNetworkAddress: tokenNetwork,\n ...(params.token ? { tokenAddress: params.token } : {}),\n });\n\n // Deposit initial funds if specified\n if (deposit > 0n) {\n const depositHash = await walletClient.writeContract({\n address: tokenNetworkAddr,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'setTotalDeposit',\n args: [channelId as Hex, this.evmSigner.address as Hex, deposit],\n });\n await publicClient.waitForTransactionReceipt({ hash: depositHash });\n }\n\n return { channelId, status: 'opening' };\n }\n\n /**\n * Gets the current state of a payment channel from on-chain data.\n */\n async getChannelState(channelId: string): Promise<ChannelState> {\n const context = this.channelContext.get(channelId);\n if (!context) {\n throw new Error(\n `No context for channel \"${channelId}\". Channel must be opened via this client first.`\n );\n }\n\n // Mina channels are opened/deployed out-of-band; the connector performs the\n // authoritative on-chain `getChannelState(zkAppAddress)` check at claim\n // verification. Reading zkApp state client-side would require the o1js WASM\n // runtime, which the lightweight client intentionally avoids. Report `open`\n // for the configured deployed zkApp.\n if (context.chain.split(':')[0] === 'mina') {\n return { channelId, status: 'open', chain: context.chain };\n }\n\n // Solana channels read on-chain state from the PDA account, not an EVM contract.\n if (context.chain.split(':')[0] === 'solana' && this.solanaConfig) {\n const account = await getSolanaChannelAccountState(\n this.solanaConfig.rpcUrl,\n channelId\n );\n const status: ChannelState['status'] = !account.exists\n ? 'settled'\n : account.state === 'opened'\n ? 'open'\n : account.state === 'closed'\n ? 'closed'\n : 'settled';\n return { channelId, status, chain: context.chain };\n }\n\n const { publicClient } = this.createClients(context.chain);\n\n const result = await publicClient.readContract({\n address: context.tokenNetworkAddress as Hex,\n abi: TOKEN_NETWORK_ABI,\n functionName: 'channels',\n args: [channelId as Hex],\n });\n\n const [, state] = result as [\n bigint,\n number,\n bigint,\n bigint,\n string,\n string,\n ];\n const status = STATE_MAP[state] ?? 'settled';\n\n return {\n channelId,\n status,\n chain: context.chain,\n };\n }\n}\n","/**\n * Solana payment-channel primitives — connector-parity.\n *\n * Pure, dependency-light helpers that reproduce the EXACT on-chain contract the\n * connector's `SolanaPaymentChannelSDK` (`@toon-protocol/connector`\n * `settlement/solana-payment-channel-sdk.ts`) implements, so a client-issued\n * Solana payment-channel claim is accepted by connector 3.9.0's\n * `verifySolanaClaim` path:\n *\n * 1. PDA derivation — `[b\"channel\", min_pubkey, max_pubkey, token_mint]` sorted\n * lexicographically by raw 32-byte pubkey, derived against the program id.\n * This base58 PDA is the claim's `channelAccount` and the channel-state\n * account the connector reads via `provider.getChannelState`.\n * 2. The 48-byte balance-proof message the connector verifies the Ed25519\n * signature over: `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)`.\n * NOTE: this is NOT the swap-claim `balanceProofHashSolana` shape used by the\n * swap peer ↔ sender wire / SDK `verifyEd25519Signature`; the connector's on-chain\n * payment-channel verifier (`solana-payment-channel-provider.verifyBalanceProof`)\n * verifies this raw 48-byte message, un-hashed.\n * 3. The `initialize_channel` (+ `deposit`) instructions, built and submitted\n * over raw Solana JSON-RPC (no `@solana/web3.js` / `@solana/kit` runtime\n * dependency — only `@noble/curves` + `@noble/hashes`, already client deps).\n *\n * Every byte layout / discriminator / account-meta order here is mirrored from\n * the connector SDK and the SDK reference E2E\n * (`packages/sdk/tests/e2e/docker-solana-settlement-e2e.test.ts`). Keep them in\n * lock-step; a mismatch makes the connector reject the claim (ON_CHAIN_VERIFICATION_FAILED\n * or INVALID_SIGNATURE).\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { base58Encode, base58Decode } from '@toon-protocol/core';\nimport { ChannelFundingError } from '../errors.js';\n\n// ---------------------------------------------------------------------------\n// Constants (must match the Rust program + connector SDK exactly)\n// ---------------------------------------------------------------------------\n\n/** Well-known Solana program addresses (base58). */\nconst TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\nconst SYSTEM_PROGRAM_ID = '11111111111111111111111111111111';\nconst RENT_SYSVAR_ID = 'SysvarRent111111111111111111111111111111111';\n\n/** Instruction discriminators — first byte of an 8-byte LE tag. */\nconst IX_INITIALIZE_CHANNEL = new Uint8Array([0x01, 0, 0, 0, 0, 0, 0, 0]);\nconst IX_DEPOSIT = new Uint8Array([0x02, 0, 0, 0, 0, 0, 0, 0]);\n\n/** On-chain channel-account discriminator: ASCII \"pchannel\". */\nconst CHANNEL_DISCRIMINATOR = new Uint8Array([\n 0x70, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c,\n]);\n\n/** Channel-state account size in bytes. */\nconst CHANNEL_ACCOUNT_SIZE = 178;\n\n// ---------------------------------------------------------------------------\n// Byte helpers\n// ---------------------------------------------------------------------------\n\nconst MAX_U64 = (1n << 64n) - 1n;\n\nfunction writeU64LE(buf: Uint8Array, offset: number, value: bigint): void {\n if (value < 0n || value > MAX_U64) {\n throw new RangeError(`Value ${value} outside u64 range [0, 2^64-1]`);\n }\n for (let i = 0; i < 8; i++) {\n buf[offset + i] = Number((value >> BigInt(i * 8)) & 0xffn);\n }\n}\n\n/** Left-pad / trim a byte array to exactly 32 bytes. */\nfunction padTo32(bytes: Uint8Array): Uint8Array {\n if (bytes.length === 32) return bytes;\n if (bytes.length > 32) return bytes.slice(bytes.length - 32);\n const padded = new Uint8Array(32);\n padded.set(bytes, 32 - bytes.length);\n return padded;\n}\n\n/** Sort two 32-byte pubkeys lexicographically by raw bytes (matches Rust). */\nfunction sortPubkeys(a: Uint8Array, b: Uint8Array): [Uint8Array, Uint8Array] {\n for (let i = 0; i < 32; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n if (ai < bi) return [a, b];\n if (ai > bi) return [b, a];\n }\n return [a, b];\n}\n\n// ---------------------------------------------------------------------------\n// Ed25519 curve check + PDA derivation (matches Solana find_program_address)\n// ---------------------------------------------------------------------------\n\nfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {\n let result = 1n;\n base = ((base % mod) + mod) % mod;\n while (exp > 0n) {\n if (exp & 1n) result = (result * base) % mod;\n exp >>= 1n;\n base = (base * base) % mod;\n }\n return result;\n}\n\nfunction modInverse(a: bigint, m: bigint): bigint {\n return modPow(((a % m) + m) % m, m - 2n, m);\n}\n\n/** True if 32 bytes lie on the Ed25519 curve. A valid PDA must NOT be on-curve. */\nfunction isOnCurve(bytes: Uint8Array): boolean {\n const P = (1n << 255n) - 19n;\n const yBytes = new Uint8Array(32);\n yBytes.set(bytes);\n yBytes[31] = (yBytes[31] ?? 0) & 0x7f;\n\n let y = 0n;\n for (let i = 0; i < 32; i++) {\n y |= BigInt(yBytes[i] ?? 0) << BigInt(i * 8);\n }\n if (y >= P) return true;\n\n const y2 = (y * y) % P;\n const D = (P - ((121665n * modInverse(121666n, P)) % P) + P) % P;\n const numerator = (y2 - 1n + P) % P;\n const denominator = (D * y2 + 1n) % P;\n const x2 = (numerator * modInverse(denominator, P)) % P;\n if (x2 === 0n) return true;\n return modPow(x2, (P - 1n) / 2n, P) === 1n;\n}\n\nfunction findProgramAddress(\n seeds: Uint8Array[],\n programId: Uint8Array\n): { pda: Uint8Array; bump: number } {\n const PDA_MARKER = new TextEncoder().encode('ProgramDerivedAddress');\n for (let bump = 255; bump >= 0; bump--) {\n const allSeeds = [...seeds, new Uint8Array([bump])];\n let totalLen = programId.length + PDA_MARKER.length;\n for (const s of allSeeds) totalLen += s.length;\n\n const input = new Uint8Array(totalLen);\n let offset = 0;\n for (const s of allSeeds) {\n input.set(s, offset);\n offset += s.length;\n }\n input.set(programId, offset);\n offset += programId.length;\n input.set(PDA_MARKER, offset);\n\n const hash = sha256(input);\n if (!isOnCurve(hash)) return { pda: hash, bump };\n }\n throw new Error('Could not find a viable PDA bump seed');\n}\n\n/**\n * Derive the channel PDA — connector-parity.\n * Seeds: `[b\"channel\", min_pubkey, max_pubkey, token_mint]` (participants sorted).\n *\n * @returns base58 PDA + bump.\n */\nexport function deriveChannelPDA(\n participantA: string,\n participantB: string,\n tokenMint: string,\n programId: string\n): { pda: string; bump: number } {\n const a = padTo32(base58Decode(participantA));\n const b = padTo32(base58Decode(participantB));\n const mint = padTo32(base58Decode(tokenMint));\n const program = padTo32(base58Decode(programId));\n const [min, max] = sortPubkeys(a, b);\n const seeds = [new TextEncoder().encode('channel'), min, max, mint];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\n}\n\n/**\n * Derive the Associated Token Account (ATA) for an owner + SPL mint — the\n * standard SPL ATA PDA over seeds `[owner, TOKEN_PROGRAM_ID, mint]` under the\n * Associated-Token-Account program. Deterministic from `(owner, mint)`, so\n * callers (e.g. a Solana channel deposit) need not supply the funded token\n * account explicitly — it is always the owner's ATA for the channel's mint.\n *\n * @param owner - base58 wallet pubkey that owns the token account.\n * @param tokenMint - base58 SPL mint.\n * @returns base58 ATA address.\n */\nexport function deriveAssociatedTokenAccount(\n owner: string,\n tokenMint: string\n): string {\n // Canonical mainnet/devnet SPL program ids (same on every cluster).\n const TOKEN_PROGRAM_ID = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';\n const ASSOCIATED_TOKEN_PROGRAM_ID =\n 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';\n const seeds = [\n padTo32(base58Decode(owner)),\n padTo32(base58Decode(TOKEN_PROGRAM_ID)),\n padTo32(base58Decode(tokenMint)),\n ];\n const { pda } = findProgramAddress(\n seeds,\n padTo32(base58Decode(ASSOCIATED_TOKEN_PROGRAM_ID))\n );\n return base58Encode(pda);\n}\n\n/**\n * Derive the vault PDA for a channel — connector-parity.\n * Seeds: `[b\"vault\", channel_pda]`.\n */\nexport function deriveVaultPDA(\n channelPDA: string,\n programId: string\n): { pda: string; bump: number } {\n const channel = padTo32(base58Decode(channelPDA));\n const program = padTo32(base58Decode(programId));\n const seeds = [new TextEncoder().encode('vault'), channel];\n const { pda, bump } = findProgramAddress(seeds, program);\n return { pda: base58Encode(pda), bump };\n}\n\n// ---------------------------------------------------------------------------\n// Balance-proof message + signing (connector-parity)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the connector's canonical 48-byte balance-proof message:\n * `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)`.\n *\n * Mirrors `SolanaPaymentChannelSDK._buildBalanceProofMessage`. This is the EXACT\n * message the connector's `solana-payment-channel-provider.verifyBalanceProof`\n * reconstructs and Ed25519-verifies (un-hashed).\n */\nexport function buildBalanceProofMessage(\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint\n): Uint8Array {\n const message = new Uint8Array(48);\n message.set(padTo32(base58Decode(channelPDA)), 0);\n writeU64LE(message, 32, nonce);\n writeU64LE(message, 40, transferredAmount);\n return message;\n}\n\n/** Sign the 48-byte balance-proof message with a 32-byte Ed25519 seed. */\nexport function signBalanceProofMessage(\n channelPDA: string,\n nonce: bigint,\n transferredAmount: bigint,\n seed: Uint8Array\n): Uint8Array {\n const message = buildBalanceProofMessage(\n channelPDA,\n nonce,\n transferredAmount\n );\n return ed25519.sign(message, seed);\n}\n\n// ---------------------------------------------------------------------------\n// On-chain channel open (initialize_channel + deposit) over raw JSON-RPC\n// ---------------------------------------------------------------------------\n\ninterface InstructionKey {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\ninterface RawInstruction {\n programId: string;\n keys: InstructionKey[];\n data: Uint8Array;\n}\n\ninterface Signer {\n publicKey: Uint8Array;\n privateKey: Uint8Array;\n}\n\nlet rpcIdCounter = 1;\n\n/**\n * A JSON-RPC-level error — the node answered, and said no. Distinct from a\n * TRANSPORT fault (DNS, timeout, 429, 5xx, malformed body), which surfaces as\n * whatever `fetch`/`json()` threw. Callers must not conflate the two: \"the node\n * says this account does not exist\" is a fact about the chain, while \"the node\n * did not answer\" is a fact about the network, and treating the latter as the\n * former turns a transient blip into a false accusation that the user's wallet\n * is unfunded.\n */\nexport class SolanaRpcError extends Error {\n constructor(\n readonly method: string,\n readonly code: number,\n readonly rpcMessage: string\n ) {\n super(`Solana RPC error [${method}]: ${rpcMessage} (code ${code})`);\n this.name = 'SolanaRpcError';\n }\n}\n\n/**\n * True when `err` is the node reporting that the queried account does not\n * exist. Solana answers `getTokenAccountBalance` for an absent account with a\n * JSON-RPC error (`-32602 Invalid param: could not find account`) rather than a\n * zero balance, so absence is only ever observable as an error — which is\n * exactly why it must be told apart from transport faults by CONTENT, not by\n * \"something threw\".\n */\nfunction isAccountNotFoundError(err: unknown): boolean {\n if (!(err instanceof SolanaRpcError)) return false;\n return /could not find account|account not found|account does not exist/i.test(\n err.rpcMessage\n );\n}\n\nasync function solanaRpc(\n rpcUrl: string,\n method: string,\n params: unknown[] = []\n): Promise<unknown> {\n const res = await fetch(rpcUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n method,\n params,\n id: rpcIdCounter++,\n }),\n signal: AbortSignal.timeout(30000),\n });\n const json = (await res.json()) as {\n result?: unknown;\n error?: { message: string; code: number };\n };\n if (json.error) {\n throw new SolanaRpcError(method, json.error.code, json.error.message);\n }\n return json.result;\n}\n\nasync function getLatestBlockhash(rpcUrl: string): Promise<string> {\n const result = (await solanaRpc(rpcUrl, 'getLatestBlockhash', [\n { commitment: 'confirmed' },\n ])) as { value: { blockhash: string } };\n return result.value.blockhash;\n}\n\ninterface AccountInfo {\n data: [string, string];\n owner: string;\n lamports: number;\n}\n\nasync function getAccountInfo(\n rpcUrl: string,\n pubkey: string\n): Promise<AccountInfo | null> {\n const result = (await solanaRpc(rpcUrl, 'getAccountInfo', [\n pubkey,\n { encoding: 'base64', commitment: 'confirmed' },\n ])) as { value: AccountInfo | null };\n return result.value;\n}\n\n/**\n * Balance (base units) of an SPL token account, or `null` when the node reports\n * that the account does not exist (an owner who has never held the mint has no\n * ATA).\n *\n * ONLY that one answer becomes `null`. A transport fault — timeout, 429, 5xx,\n * DNS — propagates, because \"the RPC is unreachable\" is not evidence about the\n * user's balance, and swallowing it here would turn a transient blip into a\n * hard `ChannelFundingError` telling the user to fund an already-funded wallet.\n */\nasync function getTokenAccountBalance(\n rpcUrl: string,\n tokenAccount: string\n): Promise<bigint | null> {\n try {\n const result = (await solanaRpc(rpcUrl, 'getTokenAccountBalance', [\n tokenAccount,\n { commitment: 'confirmed' },\n ])) as { value?: { amount?: string } } | null;\n const amount = result?.value?.amount;\n return amount === undefined ? null : BigInt(amount);\n } catch (err) {\n if (isAccountNotFoundError(err)) return null;\n throw err;\n }\n}\n\n/** Native SOL balance (lamports) of an account; 0 for an account that does not exist. */\nasync function getLamports(rpcUrl: string, pubkey: string): Promise<bigint> {\n const result = (await solanaRpc(rpcUrl, 'getBalance', [\n pubkey,\n { commitment: 'confirmed' },\n ])) as { value?: number | string } | null;\n return BigInt(result?.value ?? 0);\n}\n\n/** Base fee per signature (lamports). Each of our txs carries exactly one. */\nconst LAMPORTS_PER_SIGNATURE = 5_000n;\n\n/**\n * Native SOL (lamports) a FRESH channel open must be able to SPEND, computed\n * rather than guessed:\n *\n * rent-exempt(178-byte channel account) = (128 + 178) × 6960 = 2_129_760\n * rent-exempt(165-byte SPL vault) = (128 + 165) × 6960 = 2_039_280\n * 2 signatures (initialize_channel, deposit) × 5_000 = 10_000\n * ──────────\n * 4_179_040\n *\n * (6960 lamports/byte-year × 2 years is Solana's rent-exemption rate, and 128\n * bytes is the fixed per-account overhead.) The devnet open behind\n * connector#646 spent ≈0.0042 SOL end to end, which matches.\n *\n * This bounds the SPEND, which is not quite the chain's whole requirement:\n * Solana additionally rejects a transaction that leaves the fee payer\n * rent-paying rather than rent-exempt (`RentState::transition_allowed`), so a\n * payer must really end at either 0 or ≥ the 890_880-lamport minimum. A payer\n * holding somewhere in [4_179_040, 5_069_920) therefore passes this preflight\n * and is still rejected on-chain with `InsufficientFundsForRent`.\n *\n * That window is left deliberately un-padded. Adding 890_880 here would reject\n * the payer who spends down to exactly 0 — which the chain permits — and this\n * preflight exists to REPLACE opaque failures with actionable ones, not to\n * invent refusals of its own. A payer inside the window still gets the chain's\n * error, exactly as it did before this preflight existed; everyone below the\n * floor gets a message naming the wallet and the shortfall.\n */\nexport const MIN_LAMPORTS_FOR_CHANNEL_OPEN = 4_179_040n;\n\n/**\n * Native SOL (lamports) a standalone top-up of an EXISTING channel must be able\n * to spend: one signature, no rent — both accounts already exist and are\n * already rent-exempt. The same rent-state caveat as\n * {@link MIN_LAMPORTS_FOR_CHANNEL_OPEN} applies, over [5_000, 895_880).\n */\nexport const MIN_LAMPORTS_FOR_DEPOSIT = LAMPORTS_PER_SIGNATURE;\n\n/**\n * Fail an on-chain open BEFORE spending anything when the payer cannot fund it.\n *\n * Two distinct assets are required and neither implies the other: native SOL\n * pays the rent for the channel + vault accounts and the signature fees, while\n * the SPL settlement token is what the `deposit` instruction moves into the\n * vault. A wallet holding USDC but no SOL fails partway through the open; a\n * wallet holding SOL but no USDC aborts the deposit AFTER `initialize_channel`\n * has already created a (rent-paying, 0-collateral) channel — exactly the state\n * connector#646 observed. Reading both up front turns either case into an\n * actionable {@link ChannelFundingError}.\n */\nasync function assertOpenFunding(opts: {\n rpcUrl: string;\n payerPubkey: string;\n tokenMint: string;\n /** Lamport floor for the transactions about to be sent. */\n minLamports: bigint;\n deposit?: { amount: bigint; payerTokenAccount: string };\n}): Promise<void> {\n const { rpcUrl, payerPubkey, tokenMint, minLamports, deposit } = opts;\n\n const lamports = await getLamports(rpcUrl, payerPubkey);\n if (lamports < minLamports) {\n throw new ChannelFundingError(\n `Solana settlement wallet ${payerPubkey} holds ${lamports} lamports, below the ` +\n `${minLamports} needed here (rent for the channel + vault accounts, plus ` +\n `signature fees). Native SOL is separate from the settlement token: holding ` +\n `the SPL token is not enough. Airdrop/fund SOL to that address and retry.`\n );\n }\n\n if (!deposit || deposit.amount <= 0n) return;\n\n const held = await getTokenAccountBalance(rpcUrl, deposit.payerTokenAccount);\n if (held === null) {\n throw new ChannelFundingError(\n `Solana token account ${deposit.payerTokenAccount} does not exist, so the ` +\n `${deposit.amount} base-unit channel deposit of mint ${tokenMint} cannot ` +\n `be funded. Fund the settlement wallet with that token (which creates the ` +\n `associated token account) and retry.`\n );\n }\n if (held < deposit.amount) {\n throw new ChannelFundingError(\n `Solana token account ${deposit.payerTokenAccount} holds ${held} base units ` +\n `of mint ${tokenMint}, short of the ${deposit.amount} base-unit channel ` +\n `deposit. Fund the settlement wallet, or lower the deposit ` +\n `(\\`solanaChannel.deposit.amount\\` / \\`initialDeposit\\`), and retry.`\n );\n }\n}\n\nasync function waitForConfirmation(\n rpcUrl: string,\n signature: string,\n timeoutMs = 30000\n): Promise<void> {\n const start = Date.now();\n while (Date.now() - start < timeoutMs) {\n const result = (await solanaRpc(rpcUrl, 'getSignatureStatuses', [\n [signature],\n ])) as {\n value: ({ confirmationStatus: string; err?: unknown } | null)[];\n };\n const status = result.value[0];\n if (\n status?.confirmationStatus === 'confirmed' ||\n status?.confirmationStatus === 'finalized'\n ) {\n if (status.err) {\n throw new Error(\n `Transaction ${signature} failed: ${JSON.stringify(status.err)}`\n );\n }\n return;\n }\n await new Promise((r) => setTimeout(r, 500));\n }\n throw new Error(\n `Transaction ${signature} not confirmed within ${timeoutMs}ms`\n );\n}\n\nfunction compactU16Size(value: number): number {\n if (value > 0xffff) {\n throw new RangeError(`compact-u16 value ${value} exceeds u16 max (0xFFFF)`);\n }\n return value < 0x80 ? 1 : value < 0x4000 ? 2 : 3;\n}\n\nfunction writeCompactU16(\n buf: Uint8Array,\n offset: number,\n value: number\n): number {\n if (value < 0x80) {\n buf[offset++] = value;\n } else if (value < 0x4000) {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = value >> 7;\n } else {\n buf[offset++] = (value & 0x7f) | 0x80;\n buf[offset++] = ((value >> 7) & 0x7f) | 0x80;\n buf[offset++] = value >> 14;\n }\n return offset;\n}\n\ninterface AccountEntry {\n pubkey: string;\n isSigner: boolean;\n isWritable: boolean;\n}\n\n/**\n * Build, sign, and send a Solana legacy transaction over raw JSON-RPC, then wait\n * for confirmation. Mirrors the SDK reference E2E's `buildAndSendTransaction`.\n */\nasync function buildAndSendTransaction(\n rpcUrl: string,\n feePayer: Signer,\n instructions: RawInstruction[],\n additionalSigners: Signer[] = []\n): Promise<string> {\n const blockhash = await getLatestBlockhash(rpcUrl);\n const feePayerPubkey = base58Encode(feePayer.publicKey);\n\n const accountMap = new Map<string, AccountEntry>();\n accountMap.set(feePayerPubkey, {\n pubkey: feePayerPubkey,\n isSigner: true,\n isWritable: true,\n });\n for (const ix of instructions) {\n for (const key of ix.keys) {\n const existing = accountMap.get(key.pubkey);\n if (existing) {\n existing.isSigner = existing.isSigner || key.isSigner;\n existing.isWritable = existing.isWritable || key.isWritable;\n } else {\n accountMap.set(key.pubkey, { ...key });\n }\n }\n if (!accountMap.has(ix.programId)) {\n accountMap.set(ix.programId, {\n pubkey: ix.programId,\n isSigner: false,\n isWritable: false,\n });\n }\n }\n\n const accounts = [...accountMap.values()].sort((a, b) => {\n if (a.pubkey === feePayerPubkey) return -1;\n if (b.pubkey === feePayerPubkey) return 1;\n const aScore = (a.isSigner ? 2 : 0) + (a.isWritable ? 1 : 0);\n const bScore = (b.isSigner ? 2 : 0) + (b.isWritable ? 1 : 0);\n return bScore - aScore;\n });\n\n const numSigners = accounts.filter((a) => a.isSigner).length;\n const numReadonlySigners = accounts.filter(\n (a) => a.isSigner && !a.isWritable\n ).length;\n const numReadonlyNonSigners = accounts.filter(\n (a) => !a.isSigner && !a.isWritable\n ).length;\n\n const accountIndexMap = new Map<string, number>();\n accounts.forEach((a, i) => accountIndexMap.set(a.pubkey, i));\n\n const compiled = instructions.map((ix) => ({\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- programId added to accountMap above\n programIdIndex: accountIndexMap.get(ix.programId)!,\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- every key added to accountMap above\n accountIndices: ix.keys.map((k) => accountIndexMap.get(k.pubkey)!),\n data: ix.data,\n }));\n\n const blockhashBytes = base58Decode(blockhash);\n\n let instructionSize = compactU16Size(compiled.length);\n for (const ix of compiled) {\n instructionSize += 1;\n instructionSize +=\n compactU16Size(ix.accountIndices.length) + ix.accountIndices.length;\n instructionSize += compactU16Size(ix.data.length) + ix.data.length;\n }\n\n const messageSize =\n 3 +\n compactU16Size(accounts.length) +\n 32 * accounts.length +\n 32 +\n instructionSize;\n const message = new Uint8Array(messageSize);\n let offset = 0;\n\n message[offset++] = numSigners;\n message[offset++] = numReadonlySigners;\n message[offset++] = numReadonlyNonSigners;\n\n offset = writeCompactU16(message, offset, accounts.length);\n for (const acct of accounts) {\n message.set(padTo32(base58Decode(acct.pubkey)), offset);\n offset += 32;\n }\n\n message.set(padTo32(blockhashBytes), offset);\n offset += 32;\n\n offset = writeCompactU16(message, offset, compiled.length);\n for (const ix of compiled) {\n message[offset++] = ix.programIdIndex;\n offset = writeCompactU16(message, offset, ix.accountIndices.length);\n for (const idx of ix.accountIndices) message[offset++] = idx;\n offset = writeCompactU16(message, offset, ix.data.length);\n message.set(ix.data, offset);\n offset += ix.data.length;\n }\n\n const finalMessage = message.slice(0, offset);\n\n const allSigners = [feePayer, ...additionalSigners];\n const signerPubkeys = accounts.filter((a) => a.isSigner).map((a) => a.pubkey);\n const signatures: Uint8Array[] = [];\n for (const signerPubkey of signerPubkeys) {\n const signer = allSigners.find(\n (s) => base58Encode(s.publicKey) === signerPubkey\n );\n if (!signer) throw new Error(`Missing signer for ${signerPubkey}`);\n signatures.push(ed25519.sign(finalMessage, signer.privateKey));\n }\n\n const txSize =\n compactU16Size(signatures.length) +\n signatures.length * 64 +\n finalMessage.length;\n const tx = new Uint8Array(txSize);\n let txOffset = 0;\n txOffset = writeCompactU16(tx, txOffset, signatures.length);\n for (const sig of signatures) {\n tx.set(sig, txOffset);\n txOffset += 64;\n }\n tx.set(finalMessage, txOffset);\n\n const txBase64 = Buffer.from(tx).toString('base64');\n const txSig = (await solanaRpc(rpcUrl, 'sendTransaction', [\n txBase64,\n {\n encoding: 'base64',\n skipPreflight: false,\n preflightCommitment: 'confirmed',\n },\n ])) as string;\n await waitForConfirmation(rpcUrl, txSig);\n return txSig;\n}\n\n/** Parsed status of an on-chain channel account. */\nexport interface SolanaChannelAccountState {\n exists: boolean;\n /** 'opened' | 'closed' | 'settled' when the account exists with valid data. */\n state?: 'opened' | 'closed' | 'settled';\n participantA?: string;\n participantB?: string;\n /**\n * PER-PARTICIPANT collateral (base units), as the program tracks it.\n *\n * These are what bound redeemability, NOT the vault's token balance: the\n * vault holds `deposit_a + deposit_b`, but `Claim` rejects a claim whose\n * `transferred_amount` exceeds the CLAIMER'S OWN deposit\n * (`TransferredAmountExceedsDeposit`). A peer-funded vault can therefore look\n * amply funded while this client's own collateral is still 0.\n */\n depositA?: bigint;\n depositB?: bigint;\n}\n\nconst STATE_MAP = ['opened', 'closed', 'settled'] as const;\n\n/** Read a little-endian u64 at `offset`. */\nfunction readU64LE(data: Uint8Array, offset: number): bigint {\n let value = 0n;\n for (let i = 7; i >= 0; i--) {\n value = (value << 8n) | BigInt(data[offset + i] ?? 0);\n }\n return value;\n}\n\n/**\n * Fetch + minimally parse the on-chain channel account at a PDA.\n *\n * Offsets mirror the program's `state.rs` layout (178-byte account):\n * `[8..40]` participant_a, `[40..72]` participant_b, `[104..112]` deposit_a,\n * `[112..120]` deposit_b, `[160]` state.\n */\nexport async function getChannelAccountState(\n rpcUrl: string,\n channelPDA: string\n): Promise<SolanaChannelAccountState> {\n const info = await getAccountInfo(rpcUrl, channelPDA);\n if (!info) return { exists: false };\n const data = new Uint8Array(Buffer.from(info.data[0], 'base64'));\n if (data.length < CHANNEL_ACCOUNT_SIZE) return { exists: false };\n for (let i = 0; i < 8; i++) {\n if (data[i] !== CHANNEL_DISCRIMINATOR[i]) return { exists: false };\n }\n return {\n exists: true,\n state: STATE_MAP[data[160] ?? 0] ?? 'opened',\n participantA: base58Encode(data.slice(8, 40)),\n participantB: base58Encode(data.slice(40, 72)),\n depositA: readU64LE(data, 104),\n depositB: readU64LE(data, 112),\n };\n}\n\n/**\n * This payer's OWN recorded collateral on an existing channel — the quantity\n * that bounds what its claims can redeem.\n *\n * @throws when the payer is neither participant. Unreachable via the normal\n * path (the channel PDA is derived from `[b\"channel\", min(payer,peer),\n * max(payer,peer), mint]`, so membership is structural), which is exactly why\n * a mismatch must be surfaced rather than silently skipped: it means the\n * account we parsed is not the channel we think it is.\n */\nfunction ownDeposit(\n account: SolanaChannelAccountState,\n payerPubkey: string\n): bigint {\n if (account.participantA === payerPubkey) return account.depositA ?? 0n;\n if (account.participantB === payerPubkey) return account.depositB ?? 0n;\n throw new Error(\n `Solana channel participants (${account.participantA}, ${account.participantB}) ` +\n `do not include the payer ${payerPubkey} — refusing to reason about its collateral.`\n );\n}\n\nexport interface OpenSolanaChannelParams {\n rpcUrl: string;\n programId: string;\n tokenMint: string;\n /** Client's 32-byte Ed25519 seed (participant A + fee payer). */\n payerSeed: Uint8Array;\n /** Client's base58 pubkey (participant A). */\n payerPubkey: string;\n /** Apex's base58 settlement pubkey (participant B). */\n peerPubkey: string;\n /** Challenge-period duration in seconds. */\n challengeDuration: bigint;\n /** Optional deposit amount + funded SPL token account (ATA) of the payer. */\n deposit?: { amount: bigint; payerTokenAccount: string };\n}\n\nexport interface OpenSolanaChannelResult {\n channelPDA: string;\n /** True if a fresh on-chain initialize_channel tx was submitted. */\n opened: boolean;\n initTxSignature?: string;\n depositTxSignature?: string;\n /**\n * Collateral in the channel vault (base units) after this call. Present\n * whenever it was established here — read from chain on the existing-channel\n * path, known by construction on the fresh-open path. REPORTING only: nothing\n * gates spending on it (the Solana balance-proof signer never reads it), it\n * exists so callers can show and log real collateral instead of 0.\n */\n depositTotal?: bigint;\n}\n\n/**\n * Bring an ALREADY-OPEN channel up to the target collateral, depositing only\n * the shortfall. A no-op when no deposit is requested or when the payer's own\n * collateral already meets the target.\n *\n * Measures the PAYER'S OWN `deposit_a`/`deposit_b`, never the vault's token\n * balance. The vault holds BOTH participants' collateral, but `Claim` bounds a\n * claim by the claimer's own deposit alone — so a vault funded by the peer can\n * read at or above target while this client's collateral is still 0, and\n * comparing against it would no-op in exactly the case a top-up is needed. The\n * figure is read from the channel account already fetched for the idempotency\n * check, so this costs no extra RPC.\n *\n * This is what makes the fix reach channels that already exist: the connector#646\n * devnet channel is open with 0 collateral, and a client that merely skipped it\n * would go on signing claims that cannot be redeemed.\n */\nasync function topUpExistingChannel(opts: {\n rpcUrl: string;\n programId: string;\n tokenMint: string;\n channelPDA: string;\n payerSeed: Uint8Array;\n payerPubkey: string;\n /** The channel account already read for the idempotency check. */\n existing: SolanaChannelAccountState;\n deposit?: { amount: bigint; payerTokenAccount: string };\n}): Promise<{ depositTxSignature?: string; depositTotal?: bigint }> {\n const {\n rpcUrl,\n programId,\n tokenMint,\n channelPDA,\n payerPubkey,\n existing,\n deposit,\n } = opts;\n if (!deposit || deposit.amount <= 0n) return {};\n\n const own = ownDeposit(existing, payerPubkey);\n if (own >= deposit.amount) return { depositTotal: own };\n\n const shortfall = deposit.amount - own;\n // No rent here — both accounts already exist — so only the signature fee.\n await assertOpenFunding({\n rpcUrl,\n payerPubkey,\n tokenMint,\n minLamports: MIN_LAMPORTS_FOR_DEPOSIT,\n deposit: {\n amount: shortfall,\n payerTokenAccount: deposit.payerTokenAccount,\n },\n });\n\n const { depositTxSignature } = await depositSolanaChannel({\n rpcUrl,\n programId,\n channelPDA,\n payerSeed: opts.payerSeed,\n payerPubkey,\n payerTokenAccount: deposit.payerTokenAccount,\n amount: shortfall,\n });\n return { depositTxSignature, depositTotal: own + shortfall };\n}\n\n/**\n * Open (initialize) and collateralize a real on-chain Solana payment channel at\n * the connector-parity PDA. Idempotent in the only sense that matters: an\n * existing channel is never re-initialized, but its vault IS topped up to the\n * requested collateral, so the outcome — \"an open channel holding `deposit`\" —\n * is the same whether or not the channel existed beforehand.\n *\n * The Ed25519 keypair derives both the participant-A identity and the fee\n * payer; the apex pubkey is participant B. The returned `channelPDA` (base58) is\n * the value carried in the claim's `channelAccount`.\n */\nexport async function openSolanaChannel(\n params: OpenSolanaChannelParams\n): Promise<OpenSolanaChannelResult> {\n const {\n rpcUrl,\n programId,\n tokenMint,\n payerSeed,\n payerPubkey,\n peerPubkey,\n challengeDuration,\n } = params;\n\n const { pda: channelPDA } = deriveChannelPDA(\n payerPubkey,\n peerPubkey,\n tokenMint,\n programId\n );\n\n // Idempotent: skip initialize if the channel account already exists — but do\n // NOT skip the collateral. A channel opened before connector#646 was fixed\n // exists on-chain with a 0-balance vault, and returning here would let the\n // client keep signing uncollateralized claims against it forever, which is\n // the very defect this path is meant to close. Top it up to the target\n // instead; already-collateralized channels are a no-op.\n const existing = await getChannelAccountState(rpcUrl, channelPDA);\n if (existing.exists) {\n // …but ONLY an `Opened` channel can take a deposit: the program rejects\n // `Deposit` on a closed/settled channel (`ChannelNotOpened`). Resuming a\n // channel this client has CLOSED is a supported, persisted state (the\n // withdraw flow), so returning it unchanged is the correct answer — firing\n // a doomed deposit would turn that flow into an opaque `custom program\n // error`. Collateral is a question for a channel that can still spend.\n if (existing.state !== 'opened') {\n return { channelPDA, opened: false };\n }\n const topUp = await topUpExistingChannel({\n rpcUrl,\n programId,\n tokenMint,\n channelPDA,\n payerSeed,\n payerPubkey,\n existing,\n deposit: params.deposit,\n });\n return { channelPDA, opened: false, ...topUp };\n }\n\n // Only a FRESH open pays rent, so the full rent+fee floor is required here.\n await assertOpenFunding({\n rpcUrl,\n payerPubkey,\n tokenMint,\n minLamports: MIN_LAMPORTS_FOR_CHANNEL_OPEN,\n deposit: params.deposit,\n });\n\n const payerPublicKey = padTo32(base58Decode(payerPubkey));\n const payer: Signer = { publicKey: payerPublicKey, privateKey: payerSeed };\n\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // initialize_channel: discriminator(8) + challenge_duration(8 LE)\n const initData = new Uint8Array(16);\n initData.set(IX_INITIALIZE_CHANNEL, 0);\n writeU64LE(initData, 8, challengeDuration);\n\n const initTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: true },\n { pubkey: payerPubkey, isSigner: false, isWritable: false }, // participant A\n { pubkey: peerPubkey, isSigner: false, isWritable: false }, // participant B\n { pubkey: tokenMint, isSigner: false, isWritable: false },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: SYSTEM_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n { pubkey: RENT_SYSVAR_ID, isSigner: false, isWritable: false },\n ],\n data: initData,\n },\n ]);\n\n let depositTxSignature: string | undefined;\n if (params.deposit && params.deposit.amount > 0n) {\n ({ depositTxSignature } = await depositSolanaChannel({\n rpcUrl,\n programId,\n channelPDA,\n payerSeed,\n payerPubkey,\n payerTokenAccount: params.deposit.payerTokenAccount,\n amount: params.deposit.amount,\n }));\n }\n\n return {\n channelPDA,\n opened: true,\n initTxSignature,\n depositTxSignature,\n ...(depositTxSignature ? { depositTotal: params.deposit?.amount } : {}),\n };\n}\n\nexport interface DepositSolanaChannelParams {\n rpcUrl: string;\n programId: string;\n /** The channel PDA (base58) — the Solana channel id. */\n channelPDA: string;\n /** Ed25519 signing seed (32 bytes) of the payer. */\n payerSeed: Uint8Array;\n /** Payer public key (base58). */\n payerPubkey: string;\n /** Funded SPL token account (ATA, base58) the collateral is pulled from. */\n payerTokenAccount: string;\n /** Delta to deposit (base units). The on-chain `deposit` ix adds this amount. */\n amount: bigint;\n}\n\n/**\n * Deposit additional collateral into an existing on-chain Solana channel — the\n * standalone `deposit` instruction (discriminator + amount LE), the same one the\n * open flow fires post-init. Incremental: the program adds `amount` to the\n * channel vault. Returns the deposit tx signature.\n */\nexport async function depositSolanaChannel(\n params: DepositSolanaChannelParams\n): Promise<{ depositTxSignature: string }> {\n const {\n rpcUrl,\n programId,\n channelPDA,\n payerSeed,\n payerPubkey,\n payerTokenAccount,\n amount,\n } = params;\n if (amount <= 0n) throw new Error('Solana deposit amount must be positive.');\n\n const payer: Signer = {\n publicKey: padTo32(base58Decode(payerPubkey)),\n privateKey: payerSeed,\n };\n const { pda: vaultPDA } = deriveVaultPDA(channelPDA, programId);\n\n // deposit: discriminator(8) + amount(8 LE)\n const depositData = new Uint8Array(16);\n depositData.set(IX_DEPOSIT, 0);\n writeU64LE(depositData, 8, amount);\n\n const depositTxSignature = await buildAndSendTransaction(rpcUrl, payer, [\n {\n programId,\n keys: [\n { pubkey: payerPubkey, isSigner: true, isWritable: false },\n { pubkey: payerTokenAccount, isSigner: false, isWritable: true },\n { pubkey: vaultPDA, isSigner: false, isWritable: true },\n { pubkey: channelPDA, isSigner: false, isWritable: true },\n { pubkey: TOKEN_PROGRAM_ID, isSigner: false, isWritable: false },\n ],\n data: depositData,\n },\n ]);\n return { depositTxSignature };\n}\n\n// Internal helpers exported for unit tests (parity assertions).\nexport const __testing = { padTo32, sortPubkeys, isOnCurve };\n","import { privateKeyToAccount, type PrivateKeyAccount } from 'viem/accounts';\nimport { type Hex, toHex } from 'viem';\nimport type { BalanceProofParams, SignedBalanceProof } from '../types.js';\n// Types re-exported for convenience\nexport type { ClaimMessage } from './types.js';\n\n/**\n * EVM claim message for BTP protocol data.\n * Matches @toon-protocol/connector's EVMClaimMessage interface.\n *\n * The connector's validateClaimMessage() requires envelope fields\n * (version, messageId, timestamp) plus EVM claim fields, and optionally\n * chainId + tokenNetworkAddress for self-describing signature verification.\n */\nexport interface EVMClaimMessage {\n version: '1.0';\n blockchain: 'evm';\n messageId: string;\n timestamp: string;\n senderId: string;\n channelId: string;\n nonce: number;\n transferredAmount: string;\n lockedAmount: string;\n locksRoot: string;\n signature: string;\n signerAddress: string;\n /** Chain ID for self-describing EIP-712 verification */\n chainId: number;\n /** TokenNetwork address for self-describing EIP-712 verification */\n tokenNetworkAddress: string;\n /** ERC-20 token address for self-describing claim verification */\n tokenAddress?: string;\n}\n\n/**\n * EIP-712 domain for TokenNetwork balance proofs.\n * Must match connector's eip712-helper.js getDomainSeparator().\n */\nfunction getBalanceProofDomain(chainId: number, tokenNetworkAddress: string) {\n return {\n name: 'TokenNetwork' as const,\n version: '1' as const,\n chainId,\n verifyingContract: tokenNetworkAddress as Hex,\n };\n}\n\n/**\n * EIP-712 types for balance proofs.\n * Must match connector's eip712-helper.js getBalanceProofTypes().\n */\nconst BALANCE_PROOF_TYPES = {\n BalanceProof: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'nonce', type: 'uint256' },\n { name: 'transferredAmount', type: 'uint256' },\n { name: 'lockedAmount', type: 'uint256' },\n { name: 'locksRoot', type: 'bytes32' },\n ],\n} as const;\n\n/**\n * EVM signer for EIP-712 balance proofs and on-chain transactions.\n *\n * Encapsulates the private key — no getPrivateKey() method is exposed.\n */\nexport class EvmSigner {\n readonly chainType = 'evm' as const;\n private readonly _account: PrivateKeyAccount;\n\n /**\n * @param privateKey - EVM private key as hex string (with or without 0x prefix) or Uint8Array\n */\n constructor(privateKey: string | Uint8Array) {\n let hexKey: Hex;\n if (privateKey instanceof Uint8Array) {\n hexKey = toHex(privateKey);\n } else {\n hexKey = (\n privateKey.startsWith('0x') ? privateKey : `0x${privateKey}`\n ) as Hex;\n }\n this._account = privateKeyToAccount(hexKey);\n }\n\n /** Derived 0x EVM address */\n get address(): string {\n return this._account.address;\n }\n\n /** ChainSigner identifier — EVM address */\n get signerIdentifier(): string {\n return this._account.address;\n }\n\n /** Viem PrivateKeyAccount — usable with walletClient for on-chain transactions */\n get account(): PrivateKeyAccount {\n return this._account;\n }\n\n /**\n * Signs a balance proof using EIP-712 typed data.\n *\n * @param params - Balance proof parameters plus chain context\n * @returns Signed balance proof with signature\n */\n async signBalanceProof(\n params: BalanceProofParams & {\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n }\n ): Promise<SignedBalanceProof> {\n const domain = getBalanceProofDomain(\n params.chainId,\n params.tokenNetworkAddress\n );\n\n const signature = await this._account.signTypedData({\n domain,\n types: BALANCE_PROOF_TYPES,\n primaryType: 'BalanceProof',\n message: {\n channelId: params.channelId as Hex,\n nonce: BigInt(params.nonce),\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot as Hex,\n },\n });\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature,\n signerAddress: this._account.address,\n chainId: params.chainId,\n tokenNetworkAddress: params.tokenNetworkAddress,\n ...(params.tokenAddress && { tokenAddress: params.tokenAddress }),\n };\n }\n\n /**\n * Builds an EVMClaimMessage from a signed balance proof.\n * Static so it can be called without an EvmSigner instance.\n *\n * @param proof - Signed balance proof (includes chainId and tokenNetworkAddress)\n * @param senderId - Nostr pubkey or identifier of the sender\n * @returns EVMClaimMessage compatible with BTP_CLAIM_PROTOCOL\n */\n static buildClaimMessage(\n proof: SignedBalanceProof,\n senderId: string\n ): EVMClaimMessage {\n return {\n version: '1.0',\n blockchain: 'evm',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n channelId: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n lockedAmount: proof.lockedAmount.toString(),\n locksRoot: proof.locksRoot,\n signature: proof.signature,\n signerAddress: proof.signerAddress,\n chainId: proof.chainId,\n tokenNetworkAddress: proof.tokenNetworkAddress,\n ...(proof.tokenAddress && { tokenAddress: proof.tokenAddress }),\n };\n }\n}\n","import { ed25519 } from '@noble/curves/ed25519.js';\nimport { base58Encode } from '@toon-protocol/core';\nimport type { SignedBalanceProof } from '../types.js';\nimport type {\n ChainSigner,\n ChainMetadata,\n ClaimMessage,\n SolanaClaimMessage,\n} from './types.js';\nimport { toHex as bytesToHex } from '../utils/binary.js';\nimport { buildBalanceProofMessage } from '../channel/solana-payment-channel.js';\n\n/**\n * Solana signer for the connector payment-channel claim path.\n *\n * Signs the connector's on-chain payment-channel balance-proof message — the\n * raw 48-byte `channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)` (see\n * `@toon-protocol/connector` `SolanaPaymentChannelSDK._buildBalanceProofMessage`\n * + `solana-payment-channel-provider.verifyBalanceProof`). The produced 64-byte\n * Ed25519 signature verifies on the connector's `verifySolanaClaim` path, which\n * is what makes a client-issued Solana payment-channel claim (paying the apex\n * to write) acceptable on connector 3.9.0.\n *\n * NOTE: this is a DIFFERENT message from the swap peer ↔ sender swap-claim wire\n * contract (`balanceProofHashSolana`, SDK `verifyEd25519Signature`). The client\n * here is paying a payment-channel claim to the apex, not issuing a swap claim,\n * so it must sign the connector's on-chain payment-channel message. `channelId`\n * MUST be the base58 channel PDA (produced by `OnChainChannelClient.openChannel`).\n */\nexport class SolanaSigner implements ChainSigner {\n readonly chainType = 'solana' as const;\n /** 32-byte Ed25519 seed. */\n private readonly privateKey: Uint8Array;\n private pubkeyBase58Cache?: string;\n\n /**\n * @param privateKey - 32-byte Ed25519 seed (e.g. `identity.solana.secretKey.slice(0, 32)`).\n * @param publicKeyBase58 - Optional base58 public key (e.g. `identity.solana.publicKey`).\n * When omitted it is derived lazily from `privateKey`.\n */\n constructor(privateKey: Uint8Array, publicKeyBase58?: string) {\n if (privateKey.length !== 32) {\n throw new Error(\n `SolanaSigner requires a 32-byte Ed25519 seed, got ${privateKey.length} bytes`\n );\n }\n this.privateKey = privateKey;\n this.pubkeyBase58Cache = publicKeyBase58;\n }\n\n private ensurePublicKey(): string {\n if (this.pubkeyBase58Cache) return this.pubkeyBase58Cache;\n const pk = ed25519.getPublicKey(this.privateKey);\n this.pubkeyBase58Cache = base58Encode(new Uint8Array(pk));\n return this.pubkeyBase58Cache;\n }\n\n get signerIdentifier(): string {\n return this.pubkeyBase58Cache ?? 'uninitialized';\n }\n\n async signBalanceProof(params: {\n channelId: string;\n nonce: number;\n transferredAmount: bigint;\n lockedAmount: bigint;\n locksRoot: string;\n recipient: string;\n metadata: ChainMetadata;\n }): Promise<SignedBalanceProof> {\n if (params.metadata.chainType !== 'solana') {\n throw new Error(\n `SolanaSigner cannot sign for chain type: ${params.metadata.chainType}`\n );\n }\n\n const base58 = this.ensurePublicKey();\n\n // Connector on-chain payment-channel balance-proof message:\n // channel_pda(32) || nonce(8 LE) || transferredAmount(8 LE)\n // `channelId` is the base58 channel PDA (from OnChainChannelClient.openChannel).\n // cumulativeAmount == transferredAmount. No recipient term — the connector's\n // verifyBalanceProof reconstructs exactly these three fields.\n const message = buildBalanceProofMessage(\n params.channelId,\n BigInt(params.nonce),\n params.transferredAmount\n );\n\n const signature = ed25519.sign(message, this.privateKey);\n const signatureHex = '0x' + bytesToHex(new Uint8Array(signature));\n\n return {\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n signature: signatureHex,\n signerAddress: base58,\n chainId: 0,\n tokenNetworkAddress: params.metadata.programId,\n recipient: params.recipient,\n };\n }\n\n buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage {\n // The connector verifies a base64 Ed25519 signature; the signed proof carries\n // a 0x-prefixed 64-byte hex signature, so convert hex -> bytes -> base64.\n const sigHex = proof.signature.startsWith('0x')\n ? proof.signature.slice(2)\n : proof.signature;\n const sigBytes = Uint8Array.from(\n sigHex.match(/.{1,2}/g)?.map((b) => parseInt(b, 16)) ?? []\n );\n const signatureBase64 = Buffer.from(sigBytes).toString('base64');\n\n const claim: SolanaClaimMessage = {\n version: '1.0',\n blockchain: 'solana',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n // channelId IS the base58 channel PDA -> connector's channelAccount.\n channelAccount: proof.channelId,\n nonce: proof.nonce,\n transferredAmount: proof.transferredAmount.toString(),\n signature: signatureBase64,\n signerPublicKey: this.pubkeyBase58Cache ?? proof.signerAddress,\n programId: proof.tokenNetworkAddress,\n };\n return claim;\n }\n}\n","import { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { bytesToHex } from '@noble/hashes/utils.js';\nimport type { SignedBalanceProof } from '../types.js';\nimport type {\n ChainSigner,\n ChainMetadata,\n ClaimMessage,\n MinaClaimMessage,\n} from './types.js';\nimport {\n buildMinaPaymentChannelProof,\n loadMinaPaymentChannelBindings,\n} from '../channel/mina-payment-channel.js';\nimport { readMinaDepositTotal } from '../channel/mina-deposit.js';\n\n/** Reads a channel zkApp's on-chain `depositTotal` (base units). */\nexport type MinaDepositReader = (zkAppAddress: string) => Promise<bigint>;\n\n/** Optional `MinaSigner` wiring for on-chain `depositTotal` resolution. */\nexport interface MinaSignerOptions {\n /**\n * Mina GraphQL URL used to read the channel's on-chain `depositTotal` when a\n * caller doesn't supply it to `signBalanceProof`. Enables conserved\n * `balanceB = depositTotal − balanceA` claims (settleable on funded zkApps).\n */\n graphqlUrl?: string;\n /** Inject a deposit reader (tests / custom transport). Overrides `graphqlUrl`. */\n depositReader?: MinaDepositReader;\n}\n\n/** Default Mina token id when the metadata omits one. */\nconst DEFAULT_MINA_TOKEN_ID = 'MINA';\n\n/** Mina network id carried in the claim (matches the connector devnet prefix). */\nconst MINA_CLAIM_NETWORK = 'devnet' as const;\n\n/**\n * Pallas base-field-safe salt derived from `(zkAppAddress, nonce)`.\n *\n * The commitment binds an arbitrary salt; we derive it deterministically so the\n * same (channel, nonce) reproduces the same proof, and take the first 240 bits\n * of `sha256` to stay safely inside the Pallas field (< 2^254). Non-zero by\n * construction (connector `validateMinaClaim` requires a non-empty `salt`).\n */\nexport function deriveMinaSalt(zkAppAddress: string, nonce: number): bigint {\n const digestHex = bytesToHex(\n sha256(new TextEncoder().encode(`mina-pc-salt:${zkAppAddress}:${nonce}`))\n );\n const salt = BigInt('0x' + digestHex.slice(0, 60));\n return salt === 0n ? 1n : salt;\n}\n\n/**\n * Mina (Pallas) signer for the connector payment-channel claim path.\n *\n * Produces the connector 3.9.0 `MinaClaimMessage` contract — `{ zkAppAddress,\n * tokenId, balanceCommitment, proof (base64), salt, nonce }` — by reproducing\n * `MinaPaymentChannelSDK.signBalanceProof` exactly (via\n * {@link buildMinaPaymentChannelProof}):\n *\n * commitment = Poseidon([Field(balanceA), Field(0), Field(salt)])\n * channelHashField = Poseidon([participantA.x, participantB.x, 0]) (see below)\n * proof = base64(JSON{ commitment, signature: { r, s }, nonce, signerPublicKey })\n *\n * with the Schnorr signature computed over `[commitment, Field(nonce),\n * channelHashField]` using the Mina `'devnet'` network id (matching o1js's\n * hardcoded `Signature.create` prefix). Verified field-by-field against the\n * connector's o1js `Signature.fromJSON({r,s}).verify` (see the package tests).\n *\n * `channelHashField` is the ON-CHAIN participant form\n * (`Poseidon([client.x, apex.x, 0])`, participantA=client, participantB=apex)\n * whenever the apex's Mina pubkey is known (the negotiated `recipient`), so the\n * claim can SETTLE on-chain via the zkApp's `claimFromChannel` (which only\n * verifies the participant form). When the apex pubkey is unavailable the signer\n * falls back to the legacy zkApp-x form (`Poseidon([zkApp.x])`); the connector's\n * off-chain `verifyBalanceProof` accepts EITHER, so off-chain store/FULFILL works\n * in both cases — only on-chain settle requires the participant form.\n *\n * NOTE: this is a DIFFERENT message + format from the swap peer ↔ sender swap-claim\n * wire contract (`balanceProofFieldsMina` in `@toon-protocol/core`, verified by\n * the SDK's `verifyMinaSignature`). The client here pays a payment-channel claim\n * to the apex, so it signs the connector's on-chain payment-channel scheme; the\n * swap-format hash is left untouched (mirrors the Solana #105 separation).\n *\n * `channelId` MUST be the deployed payment-channel zkApp B62 address (the same\n * address the apex's Mina provider resolves on-chain via `getChannelState`),\n * which is what `OnChainChannelClient.openMinaChannel` returns.\n *\n * `mina-signer` is an OPTIONAL dependency: its crypto (Poseidon, Pallas Schnorr,\n * the base58 signature codec) is loaded dynamically so the client builds and runs\n * for non-Mina users without it installed, and WITHOUT pulling the o1js WASM\n * circuit runtime.\n */\nexport class MinaSigner implements ChainSigner {\n readonly chainType = 'mina' as const;\n /** Big-endian hex scalar (or already-`EK…` base58) Mina private key. */\n private readonly privateKey: string;\n private publicKeyBase58?: string;\n private readonly depositReader?: MinaDepositReader;\n /** Per-zkApp `depositTotal` cache (deposits are rare; the connector re-reads). */\n private readonly depositCache = new Map<string, bigint>();\n\n /**\n * @param privateKey - Mina private key as big-endian hex scalar (the form\n * `deriveFullIdentity()` emits, `identity.mina.privateKey`) or an `EK…`\n * base58 key. Converted to the base58check form mina-signer requires.\n * @param publicKeyBase58 - Optional base58 public key (e.g.\n * `identity.mina.publicKey`). When omitted it is derived during signing.\n * @param options - Optional on-chain `depositTotal` resolution (graphqlUrl or\n * an injected reader) so claims conserve balances on funded zkApps.\n */\n constructor(\n privateKey: string,\n publicKeyBase58?: string,\n options?: MinaSignerOptions\n ) {\n this.privateKey = privateKey;\n this.publicKeyBase58 = publicKeyBase58;\n if (options?.depositReader) {\n this.depositReader = options.depositReader;\n } else if (options?.graphqlUrl) {\n const url = options.graphqlUrl;\n this.depositReader = (zkAppAddress) =>\n readMinaDepositTotal(url, zkAppAddress);\n }\n }\n\n /**\n * Resolve the channel's on-chain `depositTotal`, caching per zkApp. Returns\n * `undefined` when no reader is configured or the read fails — callers then\n * fall back to the legacy `balanceB = 0` commitment.\n */\n private async resolveDepositTotal(\n zkAppAddress: string\n ): Promise<bigint | undefined> {\n if (this.depositCache.has(zkAppAddress)) {\n return this.depositCache.get(zkAppAddress);\n }\n if (!this.depositReader) return undefined;\n try {\n const depositTotal = await this.depositReader(zkAppAddress);\n this.depositCache.set(zkAppAddress, depositTotal);\n return depositTotal;\n } catch {\n return undefined;\n }\n }\n\n get signerIdentifier(): string {\n return this.publicKeyBase58 ?? 'uninitialized';\n }\n\n /** Derive this signer's B62 public key from its (base58) private key. */\n private async deriveOwnPublicKey(\n minaPrivateKeyBase58: string\n ): Promise<string> {\n const { Client } = await loadMinaPaymentChannelBindings();\n return new Client({ network: MINA_CLAIM_NETWORK }).derivePublicKey(\n minaPrivateKeyBase58\n );\n }\n\n async signBalanceProof(params: {\n channelId: string;\n nonce: number;\n transferredAmount: bigint;\n lockedAmount: bigint;\n locksRoot: string;\n recipient: string;\n metadata: ChainMetadata;\n /**\n * On-chain channel `depositTotal`. When provided (>0), the signed commitment\n * binds `balanceB = depositTotal − balanceA` (the funder's remaining\n * balance), matching the connector's claimFromChannel reconstruction\n * (toon-protocol/connector#133) and the on-chain circuit's\n * `balanceA + balanceB == depositTotal` invariant. Omitted/0 keeps the\n * legacy `balanceB = 0` form (off-chain-store-only, non-settleable).\n */\n depositTotal?: bigint;\n }): Promise<SignedBalanceProof> {\n if (params.metadata.chainType !== 'mina') {\n throw new Error(\n `MinaSigner cannot sign for chain type: ${params.metadata.chainType}`\n );\n }\n\n // The zkApp address IS the channel id: it is the channel-hash preimage the\n // connector binds the proof to and the on-chain account it reads. Prefer the\n // negotiated channelId, fall back to the metadata zkAppAddress.\n const zkAppAddress = params.channelId || params.metadata.zkAppAddress;\n if (!zkAppAddress) {\n throw new Error(\n 'MinaSigner requires a zkAppAddress (channel id) to sign a balance proof'\n );\n }\n\n const minaPrivateKey = hexToMinaBase58PrivateKey(this.privateKey);\n const tokenId = params.metadata.tokenId ?? DEFAULT_MINA_TOKEN_ID;\n const salt = deriveMinaSalt(zkAppAddress, params.nonce);\n\n // Derive the client's own Mina pubkey now (needed as participantA for the\n // on-chain channelHash). `buildMinaPaymentChannelProof` derives it too, but\n // we need it here to pass the participant pair.\n const clientPubKey =\n this.publicKeyBase58 ?? (await this.deriveOwnPublicKey(minaPrivateKey));\n this.publicKeyBase58 = clientPubKey;\n\n // The apex's Mina settlement pubkey (B62) is the channel counterparty\n // (participantB). It flows through as the negotiated recipient. When present,\n // sign over the on-chain participant-form channelHash so the claim can SETTLE\n // on-chain (the zkApp's claimFromChannel verifies sigA over\n // Poseidon([client.x, apex.x, 0])). Order matches the open:\n // participantA = client (payer), participantB = apex (peer).\n const apexPubKey =\n params.recipient && /^B62[a-zA-Z0-9]{40,60}$/.test(params.recipient)\n ? params.recipient\n : undefined;\n\n // Conserved counterparty balance for the signed commitment. The on-chain\n // PaymentChannel.claimFromChannel circuit verifies signatureA over\n // Poseidon([balanceA, balanceB, salt]) AND asserts balanceA + balanceB ==\n // depositTotal. The connector reconstructs balanceB = depositTotal − balanceA\n // from the public on-chain depositTotal (toon-protocol/connector#133), so the\n // CLIENT must sign over that same balanceB or signatureA fails verification\n // (\"participant A signature verification failed\") at proof generation. When\n // depositTotal is unknown (legacy/off-chain-only), fall back to balanceB = 0.\n // Prefer a caller-supplied depositTotal; otherwise self-resolve it from\n // chain (when this signer was configured with a graphqlUrl / reader) so the\n // claim conserves balances on a FUNDED zkApp. Falls back to balanceB = 0\n // (legacy, off-chain-store-only) when neither is available.\n const depositTotal =\n params.depositTotal ?? (await this.resolveDepositTotal(zkAppAddress));\n let balanceB = 0n;\n if (depositTotal != null && depositTotal > 0n) {\n if (params.transferredAmount > depositTotal) {\n throw new Error(\n `Mina claim balanceA (${params.transferredAmount}) exceeds on-chain ` +\n `depositTotal (${depositTotal}) — cannot conserve balances`\n );\n }\n balanceB = depositTotal - params.transferredAmount;\n }\n\n const built = await buildMinaPaymentChannelProof({\n zkAppAddress,\n minaPrivateKeyBase58: minaPrivateKey,\n signerPublicKey: clientPubKey,\n // Recipient-credit (unidirectional): party A carries the cumulative amount;\n // party B carries the funder's remaining balance (depositTotal − balanceA)\n // so the signed commitment conserves and the on-chain claimFromChannel\n // signatureA check passes. `signatureB` remains apex-co-signed downstream.\n balanceA: params.transferredAmount,\n balanceB,\n salt,\n nonce: BigInt(params.nonce),\n // Participant-form channelHash (on-chain-settleable) when the apex pubkey\n // is known; otherwise the legacy zkApp-x form (off-chain-store only).\n ...(apexPubKey\n ? { participantA: clientPubKey, participantB: apexPubKey }\n : {}),\n });\n this.publicKeyBase58 = built.signerPublicKey;\n\n return {\n channelId: zkAppAddress,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n // `signature` is unused on the Mina wire (the proof carries the Schnorr\n // signature); keep the base64 proof here too for symmetry / debugging.\n signature: built.proof,\n signerAddress: built.signerPublicKey,\n chainId: 0,\n tokenNetworkAddress: zkAppAddress,\n recipient: params.recipient,\n mina: {\n balanceCommitment: built.balanceCommitment,\n proof: built.proof,\n salt: built.salt,\n tokenId,\n },\n };\n }\n\n buildClaimMessage(proof: SignedBalanceProof, senderId: string): ClaimMessage {\n if (!proof.mina) {\n throw new Error(\n 'MinaSigner.buildClaimMessage requires a Mina-signed proof (missing `mina` fields)'\n );\n }\n const claim: MinaClaimMessage = {\n version: '1.0',\n blockchain: 'mina',\n messageId: crypto.randomUUID(),\n timestamp: new Date().toISOString().replace(/\\.\\d{3}Z$/, '.000Z'),\n senderId,\n zkAppAddress: proof.channelId,\n tokenId: proof.mina.tokenId,\n balanceCommitment: proof.mina.balanceCommitment,\n nonce: proof.nonce,\n proof: proof.mina.proof,\n salt: proof.mina.salt,\n transferredAmount: proof.transferredAmount.toString(),\n // Surface the signer's Mina pubkey top-level (it is also embedded in the\n // base64 `proof`). The connector's SettlementExecutor reads\n // `latestClaim.signerPublicKey` to resolve participant keys for the\n // on-chain claimFromChannel on an inbound/externally-opened channel;\n // without it the Mina SDK throws ACCOUNT_NOT_FOUND. `signerAddress`\n // carries the B62 base58 pubkey for Mina proofs (see MinaSigner.sign*).\n signerPublicKey: proof.signerAddress,\n network: MINA_CLAIM_NETWORK,\n };\n return claim;\n }\n}\n","/**\n * Mina payment-channel primitives — connector-parity.\n *\n * Pure, dependency-light helpers that reproduce the EXACT off-chain\n * balance-proof contract the connector's `MinaPaymentChannelSDK`\n * (`@toon-protocol/connector` `settlement/mina-payment-channel-sdk.ts`)\n * implements, so a client-issued Mina payment-channel claim is structurally\n * accepted by connector 3.9.0's `validateMinaClaim` PREPARE gate and (once the\n * connector's proof-encoding bug is fixed, see below) verified by its\n * `verifyMinaClaim` / `verifyBalanceProof` settlement path.\n *\n * ## The connector's payment-channel scheme (authoritative, from 3.9.0 dist)\n *\n * `MinaPaymentChannelSDK.signBalanceProof(channel, balA, balB, salt, nonce)`:\n *\n * commitment = Poseidon.hash([Field(balA), Field(balB), Field(salt)])\n * channelHashField = Poseidon.hash([PublicKey.fromBase58(zkAppAddress).x])\n * message = [commitment, Field(nonce), channelHashField]\n * signature = Signature.create(privKey, message) // Schnorr, Pallas\n * proof (string) = JSON.stringify({\n * commitment: commitment.toString(),\n * signature: { r, s }, // o1js JSON form\n * nonce: nonce.toString(),\n * })\n *\n * `MinaPaymentChannelSDK.verifyBalanceProof(channel, balanceCommitment, proof, nonce)`\n * re-derives `channelHashField` from `channel`, parses `proof` as the JSON above,\n * checks `proof.commitment === balanceCommitment` and `BigInt(proof.nonce) === nonce`,\n * then `Signature.fromJSON({r,s}).verify(signerPubKey, [commitment, Field(nonce),\n * channelHashField])`. The signer prefix is HARDCODED to `'devnet'` inside o1js\n * `Signature.create` / `.verify`, so the off-chain signature MUST be produced\n * with the Mina `'devnet'` network id (NOT `'mainnet'`).\n *\n * This is DISTINCT from the swap peer ↔ sender swap-claim wire contract\n * (`balanceProofFieldsMina` in `@toon-protocol/core` — a Schnorr signature over\n * `[minaHashToField(channelId), amount, nonce, minaHashToField(recipient)]`).\n * That format is unchanged; this module is the separate payment-channel path\n * (mirrors the Solana #105 precedent: a payment-channel-specific message\n * distinct from the swap-format hash).\n *\n * ## Why mina-signer (not o1js)\n *\n * Poseidon, the Pallas Schnorr signature, the base58 signature codec and the\n * Pallas `PublicKey` field decode are all shipped INSIDE `mina-signer` (the same\n * implementations o1js re-exports). We reach them via a file-URL deep import off\n * the resolved `mina-signer` package root, so the client reproduces the\n * connector's scheme byte-for-byte WITHOUT pulling the multi-hundred-MB o1js\n * WASM circuit runtime. `mina-signer` is an OPTIONAL dependency.\n *\n * ## ⚠️ Connector 3.9.0 proof-encoding bug (documented, NOT worked around here)\n *\n * `validateMinaClaim` requires `claim.proof` to match `/^[A-Za-z0-9+/]+=*$/`\n * (base64), but `verifyBalanceProof` (and the connector's OWN claim producer\n * `per-packet-claim-service`) treat `proof` as RAW JSON (`JSON.parse(proof)` with\n * no base64 decode — and the connector emits the raw `JSON.stringify(...)` above).\n * Raw JSON fails the base64 regex, so a raw-JSON proof is REJECTED at the PREPARE\n * gate (no FULFILL). To pass the PREPARE gate (the FULFILL-deciding path) the\n * client MUST base64-encode the proof JSON. The connector's settlement-side\n * `JSON.parse` then fails on the base64 string — but that is post-FULFILL and is\n * the connector's own inconsistency (its producer and consumer disagree with its\n * validator). For non-EVM dynamic hidden-service peers settlement is gated by\n * connector#88 (`No chain configured for peer`) regardless, so this is a\n * documented connector follow-up, not a client defect. See\n * {@link buildMinaPaymentChannelProof} `proofEncoding`.\n *\n * @module\n */\n\n/** Result of building a connector-parity Mina payment-channel proof. */\nexport interface MinaPaymentChannelProof {\n /** `Poseidon([balanceA, balanceB, salt]).toString()` — the claim's `balanceCommitment`. */\n balanceCommitment: string;\n /**\n * The claim's `proof` field: base64-encoded JSON\n * `{ commitment, signature: { r, s }, nonce, signerPublicKey }`. Base64 is\n * REQUIRED to pass connector 3.9.0 `validateMinaClaim` (see module note).\n */\n proof: string;\n /** Decimal salt string — the claim's `salt` field. */\n salt: string;\n /** Base58 signer public key — echoed for convenience. */\n signerPublicKey: string;\n}\n\ninterface MinaSignerClientLike {\n signFields(fields: bigint[], privateKey: string): { signature: string };\n derivePublicKey(privateKey: string): string;\n}\ntype MinaSignerClientCtor = new (opts: {\n network: string;\n}) => MinaSignerClientLike;\n\ninterface PoseidonLike {\n hash(input: bigint[]): bigint;\n}\ninterface SignatureCodecLike {\n fromBase58(base58: string): { r: bigint; s: bigint };\n}\ninterface PublicKeyCodecLike {\n fromBase58(base58: string): { x: bigint; y: bigint };\n}\n\ninterface MinaCryptoBindings {\n Client: MinaSignerClientCtor;\n Poseidon: PoseidonLike;\n Signature: SignatureCodecLike;\n PublicKey: PublicKeyCodecLike;\n}\n\nlet cachedBindings: MinaCryptoBindings | null = null;\n\n/**\n * Resolve the `mina-signer` package and load both its public `Client` and the\n * internal Poseidon / Signature / PublicKey codecs via file-URL deep import.\n *\n * `mina-signer`'s `package.json` `exports` map does NOT expose its\n * `bindings/crypto/poseidon.js` or `mina-signer/src/{signature,curve-bigint}.js`\n * subpaths, so a bare-specifier deep import (`import('mina-signer/.../poseidon.js')`)\n * is blocked (`ERR_PACKAGE_PATH_NOT_EXPORTED`). Node only applies the exports\n * gate to bare specifiers, NOT to `file://` URLs — so we resolve the main entry\n * to a URL and navigate to the sibling internal files. These are the same\n * implementations o1js ships; reaching them here gives byte-for-byte parity with\n * the connector's o1js verify without the o1js WASM runtime.\n */\nexport async function loadMinaPaymentChannelBindings(): Promise<MinaCryptoBindings> {\n if (cachedBindings) return cachedBindings;\n\n const specifier = 'mina-signer';\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const lib: any = await import(/* @vite-ignore */ specifier);\n const Client: MinaSignerClientCtor = 'default' in lib ? lib.default : lib;\n\n // Resolve the main entry to a file URL, then navigate to the internal modules.\n // mina-signer main: <root>/dist/node/mina-signer/mina-signer.js\n //\n // import.meta.resolve is unavailable under some module transforms (notably\n // vitest's SSR, which replaces import.meta and drops `.resolve` → throws\n // \"__vite_ssr_import_meta__.resolve is not a function\"). Fall back to Node's\n // createRequire().resolve and convert to a file URL. Both the ESM and CJS\n // entries live in dist/node/mina-signer/, so the relative navigation below is\n // identical either way.\n const resolveFn = (import.meta as { resolve?: (specifier: string) => string })\n .resolve;\n let mainUrl: string;\n if (typeof resolveFn === 'function') {\n mainUrl = resolveFn(specifier);\n } else {\n const { createRequire } = await import('node:module');\n const { pathToFileURL } = await import('node:url');\n mainUrl = pathToFileURL(\n createRequire(import.meta.url).resolve(specifier)\n ).href;\n }\n const minaSignerDir = new URL('./', mainUrl); // .../dist/node/mina-signer/\n const poseidonUrl = new URL('../bindings/crypto/poseidon.js', minaSignerDir)\n .href;\n const signatureUrl = new URL('./src/signature.js', minaSignerDir).href;\n const curveUrl = new URL('./src/curve-bigint.js', minaSignerDir).href;\n\n const [poseidonMod, signatureMod, curveMod] = await Promise.all([\n import(/* @vite-ignore */ poseidonUrl),\n import(/* @vite-ignore */ signatureUrl),\n import(/* @vite-ignore */ curveUrl),\n ]);\n\n cachedBindings = {\n Client,\n Poseidon: poseidonMod.Poseidon as PoseidonLike,\n Signature: signatureMod.Signature as SignatureCodecLike,\n PublicKey: curveMod.PublicKey as PublicKeyCodecLike,\n };\n return cachedBindings;\n}\n\n/** Reset the cached bindings (test hook). */\nexport function _resetMinaBindingsCache(): void {\n cachedBindings = null;\n}\n\n/**\n * Compute the connector's Mina balance commitment:\n * `Poseidon.hash([Field(balanceA), Field(balanceB), Field(salt)])`.\n */\nexport function minaBalanceCommitment(\n poseidon: PoseidonLike,\n balanceA: bigint,\n balanceB: bigint,\n salt: bigint\n): bigint {\n return poseidon.hash([balanceA, balanceB, salt]);\n}\n\n/**\n * Compute the connector's LEGACY channel-hash field, bound into the signed\n * message: `Poseidon.hash([PublicKey.fromBase58(zkAppAddress).x])`.\n *\n * This is the off-chain-only form. The connector's `verifyBalanceProof` accepts\n * a signature over EITHER this OR the participant form (see\n * {@link minaParticipantChannelHashField}), but the on-chain\n * `PaymentChannel.claimFromChannel` only accepts the PARTICIPANT form — so for a\n * claim that must SETTLE on-chain, sign the participant form instead.\n */\nexport function minaChannelHashField(\n poseidon: PoseidonLike,\n publicKeyCodec: PublicKeyCodecLike,\n zkAppAddress: string\n): bigint {\n const zkAppPubKey = publicKeyCodec.fromBase58(zkAppAddress);\n return poseidon.hash([zkAppPubKey.x]);\n}\n\n/**\n * Compute the ON-CHAIN channel-hash field the zkApp stores and verifies:\n * `Poseidon.hash([participantA.x, participantB.x, channelNonce])`.\n *\n * This MUST byte-for-byte reproduce what `PaymentChannel.initializeChannel`\n * wrote (`Poseidon([participantA.x, participantB.x, nonce])`, see\n * `packages/mina-zkapp/src/PaymentChannel.ts`) so that:\n * 1. the on-chain `claimFromChannel` signature check\n * (`signatureA.verify(participantA, [commitment, nonce, storedChannelHash])`)\n * passes, and\n * 2. the connector's off-chain `verifyBalanceProof` accepts it via its\n * on-chain-channelHash message branch.\n *\n * Participant ORDER must match how the channel was opened. The client opens with\n * `participantA = client (payer)`, `participantB = apex (peer)`\n * (`OnChainChannelClient.openMinaChannel` → `openMinaChannelOnChain`), so the\n * client signs `Poseidon([client.x, apex.x, 0])`. The connector tries both\n * orderings when reconstructing, so it resolves the matching one regardless.\n */\nexport function minaParticipantChannelHashField(\n poseidon: PoseidonLike,\n publicKeyCodec: PublicKeyCodecLike,\n participantA_B62: string,\n participantB_B62: string,\n channelNonce: bigint\n): bigint {\n const a = publicKeyCodec.fromBase58(participantA_B62);\n const b = publicKeyCodec.fromBase58(participantB_B62);\n return poseidon.hash([a.x, b.x, channelNonce]);\n}\n\n/**\n * Build a connector-parity Mina payment-channel balance proof.\n *\n * Reproduces `MinaPaymentChannelSDK.signBalanceProof` exactly: computes the\n * Poseidon balance commitment, the Poseidon channel-hash field, signs the\n * `[commitment, Field(nonce), channelHashField]` Pallas Schnorr message with the\n * `'devnet'` network id (matching o1js's hardcoded prefix), decodes the base58\n * signature to `{ r, s }` (o1js JSON form), and serializes\n * `{ commitment, signature: { r, s }, nonce, signerPublicKey }`.\n *\n * @param params.zkAppAddress Deployed payment-channel zkApp B62 address — the\n * claim's `zkAppAddress` AND the channel-hash preimage. MUST be the SAME\n * address the apex's Mina provider resolves on-chain.\n * @param params.minaPrivateKeyBase58 Signer's Mina `EK…` base58 private key.\n * @param params.balanceA Cumulative amount credited to the recipient (apex).\n * @param params.balanceB Counterparty balance (0 for the unidirectional\n * recipient-credit direction; `balanceB`/`signatureB` are OPTIONAL at\n * connector validation, so single-party suffices).\n * @param params.salt Commitment salt (bigint).\n * @param params.nonce Monotonic claim nonce.\n * @param params.proofEncoding `'base64'` (default) base64-encodes the proof JSON\n * so it passes connector 3.9.0 `validateMinaClaim`'s base64 regex (REQUIRED for\n * FULFILL). `'json'` emits the raw JSON the connector's `verifyBalanceProof`\n * actually parses (rejected at the PREPARE gate today; provided for forward\n * compatibility / tests once the connector's regex is fixed). See module note.\n */\nexport async function buildMinaPaymentChannelProof(params: {\n zkAppAddress: string;\n minaPrivateKeyBase58: string;\n signerPublicKey?: string;\n balanceA: bigint;\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n proofEncoding?: 'base64' | 'json';\n /**\n * Participant pubkeys (B62) of the on-chain channel. When BOTH are supplied,\n * the proof is signed over the ON-CHAIN participant-form channelHash\n * (`Poseidon([participantA.x, participantB.x, channelNonce])`) instead of the\n * legacy zkApp-x form, so the resulting claim can settle on-chain via the\n * zkApp's `claimFromChannel` (which only verifies the participant form). The\n * order MUST match how the channel was opened (participantA = client/payer,\n * participantB = apex/peer). The connector accepts EITHER form off-chain, so\n * this is strictly an enabler for the on-chain settle path.\n */\n participantA?: string;\n participantB?: string;\n /** Channel nonce baked into the on-chain channelHash (default 0). */\n channelNonce?: bigint;\n}): Promise<MinaPaymentChannelProof> {\n const { Client, Poseidon, Signature, PublicKey } =\n await loadMinaPaymentChannelBindings();\n\n // o1js `Signature.create`/`.verify` hardcode the 'devnet' prefix; the off-chain\n // signature must be produced with the matching mina-signer network id.\n const client = new Client({ network: 'devnet' });\n const signerPublicKey =\n params.signerPublicKey ??\n client.derivePublicKey(params.minaPrivateKeyBase58);\n\n const commitment = minaBalanceCommitment(\n Poseidon,\n params.balanceA,\n params.balanceB,\n params.salt\n );\n // Sign over the on-chain participant-form channelHash when both participants\n // are known (enables on-chain settle); otherwise fall back to the legacy\n // zkApp-x form (off-chain-store-only). Both are accepted by the connector's\n // verifyBalanceProof.\n const channelHashField =\n params.participantA && params.participantB\n ? minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n params.participantA,\n params.participantB,\n params.channelNonce ?? 0n\n )\n : minaChannelHashField(Poseidon, PublicKey, params.zkAppAddress);\n\n const message = [commitment, params.nonce, channelHashField];\n const signed = client.signFields(message, params.minaPrivateKeyBase58);\n // mina-signer `signFields` emits a base58 signature string; the connector\n // expects the o1js JSON `{ r, s }` decimal form, reachable by decoding the\n // base58 sig with the shared Pallas codec.\n const { r, s } = Signature.fromBase58(signed.signature);\n\n const proofObject = {\n commitment: commitment.toString(),\n signature: { r: r.toString(), s: s.toString() },\n nonce: params.nonce.toString(),\n signerPublicKey,\n };\n const proofJson = JSON.stringify(proofObject);\n const encoding = params.proofEncoding ?? 'base64';\n const proof =\n encoding === 'base64'\n ? Buffer.from(proofJson, 'utf8').toString('base64')\n : proofJson;\n\n return {\n balanceCommitment: commitment.toString(),\n proof,\n salt: params.salt.toString(),\n signerPublicKey,\n };\n}\n","/**\n * Read a Mina payment-channel zkApp's on-chain `depositTotal` via a plain\n * GraphQL query (no o1js / WASM). Used by {@link MinaSigner} to bind the\n * conserved `balanceB = depositTotal − balanceA` commitment that a FUNDED zkApp\n * requires (connector#133); without it the connector's `claimFromChannel`\n * verification rejects the claim with `F06 - Invalid zk-SNARK proof on claim`.\n *\n * The `PaymentChannel` zkApp app-state field order is\n * `[channelHash, balanceCommitment, nonceField, channelState, depositTotal, …]`\n * (see `mina-channel-open.ts`), so `depositTotal` is `zkappState[4]`.\n */\n\n/** GraphQL response shape (only the fields we read). */\ninterface AccountStateResponse {\n data?: { account?: { zkappState?: string[] | null } | null } | null;\n errors?: { message: string }[];\n}\n\n/**\n * `PaymentChannel` zkApp app-state field order (see `mina-channel-open.ts` and\n * the zkApp's `@state` declarations in `@toon-protocol/mina-zkapp`):\n * [0] channelHash, [1] balanceCommitment, [2] nonceField, [3] channelState,\n * [4] depositTotal, [5] closedAtSlot, [6] settlementTimeout, [7] tokenId_.\n */\nconst CHANNEL_STATE_INDEX = {\n channelHash: 0,\n balanceCommitment: 1,\n nonceField: 2,\n channelState: 3,\n depositTotal: 4,\n} as const;\n\nconst DEPOSIT_TOTAL_STATE_INDEX = CHANNEL_STATE_INDEX.depositTotal;\n\n/**\n * Query `account(publicKey).zkappState` and return the channel's `depositTotal`\n * (base units). Throws when the account/state is unavailable so callers can fall\n * back to the legacy `balanceB = 0` behavior.\n *\n * @param fetchImpl - injectable for tests; defaults to global `fetch`.\n */\nexport async function readMinaDepositTotal(\n graphqlUrl: string,\n zkAppAddress: string,\n fetchImpl: typeof fetch = fetch\n): Promise<bigint> {\n const query = 'query($pk:String!){account(publicKey:$pk){zkappState}}';\n const res = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: zkAppAddress } }),\n });\n if (!res.ok) {\n throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n }\n const json = (await res.json()) as AccountStateResponse;\n if (json.errors && json.errors.length > 0) {\n throw new Error(\n `Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`\n );\n }\n const state = json.data?.account?.zkappState;\n if (!state || state.length <= DEPOSIT_TOTAL_STATE_INDEX) {\n throw new Error(\n `Mina zkApp ${zkAppAddress} has no readable zkappState (account not found or not a zkApp)`\n );\n }\n return BigInt(state[DEPOSIT_TOTAL_STATE_INDEX] as string);\n}\n\n/** Channel-lifecycle enum written to `channelState` (matches the zkApp). */\nexport const MINA_CHANNEL_STATE = {\n UNINITIALIZED: 0,\n OPEN: 1,\n CLOSING: 2,\n SETTLED: 3,\n} as const;\n\n/**\n * On-chain `PaymentChannel` state the receive-side settler needs to assemble a\n * co-signed `claimFromChannel` — all read via plain GraphQL (NO o1js / WASM), so\n * the read path stays lightweight and unit-testable. Field semantics match\n * {@link MinaChannelState} in the connector's Mina SDK.\n */\nexport interface MinaOnChainChannelState {\n /** `Poseidon([participantA.x, participantB.x, channelNonce])`, decimal Field. */\n channelHash: string;\n /** Current `Poseidon([balanceA, balanceB, salt])`, decimal Field. */\n balanceCommitment: string;\n /** Highest claimed nonce recorded on-chain. */\n nonceField: bigint;\n /** {@link MINA_CHANNEL_STATE} enum value. */\n channelState: number;\n /** Total escrowed deposit (base units). */\n depositTotal: bigint;\n}\n\n/**\n * Read the channel's on-chain `PaymentChannel` state via GraphQL.\n *\n * Reuses the same `account(publicKey).zkappState` query as\n * {@link readMinaDepositTotal} and decodes the fields the co-signed\n * `claimFromChannel` assembly binds: `channelHash` (participant identity),\n * `depositTotal` (balance conservation), `nonceField` (monotonicity gate), and\n * `channelState` (must be OPEN). No o1js is loaded — the values are raw Field\n * decimal strings straight off the node.\n *\n * @param fetchImpl - injectable for tests; defaults to global `fetch`.\n */\nexport async function readMinaChannelState(\n graphqlUrl: string,\n zkAppAddress: string,\n fetchImpl: typeof fetch = fetch\n): Promise<MinaOnChainChannelState> {\n const query = 'query($pk:String!){account(publicKey:$pk){zkappState}}';\n const res = await fetchImpl(graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: zkAppAddress } }),\n });\n if (!res.ok) {\n throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n }\n const json = (await res.json()) as AccountStateResponse;\n if (json.errors && json.errors.length > 0) {\n throw new Error(\n `Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`\n );\n }\n const state = json.data?.account?.zkappState;\n if (!state || state.length <= DEPOSIT_TOTAL_STATE_INDEX) {\n throw new Error(\n `Mina zkApp ${zkAppAddress} has no readable zkappState (account not found or not a zkApp)`\n );\n }\n return {\n channelHash: String(state[CHANNEL_STATE_INDEX.channelHash]),\n balanceCommitment: String(state[CHANNEL_STATE_INDEX.balanceCommitment]),\n nonceField: BigInt(state[CHANNEL_STATE_INDEX.nonceField] as string),\n channelState: Number(state[CHANNEL_STATE_INDEX.channelState]),\n depositTotal: BigInt(state[CHANNEL_STATE_INDEX.depositTotal] as string),\n };\n}\n","import { EvmSigner } from '../signing/evm-signer.js';\nimport type { ChainSigner, ChainMetadata } from '../signing/types.js';\nimport type { SignedBalanceProof } from '../types.js';\nimport type { ChannelStore } from './ChannelStore.js';\nimport type { ConnectorChannelClient } from '@toon-protocol/core';\n\ninterface ChannelTracking {\n nonce: number;\n cumulativeAmount: bigint;\n chainType: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n /**\n * Counterparty settlement address on this channel's chain. Required to sign\n * Solana/Mina balance proofs (folded into the canonical message); unused for\n * the EVM EIP-712 path.\n */\n recipient?: string;\n /**\n * On-chain channel `depositTotal` (base units), captured at channel-open time\n * (#220). Threaded into the Mina signer so it binds `balanceB = depositTotal −\n * balanceA` (toon-protocol/connector#133); the Solana signer ignores it and\n * the EVM path never reads it. When unset (e.g. a channel RESUMED via\n * `trackChannel` rather than opened, or an idempotent re-open that didn't\n * surface it), the Mina signer self-resolves it from chain via its GraphQL URL\n * (#223).\n */\n depositTotal?: bigint;\n /** Withdraw flow (unix SECONDS): set when close is initiated / becomes settleable / settled. */\n closedAt?: bigint;\n settleableAt?: bigint;\n settledAt?: bigint;\n}\n\nexport interface ChannelManagerConfig {\n /**\n * Collateral (base units) locked on-chain by {@link ChannelManager.ensureChannel}\n * when it opens a channel, on every settlement chain. Default `'100000'`\n * (0.1 USDC at 6 decimals); a peer's negotiated `initialDeposit` wins over it.\n */\n initialDeposit?: string;\n settlementTimeout?: number;\n}\n\nexport interface PeerNegotiation {\n chain: string;\n chainType: string;\n chainId: number | string;\n settlementAddress: string;\n tokenAddress?: string;\n tokenNetwork?: string;\n initialDeposit?: string;\n settlementTimeout?: number;\n}\n\n/**\n * Local nonce tracking, multi-chain signing, and lazy channel opening.\n *\n * Supports multiple ChainSigner implementations (EVM, Solana, Mina).\n * The ensureChannel() method provides idempotent lazy channel opening.\n */\nexport class ChannelManager {\n private readonly channels = new Map<string, ChannelTracking>();\n private readonly chainSigners = new Map<string, ChainSigner>();\n private readonly peerChannels = new Map<string, string>();\n private readonly pendingOpens = new Map<string, Promise<string>>();\n private readonly store?: ChannelStore;\n private readonly defaultInitialDeposit: string;\n private readonly defaultSettlementTimeout: number;\n private channelClient?: ConnectorChannelClient;\n\n // Legacy: keep EvmSigner reference for backwards compatibility\n private readonly evmSigner?: EvmSigner;\n\n constructor(\n evmSigner?: EvmSigner,\n store?: ChannelStore,\n config?: ChannelManagerConfig\n ) {\n this.evmSigner = evmSigner;\n this.store = store;\n this.defaultInitialDeposit = config?.initialDeposit ?? '100000';\n this.defaultSettlementTimeout = config?.settlementTimeout ?? 86400;\n }\n\n /**\n * Register a chain-specific signer.\n */\n registerChainSigner(chainType: string, signer: ChainSigner): void {\n this.chainSigners.set(chainType, signer);\n }\n\n /**\n * Set the on-chain channel client for lazy channel opening.\n */\n setChannelClient(client: ConnectorChannelClient): void {\n this.channelClient = client;\n }\n\n /**\n * Get the signer for a tracked channel's chain type.\n * For EVM, returns an adapter wrapping the EvmSigner.\n */\n getSignerForChannel(channelId: string): ChainSigner {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n\n // Check non-EVM signers first\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer) return signer;\n\n // EVM: wrap EvmSigner as ChainSigner adapter\n if (tracking.chainType === 'evm' && this.evmSigner) {\n const evmSigner = this.evmSigner;\n return {\n chainType: 'evm' as const,\n signerIdentifier: evmSigner.address,\n async signBalanceProof(params) {\n if (params.metadata.chainType !== 'evm')\n throw new Error('Expected EVM metadata');\n return evmSigner.signBalanceProof({\n channelId: params.channelId,\n nonce: params.nonce,\n transferredAmount: params.transferredAmount,\n lockedAmount: params.lockedAmount,\n locksRoot: params.locksRoot,\n chainId: params.metadata.chainId,\n tokenNetworkAddress: params.metadata.tokenNetworkAddress,\n tokenAddress: params.metadata.tokenAddress,\n });\n },\n buildClaimMessage(proof, senderId) {\n return EvmSigner.buildClaimMessage(proof, senderId);\n },\n };\n }\n\n throw new Error(\n `No signer registered for chain type: ${tracking.chainType}`\n );\n }\n\n /**\n * Lazily open a channel for a peer. Idempotent — returns existing channel\n * if already open. Deduplicates concurrent opens for the same peer.\n */\n async ensureChannel(\n peerId: string,\n negotiation: PeerNegotiation\n ): Promise<string> {\n // Return existing channel\n const existing = this.peerChannels.get(peerId);\n if (existing) return existing;\n\n // Deduplicate concurrent opens\n const pending = this.pendingOpens.get(peerId);\n if (pending) return pending;\n\n if (!this.channelClient) {\n throw new Error(\n 'No channel client configured — cannot open payment channel'\n );\n }\n\n const openPromise = (async () => {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- channelClient checked in constructor\n const result = await this.channelClient!.openChannel({\n peerId,\n chain: negotiation.chain,\n token: negotiation.tokenAddress,\n tokenNetwork: negotiation.tokenNetwork,\n peerAddress: negotiation.settlementAddress,\n initialDeposit:\n negotiation.initialDeposit ?? this.defaultInitialDeposit,\n settlementTimeout:\n negotiation.settlementTimeout ?? this.defaultSettlementTimeout,\n });\n\n this.trackChannel(result.channelId, {\n chainType: negotiation.chainType,\n chainId:\n typeof negotiation.chainId === 'number' ? negotiation.chainId : 0,\n tokenNetworkAddress: negotiation.tokenNetwork ?? '',\n tokenAddress: negotiation.tokenAddress,\n recipient: negotiation.settlementAddress,\n // On-chain depositTotal (Mina only) — needed so the Mina signer binds\n // balanceB = depositTotal − balanceA (connector#133).\n depositTotal: result.depositTotal,\n });\n this.peerChannels.set(peerId, result.channelId);\n return result.channelId;\n } finally {\n this.pendingOpens.delete(peerId);\n }\n })();\n\n this.pendingOpens.set(peerId, openPromise);\n return openPromise;\n }\n\n /**\n * Get channel ID for a peer (if any).\n */\n getChannelForPeer(peerId: string): string | undefined {\n return this.peerChannels.get(peerId);\n }\n\n /**\n * Start tracking a channel.\n * Called after bootstrap returns a channelId.\n *\n * @param channelId - Payment channel identifier\n * @param chainContext - Chain context for signing (chainType + chainId + tokenNetworkAddress)\n * @param initialNonce - Starting nonce (default: 0)\n * @param initialAmount - Starting cumulative amount (default: 0n)\n */\n trackChannel(\n channelId: string,\n chainContext?: {\n chainType?: string;\n chainId: number;\n tokenNetworkAddress: string;\n tokenAddress?: string;\n recipient?: string;\n depositTotal?: bigint;\n },\n initialNonce = 0,\n initialAmount = 0n\n ): void {\n const cId = chainContext?.chainId ?? 31337;\n const tnAddr =\n chainContext?.tokenNetworkAddress ??\n '0x0000000000000000000000000000000000000000';\n\n // If store has persisted state for this channel, resume from it\n if (this.store) {\n const persisted = this.store.load(channelId);\n if (persisted) {\n this.channels.set(channelId, {\n nonce: persisted.nonce,\n cumulativeAmount: persisted.cumulativeAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n // Resume the withdraw-flow timers so a daemon restart mid-grace\n // doesn't strand funds (the gate can't be evaluated without them).\n ...(persisted.closedAt !== undefined\n ? { closedAt: persisted.closedAt }\n : {}),\n ...(persisted.settleableAt !== undefined\n ? { settleableAt: persisted.settleableAt }\n : {}),\n ...(persisted.settledAt !== undefined\n ? { settledAt: persisted.settledAt }\n : {}),\n });\n return;\n }\n }\n\n this.channels.set(channelId, {\n nonce: initialNonce,\n cumulativeAmount: initialAmount,\n chainType: chainContext?.chainType ?? 'evm',\n chainId: cId,\n tokenNetworkAddress: tnAddr,\n tokenAddress: chainContext?.tokenAddress,\n recipient: chainContext?.recipient,\n depositTotal: chainContext?.depositTotal,\n });\n }\n\n /**\n * Signs a balance proof for the given channel.\n * Auto-increments nonce and adds to cumulative amount.\n * Routes to the correct ChainSigner based on the channel's chain type.\n *\n * @param channelId - Payment channel identifier\n * @param additionalAmount - Amount to add to cumulative transferred amount\n * @returns Signed balance proof\n * @throws Error if channel is not being tracked\n */\n async signBalanceProof(\n channelId: string,\n additionalAmount: bigint\n ): Promise<SignedBalanceProof> {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(\n `Channel \"${channelId}\" is not being tracked. Call trackChannel() first.`\n );\n }\n\n tracking.nonce += 1;\n tracking.cumulativeAmount += additionalAmount;\n\n // Persist updated state (preserving any withdraw-flow timers).\n this.persist(channelId);\n\n // Route to appropriate signer for non-EVM chains\n const signer = this.chainSigners.get(tracking.chainType);\n if (signer && tracking.chainType !== 'evm') {\n if (!tracking.recipient) {\n throw new Error(\n `Channel \"${channelId}\" (${tracking.chainType}) has no recipient settlement address; ` +\n 'cannot sign a Solana/Mina balance proof. Ensure the peer negotiation supplied a settlementAddress.'\n );\n }\n const metadata = this.buildMetadata(tracking);\n return signer.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot:\n '0x0000000000000000000000000000000000000000000000000000000000000000',\n recipient: tracking.recipient,\n metadata,\n // On-chain depositTotal captured at open time (#220) — the Mina signer\n // binds balanceB = depositTotal − balanceA (connector#133); the Solana\n // signer ignores it. When undefined (resume / idempotent re-open) the\n // Mina signer self-resolves it from chain (#223).\n depositTotal: tracking.depositTotal,\n });\n }\n\n // EVM path (backwards compatible — uses EvmSigner directly)\n if (!this.evmSigner) {\n throw new Error('No EVM signer configured for EVM channel signing.');\n }\n return this.evmSigner.signBalanceProof({\n channelId,\n nonce: tracking.nonce,\n transferredAmount: tracking.cumulativeAmount,\n lockedAmount: 0n,\n locksRoot:\n '0x0000000000000000000000000000000000000000000000000000000000000000',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n });\n }\n\n private buildMetadata(tracking: ChannelTracking): ChainMetadata {\n switch (tracking.chainType) {\n case 'solana':\n return { chainType: 'solana', programId: tracking.tokenNetworkAddress };\n case 'mina':\n return {\n chainType: 'mina',\n zkAppAddress: tracking.tokenNetworkAddress,\n };\n default:\n return {\n chainType: 'evm',\n chainId: tracking.chainId,\n tokenNetworkAddress: tracking.tokenNetworkAddress,\n tokenAddress: tracking.tokenAddress,\n };\n }\n }\n\n /**\n * Gets the current nonce for a tracked channel.\n */\n getNonce(channelId: string): number {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.nonce;\n }\n\n /**\n * Gets the cumulative transferred amount for a tracked channel.\n */\n getCumulativeAmount(channelId: string): bigint {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.cumulativeAmount;\n }\n\n /**\n * Gets the on-chain deposit total (collateral locked at open / via deposits)\n * for a tracked channel, or `0n` when none was captured. The available\n * (spendable) balance is `depositTotal - cumulativeAmount`.\n */\n getDepositTotal(channelId: string): bigint {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n return tracking.depositTotal ?? 0n;\n }\n\n /**\n * Update the tracked on-chain deposit total after a successful deposit, so the\n * available balance (`depositTotal - cumulativeAmount`) reflects the new\n * collateral on the next read.\n */\n setDepositTotal(channelId: string, total: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.depositTotal = total;\n }\n\n /** Persist a channel's full nonce/amount + withdraw-timer state to the store. */\n private persist(channelId: string): void {\n if (!this.store) return;\n const t = this.channels.get(channelId);\n if (!t) return;\n this.store.save(channelId, {\n nonce: t.nonce,\n cumulativeAmount: t.cumulativeAmount,\n ...(t.closedAt !== undefined ? { closedAt: t.closedAt } : {}),\n ...(t.settleableAt !== undefined ? { settleableAt: t.settleableAt } : {}),\n ...(t.settledAt !== undefined ? { settledAt: t.settledAt } : {}),\n });\n }\n\n /**\n * Record that a channel was closed (withdraw flow): stores `closedAt` +\n * `settleableAt` (unix SECONDS) so the grace timer survives a daemon restart.\n */\n setChannelClosed(\n channelId: string,\n closedAt: bigint,\n settleableAt: bigint\n ): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.closedAt = closedAt;\n tracking.settleableAt = settleableAt;\n this.persist(channelId);\n }\n\n /** Record that a channel was settled (collateral released). */\n setChannelSettled(channelId: string, settledAt: bigint): void {\n const tracking = this.channels.get(channelId);\n if (!tracking) {\n throw new Error(`Channel \"${channelId}\" is not being tracked.`);\n }\n tracking.settledAt = settledAt;\n this.persist(channelId);\n }\n\n /** The `settleableAt` timestamp (unix seconds) for a closed channel, if set. */\n getSettleableAt(channelId: string): bigint | undefined {\n return this.channels.get(channelId)?.settleableAt;\n }\n\n /**\n * Where a channel sits in the withdraw journey, from the tracked timers:\n * `open` (never closed) → `closing` (closed, grace not elapsed) →\n * `settleable` (grace elapsed) → `settled`. `nowSec` is injectable for tests.\n */\n getChannelCloseState(\n channelId: string,\n nowSec = BigInt(Math.floor(Date.now() / 1000))\n ): 'open' | 'closing' | 'settleable' | 'settled' {\n const t = this.channels.get(channelId);\n if (!t || t.closedAt === undefined) return 'open';\n if (t.settledAt !== undefined) return 'settled';\n if (t.settleableAt !== undefined && nowSec >= t.settleableAt)\n return 'settleable';\n return 'closing';\n }\n\n /**\n * Gets all tracked channel IDs.\n */\n getTrackedChannels(): string[] {\n return Array.from(this.channels.keys());\n }\n\n /**\n * Returns true if the channel is being tracked.\n */\n isTracking(channelId: string): boolean {\n return this.channels.has(channelId);\n }\n}\n","import { readFileSync, writeFileSync, existsSync } from 'node:fs';\n\nexport interface ChannelStoreEntry {\n nonce: number;\n cumulativeAmount: bigint;\n /** Unix SECONDS when close was initiated (withdraw flow). */\n closedAt?: bigint;\n /** Unix SECONDS the channel becomes settleable (= closedAt + settlementTimeout). */\n settleableAt?: bigint;\n /** Unix SECONDS the channel was settled (collateral released). */\n settledAt?: bigint;\n}\n\n/**\n * Persistence interface for payment channel nonce/amount state.\n */\nexport interface ChannelStore {\n save(channelId: string, tracking: ChannelStoreEntry): void;\n load(channelId: string): ChannelStoreEntry | undefined;\n list(): string[];\n delete(channelId: string): void;\n}\n\ninterface JsonEntry {\n nonce: number;\n /** Stored as string to preserve bigint precision */\n cumulativeAmount: string;\n /** Withdraw-flow timers, string-encoded SECONDS (bigint precision). */\n closedAt?: string;\n settleableAt?: string;\n settledAt?: string;\n}\n\n/**\n * JSON file-backed ChannelStore.\n * Uses synchronous I/O to match ChannelManager's sync API surface.\n */\nexport class JsonFileChannelStore implements ChannelStore {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n save(channelId: string, tracking: ChannelStoreEntry): void {\n const data = this.readFile();\n data[channelId] = {\n nonce: tracking.nonce,\n cumulativeAmount: tracking.cumulativeAmount.toString(),\n ...(tracking.closedAt !== undefined ? { closedAt: tracking.closedAt.toString() } : {}),\n ...(tracking.settleableAt !== undefined ? { settleableAt: tracking.settleableAt.toString() } : {}),\n ...(tracking.settledAt !== undefined ? { settledAt: tracking.settledAt.toString() } : {}),\n };\n this.writeFile(data);\n }\n\n load(channelId: string): ChannelStoreEntry | undefined {\n const data = this.readFile();\n const entry = data[channelId];\n if (!entry) return undefined;\n return {\n nonce: entry.nonce,\n cumulativeAmount: BigInt(entry.cumulativeAmount),\n ...(entry.closedAt !== undefined ? { closedAt: BigInt(entry.closedAt) } : {}),\n ...(entry.settleableAt !== undefined ? { settleableAt: BigInt(entry.settleableAt) } : {}),\n ...(entry.settledAt !== undefined ? { settledAt: BigInt(entry.settledAt) } : {}),\n };\n }\n\n list(): string[] {\n return Object.keys(this.readFile());\n }\n\n delete(channelId: string): void {\n const data = this.readFile();\n const { [channelId]: _, ...rest } = data;\n this.writeFile(rest);\n }\n\n private readFile(): Record<string, JsonEntry> {\n if (!existsSync(this.filePath)) {\n return {};\n }\n const raw = readFileSync(this.filePath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonEntry>;\n }\n\n private writeFile(data: Record<string, JsonEntry>): void {\n writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');\n }\n}\n","/**\n * Read-only on-chain wallet balances.\n *\n * Reports the settlement-token balance of the client's OWN wallet on each\n * configured chain — a free read, no signing, no fund movement. Each per-chain\n * reader is independent and injectable (viem for EVM; raw JSON-RPC / GraphQL\n * `fetch` for Solana / Mina, mirroring the existing channel modules) so they\n * unit-test without a live chain. The caller ({@link ../ToonClient}) treats each\n * chain best-effort: a missing config or a failed read drops that chain rather\n * than failing the whole wallet view.\n */\nimport { createPublicClient, http, defineChain } from 'viem';\nimport { sha256 } from '@noble/hashes/sha2.js';\n\n/** One on-chain wallet token balance. `amount` is base-unit integer, decimal. */\nexport interface WalletBalance {\n chain: 'evm' | 'solana' | 'mina';\n address: string;\n amount: string;\n /** Token symbol, when resolved (e.g. `'USDC'`, `'MINA'`). */\n asset?: string;\n /** Token decimals, when resolved. */\n assetScale?: number;\n}\n\n/**\n * One asset amount within a chain's wallet view — the native coin or one token.\n * `amount` is a base-unit integer, decimal string.\n */\nexport interface WalletTokenAmount {\n /** Asset symbol (e.g. `'ETH'`, `'SOL'`, `'MINA'`, `'USDC'`), when known. */\n symbol?: string;\n /** Base-unit integer, decimal string. */\n amount: string;\n /** Decimals for formatting (ETH 18, SOL 9, MINA 9, USDC 6). */\n decimals?: number;\n /** Token contract / SPL mint address. Absent for the native coin. */\n address?: string;\n}\n\n/**\n * The full wallet view for ONE chain the identity is configured for: the native\n * coin plus every configured token, keyed by the chain's full key (e.g.\n * `'evm:31337'`). `unreadable` marks a chain whose RPC could not be reached at\n * all — the caller renders a per-chain notice rather than crashing.\n */\nexport interface WalletChainBalances {\n chain: 'evm' | 'solana' | 'mina';\n /** Full chain key, e.g. `'evm:31337'`, `'solana'`, `'mina'`. */\n chainKey: string;\n address: string;\n /** Native-coin balance, when readable. */\n native?: WalletTokenAmount;\n /** Configured token balances (e.g. USDC), each best-effort. */\n tokens: WalletTokenAmount[];\n /** True when nothing on this chain could be read (RPC unreachable). */\n unreadable?: boolean;\n /** First read error, when any read failed (for diagnostics). */\n error?: string;\n}\n\n/** Minimal ERC-20 read ABI (balance + metadata). */\nconst ERC20_READ_ABI = [\n { name: 'balanceOf', type: 'function', stateMutability: 'view', inputs: [{ name: 'account', type: 'address' }], outputs: [{ type: 'uint256' }] },\n { name: 'decimals', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'uint8' }] },\n { name: 'symbol', type: 'function', stateMutability: 'view', inputs: [], outputs: [{ type: 'string' }] },\n] as const;\n\n/** Extract the numeric chainId from an `evm:{network}:{chainId}` / `evm:{chainId}` key. */\nexport function parseEvmChainId(chainKey: string): number {\n const parts = chainKey.split(':');\n const idStr = parts.length >= 3 ? parts[2] : parts[1];\n const id = Number.parseInt(idStr ?? '', 10);\n if (!Number.isFinite(id)) throw new Error(`Invalid EVM chain key \"${chainKey}\".`);\n return id;\n}\n\n/**\n * Per-request network timeout (ms) for ONE wallet-balance RPC/GraphQL call.\n * Node's global `fetch` has NO default timeout, so a single stalled socket would\n * otherwise hang the entire multi-chain read until the caller's outer bound —\n * making one flaky endpoint hide the balances of every chain. Bounding each call\n * (viem's own `timeout` for EVM; an AbortSignal for the Solana/Mina `fetch`)\n * lets a slow endpoint degrade only its own chain to `unreadable`. Env override\n * `TOON_WALLET_RPC_TIMEOUT_MS` (`0` disables).\n */\nconst RPC_TIMEOUT_ENV = 'TOON_WALLET_RPC_TIMEOUT_MS';\nconst DEFAULT_RPC_TIMEOUT_MS = 8_000;\n\nfunction rpcTimeoutMs(): number {\n const raw =\n typeof process !== 'undefined' ? process.env?.[RPC_TIMEOUT_ENV] : undefined;\n const n = raw === undefined || raw === '' ? NaN : Number(raw);\n return Number.isFinite(n) && n >= 0 ? n : DEFAULT_RPC_TIMEOUT_MS;\n}\n\n/** AbortSignal firing after {@link rpcTimeoutMs}; undefined when disabled (`0`). */\nfunction rpcAbortSignal(): AbortSignal | undefined {\n const ms = rpcTimeoutMs();\n return ms > 0 ? AbortSignal.timeout(ms) : undefined;\n}\n\n/** Read an ERC-20 token balance (balance + decimals + symbol) for `owner`. */\nexport async function readEvmTokenBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n tokenAddress: string;\n owner: string;\n}): Promise<WalletBalance> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: http(opts.rpcUrl, { timeout: rpcTimeoutMs() || undefined, retryCount: 1 }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const token = opts.tokenAddress as `0x${string}`;\n const owner = opts.owner as `0x${string}`;\n const [amount, decimals, symbol] = await Promise.all([\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'balanceOf', args: [owner] }),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'decimals' }).catch(() => undefined),\n client.readContract({ address: token, abi: ERC20_READ_ABI, functionName: 'symbol' }).catch(() => undefined),\n ]);\n const out: WalletBalance = { chain: 'evm', address: opts.owner, amount: (amount as bigint).toString() };\n if (typeof symbol === 'string' && symbol) out.asset = symbol;\n if (decimals !== undefined) out.assetScale = Number(decimals);\n return out;\n}\n\n/** Read the native ETH balance (wei) for `owner` via `eth_getBalance`. */\nexport async function readEvmNativeBalance(opts: {\n rpcUrl: string;\n chainKey: string;\n owner: string;\n}): Promise<WalletTokenAmount> {\n const chainId = parseEvmChainId(opts.chainKey);\n const client = createPublicClient({\n transport: http(opts.rpcUrl, { timeout: rpcTimeoutMs() || undefined, retryCount: 1 }),\n chain: defineChain({\n id: chainId,\n name: opts.chainKey,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [opts.rpcUrl] } },\n }),\n });\n const wei = await client.getBalance({ address: opts.owner as `0x${string}` });\n return { symbol: 'ETH', amount: wei.toString(), decimals: 18 };\n}\n\n/** Read the native SOL balance (lamports) for `owner` via the `getBalance` RPC. */\nexport async function readSolanaNativeBalance(opts: {\n rpcUrl: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletTokenAmount> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getBalance',\n params: [opts.owner, { commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: number | string };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n const lamports = BigInt(json.result?.value ?? 0);\n return { symbol: 'SOL', amount: lamports.toString(), decimals: 9 };\n}\n\n/** Read the SPL-token balance for `owner`'s token account(s) of `mint`. */\nexport async function readSolanaTokenBalance(opts: {\n rpcUrl: string;\n mint: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const res = await fetchImpl(opts.rpcUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n jsonrpc: '2.0',\n id: 1,\n method: 'getTokenAccountsByOwner',\n params: [opts.owner, { mint: opts.mint }, { encoding: 'jsonParsed', commitment: 'confirmed' }],\n }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Solana RPC request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n result?: { value?: { account?: { data?: { parsed?: { info?: { tokenAmount?: { amount?: string; decimals?: number } } } } } }[] };\n error?: { message?: string };\n };\n if (json.error) throw new Error(`Solana RPC error: ${json.error.message ?? 'unknown'}`);\n let amount = 0n;\n let decimals: number | undefined;\n for (const acc of json.result?.value ?? []) {\n const ta = acc.account?.data?.parsed?.info?.tokenAmount;\n if (ta?.amount) amount += BigInt(ta.amount);\n if (ta?.decimals !== undefined) decimals = ta.decimals;\n }\n const out: WalletBalance = { chain: 'solana', address: opts.owner, amount: amount.toString() };\n if (decimals !== undefined) out.assetScale = decimals;\n return out;\n}\n\n/** Read the native MINA balance (nanomina) for `owner` via the Mina GraphQL API. */\nexport async function readMinaBalance(opts: {\n graphqlUrl: string;\n owner: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const query = 'query($pk:String!){account(publicKey:$pk){balance{total}}}';\n const res = await fetchImpl(opts.graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: opts.owner } }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n data?: { account?: { balance?: { total?: string } | null } | null };\n errors?: { message?: string }[];\n };\n if (json.errors && json.errors.length > 0) {\n throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`);\n }\n return {\n chain: 'mina',\n address: opts.owner,\n amount: String(json.data?.account?.balance?.total ?? '0'),\n asset: 'MINA',\n assetScale: 9,\n };\n}\n\nconst BASE58_ALPHABET =\n '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\n\n/** base58-encode raw bytes (Bitcoin/Mina alphabet, leading-zero preserving). */\nfunction base58encode(bytes: Uint8Array): string {\n let num = 0n;\n for (const b of bytes) num = num * 256n + BigInt(b);\n let out = '';\n while (num > 0n) {\n out = BASE58_ALPHABET[Number(num % 58n)] + out;\n num /= 58n;\n }\n for (const b of bytes) {\n if (b === 0) out = '1' + out;\n else break;\n }\n return out;\n}\n\n/**\n * Encode a Mina token id (a Field, given as a decimal string) into the base58\n * `TokenId` scalar the Mina GraphQL `account(publicKey, token)` query expects.\n *\n * Mina's base58check layout is `0x1c` version byte ++ the 32-byte\n * little-endian field ++ a 4-byte double-SHA256 checksum. (The client avoids the\n * heavy o1js dependency — `TokenId.toBase58` — so this reproduces its encoding;\n * it round-trips the native token id `1` to\n * `wSHV2S4qX9jFsLjQo8r1BsMLH2ZRKsZx6EJd1sbozGPieEC4Jf`.) The decimal form the\n * GraphQL layer rejects outright, hence this conversion.\n */\nexport function minaTokenIdToBase58(tokenId: string): string {\n if (!/^\\d+$/.test(tokenId)) {\n throw new Error(`Mina tokenId must be a decimal Field string: \"${tokenId}\"`);\n }\n let field = BigInt(tokenId);\n const le = new Uint8Array(32);\n for (let i = 0; i < 32; i++) {\n le[i] = Number(field & 0xffn);\n field >>= 8n;\n }\n const body = new Uint8Array(1 + 32);\n body[0] = 0x1c;\n body.set(le, 1);\n const checksum = sha256(sha256(body)).slice(0, 4);\n const raw = new Uint8Array(body.length + 4);\n raw.set(body, 0);\n raw.set(checksum, body.length);\n return base58encode(raw);\n}\n\n/**\n * Read a CUSTOM Mina token balance (e.g. the settlement USDC) for `owner`.\n *\n * Unlike {@link readMinaBalance} (native MINA), this passes the settlement\n * `tokenId` so the GraphQL `account(publicKey, token)` query returns the\n * token-specific balance. An account holding none of the token resolves to\n * `null` → reported as `0`. Reported at the 6-decimal settlement-USDC scale —\n * NOT native MINA's 9 (see the `assetScale` comment below).\n */\nexport async function readMinaTokenBalance(opts: {\n graphqlUrl: string;\n owner: string;\n tokenId: string;\n fetchImpl?: typeof fetch;\n}): Promise<WalletBalance> {\n const fetchImpl = opts.fetchImpl ?? fetch;\n const token = minaTokenIdToBase58(opts.tokenId);\n const query =\n 'query($pk:PublicKey!,$t:TokenId){account(publicKey:$pk,token:$t){balance{total}}}';\n const res = await fetchImpl(opts.graphqlUrl, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ query, variables: { pk: opts.owner, t: token } }),\n signal: rpcAbortSignal(),\n });\n if (!res.ok) throw new Error(`Mina GraphQL request failed: HTTP ${res.status}`);\n const json = (await res.json()) as {\n data?: { account?: { balance?: { total?: string } | null } | null };\n errors?: { message?: string }[];\n };\n if (json.errors && json.errors.length > 0) {\n throw new Error(`Mina GraphQL error: ${json.errors[0]?.message ?? 'unknown'}`);\n }\n return {\n chain: 'mina',\n address: opts.owner,\n amount: String(json.data?.account?.balance?.total ?? '0'),\n asset: 'USDC',\n // TOON's settlement USDC is 6-decimal on every chain (assetScale 6), unlike\n // native MINA's 9. The Mina custom-token amount is a raw u64, so scale it at\n // 6 — otherwise a 50 USDC balance (50_000000) misreads as 0.05.\n assetScale: 6,\n };\n}\n\n/**\n * Per-chain inputs for {@link readWalletBalances}: the resolved RPC URL, the\n * identity's address on that chain, and the configured token (USDC) — sourced by\n * the caller from the network topology / presets, never hardcoded here. A chain\n * key absent from the object is simply not read.\n */\nexport interface WalletBalanceSources {\n evm?: { chainKey: string; rpcUrl: string; owner: string; tokenAddress?: string };\n solana?: { chainKey?: string; rpcUrl: string; owner: string; tokenMint?: string };\n mina?: {\n chainKey?: string;\n graphqlUrl: string;\n owner: string;\n /** Settlement-token Field id (decimal). Reads the token balance when set. */\n tokenId?: string;\n };\n /** Injectable fetch (Solana/Mina JSON-RPC & GraphQL) for tests. */\n fetchImpl?: typeof fetch;\n}\n\nconst errText = (e: unknown): string => (e instanceof Error ? e.message : String(e));\n\n/** Fold a settled native read into the chain view, recording any failure. */\nfunction foldNative(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletTokenAmount>,\n errors: string[]\n): void {\n if (settled.status === 'fulfilled') out.native = settled.value;\n else errors.push(errText(settled.reason));\n}\n\n/** Fold a settled token read (a `WalletBalance`) into the chain view. */\nfunction foldToken(\n out: WalletChainBalances,\n settled: PromiseSettledResult<WalletBalance | undefined>,\n tokenAddress: string | undefined,\n errors: string[]\n): void {\n if (settled.status === 'rejected') {\n errors.push(errText(settled.reason));\n return;\n }\n const bal = settled.value;\n if (!bal) return;\n out.tokens.push({\n symbol: bal.asset,\n amount: bal.amount,\n decimals: bal.assetScale,\n ...(tokenAddress ? { address: tokenAddress } : {}),\n });\n}\n\n/** Mark a chain unreadable when nothing could be read; attach the first error. */\nfunction finalizeChain(out: WalletChainBalances, errors: string[]): void {\n if (errors.length > 0) out.error = errors[0];\n if (out.native === undefined && out.tokens.length === 0) out.unreadable = true;\n}\n\n/**\n * Read the full wallet view — native coin + configured tokens — for every chain\n * in `sources`, keyed per chain. FREE: read-only RPC, no signing. Each chain is\n * read independently and in parallel; a chain whose RPC is unreachable degrades\n * to `{ unreadable: true, error }` instead of failing the others. Within a chain\n * the native and token reads are independent, so a native read can succeed even\n * if the token read fails (and vice versa).\n */\nexport async function readWalletBalances(\n sources: WalletBalanceSources\n): Promise<WalletChainBalances[]> {\n const { fetchImpl } = sources;\n const tasks: Promise<WalletChainBalances>[] = [];\n\n if (sources.evm) {\n const { chainKey, rpcUrl, owner, tokenAddress } = sources.evm;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'evm', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readEvmNativeBalance({ rpcUrl, chainKey, owner }),\n tokenAddress\n ? readEvmTokenBalance({ rpcUrl, chainKey, tokenAddress, owner })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n foldToken(out, tokenR, tokenAddress, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n if (sources.solana) {\n const { chainKey = 'solana', rpcUrl, owner, tokenMint } = sources.solana;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'solana', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n const [nativeR, tokenR] = await Promise.allSettled([\n readSolanaNativeBalance({ rpcUrl, owner, fetchImpl }),\n tokenMint\n ? readSolanaTokenBalance({ rpcUrl, mint: tokenMint, owner, fetchImpl })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(out, nativeR, errors);\n // Solana SPL reads carry no symbol from `getTokenAccountsByOwner`; the\n // negotiated settlement token is USDC on every configured chain.\n if (tokenR.status === 'fulfilled' && tokenR.value && tokenR.value.asset === undefined) {\n tokenR.value.asset = 'USDC';\n }\n foldToken(out, tokenR, tokenMint, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n if (sources.mina) {\n const { chainKey = 'mina', graphqlUrl, owner, tokenId } = sources.mina;\n tasks.push(\n (async () => {\n const out: WalletChainBalances = { chain: 'mina', chainKey, address: owner, tokens: [] };\n const errors: string[] = [];\n // Native MINA (gas) plus, when the deployment settles a custom token,\n // that token's balance (USDC) — read via the tokenId. Independent reads.\n const [nativeR, tokenR] = await Promise.allSettled([\n readMinaBalance({ graphqlUrl, owner, fetchImpl }),\n tokenId\n ? readMinaTokenBalance({ graphqlUrl, owner, tokenId, fetchImpl })\n : Promise.resolve<WalletBalance | undefined>(undefined),\n ]);\n foldNative(\n out,\n nativeR.status === 'fulfilled'\n ? {\n status: 'fulfilled',\n value: {\n symbol: nativeR.value.asset,\n amount: nativeR.value.amount,\n decimals: nativeR.value.assetScale,\n },\n }\n : nativeR,\n errors\n );\n foldToken(out, tokenR, undefined, errors);\n finalizeChain(out, errors);\n return out;\n })()\n );\n }\n\n return Promise.all(tasks);\n}\n","/**\n * Client-side helper for kind:5094 Arweave blob storage DVM requests.\n *\n * This composes the three steps a caller previously had to wire by hand:\n * 1. Build the kind:5094 event via `buildBlobStorageRequest()` (@toon-protocol/core).\n * 2. Publish it to the DVM destination over ILP via `ToonClient.publishEvent()`\n * (reusing the existing claim / channel plumbing).\n * 3. Decode the FULFILL `data` field into the Arweave transaction ID.\n *\n * ## FULFILL data contract\n *\n * The deployed connector is a payment-proxy (HTTP-in-ILP): a successful blob\n * upload returns the DVM's verbatim **HTTP/1.1 response message** in the ILP\n * FULFILL `data` field. For a single-packet (non-chunked) upload the body is a\n * JSON object:\n *\n * HTTP/1.1 200 OK\\r\\n\n * content-length: 189\\r\\n\n * \\r\\n\n * {\"accept\":true,\"txId\":\"<43-char base64url>\",\"data\":\"<base64 of txId>\",...}\n *\n * We parse the HTTP envelope, fail on a non-2xx status (or `accept:false`), and\n * read the Arweave tx ID from `txId` (falling back to base64-decoding `data`).\n * An Arweave tx ID is a 43-character base64url string (32 raw bytes). A legacy\n * fallback still accepts a bare `base64(utf8(txId))` FULFILL (no HTTP envelope)\n * so non-proxy providers do not regress. See {@link extractArweaveTxId}.\n *\n * See `packages/sdk/src/arweave/arweave-dvm-handler.ts` for the server side and\n * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts` for the reference\n * end-to-end flow this helper mirrors.\n *\n * Chunked uploads (multi-packet, via `uploadId` / `chunkIndex` / `totalChunks`\n * params) are intentionally out of scope for this single-packet helper — the\n * provider returns `ack:<n>` for intermediate chunks and the tx ID only on the\n * final chunk. Callers needing chunking should drive `publishEvent()` directly\n * (see the chunked case in the reference E2E test). Tracked as a follow-up.\n */\n\nimport type { NostrEvent } from 'nostr-tools/pure';\nimport { buildBlobStorageRequest } from '@toon-protocol/core';\nimport { fromBase64, decodeUtf8 } from './utils/binary.js';\nimport type { EnvelopeResponse } from './wire/envelope.js';\nimport type { ToonClient } from './ToonClient.js';\nimport type { SignedBalanceProof } from './types.js';\n\n/** Arweave tx IDs are base64url-encoded 32-byte values (43 chars, no padding). */\nconst ARWEAVE_TX_ID_REGEX = /^[A-Za-z0-9_-]{43}$/;\n\n/**\n * Parameters for {@link requestBlobStorage}.\n */\nexport interface RequestBlobStorageParams {\n /** The raw blob data to store on Arweave. */\n blobData: Uint8Array;\n\n /**\n * MIME type of the blob. Defaults to `'application/octet-stream'`\n * (matching `buildBlobStorageRequest`).\n */\n contentType?: string;\n\n /**\n * Bid amount in USDC micro-units, as a string (declared in the event's\n * `bid` tag). Defaults to the stringified `ilpAmount` when omitted.\n *\n * At least one of `bid` / `ilpAmount` should be provided so the declared\n * bid and the paid ILP amount agree.\n */\n bid?: string;\n\n /**\n * ILP destination address of the DVM that performs the upload\n * (e.g. `'g.toon.peer1'`). Falls back to the client's configured\n * `destinationAddress` when omitted.\n */\n destination?: string;\n\n /**\n * Pre-signed balance proof claim for this packet. When omitted, the\n * client's channel manager auto-opens a channel and auto-signs a claim\n * (same lazy-channel behavior as `publishEvent`).\n */\n claim?: SignedBalanceProof;\n\n /**\n * Explicit ILP payment amount (bigint micro-units). When omitted,\n * `publishEvent` computes it from the encoded event size. When `bid`\n * is omitted, this value is stringified to populate the event's bid tag.\n */\n ilpAmount?: bigint;\n}\n\n/**\n * Typed result of {@link requestBlobStorage}.\n */\nexport interface RequestBlobStorageResult {\n /** Whether the upload succeeded and a tx ID was decoded. */\n success: boolean;\n\n /** The Arweave transaction ID (43-char base64url) when `success` is true. */\n txId?: string;\n\n /** The id of the kind:5094 event that was published. */\n eventId?: string;\n\n /** Error message when `success` is false. */\n error?: string;\n}\n\n/**\n * Requests permanent Arweave blob storage from a DVM in a single ILP packet.\n *\n * Mirrors the single-packet flow in\n * `packages/client/tests/e2e/docker-arweave-dvm-e2e.test.ts`: builds a signed\n * kind:5094 event, publishes it through the supplied {@link ToonClient}\n * (reusing its claim/channel plumbing), and decodes the FULFILL `data` field\n * into an Arweave transaction ID.\n *\n * @param client - A started `ToonClient` (call `client.start()` first).\n * @param secretKey - The Nostr secret key used to sign the kind:5094 event.\n * @param params - Blob, content type, bid, destination, and payment options.\n * @returns `{ success, txId?, eventId?, error? }`.\n */\nexport async function requestBlobStorage(\n client: ToonClient,\n secretKey: Uint8Array,\n params: RequestBlobStorageParams\n): Promise<RequestBlobStorageResult> {\n const bid =\n params.bid ??\n (params.ilpAmount !== undefined ? String(params.ilpAmount) : undefined);\n\n if (bid === undefined || bid === '') {\n return {\n success: false,\n error: 'requestBlobStorage requires a bid (or ilpAmount to derive it)',\n };\n }\n\n // buildBlobStorageRequest expects a Node Buffer (it calls .toString('base64')).\n // ToonClient surfaces Uint8Array for browser-compat, so normalize here.\n const blobBuffer = Buffer.from(\n params.blobData.buffer,\n params.blobData.byteOffset,\n params.blobData.byteLength\n );\n\n let event: NostrEvent;\n try {\n event = buildBlobStorageRequest(\n {\n blobData: blobBuffer,\n contentType: params.contentType,\n bid,\n },\n secretKey\n );\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n const result = await client.publishEvent(event, {\n destination: params.destination,\n claim: params.claim,\n ilpAmount: params.ilpAmount,\n // No proxyPath: the store DESTINATION's route already terminates at the\n // store backend's own endpoint, and ADR 0025 resolves the envelope\n // target strictly beneath that handler path — '' (the default) means\n // \"the handler's own path\". The old absolute '/store' is refused by the\n // connector as an escape attempt (F00).\n });\n\n if (!result.success) {\n return {\n success: false,\n eventId: result.eventId ?? event.id,\n error: result.error ?? 'Blob storage request rejected',\n };\n }\n\n if (!result.response) {\n return {\n success: false,\n eventId: event.id,\n error:\n 'FULFILL carried no sealed response envelope; expected the store\\'s answer with the Arweave tx ID',\n };\n }\n\n let txId: string;\n try {\n txId = extractArweaveTxId(result.response);\n } catch (error) {\n return {\n success: false,\n eventId: event.id,\n error: error instanceof Error ? error.message : String(error),\n };\n }\n\n return {\n success: true,\n txId,\n eventId: event.id,\n };\n}\n\n/**\n * Extract the Arweave tx ID from the FULFILL `data` of a successful blob upload.\n *\n * The terminating connector seals the store's answer as a response envelope\n * (ADR 0018), which `publishEvent` opens and hands back as\n * `PublishEventResult.response`. For a successful single-packet upload its\n * body is `{\"accept\":true,\"txId\":\"<43-char base64url>\",\"data\":\"<base64 of\n * txId>\",…}`.\n *\n * We fail on a non-2xx status or `accept:false`, then read `txId` (preferred)\n * from the JSON body — falling back to base64-decoding the `data` field when\n * `txId` is absent.\n *\n * Exported for callers that drive `publishEvent` directly with a hand-built\n * kind:5094 event (e.g. git-object uploads carrying Git-SHA/Git-Type/Repo\n * tags, toon-client#227) and need the same FULFILL→txId decode this helper\n * applies.\n *\n * @throws {Error} If the response is non-2xx, `accept:false`, the body is not\n * parseable JSON, or no valid Arweave tx ID can be extracted.\n */\nexport function extractArweaveTxId(response: EnvelopeResponse): string {\n if (response.status < 200 || response.status >= 300) {\n const detail =\n response.body.length > 0 ? ` - ${decodeUtf8(response.body)}` : '';\n throw new Error(\n `Blob upload failed: the store answered HTTP ${response.status}${detail}`\n );\n }\n\n const text = decodeUtf8(response.body);\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new Error(`Blob upload response body was not valid JSON: \"${text}\"`);\n }\n\n const body = parsed as {\n accept?: boolean;\n txId?: unknown;\n data?: unknown;\n error?: unknown;\n };\n\n if (body.accept === false) {\n const reason = typeof body.error === 'string' ? `: ${body.error}` : '';\n throw new Error(`Blob upload rejected by DVM (accept:false)${reason}`);\n }\n\n // Preferred: explicit txId field.\n if (typeof body.txId === 'string' && ARWEAVE_TX_ID_REGEX.test(body.txId)) {\n return body.txId;\n }\n\n // Fallback: base64-encoded tx id in the `data` field.\n if (typeof body.data === 'string' && body.data.length > 0) {\n const decoded = decodeUtf8(fromBase64(body.data));\n if (ARWEAVE_TX_ID_REGEX.test(decoded)) {\n return decoded;\n }\n }\n\n throw new Error(\n `Blob upload response did not contain a valid Arweave tx ID: \"${text}\"`\n );\n}\n","/**\n * Payment-aware HTTP fetch over TOON (the \"h402\" flow).\n *\n * This adapter makes paying for an HTTP resource transparent: it issues an\n * ordinary HTTP request, and when the origin answers `402 Payment Required`\n * with an x402-style challenge that offers a `toon-channel` payment option, it\n * opens/reuses a payment channel, signs a balance-proof claim, and re-sends the\n * SAME HTTP request as a \"transparent HTTP-in-ILP\" packet to the connector's\n * `POST /ilp` endpoint (via {@link HttpIlpClient}). The connector terminates the\n * payment, forwards the request to the origin, and returns the origin's HTTP\n * response inside the ILP FULFILL `data`. We reconstruct a normal Web `Response`\n * from those bytes — the caller never sees ILP.\n *\n * ─── x402 wire contract (the 402 challenge body) ────────────────────────────\n * The shipped connector answers x402 **v2** terms (`client-edge-spec.md` §1.4,\n * `crates/connector-client-edge/src/lib.rs`), and that is the shape pinned by\n * `Http402Client.connectorTerms.test.ts`:\n *\n * ```jsonc\n * {\n * \"x402Version\": 2,\n * \"resource\": { \"url\": \"g.example.app\" },\n * \"accepts\": [\n * {\n * \"scheme\": \"toon-channel\",\n * \"network\": \"g.example.app\",\n * \"amount\": \"100\",\n * \"payTo\": \"g.example.app\",\n * \"maxTimeoutSeconds\": 60,\n * \"httpEndpoint\": \"/ilp\", // RELATIVE to the resource's origin.\n * \"extra\": { \"ilpAddress\": \"g.example.app\", \"endpoint\": \"/ilp\", \"price\": \"100\" }\n * }\n * ]\n * }\n * ```\n *\n * Two things that shape forces, both easy to get wrong:\n * - The ILP address, the endpoint and the price live under **`extra`**. The\n * top-level `payTo` happens to equal the destination today, so reading it\n * appears to work — that is a coincidence of the connector's current code,\n * not a contract, so `extra` is read first.\n * - `httpEndpoint` is **relative**; it is resolved against the URL that\n * answered `402` (`Response.url`, or `parseX402Body`'s `baseUrl` argument).\n *\n * Everything is still parsed DEFENSIVELY (mirroring `readDiscoveredIlpPeer` in\n * selectIlpTransport.ts): an unrecognised connector shape degrades to the\n * vanilla 402 rather than throwing. Field aliases (first present wins):\n * - destination: `extra.ilpAddress` | `extra.destination` | `destination` |\n * `ilpAddress` | `payTo`. (We do NOT invent a value — a missing\n * destination makes the entry unusable and we fall back to the vanilla 402.)\n * - amount: `extra.price` | `extra.amount` | `amount` | `price` |\n * `maxAmountRequired`.\n * - httpEndpoint:`httpEndpoint` | `ilpEndpoint` | `extra.httpEndpoint` |\n * `extra.endpoint` | `endpoint`.\n * - upgrade: `supportsUpgrade` | `upgradable`.\n *\n * ─── What the paid request is made of ───────────────────────────────────────\n * The paid re-send is an OER `EnvelopeRequest` sealed to the terminating\n * connector's identity, under a condition derived from the secret that seal\n * carries — the same `sealExchange` / `readExchangeOutcome` pair\n * `ToonClient.publishEvent` uses (ADR 0018/0019, toon-client#450, #451). This\n * adapter used to carry its own HTTP/1.1 codec; it does not any more, and\n * `packages/client` now has exactly one encoder.\n *\n * Two consequences of the envelope replacing HTTP text, both deliberate:\n *\n * - **`Host` and `Content-Length` are not synthesised.** The old codec added\n * both. The connector strips them either way and lets its HTTP client\n * recompute them (`connector-runtime/src/app_client.rs` skips `host` and\n * `content-length` by name), and the envelope already carries the body\n * length as an OER length determinant, so emitting them was writing bytes\n * the far side throws away. A caller that sets either explicitly still has\n * it carried verbatim, and the connector still drops it.\n * - **A response has no reason phrase.** An `EnvelopeResponse` status is two\n * bytes; `HTTP/1.1 201 Created`'s \"Created\" has nowhere to live on this\n * wire. `Response.statusText` is therefore empty, and the status is the\n * fact to read.\n *\n * A malformed answer now fails the way it fails everywhere else in this\n * package — `SealedResponseError` from `readExchangeOutcome` — rather than\n * this file's old `ConnectorError` on a bad status line while `fulfill-http.ts`\n * quietly returned `{isHttp:false}` for the very same bytes.\n *\n * Claim signing/construction is owned by the CALLER (ToonClient wires the live\n * ChannelManager + signer). This adapter never builds or validates claims —\n * payment-claim validation lives ONLY in the connector.\n */\n\nimport type { IlpSendResult } from '@toon-protocol/core';\nimport { HttpIlpClient } from './HttpIlpClient.js';\nimport {\n selectIlpTransport,\n type DiscoveredIlpPeer,\n type IlpTransportChoice,\n} from './selectIlpTransport.js';\nimport { ConnectorEdgeClient } from './ConnectorEdgeClient.js';\nimport { ConnectorError, ToonClientError } from '../errors.js';\nimport { toBase64, fromBase64, encodeUtf8 } from '../utils/binary.js';\nimport type { EnvelopeHeader, EnvelopeResponse } from '../wire/envelope.js';\nimport { readExchangeOutcome, sealExchange } from '../wire/sealed-exchange.js';\n\n// ─── x402 challenge types (documented wire contract above) ──────────────────\n\n/** A single parsed `accepts` entry that offers the `toon-channel` scheme. */\nexport interface ToonChannelAccept {\n /** Always `'toon-channel'` for a matched entry. */\n scheme: 'toon-channel';\n /** Optional chain key, e.g. `evm:base:8453` — informational. */\n network?: string;\n /** ILP destination address to pay (the connector route fronting the URL). */\n destination: string;\n /** Price in ILP base units. */\n amount: bigint;\n /** The connector's `POST /ilp` URL. */\n httpEndpoint: string;\n /** Whether the host accepts the BTP upgrade over the HTTP endpoint. */\n supportsUpgrade: boolean;\n}\n\n/** The parsed x402 402 body, with the selected `toon-channel` entry (if any). */\nexport interface ParsedX402Challenge {\n x402Version?: number;\n /** The first usable `toon-channel` accepts entry, or `undefined`. */\n toonChannel?: ToonChannelAccept;\n}\n\n// ─── h402Fetch options (PINNED PUBLIC CONTRACT) ─────────────────────────────\n\n/** Options for {@link Http402Client.fetch} / `ToonClient.h402Fetch`. */\nexport interface H402FetchOptions {\n /** HTTP method. Default `'GET'`. */\n method?: string;\n /** Request headers. */\n headers?: Record<string, string>;\n /** Request body. */\n body?: string | Uint8Array;\n /** Request timeout in milliseconds. */\n timeout?: number;\n /** Optional explicit ILP destination override (else the x402 entry's value). */\n destination?: string;\n}\n\n/**\n * Caller-supplied hook that signs a balance-proof claim for `(destination,\n * amount)` and returns the chain-appropriate claim message to attach to the ILP\n * PREPARE. ToonClient wires this to its ChannelManager + per-chain signer (the\n * exact same plumbing as `publishEvent`). The returned value is forwarded\n * opaquely as the `ILP-Payment-Channel-Claim` header by {@link HttpIlpClient}.\n */\nexport type ClaimResolver = (\n destination: string,\n amount: bigint\n) => Promise<unknown>;\n\n/** Factory for an {@link HttpIlpClient} given a resolved `POST /ilp` endpoint. */\nexport type HttpIlpClientFactory = (httpEndpoint: string) => HttpIlpClient;\n\nexport interface Http402ClientConfig {\n /**\n * Underlying HTTP fetch for the INITIAL (un-paid) request that probes for a\n * 402. Default: global `fetch`.\n */\n fetch?: typeof fetch;\n /**\n * Resolves + signs the payment-channel claim. REQUIRED to pay; if omitted,\n * a 402 with a `toon-channel` offer is surfaced unchanged (vanilla challenge).\n */\n resolveClaim?: ClaimResolver;\n /**\n * Builds the {@link HttpIlpClient} for a resolved endpoint. Default: construct\n * a new `HttpIlpClient({ httpEndpoint })`. Injectable for tests.\n */\n createIlpClient?: HttpIlpClientFactory;\n /**\n * AC4: request a duplex transport for the paid send. When `true` and the\n * toon-channel entry advertises `supportsUpgrade`, {@link selectIlpTransport}\n * returns `http-upgradable` and the send path calls\n * {@link HttpIlpClient.upgradeToBtp} before writing — the wiring for\n * large/streaming responses. Default `false` (stateless one-shot HTTP).\n *\n * NOTE (v1 limitation): even on the upgrade path the actual write is still a\n * one-shot `sendIlpPacketWithClaim`; full duplex body streaming over the BTP\n * session is a documented follow-up. The selection + upgrade CALL PATH is\n * wired and exercised here so the streaming consumer can take over the\n * returned session in a later iteration.\n */\n needsDuplex?: boolean;\n /**\n * Asks the connector named by the 402 offer for its identity key, so the\n * paid request can be sealed to it. Default: a fresh\n * {@link ConnectorEdgeClient} over this config's `fetch`. Injectable so a\n * caller that already holds one shares its identity cache rather than\n * re-fetching a key per paid request.\n */\n connectorEdge?: ConnectorEdgeClient;\n}\n\n/**\n * Reusable h402 fetch engine. `ToonClient.h402Fetch` is a thin wrapper that\n * constructs this with the live claim/channel plumbing.\n */\nexport class Http402Client {\n private readonly fetchImpl: typeof fetch;\n private readonly resolveClaim?: ClaimResolver;\n private readonly createIlpClient: HttpIlpClientFactory;\n private readonly needsDuplex: boolean;\n private readonly connectorEdge: ConnectorEdgeClient;\n\n constructor(config: Http402ClientConfig = {}) {\n this.fetchImpl = config.fetch ?? fetch;\n this.resolveClaim = config.resolveClaim;\n this.createIlpClient =\n config.createIlpClient ??\n ((httpEndpoint) => new HttpIlpClient({ httpEndpoint }));\n this.needsDuplex = config.needsDuplex ?? false;\n this.connectorEdge =\n config.connectorEdge ??\n new ConnectorEdgeClient({\n // Same `fetch` the probe uses: a host that installs its own (and a\n // test that swaps one in) must be the one the identity comes from.\n fetch: (input, init) => this.fetchImpl(input, init),\n });\n }\n\n /**\n * `fetch()`-like entry point. Issues the request; on `402` parses the x402\n * challenge and — when a usable `toon-channel` offer is present and a claim\n * resolver is configured — pays over TOON and returns the reconstructed\n * `Response`. Otherwise returns the original 402 unchanged (AC5).\n */\n async fetch(url: string, opts: H402FetchOptions = {}): Promise<Response> {\n const method = (opts.method ?? 'GET').toUpperCase();\n\n // 1. Probe: issue the ordinary HTTP request.\n const probe = await this.fetchImpl(url, {\n method,\n ...(opts.headers ? { headers: opts.headers } : {}),\n ...(opts.body !== undefined ? { body: opts.body as BodyInit } : {}),\n ...(opts.timeout !== undefined\n ? { signal: AbortSignal.timeout(opts.timeout) }\n : {}),\n });\n\n // 2. Pass-through anything that isn't a 402.\n if (probe.status !== 402) return probe;\n\n // 3. Parse the x402 challenge defensively. We must read the body to inspect\n // `accepts`; clone first so we can still return the ORIGINAL 402 on\n // fallback (a Response body is single-use).\n const challenge = await parseX402Challenge(probe.clone());\n const accept = challenge.toonChannel;\n\n // AC5: no toon-channel offer (or no signer) → surface the vanilla challenge.\n if (!accept || !this.resolveClaim) return probe;\n\n // 4. Pay over TOON and return the reconstructed Response.\n return this.payOverToon(url, method, opts, accept, this.resolveClaim);\n }\n\n /**\n * Open/reuse a channel (via the injected claim resolver), seal the request\n * envelope to the terminating connector, send it to `POST /ilp` with the\n * claim and the matching condition, and open the answer.\n *\n * The identity is fetched BEFORE a packet is formed, and there is no default\n * to fall back to: sealing to the wrong key is a confidentiality failure\n * that merely presents as an undeliverable packet (ADR 0018).\n */\n private async payOverToon(\n url: string,\n method: string,\n opts: H402FetchOptions,\n accept: ToonChannelAccept,\n resolveClaim: ClaimResolver\n ): Promise<Response> {\n const destination = opts.destination ?? accept.destination;\n\n // Sign the balance-proof claim for the demanded price (caller-owned).\n const claim = await resolveClaim(destination, accept.amount);\n\n // The key first — no packet exists without it. The 402 named the endpoint\n // to pay, so that is the connector whose identity must seal this.\n const identity = await this.connectorEdge.getIdentity(accept.httpEndpoint);\n\n // One call mints the seal and the condition that matches it, so the two\n // cannot drift apart.\n const exchange = sealExchange(\n toEnvelopeRequest(url, method, opts),\n identity.publicKey\n );\n\n // AC4: drive transport SELECTION through selectIlpTransport. A streaming\n // response (`needsDuplex`) selects the BTP upgrade path; the one-shot case\n // stays on stateless HTTP. Full duplex byte-streaming is a documented v1\n // limitation (see selectTransport below) — the selection + upgrade call path\n // is wired and unit-tested.\n const peer: DiscoveredIlpPeer = {\n httpEndpoint: accept.httpEndpoint,\n supportsUpgrade: accept.supportsUpgrade,\n };\n const choice = selectIlpTransport(peer, {\n needsDuplex: this.needsDuplex,\n });\n\n const ilpClient = this.createIlpClient(accept.httpEndpoint);\n\n const result = await this.sendOverChoice(\n ilpClient,\n choice,\n {\n destination,\n amount: String(accept.amount),\n data: toBase64(exchange.data),\n executionCondition: exchange.condition,\n ...(opts.timeout !== undefined ? { timeout: opts.timeout } : {}),\n },\n claim\n );\n\n // Open the answer with the secret this packet sealed. A REJECT sealed at\n // the termination is the DESTINATION refusing; a plaintext one is somebody\n // on the path. Both are `ConnectorError` here — `fetch()` has one failure\n // channel — but they no longer read as the same event.\n const outcome = readExchangeOutcome(\n result,\n result.data === undefined ? undefined : fromBase64(result.data),\n exchange.sharedSecret\n );\n\n if (outcome.kind === 'destination-refused') {\n throw new ConnectorError(\n `h402 request refused by the destination: ${outcome.code} ${outcome.message}`.trim()\n );\n }\n if (outcome.kind === 'path-refused') {\n throw new ConnectorError(\n `h402 request refused by a connector on the path: ${outcome.code} ${outcome.message}`.trim()\n );\n }\n\n return toWebResponse(outcome.response);\n }\n\n /**\n * Send the sealed PREPARE over the selected transport.\n *\n * - `http` / `http-upgradable`: stateless one-shot `POST /ilp` with the claim.\n * - `http-upgradable` additionally exercises {@link HttpIlpClient.upgradeToBtp}\n * for the duplex/streaming path (AC4). v1 still drives the actual write over\n * the one-shot HTTP method even after upgrading — full duplex body streaming\n * is a documented follow-up — but the upgrade call path is wired here.\n * - `btp`: not reachable from h402 (the x402 offer only carries an\n * `httpEndpoint`); guarded for completeness.\n */\n private async sendOverChoice(\n ilpClient: HttpIlpClient,\n choice: IlpTransportChoice,\n params: {\n destination: string;\n amount: string;\n data: string;\n executionCondition: Uint8Array;\n timeout?: number;\n },\n claim: unknown\n ): Promise<IlpSendResult> {\n if (choice.kind === 'http-upgradable') {\n // Wire the upgrade path: obtain (and immediately release) a duplex BTP\n // session so a streaming consumer can take it over in a follow-up. The\n // one-shot write below still terminates the payment for v1.\n const btp = await ilpClient.upgradeToBtp();\n try {\n // BtpRuntimeClient types `claim` as Record<string, unknown>; the claim\n // message is an opaque forwarded envelope (same cast ToonClient uses).\n return await btp.sendIlpPacketWithClaim(\n params,\n claim as Record<string, unknown>\n );\n } finally {\n await btp.disconnect().catch(() => undefined);\n }\n }\n if (choice.kind === 'btp') {\n throw new ToonClientError(\n 'h402 offer resolved to a BTP-only transport; the x402 toon-channel entry must advertise an httpEndpoint',\n 'INVALID_STATE'\n );\n }\n // 'http'\n return ilpClient.sendIlpPacketWithClaim(params, claim);\n }\n}\n\n// ─── x402 challenge parsing (defensive) ─────────────────────────────────────\n\n/** First defined string among the given keys on `obj`. */\nfunction readString(\n obj: Record<string, unknown>,\n keys: string[]\n): string | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'string' && v.trim().length > 0) return v.trim();\n }\n return undefined;\n}\n\n/** First parseable bigint among the given keys (string|number) on `obj`. */\nfunction readAmount(\n obj: Record<string, unknown>,\n keys: string[]\n): bigint | undefined {\n for (const k of keys) {\n const v = obj[k];\n if (typeof v === 'bigint') return v;\n if (typeof v === 'number' && Number.isFinite(v))\n return BigInt(Math.trunc(v));\n if (typeof v === 'string' && /^\\d+$/.test(v.trim()))\n return BigInt(v.trim());\n }\n return undefined;\n}\n\n/**\n * Turn an `httpEndpoint` into something fetchable.\n *\n * The Rust connector emits a RELATIVE endpoint (`\"/ilp\"`), because the terms\n * describe an endpoint on the origin that answered. Resolved against the\n * resource URL it becomes the absolute `POST /ilp` URL this adapter needs. An\n * already-absolute endpoint is returned unchanged; a relative one with no base\n * to resolve against is passed through as before, so nothing that worked\n * previously stops working.\n */\nfunction resolveEndpoint(\n endpoint: string | undefined,\n baseUrl: string | undefined\n): string | undefined {\n if (!endpoint || !baseUrl) return endpoint;\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(endpoint)) return endpoint;\n try {\n return new URL(endpoint, baseUrl).toString();\n } catch {\n return endpoint;\n }\n}\n\n/**\n * Parse a 402 `Response` body into a {@link ParsedX402Challenge}, selecting the\n * first usable `toon-channel` entry. Reads every field defensively; a malformed\n * body, a non-JSON body, or an entry missing its `destination`/`httpEndpoint`\n * yields `{ toonChannel: undefined }` so the caller falls back to the vanilla\n * 402 rather than throwing.\n */\nexport async function parseX402Challenge(\n response: Response\n): Promise<ParsedX402Challenge> {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n return {};\n }\n // `response.url` is the resource that answered 402 — the base a relative\n // `httpEndpoint` (which is what the Rust connector actually emits: `/ilp`)\n // has to be resolved against.\n return parseX402Body(body, response.url || undefined);\n}\n\n/**\n * Pure parser over an already-decoded x402 body (testable without a Response).\n *\n * `baseUrl`, when given, is the absolute URL of the resource that answered\n * `402`; a relative `httpEndpoint` is resolved against it. Omitting it keeps\n * the old behaviour of passing the endpoint through verbatim.\n */\nexport function parseX402Body(\n body: unknown,\n baseUrl?: string\n): ParsedX402Challenge {\n if (typeof body !== 'object' || body === null) return {};\n const b = body as Record<string, unknown>;\n\n const version =\n typeof b['x402Version'] === 'number'\n ? (b['x402Version'] as number)\n : undefined;\n\n const accepts = Array.isArray(b['accepts'])\n ? (b['accepts'] as unknown[])\n : [];\n\n for (const raw of accepts) {\n if (typeof raw !== 'object' || raw === null) continue;\n const entry = raw as Record<string, unknown>;\n const scheme = readString(entry, ['scheme']);\n if (scheme !== 'toon-channel') continue;\n\n // The Rust connector puts the ILP address, the endpoint and the price\n // under `extra` (`crates/connector-client-edge/src/lib.rs`, client-edge-spec\n // §1.4) — NOT at the entry's top level. `extra` is therefore read as a\n // first-class source, not a fallback: reading `payTo` instead only ever\n // worked because that connector happens to set it to the destination too,\n // which is a coincidence of today's code and not part of the contract.\n const extra =\n typeof entry['extra'] === 'object' && entry['extra'] !== null\n ? (entry['extra'] as Record<string, unknown>)\n : {};\n\n const destination =\n readString(extra, ['ilpAddress', 'destination']) ??\n readString(entry, ['destination', 'ilpAddress', 'payTo']);\n const rawEndpoint =\n readString(entry, ['httpEndpoint', 'ilpEndpoint']) ??\n readString(extra, ['httpEndpoint', 'endpoint']) ??\n readString(entry, ['endpoint']);\n const httpEndpoint = resolveEndpoint(rawEndpoint, baseUrl);\n const amount =\n readAmount(extra, ['price', 'amount']) ??\n readAmount(entry, ['amount', 'price', 'maxAmountRequired']);\n\n // A usable entry MUST carry where to pay, how much, and how to reach /ilp.\n if (!destination || !httpEndpoint || amount === undefined) continue;\n\n const network = readString(entry, ['network', 'chain']);\n const supportsUpgrade =\n entry['supportsUpgrade'] === true || entry['upgradable'] === true;\n\n return {\n ...(version !== undefined ? { x402Version: version } : {}),\n toonChannel: {\n scheme: 'toon-channel',\n ...(network !== undefined ? { network } : {}),\n destination,\n amount,\n httpEndpoint,\n supportsUpgrade,\n },\n };\n }\n\n return version !== undefined ? { x402Version: version } : {};\n}\n\n// ─── The one envelope, in and out ───────────────────────────────────────────\n\n/** Normalize an optional string|Uint8Array body to bytes. */\nfunction bodyToBytes(body: string | Uint8Array | undefined): Uint8Array {\n if (body === undefined) return new Uint8Array(0);\n return typeof body === 'string' ? encodeUtf8(body) : body;\n}\n\n/**\n * Turn a caller's `fetch`-shaped request into the `EnvelopeRequest` that is\n * sealed into the packet.\n *\n * The target is the URL's path RELATIVE to the origin root (no leading `/`),\n * plus `search`. ADR 0025 (connector #596) resolves an envelope target\n * strictly BENEATH the route's configured handler path — `''` means \"the\n * handler's own path\", and an absolute `/…` target is refused outright\n * (F00) as an escape attempt, so origin-form is no longer speakable on this\n * wire.\n *\n * Headers are carried in the caller's own order, names verbatim. The envelope\n * is a LIST of pairs, not a map, so order and duplicates both survive — which\n * the old `Map`-based serializer destroyed. Nothing is synthesised: `Host` and\n * `Content-Length` are the connector's to recompute (see the module docs).\n */\nfunction toEnvelopeRequest(\n url: string,\n method: string,\n opts: H402FetchOptions\n): {\n method: string;\n target: string;\n headers: EnvelopeHeader[];\n body: Uint8Array;\n} {\n const u = new URL(url);\n const headers: EnvelopeHeader[] = Object.entries(opts.headers ?? {}).map(\n ([name, value]) => [name, value] as EnvelopeHeader\n );\n return {\n method: method.toUpperCase(),\n // Strip the leading '/' — ADR 0025 targets are handler-relative, and\n // the empty string ('' + no search) is exactly \"the handler's path\".\n target: `${u.pathname.replace(/^\\/+/, '')}${u.search}`,\n headers,\n body: bodyToBytes(opts.body),\n };\n}\n\n/**\n * Present a decoded {@link EnvelopeResponse} as the standard Web `Response`\n * this adapter's callers expect.\n *\n * An adaptation, not a codec: nothing is parsed here, because the status,\n * headers and body arrived already separated by the envelope decoder.\n *\n * `statusText` is left empty — the envelope carries a two-byte status and no\n * reason phrase, so there is no \"Created\" to report. `Headers.append` keeps\n * duplicates (`set-cookie`), and a null-body status never gets one, which\n * `Response` would throw over.\n */\nfunction toWebResponse(envelope: EnvelopeResponse): Response {\n const headers = new Headers();\n for (const [name, value] of envelope.headers) {\n // Hop-by-hop framing headers describe an HTTP/1.1 connection that no\n // longer exists once the answer is an envelope; `Response` recomputes its\n // own body length regardless.\n if (name.toLowerCase() === 'content-length') continue;\n headers.append(name, value);\n }\n\n const status = envelope.status;\n const nullBodyStatus =\n status === 101 || status === 204 || status === 205 || status === 304;\n\n return new Response(\n nullBodyStatus || envelope.body.length === 0\n ? null\n : (envelope.body.slice() as unknown as BodyInit),\n { status, headers }\n );\n}\n","/**\n * Receive-side swap settlement (toon-client#352): turn persisted\n * {@link ReceivedClaimEntry} watermarks into on-chain settlement submissions.\n *\n * Building is pure and chain-agnostic — `buildSettlementTx` (sdk) re-verifies\n * the stored claim's signature and produces one {@link SettlementBundle} per\n * `(chain, channelId)` with the FINAL watermark, so N received advances net to\n * one on-chain close per channel (spec §9). Submission is chain-gated:\n *\n * - **EVM** — implemented here ({@link submitEvmSettlement}): the bundle's\n * unsigned RLP is decoded for `to`/calldata, gas is estimated against the\n * configured RPC, and the tx is signed by the client's EVM account (the\n * claim recipient) and broadcast. Real submission is therefore env-gated on\n * `chainRpcUrls[chain]` — absent RPC config yields a built-not-submitted\n * result, never a throw.\n * - **Solana** — the bundle carries a serialized Message; a submission path is\n * not wired yet (follow-up under toon-meta#145).\n * - **Mina** — receive-side redemption needs a co-sign (`claimFromChannel`\n * takes `signatureA` AND `signatureB`) plus o1js proof generation; the\n * client has no receive-side co-sign path. Explicitly out of scope for #352\n * (documented gap; follow-up: toon-client#357).\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n buildSettlementTx,\n SettlementTxError,\n type MinaSignerClientLike,\n type SettlementBundle,\n type SwapSignerConfig,\n} from '@toon-protocol/sdk';\nimport {\n createPublicClient,\n defineChain,\n fromRlp,\n http,\n type Hex,\n type PrivateKeyAccount,\n} from 'viem';\nimport type { ReceivedClaimEntry } from '../channel/ReceivedClaimStore.js';\n\n/** One per-channel settlement build outcome (result-shaped, never thrown). */\nexport interface SwapSettlementBuild {\n chain: string;\n channelId: string;\n /** The bundle, when the claim verified and the chain config sufficed. */\n bundle?: SettlementBundle;\n /** Why no bundle was produced (missing config, failed re-verification, …). */\n error?: { code: string; message: string };\n}\n\nexport interface BuildSwapSettlementsParams {\n /** Persisted watermarks to settle (typically `store.list()`, filtered). */\n entries: readonly ReceivedClaimEntry[];\n /**\n * Per-chain settlement contract: EVM TokenNetwork address / Solana\n * programId, keyed by the FULL chain key (e.g. `evm:base:8453`). Matches the\n * daemon config's `tokenNetworks` map.\n */\n tokenNetworks?: Record<string, string>;\n /** Pre-loaded `mina-signer` client for `mina:*` re-verification. */\n minaSignerClient?: MinaSignerClientLike;\n /**\n * Re-verify the stored claim's signature at settle time (defense in depth\n * over the store file). Default `true` — the published **v2** sdk\n * (`@toon-protocol/sdk@^3`, connector#324 finding #1) verifies EVM claims\n * against the **v2** EIP-712 domain-separated balance-proof digest, the SAME\n * digest the receive-side used (`ingestReceivedClaims`). Reconstructing that\n * EIP-712 domain needs `chainId` + `verifyingContract`, which this builder\n * threads into the sdk signer config from `tokenNetworks` (for EVM claims) —\n * so a claim verified at receipt re-verifies correctly here.\n *\n * Set `false` only to skip the settle-time re-verify entirely (e.g. when the\n * receive-side verify is treated as the sole authoritative gate); the sdk is\n * then used only to BUILD the settlement calldata.\n */\n verifySignatures?: boolean;\n}\n\n/** Rebuild the sdk `AccumulatedClaim` shape from a persisted entry. */\nexport function entryToAccumulatedClaim(\n entry: ReceivedClaimEntry\n): AccumulatedClaim {\n return {\n packetIndex: 0,\n sourceAmount: 0n,\n targetAmount: entry.cumulativeAmount,\n claimBytes: entry.claimBytes,\n swapEphemeralPubkey: '',\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n channelId: entry.channelId,\n nonce: entry.nonce.toString(),\n cumulativeAmount: entry.cumulativeAmount.toString(),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n };\n}\n\n/**\n * Parse the numeric chain id off an `evm:{network}:{chainId}` / `evm:{chainId}`\n * chain key. Returns undefined for malformed keys (reported result-shaped).\n */\nexport function parseEvmChainId(chain: string): number | undefined {\n const parts = chain.split(':');\n const raw = parts.length >= 3 ? parts[2] : parts[1];\n const chainId = Number.parseInt(raw ?? '', 10);\n return Number.isInteger(chainId) && chainId > 0 ? chainId : undefined;\n}\n\n/**\n * Build one settlement bundle per persisted entry via the sdk's\n * `buildSettlementTx` (signature re-verified at settle time — a tampered\n * store never reaches a submission). Per-entry isolation: one bad channel\n * cannot block the others.\n */\nexport function buildSwapSettlements(\n params: BuildSwapSettlementsParams\n): SwapSettlementBuild[] {\n return params.entries.map((entry) => {\n const base = { chain: entry.chain, channelId: entry.channelId };\n const signer: SwapSignerConfig = { address: entry.swapSignerAddress };\n const contract = params.tokenNetworks?.[entry.chain];\n if (entry.chain.startsWith('evm')) {\n const chainId = parseEvmChainId(entry.chain);\n if (!contract || chainId === undefined) {\n return {\n ...base,\n error: {\n code: 'MISSING_CHAIN_CONFIG',\n message:\n `EVM settlement for ${entry.chain} needs tokenNetworks[\"${entry.chain}\"] ` +\n `(TokenNetwork contract) and a numeric chain id in the chain key.`,\n },\n };\n }\n signer.contractAddress = contract;\n signer.chainId = chainId;\n } else if (entry.chain.startsWith('solana')) {\n if (!contract) {\n return {\n ...base,\n error: {\n code: 'MISSING_CHAIN_CONFIG',\n message: `Solana settlement for ${entry.chain} needs tokenNetworks[\"${entry.chain}\"] (programId).`,\n },\n };\n }\n signer.programId = contract;\n }\n try {\n const result = buildSettlementTx({\n claims: [entryToAccumulatedClaim(entry)],\n signers: { [entry.chain]: signer },\n recipients: { [entry.chain]: entry.recipient },\n ...(params.verifySignatures !== undefined\n ? { verifySignatures: params.verifySignatures }\n : {}),\n ...(params.minaSignerClient\n ? { minaSignerClient: params.minaSignerClient }\n : {}),\n });\n const firstRejected = result.rejected[0];\n if (firstRejected) {\n return {\n ...base,\n error: {\n code: firstRejected.reason,\n message:\n firstRejected.details ??\n `stored claim for ${entry.chain}/${entry.channelId} failed settlement re-verification`,\n },\n };\n }\n const bundle = result.bundles[0];\n if (!bundle) {\n return {\n ...base,\n error: {\n code: 'NO_BUNDLE',\n message: `buildSettlementTx produced no bundle for ${entry.chain}/${entry.channelId}`,\n },\n };\n }\n return { ...base, bundle };\n } catch (err) {\n const code = err instanceof SettlementTxError ? err.code : 'BUILD_FAILED';\n return {\n ...base,\n error: {\n code,\n message: err instanceof Error ? err.message : String(err),\n },\n };\n }\n });\n}\n\nexport interface SubmitEvmSettlementParams {\n /** JSON-RPC endpoint of the bundle's chain (`chainRpcUrls[bundle.chain]`). */\n rpcUrl: string;\n /** The claim recipient's EVM account (signs + pays gas for the redeem). */\n account: PrivateKeyAccount;\n /** Receipt wait bound, ms (default 60_000). */\n timeoutMs?: number;\n}\n\nexport interface SubmitEvmSettlementResult {\n txHash: string;\n /** Receipt status when the wait succeeded within the bound. */\n status?: 'success' | 'reverted';\n}\n\n/**\n * Decode the unsigned legacy-RLP tx a settlement bundle carries.\n * Layout (EIP-155 unsigned): [nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0].\n */\nexport function decodeEvmSettlementTx(bundle: SettlementBundle): {\n to: Hex;\n data: Hex;\n chainId: number;\n} {\n const fields = fromRlp(bundle.unsignedTxBytes, 'hex');\n if (!Array.isArray(fields) || fields.length !== 9) {\n throw new Error(\n `settlement bundle RLP is not a 9-field unsigned EVM tx (got ${Array.isArray(fields) ? fields.length : typeof fields})`\n );\n }\n const to = fields[3] as Hex;\n const data = fields[5] as Hex;\n const chainIdHex = fields[6] as Hex;\n const chainId = Number.parseInt(chainIdHex === '0x' ? '0x0' : chainIdHex, 16);\n if (typeof to !== 'string' || to.length !== 42) {\n throw new Error(\n `settlement tx \"to\" is not a 20-byte address: ${String(to)}`\n );\n }\n return { to, data: (data === '0x' ? '0x' : data) as Hex, chainId };\n}\n\n/**\n * Sign + broadcast an EVM settlement bundle from the recipient's account.\n * Gas/nonce are read from the RPC; the tx is signed locally (non-custodial)\n * and sent as a raw transaction, then awaited to a receipt (bounded).\n */\nexport async function submitEvmSettlement(\n bundle: SettlementBundle,\n params: SubmitEvmSettlementParams\n): Promise<SubmitEvmSettlementResult> {\n if (bundle.chainKind !== 'evm') {\n throw new Error(\n `submitEvmSettlement only submits evm bundles (got ${bundle.chainKind} for ${bundle.chain})`\n );\n }\n const { to, data, chainId } = decodeEvmSettlementTx(bundle);\n const chain = defineChain({\n id: chainId,\n name: bundle.chain,\n nativeCurrency: { name: 'ETH', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [params.rpcUrl] } },\n });\n const publicClient = createPublicClient({\n chain,\n transport: http(params.rpcUrl),\n });\n\n const [nonce, gasPrice, gas] = await Promise.all([\n publicClient.getTransactionCount({\n address: params.account.address,\n blockTag: 'pending',\n }),\n publicClient.getGasPrice(),\n publicClient.estimateGas({ account: params.account.address, to, data }),\n ]);\n\n const signed = await params.account.signTransaction({\n type: 'legacy',\n chainId,\n nonce,\n gasPrice,\n gas,\n to,\n value: 0n,\n data,\n });\n const txHash = await publicClient.sendRawTransaction({\n serializedTransaction: signed,\n });\n try {\n const receipt = await publicClient.waitForTransactionReceipt({\n hash: txHash,\n timeout: params.timeoutMs ?? 60_000,\n });\n return { txHash, status: receipt.status };\n } catch {\n // The tx is broadcast; a slow chain just means the caller re-checks later.\n return { txHash };\n }\n}\n","/**\n * Mina receive-side swap settlement (toon-client#357, part of the rolling-swap\n * epic toon-meta#145; follow-up to the #352 receive-side ingestion PR).\n *\n * #352 shipped VERIFICATION of swapped-in Mina claims but explicitly left\n * REDEMPTION out: `POST /swap/settle` returned `SUBMISSION_UNSUPPORTED` for\n * `mina:*` bundles. This module is the missing redemption seam — it turns a\n * verified accumulated Mina claim into an on-chain co-signed `claimFromChannel`\n * transaction against the payment-channel zkApp.\n *\n * ## Why Mina needs a co-sign (and EVM/Solana do not)\n *\n * The zkApp's `claimFromChannel(newBalanceA, newBalanceB, newSalt, signatureA,\n * signatureB, participantA, participantB, channelNonce, newBalanceCommitment,\n * newNonce)` is DUAL-PARTY (connector#84): it verifies BOTH participants signed\n * the SAME message `[newBalanceCommitment, newNonce, storedChannelHash]`\n * (`packages/mina-zkapp/src/PaymentChannel.ts`). The client's existing\n * {@link MinaSigner} is payer-side only. On the swap RECEIVE side the client is\n * the RECIPIENT of the channel, so it must contribute the recipient's\n * co-signature (`signatureB` for its participant slot).\n *\n * ## Signature-message mismatch — the maker-side dependency\n *\n * The swap-wire claim (`AccumulatedClaim.claimBytes`) carries the maker's\n * Schnorr signature over `balanceProofFieldsMina(channelId, cumulativeAmount,\n * nonce, recipient)` (verified by the sdk's `verifyMinaSignature`). That is a\n * DIFFERENT message than the on-chain `[commitment, nonce, channelHash]`, so it\n * CANNOT be reused as an on-chain participant signature. On-chain redemption\n * therefore needs the maker to ALSO contribute a payment-channel-commitment-form\n * signature over `[commitment, nonce, channelHash]` (the same form the connector\n * payment-channel provider produces from a client claim). Until a maker delivers\n * that, {@link submitMinaSettlement} fails closed with\n * `MINA_MAKER_COSIGN_REQUIRED` (never a silent pass). See the PR body for the\n * cross-repo maker/wire follow-up.\n *\n * ## globalSlot preconditions\n *\n * Unlike `initiateClose`/`settle` (which pin `network.globalSlotSinceGenesis`\n * and were the subject of the #202 exact-slot-precondition bug), the zkApp's\n * `claimFromChannel` binds NO slot precondition — only `channelState == OPEN`,\n * `channelHash`, `depositTotal`, and a strictly-increasing `nonceField`. The\n * redeem path is therefore immune to the #202 slot-drift failure. The eventual\n * close+settle that pays escrow out to the recipient DOES touch the slot window\n * and remains the connector's `settleChannel` responsibility (a separate step).\n *\n * ## What runs where\n *\n * - On-chain STATE READ + co-sign assembly ({@link buildMinaCoSignedClaim}):\n * plain GraphQL + `mina-signer` (Pallas Schnorr / Poseidon) — NO o1js, fully\n * unit-testable in-process.\n * - Proof generation + broadcast ({@link submitMinaSettlement}): drives an\n * injectable {@link MinaClaimSubmitter}; the default is an o1js-backed settler\n * ({@link createO1jsMinaClaimSubmitter}) that dynamically imports `o1js` +\n * `@toon-protocol/mina-zkapp` only when invoked (never loaded by the non-Mina\n * suite). o1js circuit compilation + proving is slow (30-120s) and is exercised\n * only against live devnet Mina behind an env gate.\n */\n\nimport { hexToMinaBase58PrivateKey } from '@toon-protocol/core';\nimport type { SettlementBundle } from '@toon-protocol/sdk';\nimport {\n buildMinaPaymentChannelProof,\n loadMinaPaymentChannelBindings,\n minaBalanceCommitment,\n minaParticipantChannelHashField,\n} from '../channel/mina-payment-channel.js';\nimport {\n readMinaChannelState,\n MINA_CHANNEL_STATE,\n type MinaOnChainChannelState,\n} from '../channel/mina-deposit.js';\nimport { deriveMinaSalt } from '../signing/mina-signer.js';\n\n/** Bare Pallas Schnorr signature in the o1js JSON (decimal `r`/`s`) form. */\nexport interface MinaSignaturePair {\n r: string;\n s: string;\n}\n\n/** Stable failure codes for Mina receive-side settlement. */\nexport type MinaSettlementErrorCode =\n | 'NOT_MINA_BUNDLE'\n | 'NO_GRAPHQL_CONFIGURED'\n | 'CHANNEL_NOT_OPEN'\n | 'NONCE_NOT_ADVANCING'\n | 'CHANNEL_HASH_MISMATCH'\n | 'CUMULATIVE_EXCEEDS_DEPOSIT'\n | 'MINA_MAKER_COSIGN_REQUIRED'\n | 'PROVING_FAILED';\n\n/** Result-shaped-by-throw settlement error carrying a stable {@link code}. */\nexport class MinaSettlementError extends Error {\n readonly code: MinaSettlementErrorCode;\n constructor(code: MinaSettlementErrorCode, message: string) {\n super(`${code}: ${message}`);\n this.name = 'MinaSettlementError';\n this.code = code;\n }\n}\n\n/** Inputs to {@link buildMinaCoSignedClaim} (pure assembly, no o1js). */\nexport interface MinaCoSignInputs {\n /** Deployed payment-channel zkApp address (B62) — the on-chain channel id. */\n channelId: string;\n /** Claim nonce being redeemed (must exceed the on-chain `nonceField`). */\n nonce: bigint;\n /** Cumulative amount credited to the recipient (base units). */\n cumulativeAmount: bigint;\n /** Recipient's Mina B62 pubkey — one channel participant (the co-signer). */\n recipient: string;\n /** Swap maker's Mina B62 pubkey — the other channel participant. */\n swapSignerAddress: string;\n /** On-chain `depositTotal` (base units) for balance conservation. */\n depositTotal: bigint;\n /** On-chain `channelHash` (decimal Field) used to resolve A/B ordering. */\n onChainChannelHash: string;\n /** Recipient's Mina private key (big-endian hex scalar OR `EK…` base58). */\n recipientPrivateKey: string;\n /** Channel nonce baked into the on-chain `channelHash` (default 0). */\n channelNonce?: bigint;\n /** Override the deterministic salt (else {@link deriveMinaSalt}). */\n saltOverride?: bigint;\n /**\n * Maker's payment-channel-commitment-form signature over\n * `[commitment, nonce, channelHash]`. REQUIRED for a fully-redeemable claim;\n * when absent the returned claim reports {@link makerSignatureMissing}.\n */\n makerSignature?: MinaSignaturePair;\n}\n\n/** A dual-party claim assembled for the zkApp's `claimFromChannel`. */\nexport interface MinaCoSignedClaim {\n channelId: string;\n /** Balance credited to `participantA` (base units). */\n balanceA: bigint;\n /** Balance credited to `participantB` (`depositTotal - balanceA`). */\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n channelNonce: bigint;\n /** `Poseidon([balanceA, balanceB, salt])`, decimal Field. */\n balanceCommitment: string;\n /** Participant A B62 (ordered to reproduce the on-chain `channelHash`). */\n participantA: string;\n /** Participant B B62. */\n participantB: string;\n /** Which participant slot the recipient/co-signer occupies. */\n recipientRole: 'A' | 'B';\n /** The recipient's co-signature over `[commitment, nonce, channelHash]`. */\n recipientSignature: MinaSignaturePair;\n /** Signature for participant A (recipient's or maker's per {@link recipientRole}). */\n signatureA?: MinaSignaturePair;\n /** Signature for participant B. */\n signatureB?: MinaSignaturePair;\n /** True when no maker co-signature was supplied (claim not yet redeemable). */\n makerSignatureMissing: boolean;\n}\n\n/** Extract the bare `{ r, s }` from a `buildMinaPaymentChannelProof` proof JSON. */\nfunction parseProofSignature(proofJson: string): MinaSignaturePair {\n const parsed = JSON.parse(proofJson) as {\n signature?: { r?: unknown; s?: unknown };\n };\n const r = parsed.signature?.r;\n const s = parsed.signature?.s;\n if (typeof r !== 'string' || typeof s !== 'string') {\n throw new Error('recipient co-signature proof did not carry string r/s');\n }\n return { r, s };\n}\n\n/**\n * Assemble a dual-party `claimFromChannel` claim from a verified swap claim.\n *\n * Pure crypto (GraphQL-read state is passed in): resolves the on-chain A/B\n * participant ordering by reproducing `channelHash`, conserves balances against\n * `depositTotal`, computes the Poseidon commitment, and produces the recipient's\n * co-signature over `[commitment, nonce, channelHash]` with `mina-signer`. No\n * o1js is loaded.\n *\n * @throws {MinaSettlementError} `CHANNEL_HASH_MISMATCH` when neither ordering of\n * `{recipient, swapSignerAddress}` reproduces `onChainChannelHash`;\n * `CUMULATIVE_EXCEEDS_DEPOSIT` when the credit exceeds the escrow.\n */\nexport async function buildMinaCoSignedClaim(\n inputs: MinaCoSignInputs\n): Promise<MinaCoSignedClaim> {\n const channelNonce = inputs.channelNonce ?? 0n;\n const salt =\n inputs.saltOverride ?? deriveMinaSalt(inputs.channelId, Number(inputs.nonce));\n\n if (inputs.cumulativeAmount > inputs.depositTotal) {\n throw new MinaSettlementError(\n 'CUMULATIVE_EXCEEDS_DEPOSIT',\n `claim cumulativeAmount (${inputs.cumulativeAmount}) exceeds the channel ` +\n `depositTotal (${inputs.depositTotal}) — cannot conserve balances`\n );\n }\n\n const { Poseidon, PublicKey } = await loadMinaPaymentChannelBindings();\n\n // Resolve which participant slot each party occupies by reproducing the\n // on-chain channelHash = Poseidon([A.x, B.x, channelNonce]). The zkApp verifies\n // signatureA against participantA and signatureB against participantB, so the\n // balances + signatures must be assigned to the ordering the channel was\n // opened with.\n const hashRecipientFirst = minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n inputs.recipient,\n inputs.swapSignerAddress,\n channelNonce\n ).toString();\n const hashMakerFirst = minaParticipantChannelHashField(\n Poseidon,\n PublicKey,\n inputs.swapSignerAddress,\n inputs.recipient,\n channelNonce\n ).toString();\n\n let participantA: string;\n let participantB: string;\n let recipientRole: 'A' | 'B';\n if (hashRecipientFirst === inputs.onChainChannelHash) {\n participantA = inputs.recipient;\n participantB = inputs.swapSignerAddress;\n recipientRole = 'A';\n } else if (hashMakerFirst === inputs.onChainChannelHash) {\n participantA = inputs.swapSignerAddress;\n participantB = inputs.recipient;\n recipientRole = 'B';\n } else {\n throw new MinaSettlementError(\n 'CHANNEL_HASH_MISMATCH',\n `neither ordering of recipient ${inputs.recipient} / maker ` +\n `${inputs.swapSignerAddress} reproduces the on-chain channelHash ` +\n `${inputs.onChainChannelHash} (channelNonce ${channelNonce})`\n );\n }\n\n // Recipient-credit: the recipient's balance is the cumulative amount; the\n // maker (funder) keeps the remainder. Assign to A/B by the resolved ordering.\n const recipientBalance = inputs.cumulativeAmount;\n const makerBalance = inputs.depositTotal - inputs.cumulativeAmount;\n const balanceA = recipientRole === 'A' ? recipientBalance : makerBalance;\n const balanceB = inputs.depositTotal - balanceA;\n\n const balanceCommitment = minaBalanceCommitment(\n Poseidon,\n balanceA,\n balanceB,\n salt\n ).toString();\n\n // Recipient co-signs [commitment, nonce, channelHash] with its own key over\n // the SAME participant-form channelHash the zkApp stored. Reuse the connector-\n // parity proof builder so signer and on-chain verifier cannot drift.\n const recipientPrivateKeyBase58 = hexToMinaBase58PrivateKey(\n inputs.recipientPrivateKey\n );\n const built = await buildMinaPaymentChannelProof({\n zkAppAddress: inputs.channelId,\n minaPrivateKeyBase58: recipientPrivateKeyBase58,\n signerPublicKey: inputs.recipient,\n balanceA,\n balanceB,\n salt,\n nonce: inputs.nonce,\n participantA,\n participantB,\n channelNonce,\n proofEncoding: 'json',\n });\n if (built.balanceCommitment !== balanceCommitment) {\n // Defense-in-depth: the proof builder recomputes the commitment; a mismatch\n // means the two Poseidon paths diverged (should never happen).\n throw new Error(\n `co-sign commitment drift: builder ${built.balanceCommitment} != ${balanceCommitment}`\n );\n }\n const recipientSignature = parseProofSignature(built.proof);\n\n const signatureA =\n recipientRole === 'A' ? recipientSignature : inputs.makerSignature;\n const signatureB =\n recipientRole === 'B' ? recipientSignature : inputs.makerSignature;\n\n return {\n channelId: inputs.channelId,\n balanceA,\n balanceB,\n salt,\n nonce: inputs.nonce,\n channelNonce,\n balanceCommitment,\n participantA,\n participantB,\n recipientRole,\n recipientSignature,\n ...(signatureA ? { signatureA } : {}),\n ...(signatureB ? { signatureB } : {}),\n makerSignatureMissing: inputs.makerSignature === undefined,\n };\n}\n\n/** Arguments handed to a {@link MinaClaimSubmitter} (o1js proving boundary). */\nexport interface MinaClaimSubmitArgs {\n /** Mina GraphQL endpoint bound as the active o1js network. */\n graphqlUrl: string;\n /** Channel zkApp address (B62). */\n channelId: string;\n balanceA: bigint;\n balanceB: bigint;\n salt: bigint;\n nonce: bigint;\n /** Participant pubkeys (B62), ordered to match the on-chain `channelHash`. */\n participantA: string;\n participantB: string;\n channelNonce: bigint;\n signatureA: MinaSignaturePair;\n signatureB: MinaSignaturePair;\n /** Fee-payer / submitter Mina private key (hex scalar or `EK…` base58). */\n feePayerPrivateKey: string;\n /** zkApp tx fee (nanomina); the default settler applies 0.1 MINA when unset. */\n txFeeNanomina?: bigint;\n}\n\n/**\n * Generates the o1js proof and broadcasts the `claimFromChannel` tx. Injected so\n * the assembly logic can be unit-tested without loading the WASM circuit runtime.\n */\nexport interface MinaClaimSubmitter {\n claimFromChannel(args: MinaClaimSubmitArgs): Promise<{ txHash: string }>;\n}\n\n/** Read seam for the on-chain channel state (default: plain GraphQL). */\nexport type MinaChannelStateReader = (\n graphqlUrl: string,\n zkAppAddress: string\n) => Promise<MinaOnChainChannelState>;\n\n/** Context for {@link submitMinaSettlement}. */\nexport interface MinaSettlementContext {\n /** Mina GraphQL URL (reads state + binds the o1js network). */\n graphqlUrl?: string;\n /** Recipient's Mina private key (co-signs; also the default fee payer). */\n recipientPrivateKey: string;\n /** Maker's on-chain-form co-signature over `[commitment, nonce, channelHash]`. */\n makerSignature?: MinaSignaturePair;\n /** Fee-payer key override (defaults to `recipientPrivateKey`). */\n feePayerPrivateKey?: string;\n /** zkApp tx fee (nanomina). */\n txFeeNanomina?: bigint;\n /** Channel nonce for the on-chain `channelHash` (default 0). */\n channelNonce?: bigint;\n /** Inject a state reader (tests). Defaults to {@link readMinaChannelState}. */\n reader?: MinaChannelStateReader;\n /** Inject a proof submitter (tests). Defaults to an o1js-backed settler. */\n submitter?: MinaClaimSubmitter;\n}\n\nexport interface MinaSettlementResult {\n txHash: string;\n}\n\n/**\n * Redeem a verified Mina swap claim via a co-signed on-chain `claimFromChannel`.\n *\n * Env/config-gated like the EVM path: with no `graphqlUrl` the caller gets\n * `NO_GRAPHQL_CONFIGURED` (built-not-submitted). Reads the live channel state,\n * asserts it is OPEN and the claim nonce advances the on-chain watermark,\n * assembles the dual-party claim ({@link buildMinaCoSignedClaim}), and — only\n * with a maker co-signature present — drives the o1js proof + broadcast.\n *\n * @throws {MinaSettlementError} with a stable {@link MinaSettlementErrorCode}.\n */\nexport async function submitMinaSettlement(\n bundle: SettlementBundle,\n context: MinaSettlementContext\n): Promise<MinaSettlementResult> {\n if (bundle.chainKind !== 'mina') {\n throw new MinaSettlementError(\n 'NOT_MINA_BUNDLE',\n `submitMinaSettlement only settles mina bundles (got ${bundle.chainKind} for ${bundle.chain})`\n );\n }\n if (!context.graphqlUrl) {\n throw new MinaSettlementError(\n 'NO_GRAPHQL_CONFIGURED',\n `no Mina graphqlUrl configured for \"${bundle.chain}\" — set minaChannel.graphqlUrl to enable receive-side settlement.`\n );\n }\n const graphqlUrl = context.graphqlUrl;\n const channelNonce = context.channelNonce ?? 0n;\n const nonce = BigInt(bundle.nonce);\n const cumulativeAmount = BigInt(bundle.cumulativeAmount);\n\n const read = context.reader ?? readMinaChannelState;\n const state = await read(graphqlUrl, bundle.channelId);\n\n if (state.channelState !== MINA_CHANNEL_STATE.OPEN) {\n throw new MinaSettlementError(\n 'CHANNEL_NOT_OPEN',\n `channel ${bundle.channelId} is not OPEN (channelState=${state.channelState}); claimFromChannel only applies to an OPEN channel.`\n );\n }\n if (nonce <= state.nonceField) {\n throw new MinaSettlementError(\n 'NONCE_NOT_ADVANCING',\n `claim nonce ${nonce} does not advance the on-chain nonceField ${state.nonceField} for ${bundle.channelId} (already claimed).`\n );\n }\n\n const claim = await buildMinaCoSignedClaim({\n channelId: bundle.channelId,\n nonce,\n cumulativeAmount,\n recipient: bundle.recipient,\n swapSignerAddress: bundle.swapSignerAddress,\n depositTotal: state.depositTotal,\n onChainChannelHash: state.channelHash,\n recipientPrivateKey: context.recipientPrivateKey,\n channelNonce,\n ...(context.makerSignature ? { makerSignature: context.makerSignature } : {}),\n });\n\n if (claim.makerSignatureMissing || !claim.signatureA || !claim.signatureB) {\n throw new MinaSettlementError(\n 'MINA_MAKER_COSIGN_REQUIRED',\n `on-chain claimFromChannel is dual-party: it needs the maker's ` +\n `payment-channel-commitment signature over [commitment, nonce, channelHash] ` +\n `in addition to the recipient's co-signature. The swap-wire claim only carries ` +\n `the maker's balanceProofFieldsMina signature (a different message), so the maker ` +\n `must additionally deliver an on-chain-form co-signature. Recipient co-signature ` +\n `assembled and ready (${bundle.channelId} nonce ${nonce}).`\n );\n }\n\n const submitter = context.submitter ?? createO1jsMinaClaimSubmitter();\n const { txHash } = await submitter.claimFromChannel({\n graphqlUrl,\n channelId: bundle.channelId,\n balanceA: claim.balanceA,\n balanceB: claim.balanceB,\n salt: claim.salt,\n nonce: claim.nonce,\n participantA: claim.participantA,\n participantB: claim.participantB,\n channelNonce: claim.channelNonce,\n signatureA: claim.signatureA,\n signatureB: claim.signatureB,\n feePayerPrivateKey:\n context.feePayerPrivateKey ?? context.recipientPrivateKey,\n ...(context.txFeeNanomina !== undefined\n ? { txFeeNanomina: context.txFeeNanomina }\n : {}),\n });\n return { txHash };\n}\n\n/** Default zkApp tx fee (0.1 MINA in nanomina) — real networks reject 0-fee txs. */\nconst DEFAULT_MINA_TX_FEE_NANOMINA = 100_000_000n;\n\n/**\n * Build the default o1js-backed {@link MinaClaimSubmitter}.\n *\n * Mirrors the connector's `MinaPaymentChannelSDK.claimFromChannel`: binds the\n * active Mina network, fetches the channel + fee-payer accounts, deserializes the\n * `{r,s}` signatures, and builds + proves + broadcasts the zkApp\n * `claimFromChannel` method. o1js and `@toon-protocol/mina-zkapp` are imported\n * dynamically INSIDE `claimFromChannel` so the non-Mina test suite never loads\n * the multi-hundred-MB WASM circuit runtime. Compilation + proving are slow\n * (30-120s) and only run against live devnet Mina.\n */\nexport function createO1jsMinaClaimSubmitter(): MinaClaimSubmitter {\n return {\n async claimFromChannel(args: MinaClaimSubmitArgs): Promise<{ txHash: string }> {\n try {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const o1js: any = await import('o1js');\n const {\n Mina,\n PrivateKey,\n PublicKey,\n Field,\n Poseidon,\n Signature,\n fetchAccount,\n } = o1js;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const zkAppMod: any = await import('@toon-protocol/mina-zkapp');\n const PaymentChannel = zkAppMod.PaymentChannel;\n\n Mina.setActiveInstance(Mina.Network(args.graphqlUrl));\n\n const feePayerKey = PrivateKey.fromBase58(\n hexToMinaBase58PrivateKey(args.feePayerPrivateKey)\n );\n const feePayerPub = feePayerKey.toPublicKey();\n\n await PaymentChannel.compile();\n\n const zkAppPub = PublicKey.fromBase58(args.channelId);\n await fetchAccount({ publicKey: zkAppPub });\n await fetchAccount({ publicKey: feePayerPub });\n const zkApp = new PaymentChannel(zkAppPub);\n\n const balA = Field(args.balanceA);\n const balB = Field(args.balanceB);\n const saltField = Field(args.salt);\n const newNonce = Field(args.nonce);\n const channelNonce = Field(args.channelNonce);\n const newBalanceCommitment = Poseidon.hash([balA, balB, saltField]);\n const sigA = Signature.fromJSON({\n r: args.signatureA.r,\n s: args.signatureA.s,\n });\n const sigB = Signature.fromJSON({\n r: args.signatureB.r,\n s: args.signatureB.s,\n });\n const partA = PublicKey.fromBase58(args.participantA);\n const partB = PublicKey.fromBase58(args.participantB);\n\n const fee = (\n args.txFeeNanomina ?? DEFAULT_MINA_TX_FEE_NANOMINA\n ).toString();\n const txn = await Mina.transaction(\n { sender: feePayerPub, fee },\n async () => {\n await zkApp.claimFromChannel(\n balA,\n balB,\n saltField,\n sigA,\n sigB,\n partA,\n partB,\n channelNonce,\n newBalanceCommitment,\n newNonce\n );\n }\n );\n await txn.prove();\n const sent = await txn.sign([feePayerKey]).send();\n return { txHash: sent.hash ?? '' };\n } catch (err) {\n throw new MinaSettlementError(\n 'PROVING_FAILED',\n err instanceof Error ? err.message : String(err)\n );\n }\n },\n };\n}\n","import type { ConnectorAdminClient } from '@toon-protocol/core';\nimport {\n ValidationError,\n NetworkError,\n ConnectorError,\n UnauthorizedError,\n PeerNotFoundError,\n PeerAlreadyExistsError,\n} from '../errors.js';\nimport { withRetry } from '../utils/retry.js';\n\n/**\n * Configuration for HttpConnectorAdmin.\n */\nexport interface HttpConnectorAdminConfig {\n /** Admin API base URL (e.g., 'http://localhost:8081') */\n adminUrl: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts for network failures (default: 3) */\n maxRetries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** HTTP client for testing (default: global fetch) */\n httpClient?: typeof fetch;\n}\n\n/**\n * Result of a bulk peer operation.\n */\nexport interface PeerOperationResult {\n /** Peer ID that was operated on */\n peerId: string;\n /** Whether the operation succeeded */\n success: boolean;\n /** Error that occurred (if failed) */\n error?: Error;\n}\n\n/**\n * HTTP-based connector admin client for managing ILP peers via REST API.\n *\n * Implements the ConnectorAdminClient interface using HTTP requests to the\n * connector's admin API (typically port 8081).\n *\n * @example\n * ```typescript\n * // Embedded mode (DirectConnectorAdmin)\n * const adminClient = new DirectConnectorAdmin(connectorNode);\n *\n * // HTTP mode (HttpConnectorAdmin)\n * const adminClient = new HttpConnectorAdmin({\n * adminUrl: 'http://localhost:8081'\n * });\n *\n * // Add peer\n * await adminClient.addPeer({\n * id: 'nostr-abc123',\n * url: 'btp+ws://alice.example.com:3000',\n * authToken: 'secret-token',\n * routes: [{ prefix: 'g.toon.alice' }]\n * });\n *\n * // Remove peer\n * await adminClient.removePeer('nostr-abc123');\n * ```\n *\n * @throws {ValidationError} Input validation failed (before HTTP request)\n * @throws {NetworkError} Connection failed (ECONNREFUSED, ETIMEDOUT)\n * @throws {UnauthorizedError} Admin API returned 401 (missing/invalid auth)\n * @throws {PeerAlreadyExistsError} Admin API returned 409 (duplicate peer)\n * @throws {PeerNotFoundError} Admin API returned 404 (peer not found)\n * @throws {ConnectorError} Admin API returned 5xx (server error)\n */\nexport class HttpConnectorAdmin implements ConnectorAdminClient {\n private readonly adminUrl: string;\n private readonly timeout: number;\n private readonly retryConfig: { maxRetries: number; retryDelay: number };\n private readonly httpClient: typeof fetch;\n\n constructor(config: HttpConnectorAdminConfig) {\n this.adminUrl = config.adminUrl.replace(/\\/$/, ''); // Remove trailing slash\n this.timeout = config.timeout ?? 30000;\n this.retryConfig = {\n maxRetries: config.maxRetries ?? 3,\n retryDelay: config.retryDelay ?? 1000,\n };\n this.httpClient = config.httpClient ?? fetch;\n }\n\n /**\n * Add a peer to the connector via the admin API.\n *\n * Validates peer config parameters and sends HTTP POST to /admin/peers.\n *\n * @param config - Peer configuration\n * @param config.id - Unique peer identifier (non-empty string)\n * @param config.url - BTP WebSocket URL (must start with 'btp+ws://' or 'btp+wss://')\n * @param config.authToken - Authentication token (non-empty string)\n * @param config.routes - Optional routing table entries\n * @param config.settlement - Optional settlement configuration\n *\n * @throws {ValidationError} Invalid peer config (missing id, invalid url, etc.)\n * @throws {PeerAlreadyExistsError} Peer with same ID already exists (409 Conflict)\n * @throws {UnauthorizedError} Admin API authentication failed (401)\n * @throws {NetworkError} Connection to admin API failed\n * @throws {ConnectorError} Admin API server error (5xx)\n */\n async addPeer(config: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }): Promise<void> {\n // Validate required fields\n if (\n !config.id ||\n typeof config.id !== 'string' ||\n config.id.trim() === ''\n ) {\n throw new ValidationError('Peer id must be a non-empty string');\n }\n\n if (\n !config.url ||\n typeof config.url !== 'string' ||\n config.url.trim() === ''\n ) {\n throw new ValidationError('Peer url must be a non-empty string');\n }\n\n // Validate BTP URL format (accept both ws:// and btp+ws:// formats)\n const hasWsPrefix =\n config.url.startsWith('ws://') || config.url.startsWith('wss://');\n const hasBtpPrefix =\n config.url.startsWith('btp+ws://') || config.url.startsWith('btp+wss://');\n\n if (!hasWsPrefix && !hasBtpPrefix) {\n throw new ValidationError(\n `Invalid BTP URL format: \"${config.url}\". Must start with 'ws://', 'wss://', 'btp+ws://', or 'btp+wss://'`\n );\n }\n\n // authToken can be empty string for BTP (doesn't require authentication)\n if (\n config.authToken === undefined ||\n config.authToken === null ||\n typeof config.authToken !== 'string'\n ) {\n throw new ValidationError(\n 'Peer authToken must be a string (can be empty for no auth)'\n );\n }\n\n // Validate routes (if provided)\n if (config.routes !== undefined) {\n if (!Array.isArray(config.routes)) {\n throw new ValidationError('Peer routes must be an array');\n }\n\n for (const route of config.routes) {\n if (\n !route.prefix ||\n typeof route.prefix !== 'string' ||\n route.prefix.trim() === ''\n ) {\n throw new ValidationError('Route prefix must be a non-empty string');\n }\n if (\n route.priority !== undefined &&\n typeof route.priority !== 'number'\n ) {\n throw new ValidationError('Route priority must be a number');\n }\n }\n }\n\n // Validate settlement (if provided)\n if (config.settlement !== undefined) {\n if (typeof config.settlement !== 'object' || config.settlement === null) {\n throw new ValidationError('Peer settlement must be an object');\n }\n\n if (\n !config.settlement.preference ||\n typeof config.settlement.preference !== 'string'\n ) {\n throw new ValidationError(\n 'Settlement preference must be a non-empty string'\n );\n }\n }\n\n // Send HTTP POST request with retry logic\n const url = `${this.adminUrl}/admin/peers`;\n\n await withRetry(async () => this.sendAddPeerRequest(url, config), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors (ECONNREFUSED, ETIMEDOUT)\n // Do not retry on validation errors, 4xx, or 5xx errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Remove a peer from the connector via the admin API.\n *\n * Sends HTTP DELETE to /admin/peers/:id.\n *\n * @param peerId - Unique peer identifier to remove (non-empty string)\n *\n * @throws {ValidationError} Invalid peerId (empty string)\n * @throws {PeerNotFoundError} Peer does not exist (404 Not Found)\n * @throws {UnauthorizedError} Admin API authentication failed (401)\n * @throws {NetworkError} Connection to admin API failed\n * @throws {ConnectorError} Admin API server error (5xx)\n */\n async removePeer(peerId: string): Promise<void> {\n // Validate peerId\n if (!peerId || typeof peerId !== 'string' || peerId.trim() === '') {\n throw new ValidationError('peerId must be a non-empty string');\n }\n\n // Send HTTP DELETE request with retry logic\n const url = `${this.adminUrl}/admin/peers/${encodeURIComponent(peerId)}`;\n\n await withRetry(async () => this.sendRemovePeerRequest(url, peerId), {\n maxRetries: this.retryConfig.maxRetries,\n retryDelay: this.retryConfig.retryDelay,\n exponentialBackoff: true,\n shouldRetry: (error) => {\n // Only retry on network errors\n return error instanceof NetworkError;\n },\n });\n }\n\n /**\n * Add multiple peers in parallel for efficient bootstrapping.\n *\n * Uses Promise.allSettled() to execute peer additions concurrently,\n * returning results for each operation regardless of individual failures.\n *\n * @param configs - Array of peer configurations to add\n * @returns Array of results indicating success/failure for each peer\n *\n * @example\n * ```typescript\n * const results = await admin.addPeers([\n * { id: 'peer1', url: 'btp+ws://...', authToken: 'token1' },\n * { id: 'peer2', url: 'btp+ws://...', authToken: 'token2' },\n * ]);\n *\n * results.forEach(result => {\n * if (result.success) {\n * console.log(`Added peer: ${result.peerId}`);\n * } else {\n * console.error(`Failed to add ${result.peerId}:`, result.error);\n * }\n * });\n * ```\n */\n async addPeers(\n configs: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }[]\n ): Promise<PeerOperationResult[]> {\n const results = await Promise.allSettled(\n configs.map((config) => this.addPeer(config))\n );\n\n return results.map((result, index) => {\n const config = configs[index];\n return {\n peerId: config ? config.id : 'unknown',\n success: result.status === 'fulfilled',\n error: result.status === 'rejected' ? result.reason : undefined,\n };\n });\n }\n\n /**\n * Remove multiple peers in parallel.\n *\n * Uses Promise.allSettled() to execute peer removals concurrently,\n * returning results for each operation regardless of individual failures.\n *\n * @param peerIds - Array of peer IDs to remove\n * @returns Array of results indicating success/failure for each peer\n *\n * @example\n * ```typescript\n * const results = await admin.removePeers(['peer1', 'peer2', 'peer3']);\n *\n * const succeeded = results.filter(r => r.success).length;\n * console.log(`Removed ${succeeded}/${results.length} peers`);\n * ```\n */\n async removePeers(peerIds: string[]): Promise<PeerOperationResult[]> {\n const results = await Promise.allSettled(\n peerIds.map((peerId) => this.removePeer(peerId))\n );\n\n return results.map((result, index) => {\n const peerId = peerIds[index];\n return {\n peerId: peerId ?? 'unknown',\n success: result.status === 'fulfilled',\n error: result.status === 'rejected' ? result.reason : undefined,\n };\n });\n }\n\n /**\n * Send HTTP POST request to add a peer.\n * Separated for retry logic wrapping.\n */\n private async sendAddPeerRequest(\n url: string,\n config: {\n id: string;\n url: string;\n authToken: string;\n routes?: { prefix: string; priority?: number }[];\n settlement?: {\n preference: string;\n evmAddress?: string;\n tokenAddress?: string;\n tokenNetworkAddress?: string;\n chainId?: number;\n channelId?: string;\n initialDeposit?: string;\n };\n }\n ): Promise<void> {\n // Normalize URL for connector API (expects ws:// or wss://)\n // Strip btp+ prefix if present, or use as-is if already plain ws://\n let connectorUrl = config.url;\n if (connectorUrl.startsWith('btp+')) {\n connectorUrl = connectorUrl.replace(/^btp\\+/, '');\n }\n\n try {\n const response = await this.httpClient(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n ...config,\n url: connectorUrl,\n }),\n signal: AbortSignal.timeout(this.timeout),\n });\n\n if (response.ok) {\n return; // Success (201 Created)\n }\n\n // Handle error responses\n await this.handleErrorResponse(response, `POST ${url}`, config.id);\n } catch (error) {\n this.handleNetworkError(error, url, 'addPeer');\n }\n }\n\n /**\n * Send HTTP DELETE request to remove a peer.\n * Separated for retry logic wrapping.\n */\n private async sendRemovePeerRequest(\n url: string,\n peerId: string\n ): Promise<void> {\n try {\n const response = await this.httpClient(url, {\n method: 'DELETE',\n signal: AbortSignal.timeout(this.timeout),\n });\n\n if (response.ok) {\n return; // Success (204 No Content)\n }\n\n // Handle error responses\n await this.handleErrorResponse(response, `DELETE ${url}`, peerId);\n } catch (error) {\n this.handleNetworkError(error, url, 'removePeer');\n }\n }\n\n /**\n * Handle network errors from HTTP requests.\n *\n * Converts connection failures, timeouts, and unknown errors to NetworkError.\n * Re-throws existing ToonClientError instances.\n *\n * @param error - Error thrown by HTTP client\n * @param url - Request URL (for error messages)\n * @param operation - Operation name (for error messages)\n * @throws {NetworkError} Network connection or timeout error\n */\n private handleNetworkError(\n error: unknown,\n url: string,\n operation: string\n ): never {\n // Timeout errors (AbortSignal)\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request to ${url} timed out after ${this.timeout}ms`,\n error\n );\n }\n\n // Connection errors (ECONNREFUSED, ETIMEDOUT, DNS failures)\n if (\n error instanceof Error &&\n (error.message.includes('ECONNREFUSED') ||\n error.message.includes('ETIMEDOUT') ||\n error.message.includes('ENOTFOUND'))\n ) {\n throw new NetworkError(\n `Failed to connect to connector admin API at ${url}: ${error.message}`,\n error\n );\n }\n\n // Re-throw if already a ToonClientError\n if (\n error instanceof ValidationError ||\n error instanceof PeerAlreadyExistsError ||\n error instanceof PeerNotFoundError ||\n error instanceof UnauthorizedError ||\n error instanceof ConnectorError\n ) {\n throw error;\n }\n\n // Unknown error - wrap in NetworkError\n throw new NetworkError(\n `Unexpected error during ${operation}: ${error instanceof Error ? error.message : String(error)}`,\n error instanceof Error ? error : undefined\n );\n }\n\n /**\n * Handle HTTP error responses from the admin API.\n *\n * Converts HTTP status codes to appropriate error types.\n *\n * @param response - HTTP response from admin API\n * @param endpoint - Endpoint being called (for error messages)\n * @param peerId - Peer ID (for error messages)\n * @throws {UnauthorizedError} 401 Unauthorized\n * @throws {PeerNotFoundError} 404 Not Found\n * @throws {PeerAlreadyExistsError} 409 Conflict\n * @throws {ConnectorError} 5xx Server Error\n */\n private async handleErrorResponse(\n response: Response,\n endpoint: string,\n peerId: string\n ): Promise<never> {\n const status = response.status;\n const statusText = response.statusText;\n\n // Try to extract error message from response body\n let errorMessage = '';\n try {\n const body = await response.text();\n if (body) {\n errorMessage = ` - ${body}`;\n }\n } catch {\n // Ignore body parsing errors\n }\n\n switch (status) {\n case 401:\n throw new UnauthorizedError(\n `Admin API authentication failed for ${endpoint}: ${statusText}${errorMessage}`\n );\n\n case 404:\n throw new PeerNotFoundError(\n `Peer not found: \"${peerId}\" (${endpoint}): ${statusText}${errorMessage}`\n );\n\n case 409:\n throw new PeerAlreadyExistsError(\n `Peer already exists: \"${peerId}\" (${endpoint}): ${statusText}${errorMessage}`\n );\n\n default:\n if (status >= 500) {\n throw new ConnectorError(\n `Connector admin API error (${endpoint}): ${status} ${statusText}${errorMessage}`\n );\n }\n\n // Other 4xx errors (400, 403, etc.)\n throw new ConnectorError(\n `Admin API error (${endpoint}): ${status} ${statusText}${errorMessage}`\n );\n }\n }\n}\n","import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { SwapPair } from '@toon-protocol/core';\n\n/**\n * The persisted receive-side watermark for one swap target channel: the\n * HIGHEST-NONCE verified chain-B claim per `(chain, channelId)` (toon-client\n * issue #352, rolling-swap spec toon-meta docs/rolling-swap.md §3.2/§9).\n *\n * Claims are cumulative balance proofs — a higher-nonce claim supersedes every\n * earlier one — so persisting only the winner per channel is lossless for\n * settlement: `buildSettlementTx` redeems exactly this claim. Superseded claims\n * are informational and dropped.\n */\nexport interface ReceivedClaimEntry {\n /** Target chain the claim settles on (`pair.to.chain`, e.g. `evm:base:8453`). */\n chain: string;\n /** Payment-channel id on the target chain (0x-hex for EVM, base58 otherwise). */\n channelId: string;\n /** Balance-proof nonce (strictly increasing per channel). */\n nonce: bigint;\n /** Cumulative transferred amount, target micro-units. */\n cumulativeAmount: bigint;\n /** Recipient address the claim pays (the sender's `chainRecipient`). */\n recipient: string;\n /** Swap peer's on-chain signer address the signature verified against. */\n swapSignerAddress: string;\n /** The verified signed claim bytes (chain-specific encoding). */\n claimBytes: Uint8Array;\n /** Optional swap-side claim id. */\n claimId?: string;\n /** The SwapPair the claim was priced against (settlement-time routing). */\n pair: SwapPair;\n /** Unix ms the winning claim was accepted off the wire. */\n receivedAt: number;\n /** Unix ms this entry was last advanced. */\n updatedAt: number;\n /** Unix ms of the last successful on-chain settlement submission. */\n settledAt?: number;\n /** Watermark nonce redeemed by that settlement (claims ≤ this are settled). */\n settledNonce?: bigint;\n /** Tx hash of the last settlement submission. */\n settleTxHash?: string;\n}\n\n/**\n * Persistence interface for received (chain-B) swap claims. Mirrors\n * {@link ChannelStore}'s sync surface; keyed by `(chain, channelId)`.\n */\nexport interface ReceivedClaimStore {\n save(entry: ReceivedClaimEntry): void;\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined;\n list(): ReceivedClaimEntry[];\n delete(chain: string, channelId: string): void;\n}\n\ninterface JsonEntry {\n chain: string;\n channelId: string;\n /** Stored as strings to preserve bigint precision. */\n nonce: string;\n cumulativeAmount: string;\n recipient: string;\n swapSignerAddress: string;\n /** base64 */\n claimBytes: string;\n claimId?: string;\n pair: SwapPair;\n receivedAt: number;\n updatedAt: number;\n settledAt?: number;\n settledNonce?: string;\n settleTxHash?: string;\n}\n\nfunction key(chain: string, channelId: string): string {\n return `${chain}|${channelId}`;\n}\n\n/**\n * JSON file-backed {@link ReceivedClaimStore}. Synchronous I/O to match the\n * `JsonFileChannelStore` pattern (`ChannelStore.ts`); the parent directory is\n * created on first save so a fresh daemon home works out of the box.\n */\nexport class JsonFileReceivedClaimStore implements ReceivedClaimStore {\n private readonly filePath: string;\n\n constructor(filePath: string) {\n this.filePath = filePath;\n }\n\n save(entry: ReceivedClaimEntry): void {\n const data = this.readFile();\n data[key(entry.chain, entry.channelId)] = {\n chain: entry.chain,\n channelId: entry.channelId,\n nonce: entry.nonce.toString(),\n cumulativeAmount: entry.cumulativeAmount.toString(),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n claimBytes: Buffer.from(entry.claimBytes).toString('base64'),\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n updatedAt: entry.updatedAt,\n ...(entry.settledAt !== undefined ? { settledAt: entry.settledAt } : {}),\n ...(entry.settledNonce !== undefined\n ? { settledNonce: entry.settledNonce.toString() }\n : {}),\n ...(entry.settleTxHash !== undefined\n ? { settleTxHash: entry.settleTxHash }\n : {}),\n };\n this.writeFile(data);\n }\n\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined {\n const entry = this.readFile()[key(chain, channelId)];\n return entry ? fromJson(entry) : undefined;\n }\n\n list(): ReceivedClaimEntry[] {\n return Object.values(this.readFile()).map(fromJson);\n }\n\n delete(chain: string, channelId: string): void {\n const data = this.readFile();\n const { [key(chain, channelId)]: _, ...rest } = data;\n this.writeFile(rest);\n }\n\n private readFile(): Record<string, JsonEntry> {\n if (!existsSync(this.filePath)) {\n return {};\n }\n const raw = readFileSync(this.filePath, 'utf-8');\n return JSON.parse(raw) as Record<string, JsonEntry>;\n }\n\n private writeFile(data: Record<string, JsonEntry>): void {\n mkdirSync(dirname(this.filePath), { recursive: true });\n writeFileSync(this.filePath, JSON.stringify(data, null, 2), 'utf-8');\n }\n}\n\n/**\n * In-memory {@link ReceivedClaimStore} for tests and path-less configs. NOT\n * restart-safe — a daemon should always be given a `JsonFileReceivedClaimStore`.\n */\nexport class InMemoryReceivedClaimStore implements ReceivedClaimStore {\n private readonly entries = new Map<string, ReceivedClaimEntry>();\n\n save(entry: ReceivedClaimEntry): void {\n this.entries.set(key(entry.chain, entry.channelId), { ...entry });\n }\n\n load(chain: string, channelId: string): ReceivedClaimEntry | undefined {\n const entry = this.entries.get(key(chain, channelId));\n return entry ? { ...entry } : undefined;\n }\n\n list(): ReceivedClaimEntry[] {\n return [...this.entries.values()].map((e) => ({ ...e }));\n }\n\n delete(chain: string, channelId: string): void {\n this.entries.delete(key(chain, channelId));\n }\n}\n\nfunction fromJson(entry: JsonEntry): ReceivedClaimEntry {\n return {\n chain: entry.chain,\n channelId: entry.channelId,\n nonce: BigInt(entry.nonce),\n cumulativeAmount: BigInt(entry.cumulativeAmount),\n recipient: entry.recipient,\n swapSignerAddress: entry.swapSignerAddress,\n claimBytes: new Uint8Array(Buffer.from(entry.claimBytes, 'base64')),\n ...(entry.claimId !== undefined ? { claimId: entry.claimId } : {}),\n pair: entry.pair,\n receivedAt: entry.receivedAt,\n updatedAt: entry.updatedAt,\n ...(entry.settledAt !== undefined ? { settledAt: entry.settledAt } : {}),\n ...(entry.settledNonce !== undefined\n ? { settledNonce: BigInt(entry.settledNonce) }\n : {}),\n ...(entry.settleTxHash !== undefined\n ? { settleTxHash: entry.settleTxHash }\n : {}),\n };\n}\n","/**\n * Receive-side swap-claim ingestion + verification (toon-client#352, part of\n * the rolling-swap epic toon-meta#145; spec: toon-meta docs/rolling-swap.md\n * §3.2/§9 dependency 1).\n *\n * The deployed client used to accept swapped-in chain-B claims blind: no\n * signature check, no watermark, no persistence — `buildSettlementTx` /\n * `verifyAccumulatedClaim` had zero call sites in this repo. This module is\n * the missing pipeline: every accumulated claim harvested from a swap stream\n * is VERIFIED at receipt time and, only if it passes, persisted as the\n * highest-nonce watermark for its `(chain, channelId)` in a\n * {@link ReceivedClaimStore}. A claim that fails verification is NEVER counted\n * as value received — failures are loud and result-shaped, not thrown.\n *\n * Verification order per claim (cheapest first, every check fail-closed):\n * 1. settlement metadata completeness — a claim missing any of channelId /\n * nonce / cumulativeAmount / recipient / swapSignerAddress cannot be\n * settled (`MISSING_SETTLEMENT_METADATA` later) and is bucketed `legacy`\n * (the pre-rename-peer path, #349) rather than rejected: the existing\n * loud swap-time warning stays the surface for those.\n * 2. chain consistency — the claim must settle on the session's target chain.\n * 3. recipient — must equal the session `chainRecipient` (EVM\n * case-insensitive), the anti-substitution check.\n * 4. advertised signer — when the caller supplies the maker's advertised\n * `swapSignerAddress` (kind:10032 discovery / operator config), the\n * claim's self-reported signer must match (`SWAP_SIGNER_MISMATCH`,\n * sdk 2.x vocabulary).\n * 5. signature — against the expected signer (advertised address when given,\n * else the claim's self-reported one). EVM claims verify against the\n * **v2 EIP-712 domain-separated** balance-proof digest\n * (`verifyEvmClaimSignature`, connector#324 finding #1) — the digest binds\n * `chainId` + `verifyingContract`, so `tokenNetworks[chain]` (the\n * RollingSwapChannel address) and a numeric chain id are REQUIRED (an EVM\n * claim without them is rejected `MISSING_CHAIN_CONFIG`, fail-closed).\n * Solana/Mina keep the sdk `verifyAccumulatedClaim` path (their domain is\n * folded into the message).\n * 6. signer pinning — a claim may not silently rotate the signer of an\n * already-persisted watermark for the same channel.\n * 7. nonce/cumulative monotonicity vs the locally persisted watermark —\n * strictly increasing nonce AND cumulative; the cumulative advance must\n * cover this packet's `targetAmount` (an under-delivering advance means\n * the maker short-paid the packet).\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n verifyAccumulatedClaim,\n type MinaSignerClientLike,\n} from '@toon-protocol/sdk';\nimport type {\n ReceivedClaimEntry,\n ReceivedClaimStore,\n} from '../channel/ReceivedClaimStore.js';\nimport { verifyEvmClaimSignature } from './evm-claim-digest.js';\nimport { parseEvmChainId } from './settle-received-claims.js';\n\n/** Why a claim was rejected at receipt time. Codes are stable API. */\nexport type ReceivedClaimRejectionCode =\n | 'CHAIN_MISMATCH'\n | 'RECIPIENT_MISMATCH'\n | 'SWAP_SIGNER_MISMATCH'\n | 'SIGNER_MISMATCH'\n | 'SIGNATURE_INVALID'\n | 'MINA_VERIFICATION_UNSUPPORTED'\n | 'UNSUPPORTED_CHAIN'\n | 'NON_MONOTONIC_NONCE'\n | 'NON_MONOTONIC_CUMULATIVE'\n | 'CUMULATIVE_SHORTFALL'\n | 'MISSING_CHAIN_CONFIG'\n | 'MALFORMED_METADATA';\n\nexport interface ReceivedClaimRejection {\n claim: AccumulatedClaim;\n code: ReceivedClaimRejectionCode;\n message: string;\n}\n\nexport interface VerifiedReceivedClaim {\n claim: AccumulatedClaim;\n /** How far this claim advanced the persisted cumulative watermark. */\n watermarkAdvance: bigint;\n}\n\nexport interface IngestReceivedClaimsParams {\n /** Accumulated claims off a swap stream (`streamSwap().claims`), in order. */\n claims: readonly AccumulatedClaim[];\n /** The session's target chain (`pair.to.chain` of the requested swap). */\n expectedChain: string;\n /** The session's payout address on `expectedChain`. */\n chainRecipient: string;\n /**\n * The maker's ADVERTISED on-chain signer address for `expectedChain`\n * (kind:10032 discovery or operator-supplied). When set, a claim whose\n * self-reported `swapSignerAddress` differs is rejected with\n * `SWAP_SIGNER_MISMATCH` and the signature is verified against THIS address,\n * never the claim's own.\n */\n expectedSignerAddress?: string;\n /**\n * Per-chain settlement contract addresses (the deployed `RollingSwapChannel`\n * / `verifyingContract`), keyed by the FULL chain key (e.g. `evm:base:8453`).\n * Matches the daemon config's `tokenNetworks` map and what\n * `buildSwapSettlements` already threads on the submit side.\n *\n * REQUIRED for EVM claims under the v2 EIP-712 digest (connector#324 finding\n * #1): the claim signature is domain-separated over `(chainId,\n * verifyingContract)`, so an EVM claim whose chain key lacks a `tokenNetworks`\n * entry (or a numeric chain id) is rejected `MISSING_CHAIN_CONFIG` — it cannot\n * be verified fail-closed without the domain. Supplied by the connector/swap\n * session context (the RollingSwapChannel the client settles against). Unused\n * for Solana/Mina claims, which fold their domain into the message itself.\n */\n tokenNetworks?: Record<string, string>;\n /** Durable watermark store; verified claims are persisted here. */\n store: ReceivedClaimStore;\n /** Pre-loaded `mina-signer` client — required to verify `mina:*` claims. */\n minaSignerClient?: MinaSignerClientLike;\n /** Clock seam for tests. */\n now?: () => number;\n}\n\nexport interface IngestReceivedClaimsResult {\n /** Claims that passed every check and advanced a persisted watermark. */\n verified: VerifiedReceivedClaim[];\n /** Claims that failed verification. NEVER counted as value received. */\n rejected: ReceivedClaimRejection[];\n /**\n * Claims missing settlement metadata (pre-rename / legacy swap peer, #349).\n * Not verified, not persisted, surfaced through the existing swap-time\n * warning — behavior for legacy no-metadata swaps is unchanged.\n */\n legacy: AccumulatedClaim[];\n /** Total watermark advance across verified claims (target micro-units). */\n valueReceived: bigint;\n}\n\n/** True when the claim carries every settlement-context field. */\nexport function hasSettlementMetadata(\n claim: AccumulatedClaim\n): claim is AccumulatedClaim &\n Required<\n Pick<\n AccumulatedClaim,\n | 'channelId'\n | 'nonce'\n | 'cumulativeAmount'\n | 'recipient'\n | 'swapSignerAddress'\n >\n > {\n return (\n claim.channelId !== undefined &&\n claim.nonce !== undefined &&\n claim.cumulativeAmount !== undefined &&\n claim.recipient !== undefined &&\n claim.swapSignerAddress !== undefined\n );\n}\n\n/** EVM addresses compare case-insensitively; other chains byte-exact. */\nfunction sameAddress(chain: string, a: string, b: string): boolean {\n return chain.startsWith('evm')\n ? a.toLowerCase() === b.toLowerCase()\n : a === b;\n}\n\n/** Map a `verifyAccumulatedClaim` reason string onto a stable rejection code. */\nfunction signatureRejectionCode(reason: string): ReceivedClaimRejectionCode {\n if (reason.startsWith('SIGNER_MISMATCH')) return 'SIGNER_MISMATCH';\n if (reason.startsWith('MINA_VERIFICATION_UNSUPPORTED'))\n return 'MINA_VERIFICATION_UNSUPPORTED';\n if (reason.startsWith('UNSUPPORTED_CHAIN')) return 'UNSUPPORTED_CHAIN';\n return 'SIGNATURE_INVALID';\n}\n\n/**\n * Verify a batch of received chain-B claims and persist the winning watermark\n * per `(chain, channelId)`. See the module doc for the check ladder.\n *\n * Result-shaped: never throws on a bad claim — it lands in `rejected` with a\n * stable code, and later claims are still processed (a channel's watermark\n * only advances through claims that verified).\n */\nexport function ingestReceivedClaims(\n params: IngestReceivedClaimsParams\n): IngestReceivedClaimsResult {\n const now = params.now ?? Date.now;\n const verified: VerifiedReceivedClaim[] = [];\n const rejected: ReceivedClaimRejection[] = [];\n const legacy: AccumulatedClaim[] = [];\n let valueReceived = 0n;\n\n // Session-local watermarks layered over the store so a multi-packet stream\n // is checked claim-against-claim without re-reading the file per packet.\n const watermarks = new Map<string, ReceivedClaimEntry>();\n const reject = (\n claim: AccumulatedClaim,\n code: ReceivedClaimRejectionCode,\n message: string\n ): void => {\n rejected.push({ claim, code, message });\n };\n\n for (const claim of params.claims) {\n if (!hasSettlementMetadata(claim)) {\n legacy.push(claim);\n continue;\n }\n const chain = claim.pair.to.chain;\n if (chain !== params.expectedChain) {\n reject(\n claim,\n 'CHAIN_MISMATCH',\n `claim settles on \"${chain}\", session expected \"${params.expectedChain}\"`\n );\n continue;\n }\n if (!sameAddress(chain, claim.recipient, params.chainRecipient)) {\n reject(\n claim,\n 'RECIPIENT_MISMATCH',\n `claim recipient \"${claim.recipient}\" is not the session chainRecipient \"${params.chainRecipient}\"`\n );\n continue;\n }\n if (\n params.expectedSignerAddress !== undefined &&\n !sameAddress(chain, claim.swapSignerAddress, params.expectedSignerAddress)\n ) {\n reject(\n claim,\n 'SWAP_SIGNER_MISMATCH',\n `claim swapSignerAddress \"${claim.swapSignerAddress}\" does not match the maker's advertised signer \"${params.expectedSignerAddress}\"`\n );\n continue;\n }\n const expectedSigner =\n params.expectedSignerAddress ?? claim.swapSignerAddress;\n // Signature check. EVM uses the v2 EIP-712 domain-separated digest\n // (connector#324 finding #1): the digest binds `chainId` +\n // `verifyingContract`, so the recovered signer is only valid for the exact\n // (chain, deployment) the claim settles against — closing cross-chain /\n // cross-deployment replay. Solana/Mina fold their domain into the message\n // itself and stay on the sdk `verifyAccumulatedClaim` path.\n let sig: { valid: true } | { valid: false; reason: string };\n if (chain.startsWith('evm')) {\n const chainId = parseEvmChainId(chain);\n const verifyingContract = params.tokenNetworks?.[chain];\n if (chainId === undefined || !verifyingContract) {\n reject(\n claim,\n 'MISSING_CHAIN_CONFIG',\n `EVM v2 balance-proof verification for ${chain} needs a numeric chain id in the ` +\n `chain key AND tokenNetworks[\"${chain}\"] (the RollingSwapChannel / verifyingContract) ` +\n `to reconstruct the EIP-712 domain; supply it from the connector/swap session context.`\n );\n continue;\n }\n let msgNonce: bigint;\n let msgCumulative: bigint;\n try {\n msgNonce = BigInt(claim.nonce);\n msgCumulative = BigInt(claim.cumulativeAmount);\n } catch {\n reject(\n claim,\n 'MALFORMED_METADATA',\n `nonce \"${claim.nonce}\" / cumulativeAmount \"${claim.cumulativeAmount}\" are not decimal integers`\n );\n continue;\n }\n sig = verifyEvmClaimSignature({\n ctx: { chainId, verifyingContract },\n message: {\n channelId: claim.channelId,\n cumulativeAmount: msgCumulative,\n nonce: msgNonce,\n recipient: claim.recipient,\n },\n signature: claim.claimBytes,\n expectedSigner,\n });\n } else {\n sig = verifyAccumulatedClaim(\n claim,\n { address: expectedSigner },\n params.minaSignerClient\n );\n }\n if (!sig.valid) {\n reject(claim, signatureRejectionCode(sig.reason), sig.reason);\n continue;\n }\n\n let nonce: bigint;\n let cumulativeAmount: bigint;\n try {\n nonce = BigInt(claim.nonce);\n cumulativeAmount = BigInt(claim.cumulativeAmount);\n } catch {\n reject(\n claim,\n 'MALFORMED_METADATA',\n `nonce \"${claim.nonce}\" / cumulativeAmount \"${claim.cumulativeAmount}\" are not decimal integers`\n );\n continue;\n }\n\n const wmKey = `${chain}|${claim.channelId}`;\n const watermark =\n watermarks.get(wmKey) ?? params.store.load(chain, claim.channelId);\n\n if (watermark) {\n if (!sameAddress(chain, watermark.swapSignerAddress, expectedSigner)) {\n reject(\n claim,\n 'SWAP_SIGNER_MISMATCH',\n `channel ${claim.channelId} watermark was signed by \"${watermark.swapSignerAddress}\"; a claim signed by \"${expectedSigner}\" may not rotate it`\n );\n continue;\n }\n if (nonce <= watermark.nonce) {\n reject(\n claim,\n 'NON_MONOTONIC_NONCE',\n `nonce ${nonce} does not advance the persisted watermark nonce ${watermark.nonce} for channel ${claim.channelId}`\n );\n continue;\n }\n if (cumulativeAmount <= watermark.cumulativeAmount) {\n reject(\n claim,\n 'NON_MONOTONIC_CUMULATIVE',\n `cumulativeAmount ${cumulativeAmount} does not advance the persisted watermark ${watermark.cumulativeAmount} for channel ${claim.channelId}`\n );\n continue;\n }\n }\n\n // The watermark advance is the value this claim actually adds. It must\n // cover the packet's expected targetAmount — a smaller advance means the\n // maker short-paid the packet (e.g. re-signed value we already held).\n const advance = cumulativeAmount - (watermark?.cumulativeAmount ?? 0n);\n if (advance < claim.targetAmount) {\n reject(\n claim,\n 'CUMULATIVE_SHORTFALL',\n `cumulative advance ${advance} is less than the packet's targetAmount ${claim.targetAmount} for channel ${claim.channelId}`\n );\n continue;\n }\n\n const entry: ReceivedClaimEntry = {\n chain,\n channelId: claim.channelId,\n nonce,\n cumulativeAmount,\n recipient: claim.recipient,\n swapSignerAddress: expectedSigner,\n claimBytes: claim.claimBytes,\n ...(claim.claimId !== undefined ? { claimId: claim.claimId } : {}),\n pair: claim.pair,\n receivedAt: claim.receivedAt,\n updatedAt: now(),\n // Settlement bookkeeping survives watermark advances.\n ...(watermark?.settledAt !== undefined\n ? { settledAt: watermark.settledAt }\n : {}),\n ...(watermark?.settledNonce !== undefined\n ? { settledNonce: watermark.settledNonce }\n : {}),\n ...(watermark?.settleTxHash !== undefined\n ? { settleTxHash: watermark.settleTxHash }\n : {}),\n };\n params.store.save(entry);\n watermarks.set(wmKey, entry);\n verified.push({ claim, watermarkAdvance: advance });\n valueReceived += advance;\n }\n\n return { verified, rejected, legacy, valueReceived };\n}\n","/**\n * EVM rolling-swap **v2** balance-proof claim digest (EIP-712 domain-separated).\n *\n * Refs connector#324 **finding #1** / connector#325 (canonical spec:\n * `docs/rolling-swap-v2-digest-spec.md`). This is the client's byte-for-byte\n * conformance anchor for the v2 migration.\n *\n * ## Why this exists in the client\n *\n * The v1 digest that shipped in `@toon-protocol/core` `balanceProofHashEvm`\n * (imported transitively by the sdk's `verifyAccumulatedClaim` /\n * `buildSettlementTx`, which is what this repo used to lean on) was\n *\n * keccak256( channelId(32) || cumulativeAmount(32BE)\n * || nonce(32BE) || recipient(20) )\n *\n * — it bound **neither** `chainId` **nor** the settling contract address, so a\n * signer-signed claim redeemed on one (chain, deployment) could be replayed\n * verbatim on another for the same tuple (cross-chain / cross-deployment\n * replay). v2 folds `chainId` **and** `verifyingContract` into the signed\n * preimage via a standard **EIP-712** typed-data domain, so a signature is\n * valid on **exactly one `(chainId, contract)` pair**, and the `version=\"2\"`\n * string makes the cutover fail-closed (a v1 raw-keccak sig can never validate\n * as v2 and vice-versa).\n *\n * ## Lockstep dependency\n *\n * The canonical v2 digest util lives in `@toon-protocol/core`\n * (`balanceProofHashEvm` → EIP-712) + `@toon-protocol/sdk`\n * (`verifyAccumulatedClaim` / `buildSettlementTx`). Those packages migrate in\n * lockstep (connector#324 release order: core/sdk → swap → client). Until a v2\n * core/sdk is published, this module is the client's own v2 digest so the\n * receive-side verify (see {@link file://./received-claims.ts}) is already\n * domain-separated and the golden-vector conformance test\n * (`evm-claim-digest.test.ts`) pins the exact literals from the spec. When the\n * v2 core/sdk ships, the recompute here should delegate to it (or be asserted\n * byte-identical to it) — the golden-vector test stays as the shared fixture.\n *\n * The signer leg (`swap` `EvmPaymentChannelSigner.signBalanceProof`) MUST also\n * move to this same EIP-712 preimage and now REQUIRES `chainId` +\n * `verifyingContract` inputs it did not take before.\n */\n\nimport {\n hashTypedData,\n type Hex,\n type Address,\n type TypedDataDomain,\n} from 'viem';\nimport { secp256k1 } from '@noble/curves/secp256k1.js';\nimport { keccak_256 } from '@noble/hashes/sha3.js';\nimport { hexToBytes, bytesToHex } from '@noble/hashes/utils.js';\n\n/** EIP-712 domain `name` for the RollingSwapChannel (spec §2.1). */\nexport const ROLLING_SWAP_DOMAIN_NAME = 'RollingSwapChannel' as const;\n/** EIP-712 domain `version` — `\"2\"` is the domain-separated migration. */\nexport const ROLLING_SWAP_DOMAIN_VERSION = '2' as const;\n\n/**\n * `keccak256(\"ClaimBalanceProof(bytes32 channelId,uint256 cumulativeAmount,uint256 nonce,address recipient)\")`.\n * Pinned from the spec; asserted in `evm-claim-digest.test.ts`.\n */\nexport const CLAIM_TYPEHASH =\n '0xa0c8262c1a8615f7674d3af796b14d19672d3634f89c6093502ab35c0afe2d91' as const;\n/**\n * `keccak256(\"CooperativeClose(bytes32 channelId,uint256 cumulativeAmount,uint256 nonce)\")`.\n * Pinned from the spec; asserted in `evm-claim-digest.test.ts`.\n */\nexport const COOP_CLOSE_TYPEHASH =\n '0xa5753389755fea51cd5016d7b02b508ac03f2e822d9a7ee345ec45b36574ff9f' as const;\n\nconst CLAIM_TYPES = {\n ClaimBalanceProof: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'cumulativeAmount', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n { name: 'recipient', type: 'address' },\n ],\n} as const;\n\nconst COOP_CLOSE_TYPES = {\n CooperativeClose: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'cumulativeAmount', type: 'uint256' },\n { name: 'nonce', type: 'uint256' },\n ],\n} as const;\n\n/** The two chain-context inputs v2 adds over v1 (the domain binding). */\nexport interface EvmClaimDomainContext {\n /** Settlement chain id (`block.chainid` on-chain). e.g. `8453` for Base. */\n chainId: number;\n /** Deployed `RollingSwapChannel` address (`address(this)` / EIP-712 `verifyingContract`). */\n verifyingContract: string;\n}\n\n/** Fields of the `ClaimBalanceProof` message (the balance-proof claim leg). */\nexport interface EvmClaimMessage {\n /** Channel id, 0x-prefixed 32-byte hex. */\n channelId: string;\n /** Cumulative transferred amount (target micro-units). */\n cumulativeAmount: bigint;\n /** Monotonic balance-proof nonce. */\n nonce: bigint;\n /** Recipient (the claim payout address), 0x-prefixed 20-byte hex. */\n recipient: string;\n}\n\n/** Fields of the `CooperativeClose` message (recipient close-ack leg). */\nexport interface EvmCooperativeCloseMessage {\n channelId: string;\n cumulativeAmount: bigint;\n nonce: bigint;\n}\n\n/**\n * viem validates EIP-712 `address` fields against their checksum; the wire\n * carries non-checksummed hex (e.g. an all-lowercase or all-uppercase\n * recipient). The address BYTES are what EIP-712 encodes, so lowercasing is a\n * no-op on the digest while side-stepping the checksum guard.\n */\nfunction normalizeAddress(addr: string): Address {\n return addr.toLowerCase() as Address;\n}\n\nfunction domainOf(ctx: EvmClaimDomainContext): TypedDataDomain {\n return {\n name: ROLLING_SWAP_DOMAIN_NAME,\n version: ROLLING_SWAP_DOMAIN_VERSION,\n chainId: ctx.chainId,\n verifyingContract: normalizeAddress(ctx.verifyingContract),\n };\n}\n\n/**\n * The v2 EIP-712 claim digest — `keccak256(0x1901 || domainSeparator ||\n * hashStruct(ClaimBalanceProof))` — that the on-chain `updateBalance` verifier\n * (and the swap signer) produce. This is what a received claim's signature must\n * recover against.\n */\nexport function evmClaimDigest(\n ctx: EvmClaimDomainContext,\n message: EvmClaimMessage\n): Hex {\n return hashTypedData({\n domain: domainOf(ctx),\n types: CLAIM_TYPES,\n primaryType: 'ClaimBalanceProof',\n message: {\n channelId: message.channelId as Hex,\n cumulativeAmount: message.cumulativeAmount,\n nonce: message.nonce,\n recipient: normalizeAddress(message.recipient),\n },\n });\n}\n\n/**\n * The v2 EIP-712 cooperative-close digest — same domain as the claim, distinct\n * type hash — that a recipient's close-ack signature must recover against.\n */\nexport function evmCooperativeCloseDigest(\n ctx: EvmClaimDomainContext,\n message: EvmCooperativeCloseMessage\n): Hex {\n return hashTypedData({\n domain: domainOf(ctx),\n types: COOP_CLOSE_TYPES,\n primaryType: 'CooperativeClose',\n message: {\n channelId: message.channelId as Hex,\n cumulativeAmount: message.cumulativeAmount,\n nonce: message.nonce,\n },\n });\n}\n\n/** A 65-byte `r || s || v` signature, as 0x-hex or raw bytes. */\nexport type ClaimSignature = Hex | Uint8Array;\n\n/** Byte length of a raw `r||s||v` signature. */\nconst SIG_BYTES = 65;\n\nfunction signatureToBytes(sig: ClaimSignature): Uint8Array {\n if (typeof sig !== 'string') return sig;\n const hex = sig.startsWith('0x') ? sig.slice(2) : sig;\n return hexToBytes(hex);\n}\n\n/**\n * Recover the EVM address that signed a v2 claim digest. Uses the same\n * `@noble/curves` secp256k1 recovery + keccak address derivation as the sdk's\n * on-chain-matching `recoverEvmSignerAddress`, over the **v2** EIP-712 digest.\n * Enforces the same 65-byte `r||s||v`, `v ∈ {27,28}` envelope the on-chain OZ\n * `ECDSA.recover` accepts (fail-closed on a malformed signature).\n *\n * @returns the recovered address (lowercase 0x-hex).\n * @throws if the signature is not 65 bytes or `v` is not 27/28.\n */\nexport function recoverEvmClaimSigner(\n ctx: EvmClaimDomainContext,\n message: EvmClaimMessage,\n signature: ClaimSignature\n): Address {\n const bytes = signatureToBytes(signature);\n if (bytes.length !== SIG_BYTES) {\n throw new Error(\n `EVM signature must be 65 bytes (r||s||v), got ${bytes.length}`\n );\n }\n const v = bytes[64];\n if (v !== 27 && v !== 28) {\n throw new Error(`EVM signature v must be 27 or 28, got ${v}`);\n }\n const digest = evmClaimDigest(ctx, message).slice(2);\n const recovered = secp256k1.Signature.fromBytes(bytes.slice(0, 64), 'compact')\n .addRecoveryBit(v - 27)\n .recoverPublicKey(hexToBytes(digest));\n const uncompressed = recovered.toBytes(false);\n const addrHash = keccak_256(uncompressed.slice(1));\n return `0x${bytesToHex(addrHash.slice(-20))}` as Address;\n}\n\n/** Result of {@link verifyEvmClaimSignature}. Mirrors the sdk verify shape. */\nexport type EvmClaimVerifyResult =\n | { valid: true; recovered: Address }\n | { valid: false; reason: string };\n\n/**\n * Verify a received EVM balance-proof claim: recover the v2-digest signer and\n * check it equals `expectedSigner` (case-insensitive, per EVM address rules).\n *\n * Result-shaped — never throws; a malformed signature or a mismatch is a\n * `{ valid: false, reason }` so the receive ladder can bucket it fail-closed.\n */\nexport function verifyEvmClaimSignature(params: {\n ctx: EvmClaimDomainContext;\n message: EvmClaimMessage;\n signature: ClaimSignature;\n expectedSigner: string;\n}): EvmClaimVerifyResult {\n let recovered: Address;\n try {\n recovered = recoverEvmClaimSigner(\n params.ctx,\n params.message,\n params.signature\n );\n } catch (err) {\n return {\n valid: false,\n reason: `SIGNATURE_INVALID: ${err instanceof Error ? err.message : String(err)}`,\n };\n }\n if (recovered.toLowerCase() !== params.expectedSigner.toLowerCase()) {\n return {\n valid: false,\n reason: `SIGNER_MISMATCH: recovered ${recovered}, expected ${params.expectedSigner}`,\n };\n }\n return { valid: true, recovered };\n}\n","/**\n * Per-packet preimage retention (toon-client#360, rolling-swap epic\n * toon-meta#145 — spec `docs/rolling-swap.md` §3 R1 / §3.2 leg-B reveal).\n *\n * `withSenderConditions` (toon-client#354) mints a fresh 32-byte preimage\n * `P_i` per fill packet, sets `C_i = sha256(P_i)` on the leg-A PREPARE, and —\n * before this module — DISCARDED `P_i`. Leg-B reveal (spec §3.2) is the commit\n * act: the sender reveals `P_i` only AFTER verifying the leg-B claim, so the\n * daemon must retain each `P_i` from mint time until the reveal step consumes\n * it. This is that retention seam.\n *\n * Keyed by `packetIndex` — the 0-indexed position in the swap's packet stream.\n * `packetIndex` is the one identifier shared between the send side (the wrapper\n * mints one condition per `sendSwapPacket` call, which `streamSwap` issues in\n * strictly increasing `packetIndex` order) and the receive side\n * (`AccumulatedClaim.packetIndex`), so it correlates a retained preimage to the\n * claim whose reveal will consume it.\n *\n * Reveal is single-use: {@link PreimageRetentionStore.take} removes the entry\n * so a preimage is never revealed twice (spec R1 — a reused preimage lets an\n * observer of packet *i* fulfill packet *i+1* without the sender's consent).\n *\n * Session-scoped and in-memory by design: a preimage is only meaningful within\n * the swap stream that minted it (a fresh stream mints fresh preimages), and a\n * preimage revealed after a crash would commit leg A for a leg-B claim the\n * restarted daemon can no longer verify. Durability lives on the *watermark*\n * (`ReceivedClaimStore`), not here.\n */\n\n/** A retained per-packet hashlock secret awaiting (or past) its leg-B reveal. */\nexport interface RetainedPreimage {\n /** 0-indexed position in the swap's packet stream; the correlation key. */\n packetIndex: number;\n /** The 32-byte preimage `P_i` — revealed to commit leg A (spec R6). */\n preimage: Uint8Array;\n /** `C_i = sha256(P_i)` — what went on the leg-A PREPARE (kept for auditing). */\n condition: Uint8Array;\n /** Unix ms the preimage was minted/retained. */\n retainedAt: number;\n}\n\n/**\n * Retention interface for per-packet preimages, keyed by `packetIndex`. Mirrors\n * the sync surface of the daemon's other stores ({@link ReceivedClaimStore}).\n */\nexport interface PreimageRetentionStore {\n /** Retain `entry`, replacing any prior entry for the same `packetIndex`. */\n retain(entry: RetainedPreimage): void;\n /** Peek the retained preimage for `packetIndex` without consuming it. */\n get(packetIndex: number): RetainedPreimage | undefined;\n /** Consume (return AND remove) the preimage — single-use reveal (spec R1). */\n take(packetIndex: number): RetainedPreimage | undefined;\n /** Number of preimages still retained (awaiting reveal). */\n size(): number;\n /** Drop every retained preimage — call when the session ends. */\n clear(): void;\n}\n\n/** Defensive copy so a retained preimage cannot be mutated after the fact. */\nfunction copy(entry: RetainedPreimage): RetainedPreimage {\n return {\n packetIndex: entry.packetIndex,\n preimage: Uint8Array.from(entry.preimage),\n condition: Uint8Array.from(entry.condition),\n retainedAt: entry.retainedAt,\n };\n}\n\n/**\n * In-memory {@link PreimageRetentionStore}. The only implementation: preimages\n * are session-scoped secrets that MUST NOT outlive their stream (see the module\n * doc), so there is deliberately no file-backed variant.\n */\nexport class InMemoryPreimageRetentionStore implements PreimageRetentionStore {\n private readonly entries = new Map<number, RetainedPreimage>();\n\n retain(entry: RetainedPreimage): void {\n this.entries.set(entry.packetIndex, copy(entry));\n }\n\n get(packetIndex: number): RetainedPreimage | undefined {\n const entry = this.entries.get(packetIndex);\n return entry ? copy(entry) : undefined;\n }\n\n take(packetIndex: number): RetainedPreimage | undefined {\n const entry = this.entries.get(packetIndex);\n if (!entry) return undefined;\n this.entries.delete(packetIndex);\n return copy(entry);\n }\n\n size(): number {\n return this.entries.size;\n }\n\n clear(): void {\n this.entries.clear();\n }\n}\n","/**\n * Atomic verify -> persist -> reveal composition (toon-client#360, rolling-swap\n * epic toon-meta#145 — spec `docs/rolling-swap.md` §3 R5/R8, §3.2 leg-B reveal).\n *\n * {@link ingestReceivedClaims} (toon-client#358) verifies a received chain-B\n * claim and persists its watermark AT VERIFY TIME. But verification is not the\n * commit: leg-B reveal is (spec R5 — the sender reveals `P_i` only after the\n * claim verifies). A daemon that verifies a claim, advances the watermark, and\n * then WITHHOLDS or FAILS the reveal has advanced a watermark for value it never\n * committed to. Left there, engine rule R8 bites: after the maker rolls its own\n * side back it REUSES the rolled-back nonce for the next fill, and the client's\n * monotonicity check (`nonce <= watermark.nonce -> NON_MONOTONIC_NONCE`) would\n * falsely reject that legitimate re-fill.\n *\n * So verify/persist/reveal must compose as ONE unit whose durable effect is\n * \"watermark advanced iff the reveal committed\":\n *\n * 1. snapshot the prior watermark for the claim's `(chain, channelId)`;\n * 2. verify + persist via {@link ingestReceivedClaims} (single claim);\n * 3. reveal the retained preimage `P_i` for `claim.packetIndex`;\n * 4. on `withheld` / thrown / preimage-missing -> COMPENSATING ROLLBACK:\n * restore the snapshot (or delete when there was none), so the watermark\n * tracks only ACCEPTED/REVEALED packets and R8's reused nonce is accepted.\n *\n * Claims are processed strictly in order and each claim's fate is decided\n * before the next is verified, so cross-claim monotonicity flows through the\n * durable store: a rolled-back claim leaves no trace for the next to trip over.\n * Legacy no-metadata claims (spec §349 path) and hard verification rejects\n * never reach a reveal and never touch a watermark — behavior unchanged.\n */\n\nimport type { AccumulatedClaim } from '@toon-protocol/sdk/swap';\nimport {\n ingestReceivedClaims,\n hasSettlementMetadata,\n type IngestReceivedClaimsParams,\n type ReceivedClaimRejection,\n} from './received-claims.js';\nimport type { ReceivedClaimEntry } from '../channel/ReceivedClaimStore.js';\nimport type {\n PreimageRetentionStore,\n RetainedPreimage,\n} from './preimage-retention.js';\n\n/** The sender's leg-B decision for a verified claim (spec R5). */\nexport type RevealDecision = 'revealed' | 'withheld';\n\nexport interface RevealResult {\n decision: RevealDecision;\n /** Human-readable detail, surfaced on a rolled-back record when withheld. */\n reason?: string;\n}\n\n/**\n * Reveal a verified claim's preimage to commit leg A, OR withhold it. Receives\n * the claim and the retained preimage for its `packetIndex` (`undefined` when\n * none was retained — e.g. a legacy zero-condition packet reaching this path).\n * Returning `withheld`, resolving to no decision, or THROWING all trigger the\n * compensating rollback; only `revealed` keeps the watermark advance.\n */\nexport type RevealFn = (\n claim: AccumulatedClaim,\n preimage: RetainedPreimage | undefined\n) => RevealResult | Promise<RevealResult>;\n\nexport interface IngestAndRevealParams extends IngestReceivedClaimsParams {\n /** Leg-B reveal decision, invoked once per VERIFIED claim (spec R5/R6). */\n reveal: RevealFn;\n /**\n * Retained per-packet preimages ({@link PreimageRetentionStore}). The reveal\n * for a verified claim CONSUMES (`take`) the preimage for its `packetIndex`,\n * so a preimage is never revealed twice (spec R1). Optional: without it the\n * reveal fn receives `undefined` and decides on its own.\n */\n preimages?: PreimageRetentionStore;\n}\n\nexport interface RevealedClaim {\n claim: AccumulatedClaim;\n /** How far the (now committed) watermark advanced. */\n watermarkAdvance: bigint;\n}\n\nexport interface RolledBackClaim {\n claim: AccumulatedClaim;\n /** The advance that was persisted then rolled back (never counted). */\n watermarkAdvance: bigint;\n /** Why the reveal did not commit (withheld reason, or the thrown error). */\n reason: string;\n}\n\nexport interface IngestAndRevealResult {\n /** Claims that verified AND revealed — the only ones whose value counts. */\n revealed: RevealedClaim[];\n /**\n * Claims that verified but whose reveal was withheld/failed: the watermark\n * advance was persisted then ROLLED BACK, so a subsequent re-fill reusing\n * the same nonce (engine R8) is accepted, not falsely rejected.\n */\n rolledBack: RolledBackClaim[];\n /** Claims that failed verification. NEVER revealed, NEVER persisted. */\n rejected: ReceivedClaimRejection[];\n /** Legacy no-metadata claims (spec §349). Unchanged: not verified/revealed. */\n legacy: AccumulatedClaim[];\n /** Total watermark advance across REVEALED claims only. */\n valueRevealed: bigint;\n}\n\n/**\n * Restore the watermark to `prior` (or delete it when the channel had none),\n * compensating a verify-time persist whose reveal did not commit.\n */\nfunction rollbackWatermark(\n store: IngestReceivedClaimsParams['store'],\n chain: string,\n channelId: string,\n prior: ReceivedClaimEntry | undefined\n): void {\n if (prior === undefined) {\n store.delete(chain, channelId);\n } else {\n store.save(prior);\n }\n}\n\n/**\n * Verify, persist, and reveal a batch of received chain-B claims atomically:\n * a verified claim's watermark advance survives iff its reveal commits, and is\n * rolled back otherwise (see the module doc for why R8 needs this).\n *\n * Never throws on a bad claim or a throwing reveal — both land in the result\n * (`rejected` / `rolledBack`) with the durable watermark left consistent.\n */\nexport async function ingestAndReveal(\n params: IngestAndRevealParams\n): Promise<IngestAndRevealResult> {\n const { reveal, preimages, claims, store, ...shared } = params;\n\n const revealed: RevealedClaim[] = [];\n const rolledBack: RolledBackClaim[] = [];\n const rejected: ReceivedClaimRejection[] = [];\n const legacy: AccumulatedClaim[] = [];\n let valueRevealed = 0n;\n\n for (const claim of claims) {\n // Verify + persist this one claim against the CURRENT durable watermark.\n // Single-claim so each claim's fate is sealed (revealed or rolled back)\n // before the next is checked — rollback leaves nothing for the next claim.\n //\n // A metadata-less (legacy) claim has no `(chain, channelId)` — and its\n // `pair.to` may be absent — so only snapshot when metadata is present, and\n // never dereference `pair.to.chain` before that guard.\n const hasMeta = hasSettlementMetadata(claim);\n const chain = hasMeta ? claim.pair.to.chain : undefined;\n const channelId = hasMeta ? claim.channelId : undefined;\n // Snapshot BEFORE persist so a withheld reveal can be compensated exactly.\n const prior =\n chain !== undefined && channelId !== undefined\n ? store.load(chain, channelId)\n : undefined;\n\n const ingest = ingestReceivedClaims({ ...shared, claims: [claim], store });\n\n if (ingest.legacy.length > 0) {\n legacy.push(claim);\n continue;\n }\n const rejection = ingest.rejected[0];\n if (rejection) {\n // Hard verification failure: nothing was persisted, nothing to reveal.\n rejected.push(rejection);\n continue;\n }\n\n const verified = ingest.verified[0];\n // A metadata-carrying claim that went neither legacy nor rejected verified\n // and was persisted, so `verified`, `chain`, and `channelId` are defined.\n // The guard is belt-and-suspenders for the type-checker and future changes.\n if (!verified || chain === undefined || channelId === undefined) continue;\n const advance = verified.watermarkAdvance;\n const preimage = preimages?.take(claim.packetIndex);\n\n let outcome: RevealResult;\n try {\n outcome = await reveal(claim, preimage);\n } catch (err) {\n outcome = {\n decision: 'withheld',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n\n if (outcome.decision === 'revealed') {\n revealed.push({ claim, watermarkAdvance: advance });\n valueRevealed += advance;\n continue;\n }\n\n // Withheld / failed: compensate the verify-time persist so the watermark\n // reflects only revealed packets (engine R8 — the maker reuses the nonce).\n rollbackWatermark(store, chain, channelId, prior);\n rolledBack.push({\n claim,\n watermarkAdvance: advance,\n reason: outcome.reason ?? 'reveal withheld',\n });\n }\n\n return { revealed, rolledBack, rejected, legacy, valueRevealed };\n}\n","/**\n * Devnet faucet helper.\n *\n * The deployed TOON devnet exposes a faucet that drips the settlement token\n * (USDC) to a given chain address so a client can open payment channels and pay\n * for writes. This helper hits the USDC-ONLY faucet legs — it funds USDC and\n * assumes the wallet already holds enough native gas to transact:\n *\n * EVM `POST {faucetUrl}/api/base-sepolia/request` body `{ address }` → USDC (Base Sepolia mint)\n * Solana `POST {faucetUrl}/api/solana/usdc-request` body `{ address }` → USDC (no SOL leg)\n * Mina `POST {faucetUrl}/api/mina/usdc-request` body `{ address }` → USDC (no MINA leg)\n *\n * Devnet edge (today): `https://faucet.devnet.toonprotocol.dev`.\n *\n * All three chains are live on the deployed faucet — the request shape is\n * identical (`{ address }`); only the path differs. (The EVM leg mints the\n * ungated mock USDC on Base Sepolia and best-effort tops up gas; the Solana and\n * Mina legs are strictly USDC-only and expect the address to already hold gas.)\n */\n\nimport { NetworkError } from './errors.js';\n\n/** Supported faucet chains. */\nexport type FaucetChain = 'evm' | 'solana' | 'mina';\n\n/** Result of a successful faucet drip. */\nexport interface FundWalletResult {\n /** The chain that was funded. */\n chain: FaucetChain;\n /** The funded address (echoed back). */\n address: string;\n /** Raw parsed JSON body from the faucet (shape is faucet-defined). */\n response: unknown;\n}\n\n/** Options for {@link fundWallet}. */\nexport interface FundWalletOptions {\n /** Custom fetch implementation (for testing / custom transports). */\n fetchImpl?: typeof fetch;\n /**\n * Request timeout in milliseconds. Defaults to {@link defaultFaucetTimeout}\n * for the chain (fast 30s for evm/solana, a longer 120s for the slow-settling\n * mina faucet).\n */\n timeout?: number;\n}\n\n/**\n * Default faucet request timeout (ms) for a chain.\n *\n * The EVM (Base Sepolia mint) and Solana USDC legs respond in a few seconds, so\n * 30s is plenty. The Mina USDC leg TRANSFERS the token via an o1js-proven\n * transaction on a chain that settles much more slowly: the drip routinely\n * succeeds server-side but takes well over 30s to answer the HTTP request, so a\n * flat 30s budget makes the client give up on a request that actually worked.\n * Give mina a much longer budget.\n */\nexport function defaultFaucetTimeout(chain: FaucetChain): number {\n return chain === 'mina' ? 120000 : 30000;\n}\n\n/**\n * Map a chain to its USDC-only faucet request path. Each leg funds USDC and\n * assumes the address already holds native gas (the EVM leg still best-effort\n * tops up Base Sepolia ETH, but does not depend on it).\n */\nfunction faucetPath(chain: FaucetChain): string {\n switch (chain) {\n case 'evm':\n return '/api/base-sepolia/request';\n case 'solana':\n return '/api/solana/usdc-request';\n case 'mina':\n return '/api/mina/usdc-request';\n }\n}\n\n/**\n * Drip test funds to `address` on `chain` from the devnet `faucetUrl`.\n *\n * @param faucetUrl - Faucet base URL, e.g. `https://faucet.devnet.toonprotocol.dev`.\n * A trailing `/` is tolerated.\n * @param address - The chain address to fund (EVM 0x address, Solana base58, etc).\n * @param chain - `'evm'` | `'solana'` | `'mina'` (all live on the devnet faucet).\n * @throws {Error} If `faucetUrl` or `address` is missing.\n * @throws {NetworkError} On transport failure or a non-2xx faucet response.\n */\nexport async function fundWallet(\n faucetUrl: string,\n address: string,\n chain: FaucetChain,\n options: FundWalletOptions = {}\n): Promise<FundWalletResult> {\n if (!faucetUrl) {\n throw new Error('fundWallet: faucetUrl is required');\n }\n if (!address) {\n throw new Error('fundWallet: address is required');\n }\n\n const base = faucetUrl.replace(/\\/+$/, '');\n const url = `${base}${faucetPath(chain)}`;\n const fetchImpl = options.fetchImpl ?? fetch;\n const timeout = options.timeout ?? defaultFaucetTimeout(chain);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n let response: Response;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ address }),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Faucet request timed out after ${timeout}ms (${url})`,\n error\n );\n }\n throw new NetworkError(\n `Faucet request failed (${url}): ${\n error instanceof Error ? error.message : String(error)\n }`,\n error instanceof Error ? error : undefined\n );\n } finally {\n clearTimeout(timeoutId);\n }\n\n if (!response.ok) {\n const detail = await response.text().catch(() => '');\n throw new NetworkError(\n `Faucet responded ${response.status} ${response.statusText}${\n detail ? `: ${detail}` : ''\n } (${url})`\n );\n }\n\n // The faucet returns JSON; tolerate an empty/non-JSON body (some faucets\n // return `204`/plain text on success).\n const body = await response.text().catch(() => '');\n let parsed: unknown = body;\n if (body) {\n try {\n parsed = JSON.parse(body);\n } catch {\n parsed = body;\n }\n }\n\n return { chain, address, response: parsed };\n}\n","import { finalizeEvent } from 'nostr-tools/pure';\nimport { nip19 } from 'nostr-tools';\nimport { EvmSigner } from '../signing/evm-signer.js';\nimport { SolanaSigner } from '../signing/solana-signer.js';\nimport { MinaSigner } from '../signing/mina-signer.js';\nimport type {\n KeyManagerConfig,\n PasskeyInfo,\n ToonIdentity,\n VaultData,\n} from './types.js';\nimport {\n deriveFullIdentity,\n deriveFromNsec,\n generateMnemonic,\n validateMnemonic,\n} from './KeyDerivation.js';\nimport {\n registerPasskey,\n assertPasskey,\n hashCredentialId,\n isPrfSupported,\n} from './PasskeyAuth.js';\nimport {\n createVault,\n deriveKek,\n deriveKekFromPassword,\n unlockVault,\n addKekToVault,\n removeKekFromVault,\n addRecoveryCodeToVault,\n unlockVaultWithRecoveryCode,\n generateRecoveryCode as generateRecoveryCodeRaw,\n} from './KeyVault.js';\nimport {\n buildBackupEvent,\n publishBackupToRelays,\n fetchBackupFromRelays,\n} from './BackupService.js';\nimport { fromBase64, hexToBytes, bytesToHex } from './encoding.js';\n\n/**\n * KeyManager orchestrates the full key lifecycle:\n * generate, derive, store, backup, recover — gated by WebAuthn Passkeys.\n *\n * Usage:\n * const km = new KeyManager({ relayUrls: ['wss://relay.example'] });\n * const identity = await km.create();\n * // or: const identity = await km.recover();\n *\n * const client = new ToonClient({\n * secretKey: identity.nostr.secretKey,\n * // ...\n * });\n *\n * Security note: JavaScript strings (like mnemonics) are immutable and cannot be\n * zeroed from memory. Uint8Array key material is zeroed on lock(), but mnemonic\n * strings persist until garbage collected. This is a known JS platform limitation.\n */\nexport class KeyManager {\n private readonly config: Required<KeyManagerConfig>;\n private identity: ToonIdentity | null = null;\n private vault: VaultData | null = null;\n private activeCredentialIdHash: string | null = null;\n\n constructor(config: KeyManagerConfig) {\n if (!config.relayUrls || config.relayUrls.length === 0) {\n throw new Error('KeyManager requires at least one relay URL');\n }\n\n this.config = {\n relayUrls: config.relayUrls,\n rpId:\n config.rpId ??\n (typeof window !== 'undefined'\n ? window.location.hostname\n : 'localhost'),\n rpName: config.rpName ?? 'TOON Protocol',\n storageKey: config.storageKey ?? 'toon:keys',\n };\n }\n\n // --- Account Lifecycle ---\n\n /**\n * Create a new account: generate mnemonic, create Passkey, encrypt, backup.\n */\n async create(): Promise<ToonIdentity> {\n const mnemonic = generateMnemonic();\n const identity = await deriveFullIdentity(mnemonic);\n\n // Generate a unique PRF salt for this credential\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n\n // Convert pubkey hex to bytes for userHandle\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n // Register Passkey with PRF\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n // Derive KEK from PRF output\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n // Create encrypted vault\n this.vault = await createVault(mnemonic, kek, credIdHash, prfSalt);\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n // Persist to IndexedDB\n await this.saveToLocalStorage();\n\n // Backup to relay (best-effort)\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal — local vault is still available\n });\n\n return identity;\n }\n\n /**\n * Recover an account using a synced Passkey.\n * The Nostr pubkey is extracted from the Passkey's userHandle.\n *\n * Flow: single assertion → userHandle → fetch backup → derive KEK → unlock.\n * If the local vault is available (has the PRF salt), we use a single assertion\n * with the correct salt. Otherwise, we need the backup from relays first, which\n * requires a discovery assertion to get the pubkey.\n */\n async recover(): Promise<ToonIdentity> {\n // Check local vault first — if available, we can do a single-assertion unlock\n const localVault = await this.loadFromLocalStorage();\n if (localVault) {\n return this.unlockWithVault(localVault);\n }\n\n // No local vault — need to discover pubkey from Passkey userHandle,\n // fetch backup from relays, then do a second assertion with the correct salt.\n // This is the cross-device recovery path (two assertions unavoidable).\n const discovery = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: crypto.getRandomValues(new Uint8Array(32)), // Dummy salt for discovery\n });\n\n if (!discovery.userHandle || discovery.userHandle.length === 0) {\n throw new Error(\n 'Passkey did not return a userHandle. Cannot determine Nostr pubkey for recovery.'\n );\n }\n\n // Extract Nostr pubkey from userHandle\n const pubkey = bytesToHex(discovery.userHandle);\n\n // Fetch backup from relays\n const vault = await fetchBackupFromRelays(pubkey, this.config.relayUrls);\n if (!vault) {\n throw new Error(\n 'No backup found on configured relays for this identity. ' +\n 'Try importing with a mnemonic or nsec instead.'\n );\n }\n\n // Find the matching wrapped key entry for this credential\n const credIdHash = await hashCredentialId(discovery.credentialId);\n const entry = vault.wrappedKeys.find((e) => e.id === credIdHash);\n if (!entry) {\n throw new Error(\n 'This Passkey is not registered with the backup. ' +\n 'Try a different Passkey or use a recovery code.'\n );\n }\n\n // Re-assert with the correct PRF salt from the backup\n const saltBytes = fromBase64(entry.salt);\n const reassertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: saltBytes,\n allowCredentials: [discovery.credentialId],\n });\n\n // Derive KEK and unlock vault\n const kek = await deriveKek(reassertion.prfOutput);\n const mnemonic = await unlockVault(vault, kek, credIdHash);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n // Cache locally for future single-assertion unlocks\n await this.saveToLocalStorage();\n\n return identity;\n }\n\n /**\n * Import an existing BIP-39 mnemonic. Creates a Passkey and backup.\n */\n async importMnemonic(mnemonic: string): Promise<ToonIdentity> {\n if (!validateMnemonic(mnemonic)) {\n throw new Error('Invalid BIP-39 mnemonic phrase');\n }\n\n const identity = await deriveFullIdentity(mnemonic);\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n this.vault = await createVault(mnemonic, kek, credIdHash, prfSalt);\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n\n return identity;\n }\n\n /**\n * Import from an nsec (Nostr-only key).\n * Nostr + EVM are derived; Solana + Mina get fresh keys (not deterministically linked).\n */\n async importNsec(nsec: string): Promise<ToonIdentity> {\n const decoded = nip19.decode(nsec);\n if (decoded.type !== 'nsec') {\n throw new Error('Invalid nsec string');\n }\n const secretKey = decoded.data;\n const identity = deriveFromNsec(secretKey);\n\n if (isPrfSupported()) {\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(identity.nostr.pubkey);\n\n try {\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const kek = await deriveKek(registration.prfOutput);\n const credIdHash = await hashCredentialId(registration.credentialId);\n\n // For nsec import without mnemonic, we store the hex-encoded secret key\n const hexKey = bytesToHex(secretKey);\n this.vault = await createVault(hexKey, kek, credIdHash, prfSalt);\n this.activeCredentialIdHash = credIdHash;\n\n await this.saveToLocalStorage();\n } catch {\n // PRF may be reported as supported but fail at registration time.\n // Proceed without vault — identity is still usable.\n }\n }\n\n this.identity = identity;\n return identity;\n }\n\n // --- Passkey Management ---\n\n /**\n * Register an additional Passkey for this identity.\n */\n async addPasskey(): Promise<void> {\n if (!this.identity || !this.vault || !this.activeCredentialIdHash) {\n throw new Error('No active identity — call create() or recover() first');\n }\n\n const prfSalt = crypto.getRandomValues(new Uint8Array(32));\n const userIdBytes = hexToBytes(this.identity.nostr.pubkey);\n\n const registration = await registerPasskey({\n rpId: this.config.rpId,\n rpName: this.config.rpName,\n userId: userIdBytes,\n userName: `TOON ${this.identity.nostr.pubkey.slice(0, 8)}`,\n prfSalt,\n });\n\n const newKek = await deriveKek(registration.prfOutput);\n const newCredIdHash = await hashCredentialId(registration.credentialId);\n\n // Re-assert the current Passkey to get KEK for unwrapping\n const currentEntry = this.vault.wrappedKeys.find(\n (e) => e.id === this.activeCredentialIdHash\n );\n if (!currentEntry) {\n throw new Error('Active credential not found in vault');\n }\n\n const currentSaltBytes = fromBase64(currentEntry.salt);\n const currentAssertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: currentSaltBytes,\n });\n const currentKek = await deriveKek(currentAssertion.prfOutput);\n\n this.vault = await addKekToVault(\n this.vault,\n currentKek,\n this.activeCredentialIdHash,\n newKek,\n newCredIdHash,\n prfSalt\n );\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n }\n\n /**\n * List registered Passkey credentials.\n */\n listPasskeys(): PasskeyInfo[] {\n if (!this.vault) return [];\n return this.vault.wrappedKeys.map((entry) => ({\n credentialIdHash: entry.id,\n createdAt: entry.created_at,\n }));\n }\n\n /**\n * Remove a Passkey from the vault. Cannot remove the last one.\n */\n async removePasskey(credentialIdHash: string): Promise<void> {\n if (!this.vault) {\n throw new Error('No active vault');\n }\n\n this.vault = removeKekFromVault(this.vault, credentialIdHash);\n\n // If we removed the active credential, switch to another\n if (this.activeCredentialIdHash === credentialIdHash) {\n const remaining = this.vault.wrappedKeys[0];\n this.activeCredentialIdHash = remaining ? remaining.id : null;\n }\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n }\n\n // --- Recovery ---\n\n /**\n * Generate a printable recovery code and add it to the vault.\n * The PBKDF2 salt is persisted alongside the wrapped DEK so the code\n * can be verified later without the original salt.\n *\n * @returns The recovery code — user must store it securely.\n */\n async generateRecoveryCode(): Promise<string> {\n if (!this.vault || !this.activeCredentialIdHash) {\n throw new Error('No active vault');\n }\n\n const code = generateRecoveryCodeRaw();\n\n // Generate and persist PBKDF2 salt for recovery code\n const salt = crypto.getRandomValues(new Uint8Array(16));\n const recoveryKek = await deriveKekFromPassword(code, salt);\n\n // Get current KEK to unwrap DEK\n const currentEntry = this.vault.wrappedKeys.find(\n (e) => e.id === this.activeCredentialIdHash\n );\n if (!currentEntry) {\n throw new Error('Active credential not found in vault');\n }\n\n const currentSaltBytes = fromBase64(currentEntry.salt);\n const currentAssertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: currentSaltBytes,\n });\n const currentKek = await deriveKek(currentAssertion.prfOutput);\n\n this.vault = await addRecoveryCodeToVault(\n this.vault,\n currentKek,\n this.activeCredentialIdHash,\n recoveryKek,\n salt\n );\n\n await this.saveToLocalStorage();\n await this.backupToRelay().catch(() => {\n // Backup failure is non-fatal\n });\n\n return code;\n }\n\n /**\n * Recover identity using a recovery code.\n * The PBKDF2 salt is read from the persisted vault data.\n */\n async recoverWithCode(code: string): Promise<ToonIdentity> {\n const vault = await this.loadFromLocalStorage();\n\n if (!vault) {\n throw new Error(\n 'No local vault found. Recovery code requires the encrypted vault. ' +\n 'If you have a Passkey, use recover() to fetch from relays first.'\n );\n }\n\n if (!vault.recoveryCodeWrappedDek || !vault.recoveryCodeSalt) {\n throw new Error('No recovery code configured for this vault');\n }\n\n // Use the persisted PBKDF2 salt to reproduce the exact KEK\n const salt = fromBase64(vault.recoveryCodeSalt);\n const recoveryKek = await deriveKekFromPassword(code, salt);\n\n const mnemonic = await unlockVaultWithRecoveryCode(vault, recoveryKek);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n\n return identity;\n }\n\n // --- Key Access ---\n\n /**\n * Get the current identity, or null if not unlocked.\n */\n getIdentity(): ToonIdentity | null {\n return this.identity;\n }\n\n /**\n * Get the Nostr secret key. Throws if not unlocked.\n */\n getNostrSecretKey(): Uint8Array {\n if (!this.identity) throw new Error('Identity not unlocked');\n return this.identity.nostr.secretKey;\n }\n\n /**\n * Get an EvmSigner instance. Throws if not unlocked.\n */\n getEvmSigner(): EvmSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n return new EvmSigner(this.identity.evm.privateKey);\n }\n\n /**\n * Get a SolanaSigner instance. Throws if not unlocked or Solana not derived.\n */\n getSolanaSigner(): SolanaSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n if (!this.identity.solana.publicKey) {\n throw new Error(\n 'Solana keys not available — was this imported from nsec?'\n );\n }\n return new SolanaSigner(this.identity.solana.secretKey);\n }\n\n /**\n * Get a MinaSigner instance. Throws if not unlocked or Mina not derived.\n */\n getMinaSigner(): MinaSigner {\n if (!this.identity) throw new Error('Identity not unlocked');\n if (!this.identity.mina.publicKey) {\n throw new Error('Mina keys not available — was this imported from nsec?');\n }\n return new MinaSigner(this.identity.mina.privateKey);\n }\n\n // --- Backup ---\n\n /**\n * Publish the current vault to configured relays as a kind:30078 event.\n */\n async backupToRelay(): Promise<void> {\n if (!this.identity || !this.vault) {\n throw new Error('No active identity or vault to backup');\n }\n\n const eventTemplate = buildBackupEvent(\n this.vault,\n this.identity.nostr.secretKey\n );\n\n // Sign with nostr-tools\n const signedEvent = finalizeEvent(\n eventTemplate,\n this.identity.nostr.secretKey\n );\n\n await publishBackupToRelays(signedEvent, this.config.relayUrls);\n }\n\n // --- Lock/Unlock ---\n\n /**\n * Clear keys from memory. The vault remains in IndexedDB.\n * Note: JavaScript strings (mnemonics) cannot be zeroed — only Uint8Array keys are cleared.\n */\n lock(): void {\n if (this.identity) {\n // Zero out sensitive Uint8Array key material\n this.identity.nostr.secretKey.fill(0);\n // evm.privateKey may be the same reference as nostr.secretKey — fill is idempotent\n this.identity.evm.privateKey.fill(0);\n this.identity.solana.secretKey.fill(0);\n }\n this.identity = null;\n }\n\n /**\n * Re-assert Passkey to decrypt local vault and restore identity.\n * Uses the local vault's stored PRF salt for a single biometric prompt.\n */\n async unlock(): Promise<ToonIdentity> {\n const vault = await this.loadFromLocalStorage();\n if (!vault) {\n throw new Error('No local vault found — use create() or recover()');\n }\n\n return this.unlockWithVault(vault);\n }\n\n // --- Private helpers ---\n\n /**\n * Unlock a vault with a single Passkey assertion using stored PRF salts.\n * If the vault has only one credential, uses allowCredentials to constrain.\n */\n private async unlockWithVault(vault: VaultData): Promise<ToonIdentity> {\n // We don't have the raw credential IDs (only hashes), so we can't constrain\n // allowCredentials. The user picks a credential, then we verify it matches.\n const firstEntry = vault.wrappedKeys[0];\n if (!firstEntry) {\n throw new Error('Vault has no registered credentials');\n }\n\n const assertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: fromBase64(firstEntry.salt),\n });\n\n const credIdHash = await hashCredentialId(assertion.credentialId);\n const matchingEntry = vault.wrappedKeys.find((e) => e.id === credIdHash);\n\n if (!matchingEntry) {\n throw new Error('This Passkey is not registered with the local vault');\n }\n\n // If the user picked the first credential, we already have the correct PRF output.\n // If they picked a different one, we need to re-assert with the correct salt.\n let prfOutput = assertion.prfOutput;\n if (matchingEntry.id !== firstEntry.id) {\n const correctSalt = fromBase64(matchingEntry.salt);\n const reassertion = await assertPasskey({\n rpId: this.config.rpId,\n prfSalt: correctSalt,\n allowCredentials: [assertion.credentialId],\n });\n prfOutput = reassertion.prfOutput;\n }\n\n const kek = await deriveKek(prfOutput);\n const mnemonic = await unlockVault(vault, kek, credIdHash);\n const identity = await deriveFullIdentity(mnemonic);\n\n this.vault = vault;\n this.identity = identity;\n this.activeCredentialIdHash = credIdHash;\n\n return identity;\n }\n\n // --- IndexedDB Persistence ---\n\n private async saveToLocalStorage(): Promise<void> {\n if (!this.vault) return;\n if (typeof indexedDB === 'undefined') return;\n\n const dbName = this.config.storageKey;\n const db = await openDb(dbName);\n const tx = db.transaction('vault', 'readwrite');\n const store = tx.objectStore('vault');\n store.put(JSON.stringify(this.vault), 'current');\n await new Promise<void>((resolve, reject) => {\n tx.oncomplete = () => resolve();\n tx.onerror = () => reject(tx.error);\n });\n db.close();\n }\n\n private async loadFromLocalStorage(): Promise<VaultData | null> {\n if (typeof indexedDB === 'undefined') return null;\n\n const dbName = this.config.storageKey;\n try {\n const db = await openDb(dbName);\n const tx = db.transaction('vault', 'readonly');\n const store = tx.objectStore('vault');\n const request = store.get('current');\n const result = await new Promise<string | undefined>(\n (resolve, reject) => {\n request.onsuccess = () =>\n resolve(request.result as string | undefined);\n request.onerror = () => reject(request.error);\n }\n );\n db.close();\n if (!result) return null;\n return JSON.parse(result) as VaultData;\n } catch {\n return null;\n }\n }\n}\n\n// --- Helpers ---\n\nfunction openDb(name: string): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(name, 1);\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains('vault')) {\n db.createObjectStore('vault');\n }\n };\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n","import type {\n PasskeyAssertionResult,\n PasskeyRegistrationResult,\n} from './types.js';\n\n/**\n * WebAuthn Passkey authentication with PRF extension for key encryption.\n *\n * Handles credential registration (create) and assertion (get) with the\n * prf extension to derive a deterministic secret from the authenticator.\n * When PRF is unavailable, callers should fall back to password-based KEK.\n */\n\n/**\n * Register a new Passkey credential with PRF extension.\n *\n * @param rpId - Relying party identifier (e.g., \"example.com\")\n * @param rpName - Human-readable relying party name\n * @param userId - Raw user ID bytes (Nostr pubkey, 32 bytes)\n * @param userName - Display name for the credential\n * @param prfSalt - Random salt for the PRF evaluation\n * @returns Registration result with PRF output and credential ID\n */\nexport async function registerPasskey(params: {\n rpId: string;\n rpName: string;\n userId: Uint8Array;\n userName: string;\n prfSalt: Uint8Array;\n}): Promise<PasskeyRegistrationResult> {\n const { rpId, rpName, userId, userName, prfSalt } = params;\n\n const publicKeyOptions: PublicKeyCredentialCreationOptions = {\n rp: { id: rpId, name: rpName },\n user: {\n id: userId as unknown as BufferSource,\n name: userName,\n displayName: userName,\n },\n challenge: crypto.getRandomValues(\n new Uint8Array(32)\n ) as unknown as BufferSource,\n pubKeyCredParams: [\n { alg: -7, type: 'public-key' }, // ES256\n { alg: -257, type: 'public-key' }, // RS256\n ],\n authenticatorSelection: {\n residentKey: 'required',\n userVerification: 'required',\n },\n extensions: {\n prf: {\n eval: {\n first: prfSalt as unknown as BufferSource,\n },\n },\n } as AuthenticationExtensionsClientInputs,\n };\n\n const credential = (await navigator.credentials.create({\n publicKey: publicKeyOptions,\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('Passkey registration was cancelled or failed');\n }\n\n const response = credential.response as AuthenticatorAttestationResponse;\n const extensionResults = credential.getClientExtensionResults();\n\n const prfResults = (extensionResults as Record<string, unknown>)['prf'] as\n | { enabled?: boolean; results?: { first: ArrayBuffer } }\n | undefined;\n\n if (!prfResults?.results?.first) {\n throw new Error(\n 'PRF extension not supported by this authenticator. ' +\n 'Passkey was created but cannot be used for key encryption. ' +\n 'Use password-based encryption as fallback.'\n );\n }\n\n const credentialId = new Uint8Array(credential.rawId);\n\n // Verify attestation response is valid\n if (!response.attestationObject) {\n throw new Error('Invalid attestation response');\n }\n\n return {\n prfOutput: prfResults.results.first,\n credentialId,\n };\n}\n\n/**\n * Assert an existing Passkey credential with PRF extension.\n *\n * @param rpId - Relying party identifier\n * @param prfSalt - The same salt used during registration for this credential\n * @param allowCredentials - Optional list of credential IDs to filter\n * @returns Assertion result with PRF output, credential ID, and userHandle\n */\nexport async function assertPasskey(params: {\n rpId: string;\n prfSalt: Uint8Array;\n allowCredentials?: Uint8Array[];\n}): Promise<PasskeyAssertionResult> {\n const { rpId, prfSalt, allowCredentials } = params;\n\n const publicKeyOptions = {\n rpId,\n challenge: crypto.getRandomValues(\n new Uint8Array(32)\n ) as unknown as BufferSource,\n userVerification: 'required' as const,\n ...(allowCredentials && {\n allowCredentials: allowCredentials.map((id) => ({\n id: id as unknown as BufferSource,\n type: 'public-key' as const,\n })),\n }),\n extensions: {\n prf: {\n eval: {\n first: prfSalt as unknown as BufferSource,\n },\n },\n } as AuthenticationExtensionsClientInputs,\n } as PublicKeyCredentialRequestOptions;\n\n const credential = (await navigator.credentials.get({\n publicKey: publicKeyOptions,\n })) as PublicKeyCredential | null;\n\n if (!credential) {\n throw new Error('Passkey assertion was cancelled or failed');\n }\n\n const response = credential.response as AuthenticatorAssertionResponse;\n const extensionResults = credential.getClientExtensionResults();\n\n const prfResults = (extensionResults as Record<string, unknown>)['prf'] as\n | { results?: { first: ArrayBuffer } }\n | undefined;\n\n if (!prfResults?.results?.first) {\n throw new Error(\n 'PRF extension did not return a result. ' +\n 'The authenticator may not support PRF.'\n );\n }\n\n return {\n prfOutput: prfResults.results.first,\n credentialId: new Uint8Array(credential.rawId),\n userHandle: response.userHandle\n ? new Uint8Array(response.userHandle)\n : null,\n };\n}\n\n/**\n * Check whether the current browser supports WebAuthn with PRF extension.\n * Returns false in Node.js or browsers without PublicKeyCredential.\n */\nexport function isPrfSupported(): boolean {\n if (typeof window === 'undefined') return false;\n if (typeof navigator === 'undefined') return false;\n if (!navigator.credentials) return false;\n if (typeof PublicKeyCredential === 'undefined') return false;\n // PRF support cannot be feature-detected without actually creating a credential,\n // so we return true if WebAuthn is available and let registration handle the error.\n return true;\n}\n\n/**\n * Compute SHA-256 hash of a credential ID for use as a lookup key.\n */\nexport async function hashCredentialId(\n credentialId: Uint8Array\n): Promise<string> {\n const arrayBuffer = credentialId.buffer.slice(\n credentialId.byteOffset,\n credentialId.byteOffset + credentialId.byteLength\n ) as ArrayBuffer;\n const hash = await crypto.subtle.digest('SHA-256', arrayBuffer);\n return Array.from(new Uint8Array(hash))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","/**\n * Browser-safe Base64 encoding/decoding utilities.\n * Accepts Uint8Array directly to avoid TypedArray .buffer offset issues.\n */\n\nexport function toBase64(data: Uint8Array | ArrayBuffer): string {\n const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);\n let binary = '';\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary);\n}\n\nexport function fromBase64(b64: string): Uint8Array<ArrayBuffer> {\n const binary = atob(b64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\nexport function hexToBytes(hex: string): Uint8Array {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);\n }\n return bytes;\n}\n\nexport function bytesToHex(bytes: Uint8Array): string {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n","import type { VaultData, WrappedKeyEntry } from './types.js';\nimport { toBase64, fromBase64 } from './encoding.js';\n\n/**\n * Envelope encryption for mnemonic storage.\n *\n * Pattern: DEK encrypts mnemonic, KEK wraps DEK.\n * Multiple KEKs (Passkeys, recovery codes) can each wrap the same DEK independently.\n *\n * - DEK: random 256-bit AES key (Data Encryption Key)\n * - KEK: derived from Passkey PRF or recovery code (Key Encryption Key)\n * - Mnemonic encrypted with AES-256-GCM using DEK\n * - DEK wrapped with AES-KW using KEK\n */\n\n// --- DEK operations ---\n\n/**\n * Generate a random 256-bit Data Encryption Key.\n */\nexport async function generateDek(): Promise<CryptoKey> {\n return crypto.subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n true, // extractable — needed for AES-KW wrapping\n ['encrypt', 'decrypt']\n );\n}\n\n/**\n * Encrypt a mnemonic string with a DEK using AES-256-GCM.\n * @returns Base64-encoded ciphertext and IV\n */\nexport async function encryptMnemonic(\n dek: CryptoKey,\n mnemonic: string\n): Promise<{ encryptedMnemonic: string; iv: string }> {\n const encoder = new TextEncoder();\n const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit GCM nonce\n const ciphertext = await crypto.subtle.encrypt(\n { name: 'AES-GCM', iv },\n dek,\n encoder.encode(mnemonic)\n );\n return {\n encryptedMnemonic: toBase64(ciphertext),\n iv: toBase64(iv),\n };\n}\n\n/**\n * Decrypt a mnemonic from its encrypted form using a DEK.\n */\nexport async function decryptMnemonic(\n dek: CryptoKey,\n encryptedMnemonic: string,\n iv: string\n): Promise<string> {\n const decoder = new TextDecoder();\n const plaintext = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: fromBase64(iv) },\n dek,\n fromBase64(encryptedMnemonic)\n );\n return decoder.decode(plaintext);\n}\n\n// --- KEK operations ---\n\n/**\n * Derive a KEK from a Passkey PRF output using HKDF.\n *\n * Flow: PRF(CredRandom, salt) → HKDF-SHA-256 → 256-bit AES-KW key\n */\nexport async function deriveKek(prfOutput: ArrayBuffer): Promise<CryptoKey> {\n // Import PRF output as HKDF key material\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n prfOutput,\n 'HKDF',\n false,\n ['deriveKey']\n );\n\n const encoder = new TextEncoder();\n return crypto.subtle.deriveKey(\n {\n name: 'HKDF',\n hash: 'SHA-256',\n salt: new Uint8Array(0), // PRF salt was already applied at the WebAuthn level\n info: encoder.encode('toon:kek'),\n },\n keyMaterial,\n { name: 'AES-KW', length: 256 },\n false, // not extractable\n ['wrapKey', 'unwrapKey']\n );\n}\n\n/**\n * Derive a KEK from a password string using PBKDF2.\n * Used as fallback when PRF is not available, or for recovery codes.\n */\nexport async function deriveKekFromPassword(\n password: string,\n salt: Uint8Array<ArrayBuffer>\n): Promise<CryptoKey> {\n const encoder = new TextEncoder();\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(password),\n 'PBKDF2',\n false,\n ['deriveKey']\n );\n\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n hash: 'SHA-256',\n salt,\n iterations: 600_000, // OWASP 2023 recommendation for SHA-256\n },\n keyMaterial,\n { name: 'AES-KW', length: 256 },\n false,\n ['wrapKey', 'unwrapKey']\n );\n}\n\n// --- Wrap/Unwrap DEK ---\n\n/**\n * Wrap (encrypt) a DEK with a KEK using AES-KW.\n * @returns Base64-encoded wrapped DEK\n */\nexport async function wrapDek(kek: CryptoKey, dek: CryptoKey): Promise<string> {\n const wrapped = await crypto.subtle.wrapKey('raw', dek, kek, 'AES-KW');\n return toBase64(new Uint8Array(wrapped));\n}\n\n/**\n * Unwrap (decrypt) a DEK from its wrapped form using a KEK.\n * @returns The unwrapped DEK as a CryptoKey\n */\nexport async function unwrapDek(\n kek: CryptoKey,\n wrappedDek: string\n): Promise<CryptoKey> {\n return crypto.subtle.unwrapKey(\n 'raw',\n fromBase64(wrappedDek),\n kek,\n 'AES-KW',\n { name: 'AES-GCM', length: 256 },\n true, // extractable — needed for re-wrapping when adding new KEKs\n ['encrypt', 'decrypt']\n );\n}\n\n// --- High-level vault operations ---\n\n/**\n * Create a new vault: generate DEK, encrypt mnemonic, wrap DEK with initial KEK.\n */\nexport async function createVault(\n mnemonic: string,\n kek: CryptoKey,\n credentialIdHash: string,\n prfSalt: Uint8Array\n): Promise<VaultData> {\n const dek = await generateDek();\n const { encryptedMnemonic, iv } = await encryptMnemonic(dek, mnemonic);\n const wrappedDek = await wrapDek(kek, dek);\n\n const entry: WrappedKeyEntry = {\n id: credentialIdHash,\n wrapped_dek: wrappedDek,\n salt: toBase64(prfSalt),\n created_at: Math.floor(Date.now() / 1000),\n };\n\n return {\n encryptedMnemonic,\n iv,\n wrappedKeys: [entry],\n };\n}\n\n/**\n * Unlock a vault: unwrap DEK with KEK, decrypt mnemonic.\n */\nexport async function unlockVault(\n vault: VaultData,\n kek: CryptoKey,\n credentialIdHash: string\n): Promise<string> {\n const entry = vault.wrappedKeys.find((e) => e.id === credentialIdHash);\n if (!entry) {\n throw new Error(`No wrapped key found for credential ${credentialIdHash}`);\n }\n\n const dek = await unwrapDek(kek, entry.wrapped_dek);\n return decryptMnemonic(dek, vault.encryptedMnemonic, vault.iv);\n}\n\n/**\n * Add a new KEK (from a new Passkey or recovery code) to an existing vault.\n * Requires an existing KEK to unwrap the DEK first.\n */\nexport async function addKekToVault(\n vault: VaultData,\n existingKek: CryptoKey,\n existingCredentialIdHash: string,\n newKek: CryptoKey,\n newCredentialIdHash: string,\n newPrfSalt: Uint8Array\n): Promise<VaultData> {\n // Unwrap DEK with existing KEK\n const existingEntry = vault.wrappedKeys.find(\n (e) => e.id === existingCredentialIdHash\n );\n if (!existingEntry) {\n throw new Error(\n `No wrapped key found for credential ${existingCredentialIdHash}`\n );\n }\n const dek = await unwrapDek(existingKek, existingEntry.wrapped_dek);\n\n // Wrap DEK with new KEK\n const newWrappedDek = await wrapDek(newKek, dek);\n\n const newEntry: WrappedKeyEntry = {\n id: newCredentialIdHash,\n wrapped_dek: newWrappedDek,\n salt: toBase64(newPrfSalt),\n created_at: Math.floor(Date.now() / 1000),\n };\n\n return {\n ...vault,\n wrappedKeys: [...vault.wrappedKeys, newEntry],\n };\n}\n\n/**\n * Remove a KEK from a vault. Always requires at least one passkey KEK to remain.\n */\nexport function removeKekFromVault(\n vault: VaultData,\n credentialIdHash: string\n): VaultData {\n const remaining = vault.wrappedKeys.filter((e) => e.id !== credentialIdHash);\n\n if (remaining.length === 0) {\n throw new Error(\n 'Cannot remove the last passkey — at least one passkey must remain for vault access'\n );\n }\n\n return {\n ...vault,\n wrappedKeys: remaining,\n };\n}\n\n/**\n * Add a recovery code KEK to the vault.\n * The PBKDF2 salt is persisted in the vault so recoverWithCode can reproduce the KEK.\n */\nexport async function addRecoveryCodeToVault(\n vault: VaultData,\n existingKek: CryptoKey,\n existingCredentialIdHash: string,\n recoveryKek: CryptoKey,\n recoverySalt: Uint8Array\n): Promise<VaultData> {\n const existingEntry = vault.wrappedKeys.find(\n (e) => e.id === existingCredentialIdHash\n );\n if (!existingEntry) {\n throw new Error(\n `No wrapped key found for credential ${existingCredentialIdHash}`\n );\n }\n const dek = await unwrapDek(existingKek, existingEntry.wrapped_dek);\n const recoveryWrappedDek = await wrapDek(recoveryKek, dek);\n\n return {\n ...vault,\n recoveryCodeWrappedDek: recoveryWrappedDek,\n recoveryCodeSalt: toBase64(recoverySalt),\n };\n}\n\n/**\n * Unlock a vault using a recovery code.\n */\nexport async function unlockVaultWithRecoveryCode(\n vault: VaultData,\n recoveryKek: CryptoKey\n): Promise<string> {\n if (!vault.recoveryCodeWrappedDek) {\n throw new Error('No recovery code is configured for this vault');\n }\n\n const dek = await unwrapDek(recoveryKek, vault.recoveryCodeWrappedDek);\n return decryptMnemonic(dek, vault.encryptedMnemonic, vault.iv);\n}\n\n/**\n * Generate a human-readable recovery code (24 random hex chars with dashes).\n * Format: XXXX-XXXX-XXXX-XXXX-XXXX-XXXX (easy to write down).\n */\nexport function generateRecoveryCode(): string {\n const bytes = crypto.getRandomValues(new Uint8Array(12));\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n const groups = hex.match(/.{4}/g) ?? [];\n return groups.join('-');\n}\n","import { getPublicKey } from 'nostr-tools/pure';\nimport type { BackupPayload, VaultData } from './types.js';\n\n/**\n * Relay-based encrypted backup service using kind:30078 (NIP-78 application-specific data).\n *\n * The backup event is a replaceable event keyed by `d: \"toon:identity-backup\"`.\n * Content is an encrypted payload — the relay cannot read the mnemonic.\n */\n\nconst BACKUP_KIND = 30078;\nconst BACKUP_D_TAG = 'toon:identity-backup';\nconst BACKUP_VERSION = '1';\n\n/**\n * Build a kind:30078 Nostr event for identity backup.\n * The event must be signed by the caller before publishing.\n *\n * @param vault - The encrypted vault data\n * @param secretKey - Nostr secret key for signing\n * @param chains - Comma-separated list of supported chains\n * @returns Unsigned Nostr event template\n */\nexport function buildBackupEvent(\n vault: VaultData,\n secretKey: Uint8Array,\n chains = 'nostr,evm,solana,mina'\n): {\n kind: number;\n pubkey: string;\n created_at: number;\n tags: string[][];\n content: string;\n} {\n const pubkey = getPublicKey(secretKey);\n\n const payload: BackupPayload = {\n encrypted_mnemonic: vault.encryptedMnemonic,\n wrapped_keys: vault.wrappedKeys,\n iv: vault.iv,\n ...(vault.recoveryCodeWrappedDek && {\n recovery_code_wrapped_dek: vault.recoveryCodeWrappedDek,\n }),\n ...(vault.recoveryCodeSalt && {\n recovery_code_salt: vault.recoveryCodeSalt,\n }),\n };\n\n return {\n kind: BACKUP_KIND,\n pubkey,\n created_at: Math.floor(Date.now() / 1000),\n tags: [\n ['d', BACKUP_D_TAG],\n ['v', BACKUP_VERSION],\n ['chains', chains],\n ],\n content: JSON.stringify(payload),\n };\n}\n\n/**\n * Build a relay filter to fetch the identity backup for a given pubkey.\n */\nexport function buildBackupFilter(pubkey: string): {\n kinds: number[];\n authors: string[];\n '#d': string[];\n} {\n return {\n kinds: [BACKUP_KIND],\n authors: [pubkey],\n '#d': [BACKUP_D_TAG],\n };\n}\n\n/**\n * Parse a backup event's content into VaultData.\n * Validates the structure before returning.\n */\nexport function parseBackupPayload(content: string): VaultData {\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch {\n throw new Error('Invalid backup event content: not valid JSON');\n }\n\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('Invalid backup event content: not an object');\n }\n\n const payload = parsed as Record<string, unknown>;\n\n if (typeof payload['encrypted_mnemonic'] !== 'string') {\n throw new Error('Invalid backup: missing encrypted_mnemonic');\n }\n if (typeof payload['iv'] !== 'string') {\n throw new Error('Invalid backup: missing iv');\n }\n if (!Array.isArray(payload['wrapped_keys'])) {\n throw new Error('Invalid backup: missing wrapped_keys array');\n }\n\n // Validate each wrapped key entry\n for (const entry of payload['wrapped_keys']) {\n if (typeof entry !== 'object' || entry === null) {\n throw new Error('Invalid backup: wrapped_keys entry is not an object');\n }\n const e = entry as Record<string, unknown>;\n if (typeof e['id'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing id');\n }\n if (typeof e['wrapped_dek'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing wrapped_dek');\n }\n if (typeof e['salt'] !== 'string') {\n throw new Error('Invalid backup: wrapped key missing salt');\n }\n if (typeof e['created_at'] !== 'number') {\n throw new Error(\n 'Invalid backup: wrapped key missing or invalid created_at'\n );\n }\n }\n\n return {\n encryptedMnemonic: payload['encrypted_mnemonic'] as string,\n iv: payload['iv'] as string,\n wrappedKeys: payload['wrapped_keys'] as VaultData['wrappedKeys'],\n ...(typeof payload['recovery_code_wrapped_dek'] === 'string' && {\n recoveryCodeWrappedDek: payload['recovery_code_wrapped_dek'],\n }),\n ...(typeof payload['recovery_code_salt'] === 'string' && {\n recoveryCodeSalt: payload['recovery_code_salt'],\n }),\n };\n}\n\n/**\n * Publish a backup event to one or more relays.\n *\n * Uses the SimplePool from nostr-tools for relay communication.\n * The event must be signed before calling this function.\n */\nexport async function publishBackupToRelays(\n signedEvent: {\n id: string;\n kind: number;\n pubkey: string;\n created_at: number;\n tags: string[][];\n content: string;\n sig: string;\n },\n relayUrls: string[]\n): Promise<void> {\n // Dynamic import to avoid pulling nostr-tools/pool into non-browser bundles\n const { SimplePool } = await import('nostr-tools/pool');\n const pool = new SimplePool();\n\n try {\n await Promise.allSettled(\n relayUrls.map((url) => pool.publish([url], signedEvent))\n );\n } finally {\n pool.close(relayUrls);\n }\n}\n\n/**\n * Fetch a backup event from relays for a given pubkey.\n * Returns the most recent backup event, or null if none found.\n */\nexport async function fetchBackupFromRelays(\n pubkey: string,\n relayUrls: string[]\n): Promise<VaultData | null> {\n const { SimplePool } = await import('nostr-tools/pool');\n const pool = new SimplePool();\n\n try {\n const filter = buildBackupFilter(pubkey);\n const events = await pool.querySync(relayUrls, filter);\n\n if (!events || events.length === 0) {\n return null;\n }\n\n // Sort by created_at descending, take most recent\n events.sort(\n (a: { created_at: number }, b: { created_at: number }) =>\n b.created_at - a.created_at\n );\n\n const latest = events[0];\n if (!latest) return null;\n return parseBackupPayload(latest.content);\n } finally {\n pool.close(relayUrls);\n }\n}\n","/**\n * Node-only encrypted mnemonic keystore for @toon-protocol/client.\n *\n * Mirrors the relay node wallet crypto (`packages/relay/src/wallet/\n * crypto.ts`): a BIP-39 mnemonic is encrypted at rest with scrypt (KDF) +\n * AES-256-GCM (authenticated encryption), serialized as JSON, and written to\n * disk with mode 0o600. Decryption requires the operator password; a wrong\n * password fails the GCM auth-tag verification and throws.\n *\n * This is the Node-side counterpart to the browser Passkey/IndexedDB\n * `KeyManager`/`KeyVault` flow — it does NOT touch those. It is guarded against\n * browser bundling: every entry point throws if `node:crypto`/`node:fs` are not\n * available (e.g. when accidentally imported in a browser bundle).\n *\n * @module\n */\n\nimport {\n scryptSync,\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} from 'node:crypto';\nimport { writeFileSync, readFileSync } from 'node:fs';\nimport {\n generateMnemonic as genMnemonic,\n validateMnemonic as isValidMnemonic,\n} from './KeyDerivation.js';\n\n/** scrypt parameters — N=2^17 (~0.5-1s on modern hardware), r=8, p=1. */\nconst SCRYPT_N = 2 ** 17;\nconst SCRYPT_R = 8;\nconst SCRYPT_P = 1;\nconst SCRYPT_KEY_LEN = 32;\n/** maxmem for scrypt: N * r * 128 * 2 (with headroom for Node.js overhead). */\nconst SCRYPT_MAXMEM = SCRYPT_N * SCRYPT_R * 256 + 32 * 1024 * 1024;\n\n/** Salt length in bytes. */\nconst SALT_LEN = 32;\n/** AES-GCM IV length in bytes. */\nconst IV_LEN = 12;\n/** AES-GCM authentication tag length in bytes (128-bit). */\nconst AUTH_TAG_LEN = 16;\n\n/**\n * Encrypted keystore file format (JSON, all binary fields base64-encoded).\n * Wire-compatible with the relay node's `EncryptedWallet`.\n */\nexport interface EncryptedKeystore {\n /** scrypt salt (base64). */\n salt: string;\n /** AES-GCM initialization vector (base64). */\n iv: string;\n /** AES-256-GCM ciphertext (base64). */\n ciphertext: string;\n /** AES-GCM authentication tag (base64). */\n tag: string;\n /** Envelope version for forward-compat (currently 1). */\n version?: number;\n}\n\n/**\n * Throws if this module is running outside Node.js. The scrypt/AES-256-GCM\n * primitives and the 0o600 file write are Node-only — there is no browser\n * equivalent of `node:crypto`'s `scryptSync` or POSIX file modes, so we fail\n * loudly rather than silently bundling broken code into a browser build.\n */\nfunction assertNode(): void {\n // `process.versions.node` is present in Node and absent in browsers.\n const versions = (\n globalThis as { process?: { versions?: { node?: string } } }\n ).process?.versions;\n if (!versions?.node) {\n throw new Error(\n 'keystore-node is Node.js-only and cannot run in a browser. ' +\n 'Use the Passkey/IndexedDB KeyManager for browser key storage.'\n );\n }\n}\n\n/**\n * Encrypt a mnemonic with a password using scrypt + AES-256-GCM.\n * Returns the JSON-serializable encrypted envelope (does NOT write to disk).\n */\nexport function encryptMnemonic(\n mnemonic: string,\n password: string\n): EncryptedKeystore {\n assertNode();\n if (typeof mnemonic !== 'string' || mnemonic.length === 0) {\n throw new Error('encryptMnemonic: mnemonic must be a non-empty string');\n }\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('encryptMnemonic: password must be a non-empty string');\n }\n\n const salt = randomBytes(SALT_LEN);\n const iv = randomBytes(IV_LEN);\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const cipher = createCipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n const ciphertext = Buffer.concat([\n cipher.update(mnemonic, 'utf8'),\n cipher.final(),\n ]);\n const tag = cipher.getAuthTag();\n\n return {\n salt: salt.toString('base64'),\n iv: iv.toString('base64'),\n ciphertext: ciphertext.toString('base64'),\n tag: tag.toString('base64'),\n version: 1,\n };\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Decrypt an encrypted keystore envelope with a password.\n * Throws on a wrong password (GCM auth-tag verification failure) or corruption.\n */\nexport function decryptMnemonic(\n encrypted: EncryptedKeystore,\n password: string\n): string {\n assertNode();\n if (typeof password !== 'string' || password.length === 0) {\n throw new Error('decryptMnemonic: password must be a non-empty string');\n }\n if (\n !encrypted ||\n typeof encrypted.salt !== 'string' ||\n typeof encrypted.iv !== 'string' ||\n typeof encrypted.ciphertext !== 'string' ||\n typeof encrypted.tag !== 'string'\n ) {\n throw new Error('decryptMnemonic: malformed keystore envelope');\n }\n\n const salt = Buffer.from(encrypted.salt, 'base64');\n const iv = Buffer.from(encrypted.iv, 'base64');\n const ciphertext = Buffer.from(encrypted.ciphertext, 'base64');\n const tag = Buffer.from(encrypted.tag, 'base64');\n\n const key = scryptSync(password, salt, SCRYPT_KEY_LEN, {\n N: SCRYPT_N,\n r: SCRYPT_R,\n p: SCRYPT_P,\n maxmem: SCRYPT_MAXMEM,\n });\n\n try {\n const decipher = createDecipheriv('aes-256-gcm', key, iv, {\n authTagLength: AUTH_TAG_LEN,\n });\n decipher.setAuthTag(tag);\n try {\n const plaintext = Buffer.concat([\n decipher.update(ciphertext),\n decipher.final(),\n ]);\n return plaintext.toString('utf8');\n } catch {\n throw new Error(\n 'Decryption failed: wrong password or corrupted keystore file'\n );\n }\n } finally {\n key.fill(0);\n }\n}\n\n/**\n * Generate a fresh 12-word BIP-39 mnemonic, encrypt it under `password`, and\n * write the encrypted keystore to `path` with mode 0o600.\n *\n * Returns the mnemonic (for one-time display/backup) alongside the encrypted\n * envelope. The caller is responsible for displaying the mnemonic securely and\n * NOT persisting it in plaintext.\n */\nexport function generateKeystore(\n path: string,\n password: string\n): { mnemonic: string; keystore: EncryptedKeystore } {\n assertNode();\n const mnemonic = genMnemonic();\n const keystore = encryptMnemonic(mnemonic, password);\n writeKeystoreFile(path, keystore);\n return { mnemonic, keystore };\n}\n\n/**\n * Import an existing BIP-39 mnemonic (12 or 24 words), encrypt it under\n * `password`, and write the encrypted keystore to `path` with mode 0o600.\n *\n * Throws if the mnemonic is not a valid BIP-39 phrase (wrong checksum/word\n * count) before any file is written.\n */\nexport function importKeystore(\n path: string,\n mnemonic: string,\n password: string\n): EncryptedKeystore {\n assertNode();\n if (!isValidMnemonic(mnemonic)) {\n throw new Error(\n 'Invalid BIP-39 mnemonic: checksum or word-list validation failed'\n );\n }\n const keystore = encryptMnemonic(mnemonic, password);\n writeKeystoreFile(path, keystore);\n return keystore;\n}\n\n/**\n * Load and decrypt a keystore file at `path` with `password`, returning the\n * plaintext mnemonic. Throws on a wrong password or corruption.\n */\nexport function loadKeystore(path: string, password: string): string {\n assertNode();\n const raw = readFileSync(path, 'utf8');\n let parsed: EncryptedKeystore;\n try {\n parsed = JSON.parse(raw) as EncryptedKeystore;\n } catch {\n throw new Error(`Keystore file at ${path} is not valid JSON`);\n }\n return decryptMnemonic(parsed, password);\n}\n\n/**\n * Serialize and write an encrypted keystore to disk with mode 0o600\n * (owner read/write only), mirroring the relay node wallet file permissions.\n */\nexport function writeKeystoreFile(\n path: string,\n keystore: EncryptedKeystore\n): void {\n assertNode();\n writeFileSync(path, JSON.stringify(keystore, null, 2), {\n encoding: 'utf8',\n mode: 0o600,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE,qBAAAA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,OACK;;;ACJP,SAAS,qBAAAC,0BAAyB;AAClC;AAAA,EACE;AAAA,OAEK;;;ACDA,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACE,SACgB,MAChB,OACA;AACA,UAAM,SAAS,EAAE,MAAM,C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MACA,UACM;AACN,aAAW;AACX,EAAAE,eAAc,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,GAAG;AAAA,IACrD,UAAU;AAAA,IACV,MAAM;AAAA,EACR,CAAC;AACH;","names":["generateSecretKey","getPublicKey","generateSecretKey","ed25519","key","generateSecretKey","toHex","key","OerErrorKind","encodeVarOctetString","decodeVarOctetString","EnvelopeErrorKind","decodeVarOctetString","concat","encodeVarOctetString","GiftWrapErrorKind","concat","key","textEncoder","sha256","randomBytes","require","http","ed25519","base58Encode","sha256","sha256","TOKEN_PROGRAM_ID","key","STATE_MAP","base58Encode","ed25519","ensureOwnedMinaZkApp","status","privateKeyToAccount","toHex","ed25519","base58Encode","ed25519","base58Encode","toHex","hexToMinaBase58PrivateKey","sha256","sha256","hexToMinaBase58PrivateKey","createPublicClient","http","defineChain","sha256","BASE58_ALPHABET","createPublicClient","defineChain","http","parseEvmChainId","hexToMinaBase58PrivateKey","hexToMinaBase58PrivateKey","generateSecretKey","getPublicKey","readFileSync","writeFileSync","existsSync","secp256k1","bytesToHex","parseEvmChainId","finalizeEvent","toBase64","fromBase64","hexToBytes","bytesToHex","toBase64","fromBase64","getPublicKey","hexToBytes","bytesToHex","fromBase64","finalizeEvent","randomBytes","writeFileSync","readFileSync","encryptMnemonic","randomBytes","key","decryptMnemonic","readFileSync","writeFileSync"]}