@toon-protocol/client 5.0.2 → 5.1.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.
@@ -32,8 +32,8 @@ import {
32
32
  resolveConfig,
33
33
  send,
34
34
  toEnvelopeRequest
35
- } from "./chunk-PCPG4CIS.js";
36
- import "./chunk-WJKJ6Y4N.js";
35
+ } from "./chunk-BHGJXLS7.js";
36
+ import "./chunk-6O5OXJVR.js";
37
37
  import "./chunk-32MD3CXE.js";
38
38
  export {
39
39
  BeforePayRefusedError,
@@ -70,4 +70,4 @@ export {
70
70
  send,
71
71
  toEnvelopeRequest
72
72
  };
73
- //# sourceMappingURL=client-WCAXMQWM.js.map
73
+ //# sourceMappingURL=client-DF3LZVLC.js.map
package/dist/index.d.ts CHANGED
@@ -6325,11 +6325,12 @@ interface JobSender {
6325
6325
  * Where a job goes: who pays for it, which route terminates it, and — on a
6326
6326
  * FORWARDED route — whose key the payload is sealed to.
6327
6327
  *
6328
- * The store and the gas station are different nodes with different connectors
6329
- * and different channels, so a ceremony spanning both takes two endpoints. One
6330
- * client can serve both only when it is attached to a node that forwards to
6331
- * each, in which case both endpoints name that client and `sealTo` names the
6332
- * far node — see `docs/devnet.md`.
6328
+ * The store and the gas station MAY be different nodes with different
6329
+ * connectors and different channels, so a ceremony spanning both takes two
6330
+ * endpoints. Where one connector terminates both — as the devnet's does, at
6331
+ * `https://toonprotocol.dev` — both endpoints name the same client and no
6332
+ * `sealTo` is needed. Where a node only forwards to one of them, `sealTo` names
6333
+ * the far node.
6333
6334
  */
6334
6335
  interface JobEndpoint {
6335
6336
  /** Pays for the request. */
@@ -6843,10 +6844,12 @@ interface DevnetNode {
6843
6844
  requiredTransport?: 'http' | 'btp';
6844
6845
  }
6845
6846
  declare const DEVNET: {
6847
+ /** The devnet's single connector. `DEVNET.store.url` and the rest all equal it. */
6848
+ readonly connector: "https://toonprotocol.dev";
6846
6849
  /**
6847
- * The store node: an Arweave-backed object store behind `g.toon.store`, and
6848
- * the one route here that METERS — 1000 base units (0.001 USDC) plus 10 per
6849
- * kibibyte of sealed payload, so no packet on it costs only `price`.
6850
+ * The store: an Arweave-backed object store behind `g.toon.store`, and a
6851
+ * route that METERS — 1000 base units (0.001 USDC) plus 10 per kibibyte of
6852
+ * sealed payload, so no packet on it costs only `price`.
6850
6853
  */
6851
6854
  readonly store: {
6852
6855
  url: string;
@@ -6855,8 +6858,8 @@ declare const DEVNET: {
6855
6858
  pricePerKib: bigint;
6856
6859
  };
6857
6860
  /**
6858
- * The gas station behind `g.toon.gas`, priced flat at 1000 base units.
6859
- * Reachable directly, or through the relay at `g.toon.relay.gas`.
6861
+ * The gas station behind `g.toon.gas`, priced flat at 1000 base units. Also
6862
+ * addressable as `g.toon.relay.gas` at the same price, on the same connector.
6860
6863
  */
6861
6864
  readonly gas: {
6862
6865
  url: string;
@@ -6864,7 +6867,7 @@ declare const DEVNET: {
6864
6867
  price: bigint;
6865
6868
  };
6866
6869
  /**
6867
- * The relay node behind `g.toon.relay`, priced at 1 base unit. Its route is
6870
+ * The relay behind `g.toon.relay`, priced at 1 base unit. Its route is
6868
6871
  * pinned to **BTP**: an HTTP one-shot to it is refused with the same terms
6869
6872
  * document an unpaid request gets, carrying `requiredTransport` in
6870
6873
  * `extensions.toon.info`.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  loadKeystore,
9
9
  openKeystore,
10
10
  writeKeystoreFile
11
- } from "./chunk-2DGVNDKA.js";
11
+ } from "./chunk-VHP6XLM3.js";
12
12
  import {
13
13
  ACCUMULATED_COST_HEADER,
14
14
  ACCUMULATED_COST_PROTOCOL,
@@ -223,7 +223,7 @@ import {
223
223
  trimTrailingSlashes,
224
224
  withRetry,
225
225
  withdrawSvmBatchChannel
226
- } from "./chunk-PCPG4CIS.js";
226
+ } from "./chunk-BHGJXLS7.js";
227
227
  import {
228
228
  DEVNET,
229
229
  HS_HOSTNAME_MAX_LENGTH,
@@ -240,7 +240,7 @@ import {
240
240
  isHiddenServiceUrl,
241
241
  isRoutableHsHostname,
242
242
  validateMnemonic
243
- } from "./chunk-WJKJ6Y4N.js";
243
+ } from "./chunk-6O5OXJVR.js";
244
244
  import {
245
245
  validateSocks5hUrl
246
246
  } from "./chunk-32MD3CXE.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,mBAAmB;AA+C5B,SAAS,eAAe,OAA6C;AACnE,SAAO,KAAK,UAAU;AAAA,IACpB;AAAA,IACA,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,EACR,CAAC;AACH;AAOO,SAAS,cAAc,QAAkC;AAC9D,QAAM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,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":[]}
1
+ {"version":3,"sources":["../src/jobs/job-event.ts","../src/jobs/send-job.ts","../src/jobs/receipts.ts","../src/jobs/ant-spawn.ts"],"sourcesContent":["/**\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 MAY be different nodes with different\n * connectors and different channels, so a ceremony spanning both takes two\n * endpoints. Where one connector terminates both — as the devnet's does, at\n * `https://toonprotocol.dev` — both endpoints name the same client and no\n * `sealTo` is needed. Where a node only forwards to one of them, `sealTo` names\n * the far node.\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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gBACP,YACA,UAC4B;AAC5B,QAAM,SAAS,2BAA2B,UAAU;AACpD,MAAI,OAAO,QAAQ,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":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toon-protocol/client",
3
- "version": "5.0.2",
3
+ "version": "5.1.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",