@toon-protocol/client 3.2.0 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/channel/solana/wire-transaction.ts","../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\n * Solana wire transactions this client did NOT build.\n *\n * {@link import('./payment-channel.js').buildAndSendTransaction} composes a\n * transaction from instructions and signs every slot it created. This module is\n * the other half: somebody else compiled the message, and the client's only job\n * is to fill in the signature slots that are its own — and, when a fee payer\n * hands back a blockhash of its choosing, to move those 32 bytes without\n * touching anything else.\n *\n * That is the shape of a brokered transaction. In the ANT spawn the store\n * composes (it is the only party with `@ar.io/sdk`), the client signs (it is\n * the only party that may own the ANT), and the gas station pays and broadcasts\n * (it is the only party with SOL). None of the three can do the other two's\n * work, and the transaction travels between them as base64 wire bytes.\n *\n * **NEVER RECOMPILE.** The signature slots are in the compiled header's account\n * order, and the message bytes are what every signature covers, so rebuilding\n * the message from a decoded view — even into something byte-identical by\n * intent — is how a transaction arrives with signatures over a message that no\n * longer exists. Everything here is an in-place overwrite at a computed offset,\n * and {@link parseSolanaWireTransaction} exists to compute those offsets, not to\n * be a step towards re-serialization.\n *\n * The wire format (`solana-sdk`'s `Transaction`):\n *\n * ```text\n * compact-u16 signature count ─┐ must equal the message's\n * 64 × count signatures, slot order │ numRequiredSignatures\n * ── message ──────────────────────────────┘\n * 1 byte 0x80 | version (VERSIONED MESSAGES ONLY)\n * 3 bytes header\n * compact-u16 static account count\n * 32 × count static account keys (slot i signs for key i)\n * 32 bytes recent blockhash ← what patching overwrites\n * … instructions, address-table lookups\n * ```\n *\n * A zero-filled 64-byte slot is how \"not signed yet\" is spelled: `@solana/kit`'s\n * decoder reads one back as `null`, and the gas station's inspector refuses such\n * a transaction as `missing_client_signature` — a diagnosis, rather than the\n * opaque signature-verification failure a stale signature would produce.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { base58Decode, base58Encode } from '../../utils/base58.js';\nimport { fromBase64, toBase64 } from '../../utils/binary.js';\nimport type { Signer } from './payment-channel.js';\n\n/** Bytes in one Ed25519 signature slot. */\nconst SIGNATURE_LENGTH = 64;\n/** Bytes in a pubkey, a blockhash, and an Ed25519 seed alike. */\nconst PUBKEY_LENGTH = 32;\n/** An Ed25519 seed — the private half of a keypair, and all of it that is stored. */\nconst SEED_LENGTH = 32;\n/** A stored `seed ‖ pubkey` secret key, the spelling most Solana tooling writes. */\nconst SECRET_KEY_LENGTH = 64;\n/** High bit of a message's first byte: set ⇒ versioned, clear ⇒ legacy. */\nconst VERSION_PREFIX_MASK = 0x80;\n\n/**\n * A wire transaction, read but not rebuilt.\n *\n * Every field is a view onto {@link bytes}, which is the caller's transaction\n * verbatim. Nothing here is enough to re-serialize the message, deliberately.\n */\nexport interface SolanaWireTransaction {\n /** The whole wire transaction, unmodified. */\n bytes: Uint8Array;\n /** `'legacy'` for a message with no version prefix, else the version number. */\n version: 'legacy' | number;\n /**\n * The signature slots in COMPILED ORDER — index `i` is the key whose\n * signature belongs in slot `i`. This is the order the header fixed when the\n * message was compiled; within a role it is address-sorted rather than\n * semantic, so map a signer to a slot by ADDRESS, never by position.\n */\n signers: string[];\n /** Base58 addresses of the slots that are still 64 zero bytes. */\n unsigned: string[];\n /** Every static account key, in compiled order. `signers` is its head. */\n staticAccounts: string[];\n /** The blockhash the message currently commits to, base58. */\n recentBlockhash: string;\n /** Byte offset of the first signature slot. */\n signaturesOffset: number;\n /** Byte offset of the message — the bytes a signature covers. */\n messageOffset: number;\n /** Byte offset of the 32 blockhash bytes inside {@link bytes}. */\n recentBlockhashOffset: number;\n}\n\n/** A compact-u16 read: the value, and where the next field starts. */\nfunction readCompactU16(\n bytes: Uint8Array,\n offset: number\n): { value: number; offset: number } {\n let value = 0;\n for (let shift = 0; shift < 3; shift++) {\n const byte = bytes[offset + shift];\n if (byte === undefined) {\n throw new Error('malformed Solana transaction: truncated compact-u16');\n }\n value |= (byte & 0x7f) << (shift * 7);\n if ((byte & 0x80) === 0) return { value, offset: offset + shift + 1 };\n }\n throw new Error('malformed Solana transaction: compact-u16 exceeds three bytes');\n}\n\n/** Coerce the two spellings a wire transaction travels in to bytes. */\nfunction toWireBytes(wire: string | Uint8Array): Uint8Array {\n return typeof wire === 'string' ? fromBase64(wire) : wire;\n}\n\n/** Answer in whatever spelling the caller handed in. */\nfunction likeInput(wire: string | Uint8Array, bytes: Uint8Array): string | Uint8Array {\n return typeof wire === 'string' ? toBase64(bytes) : bytes;\n}\n\n/**\n * Read a base64 (or raw) wire transaction far enough to locate its signature\n * slots and its blockhash. Legacy and v0 messages both parse; the address-table\n * lookups a v0 message may carry sit AFTER everything this needs and are not\n * decoded.\n *\n * @throws {Error} when the bytes are not a transaction of the shape above —\n * truncated, or claiming a signature count the header does not agree with.\n */\nexport function parseSolanaWireTransaction(\n wire: string | Uint8Array\n): SolanaWireTransaction {\n const bytes = toWireBytes(wire);\n\n const count = readCompactU16(bytes, 0);\n const signaturesOffset = count.offset;\n const messageOffset = signaturesOffset + count.value * SIGNATURE_LENGTH;\n if (messageOffset > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots do not fit in ${bytes.length} bytes`\n );\n }\n\n const prefix = bytes[messageOffset];\n if (prefix === undefined) {\n throw new Error('malformed Solana transaction: no message after the signatures');\n }\n const versioned = (prefix & VERSION_PREFIX_MASK) !== 0;\n const version = versioned ? prefix & ~VERSION_PREFIX_MASK : 'legacy';\n const headerOffset = messageOffset + (versioned ? 1 : 0);\n\n const numRequiredSignatures = bytes[headerOffset];\n if (numRequiredSignatures === undefined) {\n throw new Error('malformed Solana transaction: truncated message header');\n }\n if (numRequiredSignatures !== count.value) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots but the header requires ${numRequiredSignatures}`\n );\n }\n\n const accountCount = readCompactU16(bytes, headerOffset + 3);\n const keysOffset = accountCount.offset;\n const recentBlockhashOffset = keysOffset + accountCount.value * PUBKEY_LENGTH;\n if (recentBlockhashOffset + PUBKEY_LENGTH > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${accountCount.value} account keys and a blockhash do not fit in ${bytes.length} bytes`\n );\n }\n if (numRequiredSignatures > accountCount.value) {\n throw new Error(\n `malformed Solana transaction: header requires ${numRequiredSignatures} signatures but the message names only ${accountCount.value} accounts`\n );\n }\n\n const staticAccounts: string[] = [];\n for (let i = 0; i < accountCount.value; i++) {\n const start = keysOffset + i * PUBKEY_LENGTH;\n staticAccounts.push(base58Encode(bytes.slice(start, start + PUBKEY_LENGTH)));\n }\n\n const signers = staticAccounts.slice(0, numRequiredSignatures);\n const unsigned = signers.filter((_signer, slot) => {\n const start = signaturesOffset + slot * SIGNATURE_LENGTH;\n return bytes\n .subarray(start, start + SIGNATURE_LENGTH)\n .every((byte) => byte === 0);\n });\n\n return {\n bytes,\n version,\n signers,\n unsigned,\n staticAccounts,\n recentBlockhash: base58Encode(\n bytes.slice(recentBlockhashOffset, recentBlockhashOffset + PUBKEY_LENGTH)\n ),\n signaturesOffset,\n messageOffset,\n recentBlockhashOffset,\n };\n}\n\n/**\n * Overwrite a compiled message's recent blockhash in place, and **clear every\n * signature slot**.\n *\n * The gas station quotes a blockhash of its own and then refuses any execute\n * whose transaction does not carry it (`blockhash_mismatch`), so a client that\n * has already been handed a draft has two ways to comply: ask the composer to\n * prepare the same transaction again against the quoted blockhash, or move the\n * 32 bytes itself. This is the second, and it makes step 5 of the ceremony\n * local — one round trip fewer inside a 60-second quote TTL.\n *\n * Clearing the signatures is not a side effect, it is the point. Those 32 bytes\n * are inside the message every signature covers, so a signature made before the\n * patch is now a signature over a message that no longer exists. Left in place\n * it would fail signature verification at the validator with nothing pointing at\n * the cause; zeroed, the slot means exactly what an unsigned slot means\n * everywhere else on this path, and the gas station names it\n * (`missing_client_signature`) before spending anything. **Sign after patching,\n * never before.**\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param recentBlockhash - Base58, exactly as the quote returned it.\n * @returns The patched transaction, in the spelling `wire` arrived in.\n * @throws {Error} when `recentBlockhash` is not 32 bytes of base58.\n */\nexport function patchSolanaRecentBlockhash(wire: string, recentBlockhash: string): string;\nexport function patchSolanaRecentBlockhash(\n wire: Uint8Array,\n recentBlockhash: string\n): Uint8Array;\nexport function patchSolanaRecentBlockhash(\n wire: string | Uint8Array,\n recentBlockhash: string\n): string | Uint8Array {\n const blockhash = base58Decode(recentBlockhash);\n if (blockhash.length !== PUBKEY_LENGTH) {\n throw new Error(\n `recentBlockhash must decode to ${PUBKEY_LENGTH} bytes, got ${blockhash.length} from ${JSON.stringify(recentBlockhash)}`\n );\n }\n\n const parsed = parseSolanaWireTransaction(wire);\n const patched = new Uint8Array(parsed.bytes);\n patched.set(blockhash, parsed.recentBlockhashOffset);\n patched.fill(\n 0,\n parsed.signaturesOffset,\n parsed.signaturesOffset + parsed.signers.length * SIGNATURE_LENGTH\n );\n\n return likeInput(wire, patched);\n}\n\n/**\n * Sign a supplied wire transaction in place: for each key in `signers` that the\n * compiled header names, write its Ed25519 signature over the message bytes\n * into that key's own slot. Slots belonging to nobody in `signers` — the fee\n * payer's, above all — are left exactly as they were.\n *\n * Slots are matched by ADDRESS. A receipt's `requiredSigners` is address-sorted\n * within a role and carries no semantics, so \"the mint is second\" is a fact\n * about one particular pair of keys and not about the transaction shape.\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param signers - Keypairs to sign with; each `privateKey` is a 32-byte seed.\n * @returns The signed transaction, in the spelling `wire` arrived in.\n * @throws {Error} when a supplied signer is not one of the message's required\n * signers — signing with a key the transaction never asked for means the\n * caller built or patched the wrong thing, and silently doing nothing would\n * surface much later as `missing_client_signature`.\n */\nexport function signSolanaWireTransaction(wire: string, signers: Signer[]): string;\nexport function signSolanaWireTransaction(\n wire: Uint8Array,\n signers: Signer[]\n): Uint8Array;\nexport function signSolanaWireTransaction(\n wire: string | Uint8Array,\n signers: Signer[]\n): string | Uint8Array {\n const parsed = parseSolanaWireTransaction(wire);\n const signed = new Uint8Array(parsed.bytes);\n const message = signed.subarray(parsed.messageOffset);\n\n for (const signer of signers) {\n const address = base58Encode(signer.publicKey);\n const slot = parsed.signers.indexOf(address);\n if (slot === -1) {\n throw new Error(\n `${address} is not a required signer of this transaction (slots: ${parsed.signers.join(', ')})`\n );\n }\n signed.set(\n ed25519.sign(message, signer.privateKey),\n parsed.signaturesOffset + slot * SIGNATURE_LENGTH\n );\n }\n\n return likeInput(wire, signed);\n}\n\n/**\n * A fresh Ed25519 keypair.\n *\n * The ANT spawn needs one per attempt: its public half goes to the store as the\n * MPL Core asset address — which becomes the ANT's address, and the `processId`\n * the follow-up name purchase wants — and its private half signs one slot of one\n * transaction. Nothing needs it afterwards, so it is generated, used, and\n * dropped rather than derived from the user's phrase, where it would be one more\n * key to keep and to lose.\n */\nexport function generateSolanaKeypair(): Signer & { address: string } {\n return keypairFromSeed(randomBytes(SEED_LENGTH));\n}\n\n/**\n * The keypair a stored or derived Solana secret represents — a 32-byte seed or\n * a 64-byte `seed ‖ pubkey` secret key, as bytes or base58.\n *\n * The public half is DERIVED, never read out of the trailing 32 bytes: a\n * 64-byte input whose tail disagrees with its own seed is a corrupt file, and\n * honouring it would fill a signature slot addressed to a key that did not sign\n * it. Mirrors the rule `ToonClient`'s own config applies to `solanaSecretKey`.\n */\nexport function solanaKeypair(\n key: string | Uint8Array\n): Signer & { address: string } {\n const bytes = typeof key === 'string' ? base58Decode(key.trim()) : key;\n if (bytes.length !== SEED_LENGTH && bytes.length !== SECRET_KEY_LENGTH) {\n throw new Error(\n `a Solana secret must be a ${SEED_LENGTH}-byte seed or a ${SECRET_KEY_LENGTH}-byte ` +\n `secret key; got ${bytes.length} bytes`\n );\n }\n return keypairFromSeed(bytes.slice(0, SEED_LENGTH));\n}\n\n/** The one place a seed becomes a keypair, so both entry points agree. */\nfunction keypairFromSeed(seed: Uint8Array): Signer & { address: string } {\n const publicKey = new Uint8Array(ed25519.getPublicKey(seed));\n return { privateKey: seed, publicKey, address: base58Encode(publicKey) };\n}\n","/**\n * The signed job event a NIP-90 app behind a connector reads.\n *\n * Some apps a connector fronts are not plain HTTP handlers: the store and the\n * gas station both take their input as a **kind-tagged Nostr event** whose\n * arguments are `['param', key, value]` tags, and answer in the FULFILL body.\n * There is no relay and no round trip — the event is the request body of the\n * paid POST, and the receipt comes back in that same response.\n *\n * The signature on the event is **integrity, not identity**. Both apps say so\n * in as many words: it proves the tags were not altered between this client and\n * the handler, and nothing else — who paid is the connector's `X-TOON-Payer`\n * header, proved against a claim, and no app takes an event pubkey for an\n * authority. So the key here is generated per event by default. A caller who\n * wants a stable pubkey in the app's logs can supply one; nothing about the\n * job's outcome depends on which key it is.\n *\n * This is why the 1.0 client carries no Nostr identity. There is no key to\n * derive, back up or rotate — only 32 bytes to sign one request with and then\n * forget.\n */\n\nimport { schnorr } from '@noble/curves/secp256k1.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { encodeUtf8, toHex } from '../utils/binary.js';\n\n/**\n * A signed Nostr event, in the field order and JSON spelling every verifier\n * expects.\n */\nexport interface JobEvent {\n /** 32-byte sha256 of the serialization below, hex. */\n id: string;\n /** The signing key's x-only public half, hex. */\n pubkey: string;\n /** Unix SECONDS. */\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n /** BIP-340 signature over `id`, hex. */\n sig: string;\n}\n\n/** What one job asks for: its kind, and its `param` tags. */\nexport interface JobEventParams {\n /** The NIP-90 job kind — `5095` for the ArNS job, `5096` for Solana gas. */\n kind: number;\n /**\n * The job's arguments, emitted in iteration order as `['param', key, value]`.\n * An `undefined` value is omitted rather than sent as the string\n * `\"undefined\"`, so an optional parameter can be passed through unset.\n */\n params: Record<string, string | undefined>;\n /** Extra tags to carry beside the params. Rarely needed. */\n tags?: string[][];\n /** Default `''`. Neither of this repository's job kinds reads it. */\n content?: string;\n /** 32-byte secp256k1 secret. Default: a fresh one, used once. */\n secretKey?: Uint8Array;\n /** Unix seconds. Default `Date.now() / 1000`, floored. */\n createdAt?: number;\n}\n\n/**\n * NIP-01 serialization: a six-element array, `JSON.stringify`d exactly as\n * written. The verifier recomputes this from the event's own fields, so any\n * difference in shape — a reordered key, a number where a string belongs —\n * surfaces as an id mismatch rather than as a validation message.\n */\nfunction serializeForId(event: Omit<JobEvent, 'id' | 'sig'>): string {\n return JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n}\n\n/**\n * Build and sign one job event.\n *\n * @returns The event, ready to be the `{ event }` body of a paid POST.\n */\nexport function buildJobEvent(params: JobEventParams): JobEvent {\n const secretKey = params.secretKey ?? randomBytes(32);\n const pubkey = toHex(new Uint8Array(schnorr.getPublicKey(secretKey)));\n\n const tags: string[][] = [];\n for (const [key, value] of Object.entries(params.params)) {\n if (value !== undefined) tags.push(['param', key, value]);\n }\n if (params.tags) tags.push(...params.tags);\n\n const unsigned = {\n pubkey,\n created_at: params.createdAt ?? Math.floor(Date.now() / 1000),\n kind: params.kind,\n tags,\n content: params.content ?? '',\n };\n\n const idBytes = sha256(encodeUtf8(serializeForId(unsigned)));\n return {\n ...unsigned,\n id: toHex(idBytes),\n sig: toHex(new Uint8Array(schnorr.sign(idBytes, secretKey))),\n };\n}\n\n/** First value of a `['param', key, value]` tag, if the event carries one. */\nexport function jobEventParam(event: JobEvent, key: string): string | undefined {\n for (const tag of event.tags) {\n if (tag[0] === 'param' && tag[1] === key) return tag[2];\n }\n return undefined;\n}\n","/**\n * Putting a {@link JobEvent} through a connector, and reading what came back.\n *\n * A job is an ordinary paid request — `POST` the event to the route, get the\n * app's HTTP response — so this adds no wire of its own. What it adds is the\n * one decoding rule both NIP-90 apps in this protocol share, and a single\n * vocabulary for the three quite different ways a job can fail to produce a\n * receipt:\n *\n * - **the packet was refused** — a price, a route or a seal was wrong, and the\n * app was never reached. `send()` returns this rather than throwing, and so\n * does {@link sendJob};\n * - **the app rejected the event** — a missing param, an unregistered kind.\n * It rides home on a FULFILL with `accept: false`, so it cost what a receipt\n * would have cost;\n * - **the app answered, and the answer is a refusal.** A gas station that\n * declines to spend has done its job: `accept: true`, a receipt, and\n * `status: 'failed'` inside it. That is NOT this module's business — it is a\n * successful job, and the caller branches on the receipt's own `reason`.\n *\n * The decoding rule: a receipt is `base64(JSON)` in `data`, and both apps ALSO\n * decode it into `result` for readability. `data` is the byte-faithful one and\n * is preferred here; `result` is the fallback, so a future app that emits only\n * one of the two still works.\n */\n\nimport { fromBase64, decodeUtf8 } from '../utils/binary.js';\nimport type { SendRefused, SendRequest, SendResult, SendOptions } from '../client/types.js';\nimport type { JobEvent } from './job-event.js';\n\n/**\n * The part of a client a job needs: the ability to pay for one HTTP request.\n * `ToonClient` satisfies it, and so does any stand-in a test supplies.\n */\nexport interface JobSender {\n send(\n destination: string,\n request?: SendRequest,\n options?: SendOptions\n ): Promise<SendResult>;\n}\n\n/**\n * Where a job goes: who pays for it, which route terminates it, and — on a\n * FORWARDED route — whose key the payload is sealed to.\n *\n * The store and the gas station are different nodes with different connectors\n * and different channels, so a ceremony spanning both takes two endpoints. One\n * client can serve both only when it is attached to a node that forwards to\n * each, in which case both endpoints name that client and `sealTo` names the\n * far node — see `docs/devnet.md`.\n */\nexport interface JobEndpoint {\n /** Pays for the request. */\n client: JobSender;\n /** The ILP address of the route that terminates at the app. */\n destination: string;\n /** The terminating connector, when `destination` is forwarded. */\n sealTo?: string | Uint8Array;\n /** Per-packet timeout, in milliseconds. */\n timeoutMs?: number;\n}\n\n/**\n * What a job produced: a decoded receipt, or the reason there is none.\n *\n * `accepted: false` never means \"the app said no to what you asked\" — that is a\n * receipt. It means the receipt does not exist: the packet was refused, or the\n * app rejected the event before running it.\n */\nexport type JobAnswer<T> =\n | { accepted: true; receipt: T }\n | {\n accepted: false;\n /** An ILP reject code for a refusal, or the app's own `F00` / `T00`. */\n code: string;\n message: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n };\n\n/** The `{ accept, data, result, code, message }` envelope both apps answer in. */\ninterface JobEnvelope {\n accept?: boolean;\n data?: string;\n result?: unknown;\n /**\n * The store's answer when its `data` is NOT JSON — kind:5094 returns a bare\n * Arweave transaction id, and the backend surfaces it here rather than under\n * `result`. A documented contract, not a quirk.\n */\n txId?: unknown;\n code?: string;\n message?: string;\n}\n\n/**\n * Pay for one job and decode its receipt.\n *\n * The receipt type is the caller's assertion, not a checked fact: these apps\n * publish their receipt shapes and this client mirrors them, but nothing on the\n * wire enforces the match, so a caller reading a field it needs should still\n * check it is there.\n */\nexport async function sendJob<T>(\n endpoint: JobEndpoint,\n event: JobEvent\n): Promise<JobAnswer<T>> {\n const answer = await endpoint.client.send(\n endpoint.destination,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: { event },\n },\n {\n ...(endpoint.sealTo !== undefined ? { sealTo: endpoint.sealTo } : {}),\n ...(endpoint.timeoutMs !== undefined ? { timeoutMs: endpoint.timeoutMs } : {}),\n }\n );\n\n if (!answer.fulfilled) {\n return {\n accepted: false,\n code: answer.code,\n message: `kind:${event.kind} refused by ${answer.refusedBy}: ${answer.message}`,\n refusal: answer,\n };\n }\n\n let envelope: JobEnvelope;\n try {\n envelope = answer.json<JobEnvelope>();\n } catch {\n return {\n accepted: false,\n code: 'F00',\n message:\n `kind:${event.kind} answered ${answer.status} with a body that is not JSON: ` +\n truncate(decodeUtf8(answer.body)),\n };\n }\n\n if (envelope.accept !== true) {\n return {\n accepted: false,\n code: envelope.code ?? String(answer.status),\n message: envelope.message ?? `kind:${event.kind} was not accepted`,\n };\n }\n\n const receipt = decodeReceipt<T>(envelope);\n if (receipt === undefined) {\n return {\n accepted: false,\n code: 'F00',\n message: `kind:${event.kind} was accepted but carried no receipt`,\n };\n }\n return { accepted: true, receipt };\n}\n\n/**\n * `data` (byte-faithful) if it decodes as JSON; otherwise whichever field the\n * app said its answer in.\n *\n * The store decides between two of those by whether its base64 `data` parses\n * as a JSON object: a receipt goes to `result`, and anything else goes to\n * `txId`. kind:5094 takes the second branch — its whole answer is one Arweave\n * transaction id — so a client that reads only `result` calls a successful\n * upload \"accepted but carried no receipt\".\n */\nfunction decodeReceipt<T>(envelope: JobEnvelope): T | undefined {\n if (typeof envelope.data === 'string') {\n try {\n return JSON.parse(decodeUtf8(fromBase64(envelope.data))) as T;\n } catch {\n // Fall through: an app that base64'd something that is not JSON has still\n // said what it meant in `result` or `txId`.\n }\n }\n if (envelope.result !== null && typeof envelope.result === 'object') {\n return envelope.result as T;\n }\n // A bare id is still a receipt. Wrapped, so the caller reads `receipt.txId`\n // the same way every other job's fields are read.\n if (typeof envelope.txId === 'string' && envelope.txId.length > 0) {\n return { txId: envelope.txId } as T;\n }\n return undefined;\n}\n\nfunction truncate(text: string): string {\n return text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n","/**\n * The receipts the store and the gas station answer with.\n *\n * These MIRROR the two app repositories — `toon-protocol/store`'s\n * `ArnsAntPrepareReceipt` / `ArnsBuyReceipt` and `toon-protocol/gas-station`'s\n * `GasStationReceipt` — and mirror them by hand, because this package has no\n * TOON-protocol runtime dependencies. That makes them a claim about a remote\n * contract rather than a shared type, so every integer that could exceed 2^53\n * is a `string` here exactly as it is on the wire: reading one as a `number`\n * would be this client inventing precision the app never sent.\n *\n * A field this client does not read is still declared, so that a receipt logged\n * or forwarded whole keeps its shape.\n */\n\n/** Which cluster's ar.io deployment a kind:5095 job targets. */\nexport type ArnsNetwork = 'mainnet' | 'devnet';\n\n/** A name registration kind: a time-boxed lease, or a one-time permabuy. */\nexport type ArnsNameType = 'lease' | 'permabuy';\n\n/** Which Solana cluster the gas station pays on. */\nexport type SolanaNetwork = 'mainnet' | 'devnet';\n\n/**\n * kind:5095 `op=prepare` — the unsigned ANT-spawn transaction.\n *\n * `requiredSigners` is the compiled slot order and is **address-sorted within a\n * role**, so it says who signs, never what each one is for. Map a keypair to a\n * slot by address. The fee payer is always slot 0 and is the one slot a client\n * leaves alone.\n */\nexport interface ArnsAntPrepareReceipt {\n job: 'arns-buy';\n op: 'prepare';\n network: ArnsNetwork;\n /** The ANT's MPL Core asset pubkey — the `processId` for `op=buy`. */\n processId: string;\n /** The same key, named for the keypair the client signs with. */\n mint: string;\n owner: string;\n feePayer: string;\n name: string;\n antProgramId: string;\n /** Base64 v0 wire transaction, every signature slot zero-filled. */\n transaction: string;\n recentBlockhash: string;\n /** True ⇒ built on a placeholder blockhash: quote with it, never execute it. */\n draft: boolean;\n requiredSigners: string[];\n /** The subset the client must fill before the gas station will look at it. */\n clientSigners: string[];\n rentTransferLamports: string;\n estimatedFeePayerLamports: string;\n instructions: string[];\n}\n\n/** kind:5095 `op=buy` — the name is registered to the ANT. */\nexport interface ArnsBuyReceipt {\n job: 'arns-buy';\n network: ArnsNetwork;\n name: string;\n type: ArnsNameType;\n years: number | null;\n processId: string;\n quotedMario: string;\n registryTxId: string;\n syncAttributesTxId: string | null;\n}\n\n/**\n * Why a gas station declined, from its own closed vocabulary. The ones a client\n * driving this ceremony can act on:\n *\n * - `float_exhausted` — the node is out of gas money; nothing to retry.\n * - `dvm_key_misplaced` — the gas wallet appears where it may not. Almost\n * always a transaction built wrong.\n * - `quote_expired`, `blockhash_expired`, `blockhash_mismatch` — re-quote,\n * re-patch, re-sign.\n * - `missing_client_signature` — a slot is still zero: sign AFTER patching.\n * - `confirmation_timeout` — broadcast but not confirmed. It may still land;\n * retry with the **same** `idempotencyKey`.\n */\nexport type GasStationFailureReason =\n | 'malformed_transaction'\n | 'fee_payer_mismatch'\n | 'dvm_key_misplaced'\n | 'program_not_whitelisted'\n | 'priority_fee_exceeded'\n | 'channel_op_not_permitted'\n | 'missing_client_signature'\n | 'unknown_quote'\n | 'quote_expired'\n | 'blockhash_mismatch'\n | 'blockhash_expired'\n | 'simulation_failed'\n | 'delta_cap_exceeded'\n | 'float_exhausted'\n | 'quote_refused'\n | 'confirmation_timeout'\n | 'broadcast_failed';\n\n/** kind:5096 `phase=quote` — what this node will do, and what it will cost. */\nexport interface GasStationQuoteReceipt {\n job: 'gas-station';\n phase: 'quote';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n /** The address the transaction must name as its fee payer. */\n feePayer: string;\n maxLamports: string;\n /** The blockhash the executed transaction must carry. */\n recentBlockhash: string;\n /** ms epoch — quote TTL and blockhash validity, merged into one deadline. */\n expiresAt: number;\n}\n\n/** kind:5096 `phase=execute` — co-signed, broadcast, confirmed. */\nexport interface GasStationExecuteReceipt {\n job: 'gas-station';\n phase: 'execute';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n idempotencyKey: string;\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n /** True when this result was replayed from the idempotency store. */\n replayed?: boolean;\n}\n\n/**\n * The gate said no — and said so as an accepted job, because it was asked a\n * question and applied its rules. Branch on {@link reason}, never on `detail`.\n */\nexport interface GasStationFailureReceipt {\n job: 'gas-station';\n phase: 'quote' | 'execute';\n status: 'failed';\n network: SolanaNetwork;\n reason: GasStationFailureReason;\n detail: string;\n}\n\nexport type GasStationReceipt =\n | GasStationQuoteReceipt\n | GasStationExecuteReceipt\n | GasStationFailureReceipt;\n\n/** True when a gas-station receipt is the gate declining. */\nexport function isGasStationFailure(\n receipt: GasStationReceipt\n): receipt is GasStationFailureReceipt {\n return receipt.status === 'failed';\n}\n","/**\n * Buying an ArNS name while holding nothing but ILP credit.\n *\n * `kind:5095 op=buy` needs a `processId` — the MPL Core asset pubkey of an ANT\n * the caller already owns. Spawning one costs ~0.012 SOL of rent, and a TOON\n * client holds stablecoin credit on a payment channel, not SOL. So the work is\n * split across the three parties, and no single one has to be able to do all of\n * it:\n *\n * - the **store** composes the transaction (it is the only party with `@ar.io/sdk`)\n * - the **client** signs it (it is the only party that may own the ANT)\n * - the **gas station** pays for it and broadcasts it (it is the only party with SOL)\n *\n * The ceremony {@link spawnAnt} drives:\n *\n * ```text\n * 1. → gas kind:5096 quote, no draft → feePayer\n * 2. → store kind:5095 op=prepare → unsigned draft transaction\n * 3. sign the mint and owner slots\n * 4. → gas kind:5096 quote, with draft → quoteId, recentBlockhash, maxLamports\n * 5. patch the blockhash, sign again\n * 6. → gas kind:5096 execute → co-signed, broadcast, signature\n * ```\n *\n * Two quotes and two signings, because the gas station prices the job from a\n * SIGNED draft (that is what makes the free quote a full policy dry run) and\n * then requires the executed transaction to carry the blockhash **it** chose.\n * Everything from step 4 on runs inside one merged quote/blockhash deadline —\n * 60 seconds by default — which is why step 5 patches the 32 bytes locally\n * instead of paying for a second `op=prepare` round trip. Pass `reprepare` to\n * take that round trip anyway; the store returns a byte-identical transaction\n * but for those 32 bytes, so both routes end in the same place.\n *\n * Then {@link buyArnsName} spends the ANT: `kind:5095 op=buy` with the spawned\n * `processId`. {@link buyArnsNameWithNewAnt} is the two in order.\n *\n * **The spawned ANT is not ACL-bootstrapped.** That is ~61.4M lamports against\n * the gas station's 20M per-job ceiling, and its instructions would put the fee\n * payer in an ar.io slot, which the inspector refuses outright. The ANT resolves\n * fine; it just will not appear in \"ANTs I own\" registry lookups until the owner\n * bootstraps it later with its own SOL — and that registry is an\n * eventually-consistent secondary index, not truth.\n *\n * **Nothing here throws.** A packet the connector would not carry, an event the\n * app rejected, a gate that declined to spend and a receipt this client will not\n * sign are all outcomes — `{ spawned: false, step, reason, detail }`. By the\n * time any of them is read a packet has already been paid for, which is exactly\n * the case CLAUDE.md's rule covers: a refusal is returned, never thrown.\n *\n * `reason` is the gas station's own closed vocabulary wherever the verdict is\n * one the gas station would give — including the two checks this client makes\n * locally, which exist only to reach that verdict before paying for it.\n */\n\nimport {\n generateSolanaKeypair,\n parseSolanaWireTransaction,\n patchSolanaRecentBlockhash,\n signSolanaWireTransaction,\n} from '../channel/solana/wire-transaction.js';\nimport type { Signer } from '../channel/solana/payment-channel.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { buildJobEvent } from './job-event.js';\nimport { sendJob, type JobAnswer, type JobEndpoint } from './send-job.js';\nimport type {\n ArnsAntPrepareReceipt,\n ArnsBuyReceipt,\n ArnsNameType,\n GasStationExecuteReceipt,\n GasStationQuoteReceipt,\n GasStationReceipt,\n} from './receipts.js';\nimport type { SendRefused } from '../client/types.js';\n\n/** The NIP-90 job kind for the ArNS job — both of its ops. */\nexport const ARNS_KIND = 5095;\n/** The NIP-90 job kind for the Solana gas station — both of its phases. */\nexport const SOLANA_GAS_KIND = 5096;\n\n/** Which step of the ceremony an outcome stopped at. */\nexport type AntSpawnStep =\n | 'fee-payer-quote'\n | 'prepare'\n | 'quote'\n | 'reprepare'\n | 'sign'\n | 'execute';\n\nexport interface AntSpawnParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** Where the kind:5096 job goes — the gas station. */\n gas: JobEndpoint;\n /**\n * The keypair that will own the ANT. Its address goes to the store as\n * `owner`, and it signs the owner slot — which is also the account the fee\n * payer transfers the ANT state PDAs' rent to, in the same transaction.\n */\n owner: Signer;\n /** The ANT's display name: 1–51 lowercase alphanumerics and hyphens. */\n name: string;\n /** Arweave tx id the root `@` record points at. Default: the store's own. */\n target?: string;\n /** ANT ticker, 1–16 chars. Default: the ar.io program's own. */\n ticker?: string;\n /**\n * Override the ephemeral mint keypair. Supply one only to make a run\n * reproducible — its public half becomes the ANT's permanent address, and\n * nothing needs its private half once the spawn confirms.\n */\n mint?: Signer;\n /**\n * The gas station's execute-phase idempotency key. Default: a fresh UUID —\n * and it must be one, because that idempotency store is global and unscoped,\n * so a guessable key is somebody else's receipt.\n *\n * Reuse the SAME key to retry a `confirmation_timeout`. Both outcomes report\n * the key that was used, so a generated one is recoverable rather than lost\n * with the run that made it.\n */\n idempotencyKey?: string;\n /**\n * Ask the store to re-prepare against the quoted blockhash instead of\n * patching those 32 bytes locally. One more paid round trip inside the quote\n * TTL, for a transaction composed entirely by the party that composes it.\n */\n reprepare?: boolean;\n}\n\n/** The ANT exists on chain, and the client owns it. */\nexport interface AntSpawned {\n spawned: true;\n /** The ANT's MPL Core asset pubkey — hand this to {@link buyArnsName}. */\n processId: string;\n /** The same key, named for the keypair that signed the mint slot. */\n mint: string;\n owner: string;\n feePayer: string;\n quoteId: string;\n /** The confirmed transaction signature. */\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n recentBlockhash: string;\n /** True when the gas station replayed a receipt for this idempotency key. */\n replayed: boolean;\n /** The key used, so a `confirmation_timeout` can be retried with it. */\n idempotencyKey: string;\n /** The executed transaction, base64 — every slot filled but the fee payer's. */\n transaction: string;\n}\n\n/** Somebody said no, and said why. */\nexport interface AntSpawnRefused {\n spawned: false;\n step: AntSpawnStep;\n /**\n * The gas station's machine-readable reason where it was the gate that\n * declined, an ILP reject code where the packet was refused, or the app's own\n * `F00` / `T00` where the event was rejected. Branch on this, not on\n * {@link detail}.\n *\n * A check this client made locally answers in the gas station's OWN\n * vocabulary — `fee_payer_mismatch`, `blockhash_mismatch`,\n * `missing_client_signature` — because it is the same verdict on the same\n * bytes, reached before paying for it rather than after.\n */\n reason: string;\n detail: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n /** The ANT's address. It exists only if the spawn confirmed. */\n mint: string;\n /**\n * The key the execute carried, or would have. Together with {@link quoteId}\n * and {@link transaction} it is everything needed to re-send that execute —\n * which is the documented recovery from a `confirmation_timeout`, where the\n * transaction is broadcast and may yet land.\n */\n idempotencyKey: string;\n /** The quote the execute was made against, once there was one. */\n quoteId?: string;\n /** The bytes sent to the gas station, when the execute is what failed. */\n transaction?: string;\n}\n\nexport type AntSpawnOutcome = AntSpawned | AntSpawnRefused;\n\n/**\n * Spawn an ANT the caller owns, paid for by a gas station and composed by a\n * store. Steps 1–6 above.\n */\nexport async function spawnAnt(params: AntSpawnParams): Promise<AntSpawnOutcome> {\n const owner = base58Encode(params.owner.publicKey);\n const mintKeypair = params.mint ?? generateSolanaKeypair();\n const mint = base58Encode(mintKeypair.publicKey);\n const idempotencyKey = params.idempotencyKey ?? crypto.randomUUID();\n const held = new Map<string, Signer>([\n [mint, mintKeypair],\n [owner, params.owner],\n ]);\n\n /** Every refusal carries the same three facts about the run that produced it. */\n const stop = (\n step: AntSpawnStep,\n refused: PartialRefusal\n ): AntSpawnRefused => ({ ...refused, step, mint, idempotencyKey });\n\n // ── 1. What address must the transaction name as its fee payer? ───────────\n // A quote with no draft is the cheapest way to ask: it prices nothing and\n // returns the gas wallet, which the store needs before it can compose.\n const feePayerQuote = await quote(params.gas, undefined);\n if (!feePayerQuote.ok) return stop('fee-payer-quote', feePayerQuote.refused);\n const feePayer = feePayerQuote.receipt.feePayer;\n\n // ── 2. Compose. No blockhash yet: a draft exists only to be priced. ───────\n const drafted = await prepare(params, { mint, owner, feePayer });\n if (!drafted.ok) return stop('prepare', drafted.refused);\n const draft = drafted.receipt;\n\n const drafters = signersFor(draft, held, { mint, feePayer });\n if (!drafters.ok) return stop('prepare', drafters.refused);\n\n // ── 3. Sign the slots the store said are ours. ────────────────────────────\n const signedDraft = signSolanaWireTransaction(draft.transaction, drafters.receipt);\n\n // ── 4. Quote the SIGNED draft: a full policy dry run, for free. ───────────\n const priced = await quote(params.gas, signedDraft);\n if (!priced.ok) return stop('quote', priced.refused);\n const { quoteId, recentBlockhash } = priced.receipt;\n\n // ── 5. Carry the quoted blockhash, then sign again — in that order. ───────\n // Signing first would be signing a message about to change underneath the\n // signature, so both routes end with the signing, never with the blockhash.\n let unsigned: string;\n let signers = drafters.receipt;\n if (params.reprepare === true) {\n const reprepared = await prepare(params, { mint, owner, feePayer }, recentBlockhash);\n if (!reprepared.ok) return stop('reprepare', { ...reprepared.refused, quoteId });\n const resigners = signersFor(reprepared.receipt, held, { mint, feePayer });\n if (!resigners.ok) return stop('reprepare', { ...resigners.refused, quoteId });\n unsigned = reprepared.receipt.transaction;\n signers = resigners.receipt;\n } else {\n unsigned = patchSolanaRecentBlockhash(draft.transaction, recentBlockhash);\n }\n const executable = signSolanaWireTransaction(unsigned, signers);\n\n const unexecutable = checkExecutable(executable, { feePayer, recentBlockhash });\n if (unexecutable) return stop('sign', { ...unexecutable, quoteId, transaction: executable });\n\n // ── 6. Pay, co-sign, broadcast. ───────────────────────────────────────────\n const executed = await sendJob<GasStationReceipt>(\n params.gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: {\n phase: 'execute',\n transaction: executable,\n quoteId,\n idempotencyKey,\n },\n })\n );\n const settled = readGasStation<GasStationExecuteReceipt>(executed, 'execute');\n if (!settled.ok) {\n return stop('execute', { ...settled.refused, quoteId, transaction: executable });\n }\n\n return {\n spawned: true,\n processId: draft.processId,\n mint,\n owner,\n feePayer,\n quoteId,\n signature: settled.receipt.signature,\n slot: settled.receipt.slot,\n feeLamportsActual: settled.receipt.feeLamportsActual,\n recentBlockhash,\n replayed: settled.receipt.replayed === true,\n idempotencyKey,\n transaction: executable,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Buying the name\n// ---------------------------------------------------------------------------\n\nexport interface ArnsBuyParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** The ArNS name to register. */\n name: string;\n /** The ANT that will hold it — {@link AntSpawned.processId}. */\n processId: string;\n /** Default `'lease'`. */\n type?: ArnsNameType;\n /** Lease length, 1–5. Invalid for a permabuy. */\n years?: number;\n /** The store's own replay key for the buy. Defaults to the event id. */\n idempotencyKey?: string;\n}\n\nexport type ArnsBuyOutcome =\n | { bought: true; receipt: ArnsBuyReceipt }\n | { bought: false; reason: string; detail: string; refusal?: SendRefused };\n\n/**\n * Register an ArNS name to an ANT the caller already owns — `kind:5095 op=buy`.\n * The store's own ARIO float pays the registry; this client pays the store.\n */\nexport async function buyArnsName(params: ArnsBuyParams): Promise<ArnsBuyOutcome> {\n const answer = await sendJob<ArnsBuyReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'buy',\n name: params.name,\n processId: params.processId,\n type: params.type ?? 'lease',\n years:\n (params.type ?? 'lease') === 'lease' && params.years !== undefined\n ? String(params.years)\n : undefined,\n idempotencyKey: params.idempotencyKey,\n },\n })\n );\n if (!answer.accepted) {\n return {\n bought: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n }\n return { bought: true, receipt: answer.receipt };\n}\n\n/** Both halves: spawn an ANT, then register the name to it. */\nexport type ArnsNameWithAntOutcome =\n | { bought: true; ant: AntSpawned; receipt: ArnsBuyReceipt }\n | { bought: false; ant?: AntSpawned; step: AntSpawnStep | 'buy'; reason: string; detail: string };\n\n/**\n * The whole thing: spawn an ANT and register `name` to it.\n *\n * The two halves are separately re-runnable on purpose. If the buy fails after\n * the spawn confirmed, the ANT is still yours — call {@link buyArnsName} with\n * the `processId` in `ant` rather than spawning a second one.\n */\nexport async function buyArnsNameWithNewAnt(\n params: AntSpawnParams & Pick<ArnsBuyParams, 'type' | 'years'>\n): Promise<ArnsNameWithAntOutcome> {\n const ant = await spawnAnt(params);\n if (!ant.spawned) {\n return { bought: false, step: ant.step, reason: ant.reason, detail: ant.detail };\n }\n const bought = await buyArnsName({\n store: params.store,\n name: params.name,\n processId: ant.processId,\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.years !== undefined ? { years: params.years } : {}),\n });\n if (!bought.bought) {\n return { bought: false, ant, step: 'buy', reason: bought.reason, detail: bought.detail };\n }\n return { bought: true, ant, receipt: bought.receipt };\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\n/**\n * A refusal as a step knows it — before the facts about the run as a whole\n * (which step, which mint, which idempotency key) are stamped on by `stop`.\n */\ntype PartialRefusal = Omit<AntSpawnRefused, 'step' | 'mint' | 'idempotencyKey'>;\n\n/** A step's result: its receipt, or the refusal to hand back to the caller. */\ntype Step<T> =\n | { ok: true; receipt: T }\n | { ok: false; refused: PartialRefusal };\n\nasync function quote(\n gas: JobEndpoint,\n draft: string | undefined\n): Promise<Step<GasStationQuoteReceipt>> {\n const answer = await sendJob<GasStationReceipt>(\n gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: { phase: 'quote', transaction: draft },\n })\n );\n return readGasStation<GasStationQuoteReceipt>(answer, 'quote');\n}\n\nasync function prepare(\n params: AntSpawnParams,\n keys: { mint: string; owner: string; feePayer: string },\n recentBlockhash?: string\n): Promise<Step<ArnsAntPrepareReceipt>> {\n const answer = await sendJob<ArnsAntPrepareReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'prepare',\n name: params.name,\n owner: keys.owner,\n mint: keys.mint,\n feePayer: keys.feePayer,\n recentBlockhash,\n target: params.target,\n ticker: params.ticker,\n },\n })\n );\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n return { ok: true, receipt: answer.receipt };\n}\n\n/**\n * Read a gas-station answer. A receipt with `status: 'failed'` is the gate\n * declining — an accepted job, and the one case where {@link AntSpawnRefused}'s\n * `reason` carries the vocabulary a caller can branch on.\n */\nfunction readGasStation<T extends GasStationReceipt>(\n answer: JobAnswer<GasStationReceipt>,\n phase: 'quote' | 'execute'\n): Step<T> {\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n const receipt = answer.receipt;\n if (receipt.status === 'failed') {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: receipt.reason,\n detail: receipt.detail,\n },\n };\n }\n if (receipt.phase !== phase) {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: 'malformed_receipt',\n detail: `asked the gas station for a ${phase} and it answered with a ${receipt.phase}`,\n },\n };\n }\n return { ok: true, receipt: receipt as T };\n}\n\n/**\n * The store named the signers; resolve them to the keys we hold, BY ADDRESS.\n *\n * `clientSigners` is the subset of the compiled slots that are ours to fill, and\n * `requiredSigners` is address-sorted within a role — so a positional read of\n * either is wrong for exactly the pairs of keys that happen to sort the other\n * way, which is the kind of bug that passes every test but one run in ten.\n * Signing what the receipt NAMES, rather than what this function assumes, is\n * also the only thing that stays right if a future store composes a transaction\n * where the owner is not among the client's slots.\n *\n * A receipt this client cannot honour is a REFUSAL, not an exception: two\n * packets have already been paid for by the time it is read, and a client that\n * threw here would be throwing after the packet went out.\n */\nfunction signersFor(\n receipt: ArnsAntPrepareReceipt,\n held: Map<string, Signer>,\n expected: { mint: string; feePayer: string }\n): Step<Signer[]> {\n const unheld = receipt.clientSigners.filter((signer) => !held.has(signer));\n if (unheld.length > 0) {\n return malformed(\n `the prepared transaction needs signatures this client does not hold: ${unheld.join(', ')} ` +\n `(holding ${[...held.keys()].join(' and ')})`\n );\n }\n if (receipt.feePayer !== expected.feePayer) {\n return malformed(\n `the prepared transaction names ${receipt.feePayer} as fee payer, not the quoted ${expected.feePayer}`\n );\n }\n // The mint's public half IS the ANT's address, so a `processId` that is not\n // it would send the follow-up name purchase at somebody else's asset.\n if (receipt.processId !== expected.mint) {\n return malformed(\n `the prepared transaction spawns ${receipt.processId}, not the mint ${expected.mint} it was given`\n );\n }\n const signers: Signer[] = [];\n for (const address of receipt.clientSigners) {\n const signer = held.get(address);\n if (signer !== undefined) signers.push(signer);\n }\n return { ok: true, receipt: signers };\n}\n\n/**\n * The local half of what the gas station is about to check: the fee payer is\n * slot 0, the blockhash is the quoted one, and every other slot is filled.\n *\n * Advisory only — the gas station's inspector is the authority and runs again\n * on the same bytes. This exists so that its verdict arrives for free instead of\n * for the price of an execute, which is why it answers in that inspector's own\n * vocabulary rather than inventing a second one.\n *\n * @returns The refusal, or `undefined` when the transaction is executable.\n */\nfunction checkExecutable(\n wireBase64: string,\n expected: { feePayer: string; recentBlockhash: string }\n): PartialRefusal | undefined {\n const parsed = parseSolanaWireTransaction(wireBase64);\n if (parsed.signers[0] !== expected.feePayer) {\n return {\n spawned: false,\n reason: 'fee_payer_mismatch',\n detail: `slot 0 is ${parsed.signers[0] ?? '(none)'}, not the quoted fee payer ${expected.feePayer}`,\n };\n }\n if (parsed.recentBlockhash !== expected.recentBlockhash) {\n return {\n spawned: false,\n reason: 'blockhash_mismatch',\n detail: `the transaction carries blockhash ${parsed.recentBlockhash}, not the quoted ${expected.recentBlockhash}`,\n };\n }\n const missing = parsed.unsigned.filter((signer) => signer !== expected.feePayer);\n if (missing.length > 0) {\n return {\n spawned: false,\n reason: 'missing_client_signature',\n detail: `these slots are still unsigned: ${missing.join(', ')}`,\n };\n }\n return undefined;\n}\n\n/** A job that produced no receipt, as the refusal to hand back to the caller. */\nfunction refusalOf(\n answer: Extract<JobAnswer<unknown>, { accepted: false }>\n): PartialRefusal {\n return {\n spawned: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n}\n\n/** The store composed something this client will not sign. */\nfunction malformed(detail: string): { ok: false; refused: PartialRefusal } {\n return { ok: false, refused: { spawned: false, reason: 'malformed_receipt', detail } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAM5B,IAAM,mBAAmB;AAEzB,IAAM,gBAAgB;AAEtB,IAAM,cAAc;AAEpB,IAAM,oBAAoB;AAE1B,IAAM,sBAAsB;AAmC5B,SAAS,eACP,OACA,QACmC;AACnC,MAAI,QAAQ;AACZ,WAAS,QAAQ,GAAG,QAAQ,GAAG,SAAS;AACtC,UAAM,OAAO,MAAM,SAAS,KAAK;AACjC,QAAI,SAAS,QAAW;AACtB,YAAM,IAAI,MAAM,qDAAqD;AAAA,IACvE;AACA,cAAU,OAAO,QAAU,QAAQ;AACnC,SAAK,OAAO,SAAU,EAAG,QAAO,EAAE,OAAO,QAAQ,SAAS,QAAQ,EAAE;AAAA,EACtE;AACA,QAAM,IAAI,MAAM,+DAA+D;AACjF;AAGA,SAAS,YAAY,MAAuC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,CAAC,WAAW,WAAW,SAAS,QAAQ;AAC/E,MAAI,QAAQ,SAAS,GAAG;AACtB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,mCAAmC,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,UACP,QACgB;AAChB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ,OAAO;AAAA,IACf,QAAQ,OAAO;AAAA,IACf,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;AAAA,EACtD;AACF;AAGA,SAAS,UAAU,QAAwD;AACzE,SAAO,EAAE,IAAI,OAAO,SAAS,EAAE,SAAS,OAAO,QAAQ,qBAAqB,OAAO,EAAE;AACvF;","names":["randomBytes","randomBytes"]}
1
+ {"version":3,"sources":["../src/channel/solana/wire-transaction.ts","../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\n * Solana wire transactions this client did NOT build.\n *\n * {@link import('./payment-channel.js').buildAndSendTransaction} composes a\n * transaction from instructions and signs every slot it created. This module is\n * the other half: somebody else compiled the message, and the client's only job\n * is to fill in the signature slots that are its own — and, when a fee payer\n * hands back a blockhash of its choosing, to move those 32 bytes without\n * touching anything else.\n *\n * That is the shape of a brokered transaction. In the ANT spawn the store\n * composes (it is the only party with `@ar.io/sdk`), the client signs (it is\n * the only party that may own the ANT), and the gas station pays and broadcasts\n * (it is the only party with SOL). None of the three can do the other two's\n * work, and the transaction travels between them as base64 wire bytes.\n *\n * **NEVER RECOMPILE.** The signature slots are in the compiled header's account\n * order, and the message bytes are what every signature covers, so rebuilding\n * the message from a decoded view — even into something byte-identical by\n * intent — is how a transaction arrives with signatures over a message that no\n * longer exists. Everything here is an in-place overwrite at a computed offset,\n * and {@link parseSolanaWireTransaction} exists to compute those offsets, not to\n * be a step towards re-serialization.\n *\n * The wire format (`solana-sdk`'s `Transaction`):\n *\n * ```text\n * compact-u16 signature count ─┐ must equal the message's\n * 64 × count signatures, slot order │ numRequiredSignatures\n * ── message ──────────────────────────────┘\n * 1 byte 0x80 | version (VERSIONED MESSAGES ONLY)\n * 3 bytes header\n * compact-u16 static account count\n * 32 × count static account keys (slot i signs for key i)\n * 32 bytes recent blockhash ← what patching overwrites\n * … instructions, address-table lookups\n * ```\n *\n * A zero-filled 64-byte slot is how \"not signed yet\" is spelled: `@solana/kit`'s\n * decoder reads one back as `null`, and the gas station's inspector refuses such\n * a transaction as `missing_client_signature` — a diagnosis, rather than the\n * opaque signature-verification failure a stale signature would produce.\n */\n\nimport { ed25519 } from '@noble/curves/ed25519.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { base58Decode, base58Encode } from '../../utils/base58.js';\nimport { fromBase64, toBase64 } from '../../utils/binary.js';\nimport type { Signer } from './payment-channel.js';\n\n/** Bytes in one Ed25519 signature slot. */\nconst SIGNATURE_LENGTH = 64;\n/** Bytes in a pubkey, a blockhash, and an Ed25519 seed alike. */\nconst PUBKEY_LENGTH = 32;\n/** An Ed25519 seed — the private half of a keypair, and all of it that is stored. */\nconst SEED_LENGTH = 32;\n/** A stored `seed ‖ pubkey` secret key, the spelling most Solana tooling writes. */\nconst SECRET_KEY_LENGTH = 64;\n/** High bit of a message's first byte: set ⇒ versioned, clear ⇒ legacy. */\nconst VERSION_PREFIX_MASK = 0x80;\n\n/**\n * A wire transaction, read but not rebuilt.\n *\n * Every field is a view onto {@link bytes}, which is the caller's transaction\n * verbatim. Nothing here is enough to re-serialize the message, deliberately.\n */\nexport interface SolanaWireTransaction {\n /** The whole wire transaction, unmodified. */\n bytes: Uint8Array;\n /** `'legacy'` for a message with no version prefix, else the version number. */\n version: 'legacy' | number;\n /**\n * The signature slots in COMPILED ORDER — index `i` is the key whose\n * signature belongs in slot `i`. This is the order the header fixed when the\n * message was compiled; within a role it is address-sorted rather than\n * semantic, so map a signer to a slot by ADDRESS, never by position.\n */\n signers: string[];\n /** Base58 addresses of the slots that are still 64 zero bytes. */\n unsigned: string[];\n /** Every static account key, in compiled order. `signers` is its head. */\n staticAccounts: string[];\n /** The blockhash the message currently commits to, base58. */\n recentBlockhash: string;\n /** Byte offset of the first signature slot. */\n signaturesOffset: number;\n /** Byte offset of the message — the bytes a signature covers. */\n messageOffset: number;\n /** Byte offset of the 32 blockhash bytes inside {@link bytes}. */\n recentBlockhashOffset: number;\n}\n\n/** A compact-u16 read: the value, and where the next field starts. */\nfunction readCompactU16(\n bytes: Uint8Array,\n offset: number\n): { value: number; offset: number } {\n let value = 0;\n for (let shift = 0; shift < 3; shift++) {\n const byte = bytes[offset + shift];\n if (byte === undefined) {\n throw new Error('malformed Solana transaction: truncated compact-u16');\n }\n value |= (byte & 0x7f) << (shift * 7);\n if ((byte & 0x80) === 0) return { value, offset: offset + shift + 1 };\n }\n throw new Error('malformed Solana transaction: compact-u16 exceeds three bytes');\n}\n\n/** Coerce the two spellings a wire transaction travels in to bytes. */\nfunction toWireBytes(wire: string | Uint8Array): Uint8Array {\n return typeof wire === 'string' ? fromBase64(wire) : wire;\n}\n\n/** Answer in whatever spelling the caller handed in. */\nfunction likeInput(wire: string | Uint8Array, bytes: Uint8Array): string | Uint8Array {\n return typeof wire === 'string' ? toBase64(bytes) : bytes;\n}\n\n/**\n * Read a base64 (or raw) wire transaction far enough to locate its signature\n * slots and its blockhash. Legacy and v0 messages both parse; the address-table\n * lookups a v0 message may carry sit AFTER everything this needs and are not\n * decoded.\n *\n * @throws {Error} when the bytes are not a transaction of the shape above —\n * truncated, or claiming a signature count the header does not agree with.\n */\nexport function parseSolanaWireTransaction(\n wire: string | Uint8Array\n): SolanaWireTransaction {\n const bytes = toWireBytes(wire);\n\n const count = readCompactU16(bytes, 0);\n const signaturesOffset = count.offset;\n const messageOffset = signaturesOffset + count.value * SIGNATURE_LENGTH;\n if (messageOffset > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots do not fit in ${bytes.length} bytes`\n );\n }\n\n const prefix = bytes[messageOffset];\n if (prefix === undefined) {\n throw new Error('malformed Solana transaction: no message after the signatures');\n }\n const versioned = (prefix & VERSION_PREFIX_MASK) !== 0;\n const version = versioned ? prefix & ~VERSION_PREFIX_MASK : 'legacy';\n const headerOffset = messageOffset + (versioned ? 1 : 0);\n\n const numRequiredSignatures = bytes[headerOffset];\n if (numRequiredSignatures === undefined) {\n throw new Error('malformed Solana transaction: truncated message header');\n }\n if (numRequiredSignatures !== count.value) {\n throw new Error(\n `malformed Solana transaction: ${count.value} signature slots but the header requires ${numRequiredSignatures}`\n );\n }\n\n const accountCount = readCompactU16(bytes, headerOffset + 3);\n const keysOffset = accountCount.offset;\n const recentBlockhashOffset = keysOffset + accountCount.value * PUBKEY_LENGTH;\n if (recentBlockhashOffset + PUBKEY_LENGTH > bytes.length) {\n throw new Error(\n `malformed Solana transaction: ${accountCount.value} account keys and a blockhash do not fit in ${bytes.length} bytes`\n );\n }\n if (numRequiredSignatures > accountCount.value) {\n throw new Error(\n `malformed Solana transaction: header requires ${numRequiredSignatures} signatures but the message names only ${accountCount.value} accounts`\n );\n }\n\n const staticAccounts: string[] = [];\n for (let i = 0; i < accountCount.value; i++) {\n const start = keysOffset + i * PUBKEY_LENGTH;\n staticAccounts.push(base58Encode(bytes.slice(start, start + PUBKEY_LENGTH)));\n }\n\n const signers = staticAccounts.slice(0, numRequiredSignatures);\n const unsigned = signers.filter((_signer, slot) => {\n const start = signaturesOffset + slot * SIGNATURE_LENGTH;\n return bytes\n .subarray(start, start + SIGNATURE_LENGTH)\n .every((byte) => byte === 0);\n });\n\n return {\n bytes,\n version,\n signers,\n unsigned,\n staticAccounts,\n recentBlockhash: base58Encode(\n bytes.slice(recentBlockhashOffset, recentBlockhashOffset + PUBKEY_LENGTH)\n ),\n signaturesOffset,\n messageOffset,\n recentBlockhashOffset,\n };\n}\n\n/**\n * Overwrite a compiled message's recent blockhash in place, and **clear every\n * signature slot**.\n *\n * The gas station quotes a blockhash of its own and then refuses any execute\n * whose transaction does not carry it (`blockhash_mismatch`), so a client that\n * has already been handed a draft has two ways to comply: ask the composer to\n * prepare the same transaction again against the quoted blockhash, or move the\n * 32 bytes itself. This is the second, and it makes step 5 of the ceremony\n * local — one round trip fewer inside a 60-second quote TTL.\n *\n * Clearing the signatures is not a side effect, it is the point. Those 32 bytes\n * are inside the message every signature covers, so a signature made before the\n * patch is now a signature over a message that no longer exists. Left in place\n * it would fail signature verification at the validator with nothing pointing at\n * the cause; zeroed, the slot means exactly what an unsigned slot means\n * everywhere else on this path, and the gas station names it\n * (`missing_client_signature`) before spending anything. **Sign after patching,\n * never before.**\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param recentBlockhash - Base58, exactly as the quote returned it.\n * @returns The patched transaction, in the spelling `wire` arrived in.\n * @throws {Error} when `recentBlockhash` is not 32 bytes of base58.\n */\nexport function patchSolanaRecentBlockhash(wire: string, recentBlockhash: string): string;\nexport function patchSolanaRecentBlockhash(\n wire: Uint8Array,\n recentBlockhash: string\n): Uint8Array;\nexport function patchSolanaRecentBlockhash(\n wire: string | Uint8Array,\n recentBlockhash: string\n): string | Uint8Array {\n const blockhash = base58Decode(recentBlockhash);\n if (blockhash.length !== PUBKEY_LENGTH) {\n throw new Error(\n `recentBlockhash must decode to ${PUBKEY_LENGTH} bytes, got ${blockhash.length} from ${JSON.stringify(recentBlockhash)}`\n );\n }\n\n const parsed = parseSolanaWireTransaction(wire);\n const patched = new Uint8Array(parsed.bytes);\n patched.set(blockhash, parsed.recentBlockhashOffset);\n patched.fill(\n 0,\n parsed.signaturesOffset,\n parsed.signaturesOffset + parsed.signers.length * SIGNATURE_LENGTH\n );\n\n return likeInput(wire, patched);\n}\n\n/**\n * Sign a supplied wire transaction in place: for each key in `signers` that the\n * compiled header names, write its Ed25519 signature over the message bytes\n * into that key's own slot. Slots belonging to nobody in `signers` — the fee\n * payer's, above all — are left exactly as they were.\n *\n * Slots are matched by ADDRESS. A receipt's `requiredSigners` is address-sorted\n * within a role and carries no semantics, so \"the mint is second\" is a fact\n * about one particular pair of keys and not about the transaction shape.\n *\n * @param wire - The transaction, base64 or raw bytes.\n * @param signers - Keypairs to sign with; each `privateKey` is a 32-byte seed.\n * @returns The signed transaction, in the spelling `wire` arrived in.\n * @throws {Error} when a supplied signer is not one of the message's required\n * signers — signing with a key the transaction never asked for means the\n * caller built or patched the wrong thing, and silently doing nothing would\n * surface much later as `missing_client_signature`.\n */\nexport function signSolanaWireTransaction(wire: string, signers: Signer[]): string;\nexport function signSolanaWireTransaction(\n wire: Uint8Array,\n signers: Signer[]\n): Uint8Array;\nexport function signSolanaWireTransaction(\n wire: string | Uint8Array,\n signers: Signer[]\n): string | Uint8Array {\n const parsed = parseSolanaWireTransaction(wire);\n const signed = new Uint8Array(parsed.bytes);\n const message = signed.subarray(parsed.messageOffset);\n\n for (const signer of signers) {\n const address = base58Encode(signer.publicKey);\n const slot = parsed.signers.indexOf(address);\n if (slot === -1) {\n throw new Error(\n `${address} is not a required signer of this transaction (slots: ${parsed.signers.join(', ')})`\n );\n }\n signed.set(\n ed25519.sign(message, signer.privateKey),\n parsed.signaturesOffset + slot * SIGNATURE_LENGTH\n );\n }\n\n return likeInput(wire, signed);\n}\n\n/**\n * A fresh Ed25519 keypair.\n *\n * The ANT spawn needs one per attempt: its public half goes to the store as the\n * MPL Core asset address — which becomes the ANT's address, and the `processId`\n * the follow-up name purchase wants — and its private half signs one slot of one\n * transaction. Nothing needs it afterwards, so it is generated, used, and\n * dropped rather than derived from the user's phrase, where it would be one more\n * key to keep and to lose.\n */\nexport function generateSolanaKeypair(): Signer & { address: string } {\n return keypairFromSeed(randomBytes(SEED_LENGTH));\n}\n\n/**\n * The keypair a stored or derived Solana secret represents — a 32-byte seed or\n * a 64-byte `seed ‖ pubkey` secret key, as bytes or base58.\n *\n * The public half is DERIVED, never read out of the trailing 32 bytes: a\n * 64-byte input whose tail disagrees with its own seed is a corrupt file, and\n * honouring it would fill a signature slot addressed to a key that did not sign\n * it. Mirrors the rule `ToonClient`'s own config applies to `solanaSecretKey`.\n */\nexport function solanaKeypair(\n key: string | Uint8Array\n): Signer & { address: string } {\n const bytes = typeof key === 'string' ? base58Decode(key.trim()) : key;\n if (bytes.length !== SEED_LENGTH && bytes.length !== SECRET_KEY_LENGTH) {\n throw new Error(\n `a Solana secret must be a ${SEED_LENGTH}-byte seed or a ${SECRET_KEY_LENGTH}-byte ` +\n `secret key; got ${bytes.length} bytes`\n );\n }\n return keypairFromSeed(bytes.slice(0, SEED_LENGTH));\n}\n\n/** The one place a seed becomes a keypair, so both entry points agree. */\nfunction keypairFromSeed(seed: Uint8Array): Signer & { address: string } {\n const publicKey = new Uint8Array(ed25519.getPublicKey(seed));\n return { privateKey: seed, publicKey, address: base58Encode(publicKey) };\n}\n","/**\n * The signed job event a NIP-90 app behind a connector reads.\n *\n * Some apps a connector fronts are not plain HTTP handlers: the store and the\n * gas station both take their input as a **kind-tagged Nostr event** whose\n * arguments are `['param', key, value]` tags, and answer in the FULFILL body.\n * There is no relay and no round trip — the event is the request body of the\n * paid POST, and the receipt comes back in that same response.\n *\n * The signature on the event is **integrity, not identity**. Both apps say so\n * in as many words: it proves the tags were not altered between this client and\n * the handler, and nothing else — who paid is the connector's `X-TOON-Payer`\n * header, proved against a claim, and no app takes an event pubkey for an\n * authority. So the key here is generated per event by default. A caller who\n * wants a stable pubkey in the app's logs can supply one; nothing about the\n * job's outcome depends on which key it is.\n *\n * This is why the 1.0 client carries no Nostr identity. There is no key to\n * derive, back up or rotate — only 32 bytes to sign one request with and then\n * forget.\n */\n\nimport { schnorr } from '@noble/curves/secp256k1.js';\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { encodeUtf8, toHex } from '../utils/binary.js';\n\n/**\n * A signed Nostr event, in the field order and JSON spelling every verifier\n * expects.\n */\nexport interface JobEvent {\n /** 32-byte sha256 of the serialization below, hex. */\n id: string;\n /** The signing key's x-only public half, hex. */\n pubkey: string;\n /** Unix SECONDS. */\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n /** BIP-340 signature over `id`, hex. */\n sig: string;\n}\n\n/** What one job asks for: its kind, and its `param` tags. */\nexport interface JobEventParams {\n /** The NIP-90 job kind — `5095` for the ArNS job, `5096` for Solana gas. */\n kind: number;\n /**\n * The job's arguments, emitted in iteration order as `['param', key, value]`.\n * An `undefined` value is omitted rather than sent as the string\n * `\"undefined\"`, so an optional parameter can be passed through unset.\n */\n params: Record<string, string | undefined>;\n /** Extra tags to carry beside the params. Rarely needed. */\n tags?: string[][];\n /** Default `''`. Neither of this repository's job kinds reads it. */\n content?: string;\n /** 32-byte secp256k1 secret. Default: a fresh one, used once. */\n secretKey?: Uint8Array;\n /** Unix seconds. Default `Date.now() / 1000`, floored. */\n createdAt?: number;\n}\n\n/**\n * NIP-01 serialization: a six-element array, `JSON.stringify`d exactly as\n * written. The verifier recomputes this from the event's own fields, so any\n * difference in shape — a reordered key, a number where a string belongs —\n * surfaces as an id mismatch rather than as a validation message.\n */\nfunction serializeForId(event: Omit<JobEvent, 'id' | 'sig'>): string {\n return JSON.stringify([\n 0,\n event.pubkey,\n event.created_at,\n event.kind,\n event.tags,\n event.content,\n ]);\n}\n\n/**\n * Build and sign one job event.\n *\n * @returns The event, ready to be the `{ event }` body of a paid POST.\n */\nexport function buildJobEvent(params: JobEventParams): JobEvent {\n const secretKey = params.secretKey ?? randomBytes(32);\n const pubkey = toHex(new Uint8Array(schnorr.getPublicKey(secretKey)));\n\n const tags: string[][] = [];\n for (const [key, value] of Object.entries(params.params)) {\n if (value !== undefined) tags.push(['param', key, value]);\n }\n if (params.tags) tags.push(...params.tags);\n\n const unsigned = {\n pubkey,\n created_at: params.createdAt ?? Math.floor(Date.now() / 1000),\n kind: params.kind,\n tags,\n content: params.content ?? '',\n };\n\n const idBytes = sha256(encodeUtf8(serializeForId(unsigned)));\n return {\n ...unsigned,\n id: toHex(idBytes),\n sig: toHex(new Uint8Array(schnorr.sign(idBytes, secretKey))),\n };\n}\n\n/** First value of a `['param', key, value]` tag, if the event carries one. */\nexport function jobEventParam(event: JobEvent, key: string): string | undefined {\n for (const tag of event.tags) {\n if (tag[0] === 'param' && tag[1] === key) return tag[2];\n }\n return undefined;\n}\n","/**\n * Putting a {@link JobEvent} through a connector, and reading what came back.\n *\n * A job is an ordinary paid request — `POST` the event to the route, get the\n * app's HTTP response — so this adds no wire of its own. What it adds is the\n * one decoding rule both NIP-90 apps in this protocol share, and a single\n * vocabulary for the three quite different ways a job can fail to produce a\n * receipt:\n *\n * - **the packet was refused** — a price, a route or a seal was wrong, and the\n * app was never reached. `send()` returns this rather than throwing, and so\n * does {@link sendJob};\n * - **the app rejected the event** — a missing param, an unregistered kind.\n * It rides home on a FULFILL with `accept: false`, so it cost what a receipt\n * would have cost;\n * - **the app answered, and the answer is a refusal.** A gas station that\n * declines to spend has done its job: `accept: true`, a receipt, and\n * `status: 'failed'` inside it. That is NOT this module's business — it is a\n * successful job, and the caller branches on the receipt's own `reason`.\n *\n * The decoding rule: a receipt is `base64(JSON)` in `data`, and both apps ALSO\n * decode it into `result` for readability. `data` is the byte-faithful one and\n * is preferred here; `result` is the fallback, so a future app that emits only\n * one of the two still works.\n */\n\nimport { fromBase64, decodeUtf8 } from '../utils/binary.js';\nimport type { SendRefused, SendRequest, SendResult, SendOptions } from '../client/types.js';\nimport type { JobEvent } from './job-event.js';\n\n/**\n * The part of a client a job needs: the ability to pay for one HTTP request.\n * `ToonClient` satisfies it, and so does any stand-in a test supplies.\n */\nexport interface JobSender {\n send(\n destination: string,\n request?: SendRequest,\n options?: SendOptions\n ): Promise<SendResult>;\n}\n\n/**\n * Where a job goes: who pays for it, which route terminates it, and — on a\n * FORWARDED route — whose key the payload is sealed to.\n *\n * The store and the gas station are different nodes with different connectors\n * and different channels, so a ceremony spanning both takes two endpoints. One\n * client can serve both only when it is attached to a node that forwards to\n * each, in which case both endpoints name that client and `sealTo` names the\n * far node — see `docs/devnet.md`.\n */\nexport interface JobEndpoint {\n /** Pays for the request. */\n client: JobSender;\n /** The ILP address of the route that terminates at the app. */\n destination: string;\n /** The terminating connector, when `destination` is forwarded. */\n sealTo?: string | Uint8Array;\n /** Per-packet timeout, in milliseconds. */\n timeoutMs?: number;\n}\n\n/**\n * What a job produced: a decoded receipt, or the reason there is none.\n *\n * `accepted: false` never means \"the app said no to what you asked\" — that is a\n * receipt. It means the receipt does not exist: the packet was refused, or the\n * app rejected the event before running it.\n */\nexport type JobAnswer<T> =\n | { accepted: true; receipt: T }\n | {\n accepted: false;\n /** An ILP reject code for a refusal, or the app's own `F00` / `T00`. */\n code: string;\n message: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n };\n\n/** The `{ accept, data, result, code, message }` envelope both apps answer in. */\ninterface JobEnvelope {\n accept?: boolean;\n data?: string;\n result?: unknown;\n /**\n * The store's answer when its `data` is NOT JSON — kind:5094 returns a bare\n * Arweave transaction id, and the backend surfaces it here rather than under\n * `result`. A documented contract, not a quirk.\n */\n txId?: unknown;\n code?: string;\n message?: string;\n}\n\n/**\n * Pay for one job and decode its receipt.\n *\n * The receipt type is the caller's assertion, not a checked fact: these apps\n * publish their receipt shapes and this client mirrors them, but nothing on the\n * wire enforces the match, so a caller reading a field it needs should still\n * check it is there.\n */\nexport async function sendJob<T>(\n endpoint: JobEndpoint,\n event: JobEvent\n): Promise<JobAnswer<T>> {\n const answer = await endpoint.client.send(\n endpoint.destination,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: { event },\n },\n {\n ...(endpoint.sealTo !== undefined ? { sealTo: endpoint.sealTo } : {}),\n ...(endpoint.timeoutMs !== undefined ? { timeoutMs: endpoint.timeoutMs } : {}),\n }\n );\n\n if (!answer.fulfilled) {\n return {\n accepted: false,\n code: answer.code,\n message: `kind:${event.kind} refused by ${answer.refusedBy}: ${answer.message}`,\n refusal: answer,\n };\n }\n\n let envelope: JobEnvelope;\n try {\n envelope = answer.json<JobEnvelope>();\n } catch {\n return {\n accepted: false,\n code: 'F00',\n message:\n `kind:${event.kind} answered ${answer.status} with a body that is not JSON: ` +\n truncate(decodeUtf8(answer.body)),\n };\n }\n\n if (envelope.accept !== true) {\n return {\n accepted: false,\n code: envelope.code ?? String(answer.status),\n message: envelope.message ?? `kind:${event.kind} was not accepted`,\n };\n }\n\n const receipt = decodeReceipt<T>(envelope);\n if (receipt === undefined) {\n return {\n accepted: false,\n code: 'F00',\n message: `kind:${event.kind} was accepted but carried no receipt`,\n };\n }\n return { accepted: true, receipt };\n}\n\n/**\n * `data` (byte-faithful) if it decodes as JSON; otherwise whichever field the\n * app said its answer in.\n *\n * The store decides between two of those by whether its base64 `data` parses\n * as a JSON object: a receipt goes to `result`, and anything else goes to\n * `txId`. kind:5094 takes the second branch — its whole answer is one Arweave\n * transaction id — so a client that reads only `result` calls a successful\n * upload \"accepted but carried no receipt\".\n */\nfunction decodeReceipt<T>(envelope: JobEnvelope): T | undefined {\n if (typeof envelope.data === 'string') {\n try {\n return JSON.parse(decodeUtf8(fromBase64(envelope.data))) as T;\n } catch {\n // Fall through: an app that base64'd something that is not JSON has still\n // said what it meant in `result` or `txId`.\n }\n }\n if (envelope.result !== null && typeof envelope.result === 'object') {\n return envelope.result as T;\n }\n // A bare id is still a receipt. Wrapped, so the caller reads `receipt.txId`\n // the same way every other job's fields are read.\n if (typeof envelope.txId === 'string' && envelope.txId.length > 0) {\n return { txId: envelope.txId } as T;\n }\n return undefined;\n}\n\nfunction truncate(text: string): string {\n return text.length > 200 ? `${text.slice(0, 200)}…` : text;\n}\n","/**\n * The receipts the store and the gas station answer with.\n *\n * These MIRROR the two app repositories — `toon-protocol/store`'s\n * `ArnsAntPrepareReceipt` / `ArnsBuyReceipt` and `toon-protocol/gas-station`'s\n * `GasStationReceipt` — and mirror them by hand, because this package has no\n * TOON-protocol runtime dependencies. That makes them a claim about a remote\n * contract rather than a shared type, so every integer that could exceed 2^53\n * is a `string` here exactly as it is on the wire: reading one as a `number`\n * would be this client inventing precision the app never sent.\n *\n * A field this client does not read is still declared, so that a receipt logged\n * or forwarded whole keeps its shape.\n */\n\n/** Which cluster's ar.io deployment a kind:5095 job targets. */\nexport type ArnsNetwork = 'mainnet' | 'devnet';\n\n/** A name registration kind: a time-boxed lease, or a one-time permabuy. */\nexport type ArnsNameType = 'lease' | 'permabuy';\n\n/** Which Solana cluster the gas station pays on. */\nexport type SolanaNetwork = 'mainnet' | 'devnet';\n\n/**\n * kind:5095 `op=prepare` — the unsigned ANT-spawn transaction.\n *\n * `requiredSigners` is the compiled slot order and is **address-sorted within a\n * role**, so it says who signs, never what each one is for. Map a keypair to a\n * slot by address. The fee payer is always slot 0 and is the one slot a client\n * leaves alone.\n */\nexport interface ArnsAntPrepareReceipt {\n job: 'arns-buy';\n op: 'prepare';\n network: ArnsNetwork;\n /** The ANT's MPL Core asset pubkey — the `processId` for `op=buy`. */\n processId: string;\n /** The same key, named for the keypair the client signs with. */\n mint: string;\n owner: string;\n feePayer: string;\n name: string;\n antProgramId: string;\n /** Base64 v0 wire transaction, every signature slot zero-filled. */\n transaction: string;\n recentBlockhash: string;\n /** True ⇒ built on a placeholder blockhash: quote with it, never execute it. */\n draft: boolean;\n requiredSigners: string[];\n /** The subset the client must fill before the gas station will look at it. */\n clientSigners: string[];\n rentTransferLamports: string;\n estimatedFeePayerLamports: string;\n instructions: string[];\n}\n\n/** kind:5095 `op=buy` — the name is registered to the ANT. */\nexport interface ArnsBuyReceipt {\n job: 'arns-buy';\n network: ArnsNetwork;\n name: string;\n type: ArnsNameType;\n years: number | null;\n processId: string;\n quotedMario: string;\n registryTxId: string;\n syncAttributesTxId: string | null;\n}\n\n/**\n * Why a gas station declined, from its own closed vocabulary. The ones a client\n * driving this ceremony can act on:\n *\n * - `float_exhausted` — the node is out of gas money; nothing to retry.\n * - `dvm_key_misplaced` — the gas wallet appears where it may not. Almost\n * always a transaction built wrong.\n * - `quote_expired`, `blockhash_expired`, `blockhash_mismatch` — re-quote,\n * re-patch, re-sign.\n * - `missing_client_signature` — a slot is still zero: sign AFTER patching.\n * - `confirmation_timeout` — broadcast but not confirmed. It may still land;\n * retry with the **same** `idempotencyKey`.\n */\nexport type GasStationFailureReason =\n | 'malformed_transaction'\n | 'fee_payer_mismatch'\n | 'dvm_key_misplaced'\n | 'program_not_whitelisted'\n | 'priority_fee_exceeded'\n | 'channel_op_not_permitted'\n | 'missing_client_signature'\n | 'unknown_quote'\n | 'quote_expired'\n | 'blockhash_mismatch'\n | 'blockhash_expired'\n | 'simulation_failed'\n | 'delta_cap_exceeded'\n | 'float_exhausted'\n | 'quote_refused'\n | 'confirmation_timeout'\n | 'broadcast_failed';\n\n/** kind:5096 `phase=quote` — what this node will do, and what it will cost. */\nexport interface GasStationQuoteReceipt {\n job: 'gas-station';\n phase: 'quote';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n /** The address the transaction must name as its fee payer. */\n feePayer: string;\n maxLamports: string;\n /** The blockhash the executed transaction must carry. */\n recentBlockhash: string;\n /** ms epoch — quote TTL and blockhash validity, merged into one deadline. */\n expiresAt: number;\n}\n\n/** kind:5096 `phase=execute` — co-signed, broadcast, confirmed. */\nexport interface GasStationExecuteReceipt {\n job: 'gas-station';\n phase: 'execute';\n status: 'ok';\n network: SolanaNetwork;\n quoteId: string;\n idempotencyKey: string;\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n /** True when this result was replayed from the idempotency store. */\n replayed?: boolean;\n}\n\n/**\n * The gate said no — and said so as an accepted job, because it was asked a\n * question and applied its rules. Branch on {@link reason}, never on `detail`.\n */\nexport interface GasStationFailureReceipt {\n job: 'gas-station';\n phase: 'quote' | 'execute';\n status: 'failed';\n network: SolanaNetwork;\n reason: GasStationFailureReason;\n detail: string;\n}\n\nexport type GasStationReceipt =\n | GasStationQuoteReceipt\n | GasStationExecuteReceipt\n | GasStationFailureReceipt;\n\n/** True when a gas-station receipt is the gate declining. */\nexport function isGasStationFailure(\n receipt: GasStationReceipt\n): receipt is GasStationFailureReceipt {\n return receipt.status === 'failed';\n}\n","/**\n * Buying an ArNS name while holding nothing but ILP credit.\n *\n * `kind:5095 op=buy` needs a `processId` — the MPL Core asset pubkey of an ANT\n * the caller already owns. Spawning one costs ~0.012 SOL of rent, and a TOON\n * client holds stablecoin credit on a payment channel, not SOL. So the work is\n * split across the three parties, and no single one has to be able to do all of\n * it:\n *\n * - the **store** composes the transaction (it is the only party with `@ar.io/sdk`)\n * - the **client** signs it (it is the only party that may own the ANT)\n * - the **gas station** pays for it and broadcasts it (it is the only party with SOL)\n *\n * The ceremony {@link spawnAnt} drives:\n *\n * ```text\n * 1. → gas kind:5096 quote, no draft → feePayer\n * 2. → store kind:5095 op=prepare → unsigned draft transaction\n * 3. sign the mint and owner slots\n * 4. → gas kind:5096 quote, with draft → quoteId, recentBlockhash, maxLamports\n * 5. patch the blockhash, sign again\n * 6. → gas kind:5096 execute → co-signed, broadcast, signature\n * ```\n *\n * Two quotes and two signings, because the gas station prices the job from a\n * SIGNED draft (that is what makes the free quote a full policy dry run) and\n * then requires the executed transaction to carry the blockhash **it** chose.\n * Everything from step 4 on runs inside one merged quote/blockhash deadline —\n * 60 seconds by default — which is why step 5 patches the 32 bytes locally\n * instead of paying for a second `op=prepare` round trip. Pass `reprepare` to\n * take that round trip anyway; the store returns a byte-identical transaction\n * but for those 32 bytes, so both routes end in the same place.\n *\n * Then {@link buyArnsName} spends the ANT: `kind:5095 op=buy` with the spawned\n * `processId`. {@link buyArnsNameWithNewAnt} is the two in order.\n *\n * **The spawned ANT is not ACL-bootstrapped.** That is ~61.4M lamports against\n * the gas station's 20M per-job ceiling, and its instructions would put the fee\n * payer in an ar.io slot, which the inspector refuses outright. The ANT resolves\n * fine; it just will not appear in \"ANTs I own\" registry lookups until the owner\n * bootstraps it later with its own SOL — and that registry is an\n * eventually-consistent secondary index, not truth.\n *\n * **Nothing here throws.** A packet the connector would not carry, an event the\n * app rejected, a gate that declined to spend and a receipt this client will not\n * sign are all outcomes — `{ spawned: false, step, reason, detail }`. By the\n * time any of them is read a packet has already been paid for, which is exactly\n * the case CLAUDE.md's rule covers: a refusal is returned, never thrown.\n *\n * `reason` is the gas station's own closed vocabulary wherever the verdict is\n * one the gas station would give — including the two checks this client makes\n * locally, which exist only to reach that verdict before paying for it.\n */\n\nimport {\n generateSolanaKeypair,\n parseSolanaWireTransaction,\n patchSolanaRecentBlockhash,\n signSolanaWireTransaction,\n} from '../channel/solana/wire-transaction.js';\nimport type { Signer } from '../channel/solana/payment-channel.js';\nimport { base58Encode } from '../utils/base58.js';\nimport { buildJobEvent } from './job-event.js';\nimport { sendJob, type JobAnswer, type JobEndpoint } from './send-job.js';\nimport type {\n ArnsAntPrepareReceipt,\n ArnsBuyReceipt,\n ArnsNameType,\n GasStationExecuteReceipt,\n GasStationQuoteReceipt,\n GasStationReceipt,\n} from './receipts.js';\nimport type { SendRefused } from '../client/types.js';\n\n/** The NIP-90 job kind for the ArNS job — both of its ops. */\nexport const ARNS_KIND = 5095;\n/** The NIP-90 job kind for the Solana gas station — both of its phases. */\nexport const SOLANA_GAS_KIND = 5096;\n\n/** Which step of the ceremony an outcome stopped at. */\nexport type AntSpawnStep =\n | 'fee-payer-quote'\n | 'prepare'\n | 'quote'\n | 'reprepare'\n | 'sign'\n | 'execute';\n\nexport interface AntSpawnParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** Where the kind:5096 job goes — the gas station. */\n gas: JobEndpoint;\n /**\n * The keypair that will own the ANT. Its address goes to the store as\n * `owner`, and it signs the owner slot — which is also the account the fee\n * payer transfers the ANT state PDAs' rent to, in the same transaction.\n */\n owner: Signer;\n /** The ANT's display name: 1–51 lowercase alphanumerics and hyphens. */\n name: string;\n /** Arweave tx id the root `@` record points at. Default: the store's own. */\n target?: string;\n /** ANT ticker, 1–16 chars. Default: the ar.io program's own. */\n ticker?: string;\n /**\n * Override the ephemeral mint keypair. Supply one only to make a run\n * reproducible — its public half becomes the ANT's permanent address, and\n * nothing needs its private half once the spawn confirms.\n */\n mint?: Signer;\n /**\n * The gas station's execute-phase idempotency key. Default: a fresh UUID —\n * and it must be one, because that idempotency store is global and unscoped,\n * so a guessable key is somebody else's receipt.\n *\n * Reuse the SAME key to retry a `confirmation_timeout`. Both outcomes report\n * the key that was used, so a generated one is recoverable rather than lost\n * with the run that made it.\n */\n idempotencyKey?: string;\n /**\n * Ask the store to re-prepare against the quoted blockhash instead of\n * patching those 32 bytes locally. One more paid round trip inside the quote\n * TTL, for a transaction composed entirely by the party that composes it.\n */\n reprepare?: boolean;\n}\n\n/** The ANT exists on chain, and the client owns it. */\nexport interface AntSpawned {\n spawned: true;\n /** The ANT's MPL Core asset pubkey — hand this to {@link buyArnsName}. */\n processId: string;\n /** The same key, named for the keypair that signed the mint slot. */\n mint: string;\n owner: string;\n feePayer: string;\n quoteId: string;\n /** The confirmed transaction signature. */\n signature: string;\n slot: string | null;\n feeLamportsActual: string | null;\n recentBlockhash: string;\n /** True when the gas station replayed a receipt for this idempotency key. */\n replayed: boolean;\n /** The key used, so a `confirmation_timeout` can be retried with it. */\n idempotencyKey: string;\n /** The executed transaction, base64 — every slot filled but the fee payer's. */\n transaction: string;\n}\n\n/** Somebody said no, and said why. */\nexport interface AntSpawnRefused {\n spawned: false;\n step: AntSpawnStep;\n /**\n * The gas station's machine-readable reason where it was the gate that\n * declined, an ILP reject code where the packet was refused, or the app's own\n * `F00` / `T00` where the event was rejected. Branch on this, not on\n * {@link detail}.\n *\n * A check this client made locally answers in the gas station's OWN\n * vocabulary — `fee_payer_mismatch`, `blockhash_mismatch`,\n * `missing_client_signature` — because it is the same verdict on the same\n * bytes, reached before paying for it rather than after.\n */\n reason: string;\n detail: string;\n /** Present when the packet never reached the app. */\n refusal?: SendRefused;\n /** The ANT's address. It exists only if the spawn confirmed. */\n mint: string;\n /**\n * The key the execute carried, or would have. Together with {@link quoteId}\n * and {@link transaction} it is everything needed to re-send that execute —\n * which is the documented recovery from a `confirmation_timeout`, where the\n * transaction is broadcast and may yet land.\n */\n idempotencyKey: string;\n /** The quote the execute was made against, once there was one. */\n quoteId?: string;\n /** The bytes sent to the gas station, when the execute is what failed. */\n transaction?: string;\n}\n\nexport type AntSpawnOutcome = AntSpawned | AntSpawnRefused;\n\n/**\n * Spawn an ANT the caller owns, paid for by a gas station and composed by a\n * store. Steps 1–6 above.\n */\nexport async function spawnAnt(params: AntSpawnParams): Promise<AntSpawnOutcome> {\n const owner = base58Encode(params.owner.publicKey);\n const mintKeypair = params.mint ?? generateSolanaKeypair();\n const mint = base58Encode(mintKeypair.publicKey);\n const idempotencyKey = params.idempotencyKey ?? crypto.randomUUID();\n const held = new Map<string, Signer>([\n [mint, mintKeypair],\n [owner, params.owner],\n ]);\n\n /** Every refusal carries the same three facts about the run that produced it. */\n const stop = (\n step: AntSpawnStep,\n refused: PartialRefusal\n ): AntSpawnRefused => ({ ...refused, step, mint, idempotencyKey });\n\n // ── 1. What address must the transaction name as its fee payer? ───────────\n // A quote with no draft is the cheapest way to ask: it prices nothing and\n // returns the gas wallet, which the store needs before it can compose.\n const feePayerQuote = await quote(params.gas, undefined);\n if (!feePayerQuote.ok) return stop('fee-payer-quote', feePayerQuote.refused);\n const feePayer = feePayerQuote.receipt.feePayer;\n\n // ── 2. Compose. No blockhash yet: a draft exists only to be priced. ───────\n const drafted = await prepare(params, { mint, owner, feePayer });\n if (!drafted.ok) return stop('prepare', drafted.refused);\n const draft = drafted.receipt;\n\n const drafters = signersFor(draft, held, { mint, feePayer });\n if (!drafters.ok) return stop('prepare', drafters.refused);\n\n // ── 3. Sign the slots the store said are ours. ────────────────────────────\n const signedDraft = signSolanaWireTransaction(draft.transaction, drafters.receipt);\n\n // ── 4. Quote the SIGNED draft: a full policy dry run, for free. ───────────\n const priced = await quote(params.gas, signedDraft);\n if (!priced.ok) return stop('quote', priced.refused);\n const { quoteId, recentBlockhash } = priced.receipt;\n\n // ── 5. Carry the quoted blockhash, then sign again — in that order. ───────\n // Signing first would be signing a message about to change underneath the\n // signature, so both routes end with the signing, never with the blockhash.\n let unsigned: string;\n let signers = drafters.receipt;\n if (params.reprepare === true) {\n const reprepared = await prepare(params, { mint, owner, feePayer }, recentBlockhash);\n if (!reprepared.ok) return stop('reprepare', { ...reprepared.refused, quoteId });\n const resigners = signersFor(reprepared.receipt, held, { mint, feePayer });\n if (!resigners.ok) return stop('reprepare', { ...resigners.refused, quoteId });\n unsigned = reprepared.receipt.transaction;\n signers = resigners.receipt;\n } else {\n unsigned = patchSolanaRecentBlockhash(draft.transaction, recentBlockhash);\n }\n const executable = signSolanaWireTransaction(unsigned, signers);\n\n const unexecutable = checkExecutable(executable, { feePayer, recentBlockhash });\n if (unexecutable) return stop('sign', { ...unexecutable, quoteId, transaction: executable });\n\n // ── 6. Pay, co-sign, broadcast. ───────────────────────────────────────────\n const executed = await sendJob<GasStationReceipt>(\n params.gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: {\n phase: 'execute',\n transaction: executable,\n quoteId,\n idempotencyKey,\n },\n })\n );\n const settled = readGasStation<GasStationExecuteReceipt>(executed, 'execute');\n if (!settled.ok) {\n return stop('execute', { ...settled.refused, quoteId, transaction: executable });\n }\n\n return {\n spawned: true,\n processId: draft.processId,\n mint,\n owner,\n feePayer,\n quoteId,\n signature: settled.receipt.signature,\n slot: settled.receipt.slot,\n feeLamportsActual: settled.receipt.feeLamportsActual,\n recentBlockhash,\n replayed: settled.receipt.replayed === true,\n idempotencyKey,\n transaction: executable,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Buying the name\n// ---------------------------------------------------------------------------\n\nexport interface ArnsBuyParams {\n /** Where the kind:5095 job goes — the store. */\n store: JobEndpoint;\n /** The ArNS name to register. */\n name: string;\n /** The ANT that will hold it — {@link AntSpawned.processId}. */\n processId: string;\n /** Default `'lease'`. */\n type?: ArnsNameType;\n /** Lease length, 1–5. Invalid for a permabuy. */\n years?: number;\n /** The store's own replay key for the buy. Defaults to the event id. */\n idempotencyKey?: string;\n}\n\nexport type ArnsBuyOutcome =\n | { bought: true; receipt: ArnsBuyReceipt }\n | { bought: false; reason: string; detail: string; refusal?: SendRefused };\n\n/**\n * Register an ArNS name to an ANT the caller already owns — `kind:5095 op=buy`.\n * The store's own ARIO float pays the registry; this client pays the store.\n */\nexport async function buyArnsName(params: ArnsBuyParams): Promise<ArnsBuyOutcome> {\n const answer = await sendJob<ArnsBuyReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'buy',\n name: params.name,\n processId: params.processId,\n type: params.type ?? 'lease',\n years:\n (params.type ?? 'lease') === 'lease' && params.years !== undefined\n ? String(params.years)\n : undefined,\n idempotencyKey: params.idempotencyKey,\n },\n })\n );\n if (!answer.accepted) {\n return {\n bought: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n }\n return { bought: true, receipt: answer.receipt };\n}\n\n/** Both halves: spawn an ANT, then register the name to it. */\nexport type ArnsNameWithAntOutcome =\n | { bought: true; ant: AntSpawned; receipt: ArnsBuyReceipt }\n | { bought: false; ant?: AntSpawned; step: AntSpawnStep | 'buy'; reason: string; detail: string };\n\n/**\n * The whole thing: spawn an ANT and register `name` to it.\n *\n * The two halves are separately re-runnable on purpose. If the buy fails after\n * the spawn confirmed, the ANT is still yours — call {@link buyArnsName} with\n * the `processId` in `ant` rather than spawning a second one.\n */\nexport async function buyArnsNameWithNewAnt(\n params: AntSpawnParams & Pick<ArnsBuyParams, 'type' | 'years'>\n): Promise<ArnsNameWithAntOutcome> {\n const ant = await spawnAnt(params);\n if (!ant.spawned) {\n return { bought: false, step: ant.step, reason: ant.reason, detail: ant.detail };\n }\n const bought = await buyArnsName({\n store: params.store,\n name: params.name,\n processId: ant.processId,\n ...(params.type !== undefined ? { type: params.type } : {}),\n ...(params.years !== undefined ? { years: params.years } : {}),\n });\n if (!bought.bought) {\n return { bought: false, ant, step: 'buy', reason: bought.reason, detail: bought.detail };\n }\n return { bought: true, ant, receipt: bought.receipt };\n}\n\n// ---------------------------------------------------------------------------\n// Steps\n// ---------------------------------------------------------------------------\n\n/**\n * A refusal as a step knows it — before the facts about the run as a whole\n * (which step, which mint, which idempotency key) are stamped on by `stop`.\n */\ntype PartialRefusal = Omit<AntSpawnRefused, 'step' | 'mint' | 'idempotencyKey'>;\n\n/** A step's result: its receipt, or the refusal to hand back to the caller. */\ntype Step<T> =\n | { ok: true; receipt: T }\n | { ok: false; refused: PartialRefusal };\n\nasync function quote(\n gas: JobEndpoint,\n draft: string | undefined\n): Promise<Step<GasStationQuoteReceipt>> {\n const answer = await sendJob<GasStationReceipt>(\n gas,\n buildJobEvent({\n kind: SOLANA_GAS_KIND,\n params: { phase: 'quote', transaction: draft },\n })\n );\n return readGasStation<GasStationQuoteReceipt>(answer, 'quote');\n}\n\nasync function prepare(\n params: AntSpawnParams,\n keys: { mint: string; owner: string; feePayer: string },\n recentBlockhash?: string\n): Promise<Step<ArnsAntPrepareReceipt>> {\n const answer = await sendJob<ArnsAntPrepareReceipt>(\n params.store,\n buildJobEvent({\n kind: ARNS_KIND,\n params: {\n op: 'prepare',\n name: params.name,\n owner: keys.owner,\n mint: keys.mint,\n feePayer: keys.feePayer,\n recentBlockhash,\n target: params.target,\n ticker: params.ticker,\n },\n })\n );\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n return { ok: true, receipt: answer.receipt };\n}\n\n/**\n * Read a gas-station answer. A receipt with `status: 'failed'` is the gate\n * declining — an accepted job, and the one case where {@link AntSpawnRefused}'s\n * `reason` carries the vocabulary a caller can branch on.\n */\nfunction readGasStation<T extends GasStationReceipt>(\n answer: JobAnswer<GasStationReceipt>,\n phase: 'quote' | 'execute'\n): Step<T> {\n if (!answer.accepted) return { ok: false, refused: refusalOf(answer) };\n const receipt = answer.receipt;\n if (receipt.status === 'failed') {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: receipt.reason,\n detail: receipt.detail,\n },\n };\n }\n if (receipt.phase !== phase) {\n return {\n ok: false,\n refused: {\n spawned: false,\n reason: 'malformed_receipt',\n detail: `asked the gas station for a ${phase} and it answered with a ${receipt.phase}`,\n },\n };\n }\n return { ok: true, receipt: receipt as T };\n}\n\n/**\n * The store named the signers; resolve them to the keys we hold, BY ADDRESS.\n *\n * `clientSigners` is the subset of the compiled slots that are ours to fill, and\n * `requiredSigners` is address-sorted within a role — so a positional read of\n * either is wrong for exactly the pairs of keys that happen to sort the other\n * way, which is the kind of bug that passes every test but one run in ten.\n * Signing what the receipt NAMES, rather than what this function assumes, is\n * also the only thing that stays right if a future store composes a transaction\n * where the owner is not among the client's slots.\n *\n * A receipt this client cannot honour is a REFUSAL, not an exception: two\n * packets have already been paid for by the time it is read, and a client that\n * threw here would be throwing after the packet went out.\n */\nfunction signersFor(\n receipt: ArnsAntPrepareReceipt,\n held: Map<string, Signer>,\n expected: { mint: string; feePayer: string }\n): Step<Signer[]> {\n const unheld = receipt.clientSigners.filter((signer) => !held.has(signer));\n if (unheld.length > 0) {\n return malformed(\n `the prepared transaction needs signatures this client does not hold: ${unheld.join(', ')} ` +\n `(holding ${[...held.keys()].join(' and ')})`\n );\n }\n if (receipt.feePayer !== expected.feePayer) {\n return malformed(\n `the prepared transaction names ${receipt.feePayer} as fee payer, not the quoted ${expected.feePayer}`\n );\n }\n // The mint's public half IS the ANT's address, so a `processId` that is not\n // it would send the follow-up name purchase at somebody else's asset.\n if (receipt.processId !== expected.mint) {\n return malformed(\n `the prepared transaction spawns ${receipt.processId}, not the mint ${expected.mint} it was given`\n );\n }\n const signers: Signer[] = [];\n for (const address of receipt.clientSigners) {\n const signer = held.get(address);\n if (signer !== undefined) signers.push(signer);\n }\n return { ok: true, receipt: signers };\n}\n\n/**\n * The local half of what the gas station is about to check: the fee payer is\n * slot 0, the blockhash is the quoted one, and every other slot is filled.\n *\n * Advisory only — the gas station's inspector is the authority and runs again\n * on the same bytes. This exists so that its verdict arrives for free instead of\n * for the price of an execute, which is why it answers in that inspector's own\n * vocabulary rather than inventing a second one.\n *\n * @returns The refusal, or `undefined` when the transaction is executable.\n */\nfunction checkExecutable(\n wireBase64: string,\n expected: { feePayer: string; recentBlockhash: string }\n): PartialRefusal | undefined {\n const parsed = parseSolanaWireTransaction(wireBase64);\n if (parsed.signers[0] !== expected.feePayer) {\n return {\n spawned: false,\n reason: 'fee_payer_mismatch',\n detail: `slot 0 is ${parsed.signers[0] ?? '(none)'}, not the quoted fee payer ${expected.feePayer}`,\n };\n }\n if (parsed.recentBlockhash !== expected.recentBlockhash) {\n return {\n spawned: false,\n reason: 'blockhash_mismatch',\n detail: `the transaction carries blockhash ${parsed.recentBlockhash}, not the quoted ${expected.recentBlockhash}`,\n };\n }\n const missing = parsed.unsigned.filter((signer) => signer !== expected.feePayer);\n if (missing.length > 0) {\n return {\n spawned: false,\n reason: 'missing_client_signature',\n detail: `these slots are still unsigned: ${missing.join(', ')}`,\n };\n }\n return undefined;\n}\n\n/** A job that produced no receipt, as the refusal to hand back to the caller. */\nfunction refusalOf(\n answer: Extract<JobAnswer<unknown>, { accepted: false }>\n): PartialRefusal {\n return {\n spawned: false,\n reason: answer.code,\n detail: answer.message,\n ...(answer.refusal ? { refusal: answer.refusal } : {}),\n };\n}\n\n/** The store composed something this client will not sign. */\nfunction malformed(detail: string): { ok: false; refused: PartialRefusal } {\n return { ok: false, refused: { spawned: false, reason: 'malformed_receipt', detail } };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,SAAS,eAAe;AACxB,SAAS,mBAAmB;AAM5B,IAAM,mBAAmB;AAEzB,IAAM,gBAAgB;AAEtB,IAAM,cAAc;AAEpB,IAAM,oBAAoB;AAE1B,IAAM,sBA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AAQ,CAAC,MAAM,SAAS,UAAU;AAC3C,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,aAAa,OAAO,QAAQ,CAAC,KAAK,QAAQ,8BAA8B,SAAS,QAAQ;AAAA,IACnG;AAAA,EACF;AACA,MAAI,OAAO,oBAAoB,SAAS,iBAAiB;AACvD,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,qCAAqC,OAAO,eAAe,oBAAoB,SAAS,eAAe;AAAA,IACjH;AAAA,EACF;AACA,QAAM,UAAU,OAAO,SAAS,OAAO,CAAC,WAAW,WAAW,SAAS,QAAQ;AAC/E,MAAI,QAAQ,SAAS,GAAG;AACtB,WAAO;AAAA,MACL,SAAS;AAAA,MACT,QAAQ;AAAA,MACR,QAAQ,mCAAmC,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC/D;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,UACP,QACgB;AAChB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,QAAQ,OAAO;AAAA,IACf,QAAQ,OAAO;AAAA,IACf,GAAI,OAAO,UAAU,EAAE,SAAS,OAAO,QAAQ,IAAI,CAAC;AAAA,EACtD;AACF;AAGA,SAAS,UAAU,QAAwD;AACzE,SAAO,EAAE,IAAI,OAAO,SAAS,EAAE,SAAS,OAAO,QAAQ,qBAAqB,OAAO,EAAE;AACvF;","names":["randomBytes","randomBytes"]}
@@ -0,0 +1,23 @@
1
+ import {
2
+ DEFAULT_HS_CONNECT_TIMEOUT_MS,
3
+ DEFAULT_RPC_CONNECT_TIMEOUT_MS,
4
+ RPC_POOL_IDLE_TIMEOUT_MS,
5
+ RPC_SOCKS_USERNAMES,
6
+ createChainRpcTransport,
7
+ createHiddenServiceTransport,
8
+ probeSocks5Proxy
9
+ } from "./chunk-LJSOTVUT.js";
10
+ import {
11
+ validateSocks5hUrl
12
+ } from "./chunk-32MD3CXE.js";
13
+ export {
14
+ DEFAULT_HS_CONNECT_TIMEOUT_MS,
15
+ DEFAULT_RPC_CONNECT_TIMEOUT_MS,
16
+ RPC_POOL_IDLE_TIMEOUT_MS,
17
+ RPC_SOCKS_USERNAMES,
18
+ createChainRpcTransport,
19
+ createHiddenServiceTransport,
20
+ probeSocks5Proxy,
21
+ validateSocks5hUrl
22
+ };
23
+ //# sourceMappingURL=socks-K6QOOWJ5.js.map
@@ -1,116 +1 @@
1
- /**
2
- * `socks5h://` URL parsing, kept apart from the transport that uses it.
3
- *
4
- * Config validation has to reject a bad proxy URL, and config validation runs
5
- * everywhere — including in a browser, where `./socks.js` must never be loaded
6
- * (it reaches for `node:module` on the first line). This module is pure.
7
- */
8
- /**
9
- * Parses and validates a `socks5h://` URL.
10
- *
11
- * Enforces the `socks5h://` scheme, not `socks5://`: the trailing `h` means the
12
- * *proxy* resolves the hostname. Under plain `socks5://` the client resolves it
13
- * locally first, which for a `.anyone` address means shipping the hidden service
14
- * you are about to talk to into a plaintext DNS query — the exact fact the
15
- * hidden service exists to withhold. Mirrors the connector's `transport/socks-url.ts`.
16
- */
17
- declare function validateSocks5hUrl(socksProxy: string): {
18
- host: string;
19
- port: number;
20
- };
21
-
22
- /**
23
- * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.
24
- *
25
- * A connector deployed as a hidden service is reachable only through a running
26
- * `anon` daemon's SOCKS5 port. Three separate things in this client have to go
27
- * through that port, and — annoyingly — each needs a different object to do it:
28
- *
29
- * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in
30
- * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,
31
- * which is why the `socks-proxy-agent` this package used to depend on cannot
32
- * serve this path at all.
33
- * - **Chain RPC** goes through viem, which calls the *global* `fetch` and accepts
34
- * no injected one. Its only opening is `http(url, { fetchOptions })`, so it
35
- * needs the same dispatcher handed to it as a fetch option (ADR 0002).
36
- * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and
37
- * therefore takes an `http.Agent` and nothing else.
38
- *
39
- * So this module builds one SOCKS connection primitive and wraps it three ways.
40
- * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.
41
- *
42
- * `undici` is an optional dependency for exactly this reason: Node bundles undici
43
- * internally but exposes it under no specifier (`require('undici')` is
44
- * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a
45
- * dispatcher cannot be constructed without the package. A dispatcher built by the
46
- * userland copy *is* honoured by Node's global `fetch`, which calls
47
- * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici
48
- * defines — and that is why the dependency is pinned to **undici 7, not 8**.
49
- * Node's handler changed shape: Node 22 (undici 6.22) passes the old
50
- * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)
51
- * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —
52
- * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.
53
- * undici 8 dropped the old shape, and on Node 22 every request through such a
54
- * dispatcher dies in `assertRequestHandler` with
55
- * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both
56
- * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not
57
- * widen the range to `^8` without re-running those on the oldest supported Node.
58
- *
59
- * NODE ONLY. This module is imported dynamically, never statically, from the
60
- * paths that need it; every Node built-in is pulled in through an ESM-safe
61
- * `require` built off `import.meta.url`, because this package builds as ESM with
62
- * these deps external and esbuild rewrites a bare `require` into a `__require`
63
- * shim that throws. A browser cannot reach a `.anyone` address by any means, so
64
- * a browser bundler must never follow an edge into this file.
65
- */
66
- /**
67
- * How long to wait for the proxy to build a circuit to the hidden service.
68
- *
69
- * `socks` defaults to 30s, which is too short: an introduction-point circuit to
70
- * a cold hidden service routinely takes longer, and a too-short connect timeout
71
- * turns "slow" into "unreachable".
72
- */
73
- declare const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120000;
74
- /** Options for {@link createHiddenServiceTransport}. */
75
- interface HiddenServiceTransportOptions {
76
- /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */
77
- connectTimeoutMs?: number;
78
- }
79
- /**
80
- * The three shapes of one proxy, plus the handle that shuts it down.
81
- *
82
- * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}
83
- * to route a client by hand; pass `socksProxy` instead to have the client build
84
- * this itself.
85
- */
86
- interface HiddenServiceTransport {
87
- /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */
88
- fetch: typeof fetch;
89
- /** A `ws` factory bound to the proxy, for the BTP carriage. */
90
- createWebSocket: (url: string) => unknown;
91
- /**
92
- * The undici dispatcher behind `fetch`, for handing to something that insists
93
- * on calling the global `fetch` itself — viem's HTTP transport, in practice
94
- * (`http(url, { fetchOptions: { dispatcher } })`).
95
- */
96
- dispatcher: unknown;
97
- /** Close the dispatcher's pool and the websocket agents' sockets. */
98
- close(): Promise<void>;
99
- }
100
-
101
- /**
102
- * Builds every proxy-bound object this client needs from one `socks5h://` URL.
103
- *
104
- * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not
105
- * installed — they are optional dependencies, so a consumer who never touches
106
- * a hidden service never pays for them.
107
- */
108
- declare function createHiddenServiceTransport(socksProxy: string, options?: HiddenServiceTransportOptions): HiddenServiceTransport;
109
- /**
110
- * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a
111
- * client configured for a hidden service must not quietly fall back to clearnet,
112
- * and finding out at packet time costs a signed claim.
113
- */
114
- declare function probeSocks5Proxy(socksProxy: string, timeoutMs?: number): Promise<void>;
115
-
116
- export { DEFAULT_HS_CONNECT_TIMEOUT_MS, type HiddenServiceTransport, type HiddenServiceTransportOptions, createHiddenServiceTransport, probeSocks5Proxy, validateSocks5hUrl };
1
+ export { D as DEFAULT_HS_CONNECT_TIMEOUT_MS, g as DEFAULT_RPC_CONNECT_TIMEOUT_MS, H as HiddenServiceTransport, f as HiddenServiceTransportOptions, R as RPC_POOL_IDLE_TIMEOUT_MS, h as RPC_SOCKS_USERNAMES, i as createChainRpcTransport, j as createHiddenServiceTransport, p as probeSocks5Proxy, v as validateSocks5hUrl } from '../hidden-service-BsBH2HNi.js';
@@ -1,13 +1,21 @@
1
1
  import {
2
2
  DEFAULT_HS_CONNECT_TIMEOUT_MS,
3
+ DEFAULT_RPC_CONNECT_TIMEOUT_MS,
4
+ RPC_POOL_IDLE_TIMEOUT_MS,
5
+ RPC_SOCKS_USERNAMES,
6
+ createChainRpcTransport,
3
7
  createHiddenServiceTransport,
4
8
  probeSocks5Proxy
5
- } from "../chunk-GOLBDUNV.js";
9
+ } from "../chunk-LJSOTVUT.js";
6
10
  import {
7
11
  validateSocks5hUrl
8
12
  } from "../chunk-32MD3CXE.js";
