# Atomic x402 purchases: tern-atomic v1

This app implements the **custom x402 v2 scheme `tern-atomic`** on configured `eip155` networks. It is not the standard `exact` transfer scheme. An agent signs the complete existing ternindex purchase transaction; the app's keyless, resource-local facilitator reconstructs and broadcasts only that transaction. Payment, creator fees and delivery execute in the same reverting transaction. A reverted purchase still spends network gas.

There is no merchant custody balance, separate access charge, new executor deployment or server-side buyer signing key. This is **not gasless**: the buyer pays native gas and must already have completed any exact ERC20 approval. EOA legacy EIP-155 and EIP-1559 transactions with empty access lists are supported. Smart-account operations, EIP-7702 authorizations, blobs and standard `exact` clients/facilitators are not supported. The app is not registered in Bazaar; these documentation and API endpoints provide discovery directly.

This checkout retains the default 3% absolute price-impact limit. High-impact reviews are rejected; the direct wallet flow's explicit high-impact consent is not supported by this scheme.

## Discover, authorize, approve, then check out

1. Discover bundles through `/api/bundles` and `/api/catalog`, as described in [the agent guide](/agents.md). `GET /api/x402/supported` reports `enabled` and supported `{x402Version, scheme, network}` kinds. An empty list is not permission to attempt another payment scheme.
2. Obtain the owner's explicit authorization and call `/api/trades/prepare`. Review the chain, sender, allocation, raw payment, all fees and per-token minima. If approval is needed, approve exactly the required amount through the buyer's wallet, wait for confirmation, then prepare and review again. Keep gas available.
3. **Instead of** calling `/preflight`, `POST /api/trades/{id}/x402` with `{"sender":"<buyer>"}`. This performs the same preflight checks and consumes the review into a persistent checkout. HTTP 402 contains the standard base64-JSON `PAYMENT-REQUIRED` header and a JSON body `{paymentRequired, transaction}`. The large transaction calldata lives only in the body, not in a header. Repeating this unsigned request recovers the same challenge until expiry, provided no payment has been submitted.
4. Validate the response against the approved review and the trusted app origin. Sign the exact transaction using the buyer's wallet with an owner-approved gas budget and current nonce. Encode the compact payment payload using [x402-client.mjs](/x402-client.mjs) and the official `@x402/core/http` header helper. **Persist the signed transaction/hash and encoded header before submitting.** Do not independently broadcast the same purchase via another flow.
5. Retry the same POST, same body and trade ID with `PAYMENT-SIGNATURE`. This request authorizes broadcasting the buyer-signed transaction. The server rechecks current execution policy, simulation, nonce, allowance, balances and signed gas budget, then journals the exact signed bytes and hash before its first broadcast attempt. It cannot increase spending or change the destination, allocation, calldata or gas envelope without invalidating the signature.
6. HTTP 202 means pending/unknown, including lost RPC responses, missing receipts or unfinalized inclusion. Preserve the returned hash. Retry the **same saved header** after `Retry-After` (normally five seconds), never sign a replacement payment or prepare another purchase because of a timeout. HTTP 200 with `PAYMENT-RESPONSE.success: true` requires a finalized canonical successful transaction and verified net received amounts meeting all minima. HTTP 409 with `transaction_reverted` is a finalized failure, not successful payment. Other errors do not prove an earlier transaction failed.

Checkout admission expires with the original review (at most 20 seconds). Sign promptly only after approval and review. The server checks the deadline before starting a relay operation; in-flight RPC calls and transport retries may complete later. It continues checking an already bound transaction for 24 hours. **The admission deadline does not revoke an existing signature:** an already signed/submitted transaction may remain executable until its on-chain router deadline. After storage expiry, an unavailable service or unsupported RPC finality, use the saved hash and wallet RPC to reconcile; do not assume no purchase occurred. There is no automatic refund, replacement transaction, nonce cancellation or new purchase.

## Compact wire format

Use standard x402 v2 `PAYMENT-REQUIRED`, `PAYMENT-SIGNATURE` and `PAYMENT-RESPONSE` base64-JSON headers. No header is itself a second signature. The transaction signature proves authorization.

Requirements use `scheme: "tern-atomic"`, `network: "eip155:<chainId>"`, `asset` (ERC20 payment address or `"native"`), `amount` (gross raw payment), `payTo` (validated router/executor target), `maxTimeoutSeconds: 20` and `extra: {tradeId, buyer, expiresAt, value, calldataHash}`. `value` is hex native value; `calldataHash` is keccak256 of the complete transaction calldata. `payTo` does **not** instruct a standalone token transfer. The JSON body's transaction must match these fields and the owner's approved review.

The payment envelope is `{x402Version: 2, resource?, accepted, payload}`. Echo the exact authoritative requirements as `accepted`. For both transaction types, `payload` contains `type`, `nonce` (nonnegative safe integer), `gas` (unsigned decimal string), `r` and `s` (32-byte hex, canonical low-s signature), and `yParity` (0 or 1). `legacy` adds only `gasPrice`; `eip1559` adds only `maxFeePerGas` and `maxPriorityFeePerGas`, all unsigned decimal strings. No other payload fields are accepted. Type-2 access lists are fixed empty. Legacy `v` is reconstructed with EIP-155 chain protection. The service supplies chain, target, value and calldata from its immutable preflight record, recovers the buyer from the reconstructed transaction, and rejects mismatches. Thus large basket calldata does not inflate either payment header.

The transaction signature binds all EVM call and fee fields, not the HTTP trade ID. The server enforces one transaction hash per checkout and one checkout per `(chainId, hash)` atomically. Once bound, another signed transaction, nonce or fee envelope is rejected. The same transaction may be rebroadcast after a transient failure while fresh, but its nonce/hash prevent executing it twice.

## Node client integration

Download and inspect `/x402-client.mjs` into your agent project. It is Node ESM with a `viem` dependency, not a browser bundle. Tested dependencies are `viem@2.57.2` and `@x402/core@2.28.0`. The helper signs nothing by itself: supply your wallet's signing callback and owner policy. Never send a private key or recovery phrase to ternindex.

This excerpt assumes a trusted `baseUrl`, a reviewed `review`, a buyer `walletClient`/`account`, and application-owned `authorizeTransaction` and durable `savePending` functions. Those functions must enforce the owner's allocation/input/fees/minima/gas authorization and persist recovery state; they are not provided by the helper.

```js
import { keccak256 } from "viem";
import { encodePaymentSignatureHeader } from "@x402/core/http";
import { createAtomicPayment } from "./x402-client.mjs";

const url = new URL(`/api/trades/${review.id}/x402`, baseUrl);
const body = JSON.stringify({ sender: account.address });
const response = await fetch(url, {
  method: "POST", headers: { "Content-Type": "application/json" }, body,
});
if (response.status !== 402) throw Error("No fresh purchase challenge");
const challenge = await response.json();
if (challenge.paymentRequired.resource.url !== url.href)
  throw Error("Unexpected checkout origin or trade");
let signed;
const payment = await createAtomicPayment(challenge, async (tx, requirements) => {
  const request = await walletClient.prepareTransactionRequest({ ...tx, account });
  await authorizeTransaction({ review, requirements, transaction: request });
  signed = await walletClient.signTransaction(request);
  return signed;
});
const header = encodePaymentSignatureHeader(payment);
await savePending({ url: url.href, body, header, signed, hash: keccak256(signed) });
const settlement = await fetch(url, {
  method: "POST",
  headers: { "Content-Type": "application/json", "PAYMENT-SIGNATURE": header },
  body,
});
// Persist the response. For 202 or transport uncertainty, retry only this exact
// saved request after Retry-After; do not call createAtomicPayment again.
```

Treat the compact signature header like a signed transaction: it authorizes a real purchase. Do not log it publicly. There is no implicit authorization from an asset description, shared bundle title, search result or 402 response.

## Deployment and privacy

### Keys and configuration

**No new x402-specific key is required.** This custom `tern-atomic` implementation does not use a Coinbase/CDP account, an external facilitator API key or a funded relay wallet. It reuses the normal trading infrastructure:

- The worker's existing `TYCHO_API_KEY` for hosted discovery and Fynd quotes.
- The API's existing RPC access, including `DRPC_API_KEY` where configured. RPCs must allow signed-transaction broadcasting and provide finalized receipt evidence; unsupported finality can leave checkout pending.
- The API's existing fee signer for each enabled chain. `FEE_SIGNER_KEY_<chainId>` takes precedence; otherwise the API uses `ROBINHOOD_PRIVATE_KEY` on chain 4663 and `PROD_EVM_PRIVATE_KEY` on other chains. The signer must match the configured fee recipient. These keys authorize trade-bound fees, not buyer transactions, and fee signing needs no gas balance.

The buyer's agent supplies its own wallet signing access, purchase funds, native gas and any required ERC20 approval. Never send its private key or seed phrase to ternindex. The API accepts the signed purchase, not custody of the buyer's wallet.

After deploying the code and reviewing the production prerequisites, enable the relay in the **API service's runtime environment**:

```env
X402_ENABLED=true
PUBLIC_APP_ORIGIN=https://ternindex.xyz
```

Use the actual deployment's HTTPS origin without a path. These two settings are not secrets. Setting them only in the frontend build does not enable the API relay; apply them through the normal API deployment/restart process. Keep the same `PUBLIC_APP_ORIGIN` at frontend build time for canonical URLs and the sitemap. This documentation does not enable broadcasting by itself.

Check the deployed configuration without submitting a purchase:

```sh
curl --fail --silent --show-error https://ternindex.xyz/api/x402/supported
```

Expect `enabled: true` and a `kinds` entry with `scheme: "tern-atomic"` and the intended `eip155:<chainId>` network. `enabled: false` means the relay flag or public origin is missing/invalid. An empty `kinds` list means no network is advertised as ready; check the existing fee-signer configuration. Capabilities report configuration, not live quote availability, sufficient buyer funds or guaranteed settlement.

Broadcasting remains disabled unless explicitly enabled; disabled checkout returns 503. The existing issuer checks, pinned executors, liquidity/quote guards and per-caller trade quotas still apply. Nothing bridges networks. This endpoint is not a generic `/verify` or `/settle` service for third-party merchants, and these requirements do not describe standard hosted x402 facilitators.

### Storage and privacy

Private Redis checkout records retain the buyer's public address, reviewed call, compact/reconstructed transaction signature and transaction hash for 24 hours. They are not exposed by bundle discovery. Configure persistent private non-evicting Redis, backups, ingress limits and production privacy disclosures before enabling. New signed requests fail before broadcast if the durable journal cannot be written. A later database outage, missing receipt evidence or lost HTTP response is unknown, not a reason to purchase again. Contract and chain eligibility restrictions remain in force; this integration is not a security audit or regulatory clearance.