9
13
  export {
10
14
  DEFAULT_HS_CONNECT_TIMEOUT_MS,
15
+ DEFAULT_RPC_CONNECT_TIMEOUT_MS,
16
+ RPC_POOL_IDLE_TIMEOUT_MS,
17
+ RPC_SOCKS_USERNAMES,
18
+ createChainRpcTransport,
11
19
  createHiddenServiceTransport,
12
20
  probeSocks5Proxy,
13
21
  validateSocks5hUrl
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toon-protocol/client",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "TOON client: pay for HTTP requests per request over ILP, with EVM and Solana payment channels",
5
5
  "license": "MIT",
6
6
  "author": "Jonathan Green",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/transport/socks.ts"],"sourcesContent":["/**\n * The hidden-service carriage: one SOCKS5h proxy, everything that must ride it.\n *\n * A connector deployed as a hidden service is reachable only through a running\n * `anon` daemon's SOCKS5 port. Three separate things in this client have to go\n * through that port, and — annoyingly — each needs a different object to do it:\n *\n * - **The client edge** (`GET /ilp`, `POST /ilp`) goes through `fetch`, which in\n * Node is undici and takes a **dispatcher**. It does not take an `http.Agent`,\n * which is why the `socks-proxy-agent` this package used to depend on cannot\n * serve this path at all.\n * - **Chain RPC** goes through viem, which calls the *global* `fetch` and accepts\n * no injected one. Its only opening is `http(url, { fetchOptions })`, so it\n * needs the same dispatcher handed to it as a fetch option (ADR 0002).\n * - **The BTP carriage** goes through `ws`, which is `node:http` underneath and\n * therefore takes an `http.Agent` and nothing else.\n *\n * So this module builds one SOCKS connection primitive and wraps it three ways.\n * The SOCKS5 handshake itself is `socks`'s job; all we supply is the socket.\n *\n * `undici` is an optional dependency for exactly this reason: Node bundles undici\n * internally but exposes it under no specifier (`require('undici')` is\n * `MODULE_NOT_FOUND`, `node:undici` is `ERR_UNKNOWN_BUILTIN_MODULE`), so a\n * dispatcher cannot be constructed without the package. A dispatcher built by the\n * userland copy *is* honoured by Node's global `fetch`, which calls\n * `dispatcher.dispatch(opts, handler)` with a handler its own bundled undici\n * defines — and that is why the dependency is pinned to **undici 7, not 8**.\n * Node's handler changed shape: Node 22 (undici 6.22) passes the old\n * `onConnect`/`onHeaders`/`onData`/`onComplete` handler, Node 26 (undici 8.9)\n * passes the new `onRequestStart`/`onResponseStart` one. undici 7 accepts both —\n * its `UnwrapHandler.unwrap` passes an old-style handler through untouched.\n * undici 8 dropped the old shape, and on Node 22 every request through such a\n * dispatcher dies in `assertRequestHandler` with\n * `InvalidArgumentError: invalid onRequestStart method`. Verified green on both\n * Node 22.21 and Node 26.7 against the fake proxy in `socks.test.ts`; do not\n * widen the range to `^8` without re-running those on the oldest supported Node.\n *\n * NODE ONLY. This module is imported dynamically, never statically, from the\n * paths that need it; every Node built-in is pulled in through an ESM-safe\n * `require` built off `import.meta.url`, because this package builds as ESM with\n * these deps external and esbuild rewrites a bare `require` into a `__require`\n * shim that throws. A browser cannot reach a `.anyone` address by any means, so\n * a browser bundler must never follow an edge into this file.\n */\n\nimport { createRequire } from 'node:module';\nimport { validateSocks5hUrl } from './socks-url.js';\nimport type * as netModule from 'node:net';\nimport type * as streamModule from 'node:stream';\nimport type * as tlsModule from 'node:tls';\nimport type * as httpModule from 'node:http';\nimport type * as httpsModule from 'node:https';\nimport type * as socksModule from 'socks';\nimport type * as undiciModule from 'undici';\nimport type WSModule from 'ws';\n\n// ESM-safe require: this file builds as ESM with `undici`/`socks`/`ws` external,\n// so a bare `require(...)` would become a throwing `__require` shim in the\n// published bundle. Building a real require off `import.meta.url` keeps the\n// synchronous lookups below working. (The same pattern the deleted `socks5.ts`\n// carried, for the same reason — it was found in production.)\nconst nodeRequire = createRequire(import.meta.url);\n\n/**\n * How long to wait for the proxy to build a circuit to the hidden service.\n *\n * `socks` defaults to 30s, which is too short: an introduction-point circuit to\n * a cold hidden service routinely takes longer, and a too-short connect timeout\n * turns \"slow\" into \"unreachable\".\n */\nexport const DEFAULT_HS_CONNECT_TIMEOUT_MS = 120_000;\n\n/** Options for {@link createHiddenServiceTransport}. */\nexport interface HiddenServiceTransportOptions {\n /** Circuit-build timeout, ms. Default {@link DEFAULT_HS_CONNECT_TIMEOUT_MS}. */\n connectTimeoutMs?: number;\n}\n\n/**\n * The three shapes of one proxy, plus the handle that shuts it down.\n *\n * Spread `fetch` and `createWebSocket` into a {@link ../client/types.js!ToonClientConfig}\n * to route a client by hand; pass `socksProxy` instead to have the client build\n * this itself.\n */\nexport interface HiddenServiceTransport {\n /** `fetch`, bound to the proxy. Returns ordinary global `Response` objects. */\n fetch: typeof fetch;\n /** A `ws` factory bound to the proxy, for the BTP carriage. */\n createWebSocket: (url: string) => unknown;\n /**\n * The undici dispatcher behind `fetch`, for handing to something that insists\n * on calling the global `fetch` itself — viem's HTTP transport, in practice\n * (`http(url, { fetchOptions: { dispatcher } })`).\n */\n dispatcher: unknown;\n /** Close the dispatcher's pool and the websocket agents' sockets. */\n close(): Promise<void>;\n}\n\nexport { validateSocks5hUrl } from './socks-url.js';\n\n/** The one primitive: a TCP socket to `destination`, dialled through the proxy. */\nasync function socksConnect(\n proxy: { host: string; port: number },\n destination: { host: string; port: number },\n timeoutMs: number\n): Promise<netModule.Socket> {\n const { SocksClient } = nodeRequire('socks') as typeof socksModule;\n const { socket } = await SocksClient.createConnection({\n proxy: { host: proxy.host, port: proxy.port, type: 5 },\n command: 'connect',\n destination,\n timeout: timeoutMs,\n });\n return socket;\n}\n\n/** Default port for a scheme, when the URL does not name one. */\nfunction portFor(protocol: string, port: string | number | null | undefined): number {\n if (port !== undefined && port !== null && port !== '' && Number.isFinite(Number(port))) return Number(port);\n return protocol === 'https:' || protocol === 'wss:' ? 443 : 80;\n}\n\n/**\n * Builds every proxy-bound object this client needs from one `socks5h://` URL.\n *\n * @throws {Error} if the URL is not `socks5h://`, or if `undici`/`socks` are not\n * installed — they are optional dependencies, so a consumer who never touches\n * a hidden service never pays for them.\n */\nexport function createHiddenServiceTransport(\n socksProxy: string,\n options: HiddenServiceTransportOptions = {}\n): HiddenServiceTransport {\n const proxy = validateSocks5hUrl(socksProxy);\n const timeoutMs = options.connectTimeoutMs ?? DEFAULT_HS_CONNECT_TIMEOUT_MS;\n\n const undici = requireOptional<typeof undiciModule>('undici', socksProxy);\n requireOptional<typeof socksModule>('socks', socksProxy);\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // The dispatcher. undici hands its `connect` hook the destination it wants a\n // socket to; we dial that through SOCKS instead of `net.connect`, and wrap it\n // in TLS ourselves when the scheme calls for it (undici's default connector\n // would have done that, and we have replaced it).\n const dispatcher = new undici.Agent({\n connect(\n connectOptions: { hostname: string; port?: string | number; protocol?: string; servername?: string },\n callback: (err: Error | null, socket: unknown) => void\n ) {\n const port = portFor(connectOptions.protocol ?? 'http:', connectOptions.port);\n socksConnect(proxy, { host: connectOptions.hostname, port }, timeoutMs).then((socket) => {\n socket.setNoDelay(true);\n if (connectOptions.protocol !== 'https:') return callback(null, socket);\n const secure = tls.connect({\n socket,\n servername: connectOptions.servername ?? connectOptions.hostname,\n ALPNProtocols: ['http/1.1'],\n });\n secure.once('secureConnect', () => callback(null, secure));\n secure.once('error', (err) => callback(err, null));\n }, (err: Error) => callback(err, null));\n },\n } as unknown as undiciModule.Agent.Options);\n\n // Node's global `fetch` honours a dispatcher built by this userland undici —\n // the `connect` hook above fires — and returns ordinary global `Response`\n // objects, which `undici.fetch` would not, and callers do compare those\n // against the global class. See the note on the undici 7 pin at the top of\n // this file: this line is what makes the major version load-bearing.\n // `dispatcher` is not in the standard `RequestInit`, and @types/node carries a\n // second copy of undici's types that does not structurally match the userland\n // one — hence the cast. The runtime behaviour is verified, the types are not\n // able to express it.\n const proxiedFetch = ((input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) =>\n globalThis.fetch(input, { ...init, dispatcher } as unknown as RequestInit)) as typeof fetch;\n\n const agents = createWebSocketAgents(proxy, timeoutMs);\n\n return {\n fetch: proxiedFetch,\n createWebSocket: (url: string) => {\n const WSClass = loadWebSocketClass();\n const secure = url.startsWith('wss:') || url.startsWith('https:');\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new (WSClass as any)(url, { agent: secure ? agents.https : agents.http });\n },\n dispatcher,\n async close(): Promise<void> {\n agents.http.destroy();\n agents.https.destroy();\n await dispatcher.close();\n },\n };\n}\n\n/**\n * `ws` speaks `node:http`, so it wants an `http.Agent` — one per scheme, since\n * an `https.Agent` is what puts TLS on the socket and an `http.Agent` is what\n * must not.\n */\nfunction createWebSocketAgents(\n proxy: { host: string; port: number },\n timeoutMs: number\n): { http: httpModule.Agent; https: httpsModule.Agent } {\n const http = nodeRequire('node:http') as typeof httpModule;\n const https = nodeRequire('node:https') as typeof httpsModule;\n const tls = nodeRequire('node:tls') as typeof tlsModule;\n\n // `createConnection` is the whole extension point: everything else about\n // pooling, keep-alive and request framing stays the stock agent's business.\n class SocksHttpAgent extends http.Agent {\n override createConnection(\n opts: httpModule.ClientRequestArgs,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n socksConnect(proxy, { host: String(opts.host), port: portFor('http:', opts.port) }, timeoutMs).then(\n (socket) => callback?.(null, socket),\n (err: Error) => callback?.(err, undefined as unknown as streamModule.Duplex)\n );\n return undefined;\n }\n }\n\n class SocksHttpsAgent extends https.Agent {\n override createConnection(\n opts: httpsModule.RequestOptions,\n callback?: (err: Error | null, stream: streamModule.Duplex) => void\n ): streamModule.Duplex | null | undefined {\n const fail = (err: Error): void => callback?.(err, undefined as unknown as streamModule.Duplex);\n socksConnect(proxy, { host: String(opts.host), port: portFor('https:', opts.port) }, timeoutMs).then(\n (socket) => {\n const secure = tls.connect({\n socket,\n servername: opts.servername ?? String(opts.host),\n });\n secure.once('secureConnect', () => callback?.(null, secure));\n secure.once('error', fail);\n },\n fail\n );\n return undefined;\n }\n }\n\n return {\n http: new SocksHttpAgent({ keepAlive: false }),\n https: new SocksHttpsAgent({ keepAlive: false }),\n };\n}\n\n/**\n * CJS/ESM interop: `require('ws')` yields the class directly, `{ default }`, or\n * `{ WebSocket }` depending on loader and bundler. Walk the ladder rather than\n * accepting a namespace object as a constructor and throwing cryptically later.\n */\nfunction loadWebSocketClass(): unknown {\n const mod = nodeRequire('ws') as typeof WSModule | { default?: unknown; WebSocket?: unknown };\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const candidate = mod as any;\n const WSClass =\n typeof candidate === 'function'\n ? candidate\n : typeof candidate.default === 'function'\n ? candidate.default\n : typeof candidate.WebSocket === 'function'\n ? candidate.WebSocket\n : null;\n if (WSClass === null) {\n throw new Error(\n \"The BTP carriage over a hidden service needs the `ws` package, and require('ws') \" +\n 'did not yield a constructor on .default, .WebSocket, or the module root.'\n );\n }\n return WSClass;\n}\n\n/** Loads an optional dependency, or explains what to install and why. */\nfunction requireOptional<T>(name: string, socksProxy: string): T {\n try {\n return nodeRequire(name) as T;\n } catch {\n throw new Error(\n `Reaching a hidden service needs the optional dependency \"${name}\", which is not installed. ` +\n `Run \\`npm install ${name}\\`, or drop socksProxy (${socksProxy}) and dial a clearnet connector.`\n );\n }\n}\n\n/**\n * Probes the proxy with a plain TCP connect. Fail-closed and fail-early: a\n * client configured for a hidden service must not quietly fall back to clearnet,\n * and finding out at packet time costs a signed claim.\n */\nexport async function probeSocks5Proxy(socksProxy: string, timeoutMs = 2000): Promise<void> {\n const { host, port } = validateSocks5hUrl(socksProxy);\n const net = nodeRequire('node:net') as typeof netModule;\n\n return new Promise<void>((resolve, reject) => {\n const socket = net.createConnection({ host, port }, () => {\n socket.destroy();\n resolve();\n });\n const fail = (why: string): void => {\n socket.destroy();\n reject(\n new Error(\n `No SOCKS5 proxy at ${host}:${port} (${why}). A hidden-service connector is ` +\n 'unreachable without one: start the Anyone Protocol `anon` daemon, or run ' +\n '`toon` which can start one for you.'\n )\n );\n };\n socket.setTimeout(timeoutMs, () => fail(`timed out after ${timeoutMs}ms`));\n socket.on('error', (err) => fail(err.message));\n });\n}\n"],"mappings":";;;;;AA6CA,SAAS,qBAAqB;AAgB9B,IAAM,cAAc,cAAc,YAAY,GAAG;AAS1C,IAAM,gCAAgC;AAiC7C,eAAe,aACb,OACA,aACA,WAC2B;AAC3B,QAAM,EAAE,YAAY,IAAI,YAAY,OAAO;AAC3C,QAAM,EAAE,OAAO,IAAI,MAAM,YAAY,iBAAiB;AAAA,IACpD,OAAO,EAAE,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,EAAE;AAAA,IACrD,SAAS;AAAA,IACT;AAAA,IACA,SAAS;AAAA,EACX,CAAC;AACD,SAAO;AACT;AAGA,SAAS,QAAQ,UAAkB,MAAkD;AACnF,MAAI,SAAS,UAAa,SAAS,QAAQ,SAAS,MAAM,OAAO,SAAS,OAAO,IAAI,CAAC,EAAG,QAAO,OAAO,IAAI;AAC3G,SAAO,aAAa,YAAY,aAAa,SAAS,MAAM;AAC9D;AASO,SAAS,6BACd,YACA,UAAyC,CAAC,GAClB;AACxB,QAAM,QAAQ,mBAAmB,UAAU;AAC3C,QAAM,YAAY,QAAQ,oBAAoB;AAE9C,QAAM,SAAS,gBAAqC,UAAU,UAAU;AACxE,kBAAoC,SAAS,UAAU;AACvD,QAAM,MAAM,YAAY,UAAU;AAMlC,QAAM,aAAa,IAAI,OAAO,MAAM;AAAA,IAClC,QACE,gB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