Skip to content
PanmoniPublic

About

The check agents run before they pay — x402-paid risk checks on Hedera (ETHGlobal Agentic Markets)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Preflight ✈️

The check agents run before they pay.

Preflight is a self-funding, x402-paid risk-check agent on Hedera. Before an agent pays a counterparty, it asks Preflight for a risk verdict and pays a fraction of a cent for the answer.

Built for ETHGlobal Agentic Markets (Dec 3–6, 2026), From Scratch track.

Use it

Copy-paste for a buyer agent on Hedera testnet (@x402/core, @x402/hedera):

import { x402Client, x402HTTPClient } from "@x402/core/client";
import { createClientHederaSigner, PrivateKey } from "@x402/hedera";
import { ExactHederaScheme } from "@x402/hedera/exact/client";

// PAYER_KEY is DER-encoded. For a raw hex ECDSA key, use PrivateKey.fromStringECDSA instead.
const signer = createClientHederaSigner(process.env.PAYER_ACCOUNT_ID!, PrivateKey.fromStringDer(process.env.PAYER_KEY!), { network: "hedera:testnet" });
const http = new x402HTTPClient(new x402Client().register("hedera:testnet", new ExactHederaScheme(signer)));

async function preflightToken(tokenId: string, tier: "quick" | "standard" = "quick") {
  const url = `${process.env.PREFLIGHT_URL}/v1/check/token`;
  const body = JSON.stringify({ tokenId, tier });
  const post = (h: Record<string, string> = {}) => fetch(url, { method: "POST", headers: { "content-type": "application/json", ...h }, body });
  const unpaid = await post();
  const terms = http.getPaymentRequiredResponse((h) => unpaid.headers.get(h), await unpaid.json().catch(() => undefined));
  const paid = await post(http.encodePaymentSignatureHeader(await http.createPaymentPayload(terms)));
  // Fail closed: a 503 (LLM down, retry as Quick) or any error is not a pass.
  if (!paid.ok) throw new Error(`Preflight check failed (${paid.status}): ${await paid.text()}`);
  return paid.json(); // { verdict, score, confidence, reasons, evidence, signature, ... }
}

const check = await preflightToken("0.0.429274");
if (check.verdict === "block") throw new Error(`Preflight blocked it: ${check.reasons.join(" ")}`);

How it differs

Two npm packages already use the name. Preflight does a different job from each:

Package What it does What Preflight adds
preflight-x402 A CLEAR / HOLD / ABORT gate for x402 payments Hedera-native checks: HTS admin, freeze, wipe and supply keys, custom fees, holder concentration
@paystage/preflight Drainer checks Verdicts that cite their evidence, with HashScan and mirror-node links, signed by a key that holds no funds

Preflight is also an agent with its own books. It earns from every check and pays for its own inputs, and every revenue and cost row is public (see The books). Its npm package is preflight-agent.

Live

Each value is filled in as it goes live. "Pending" names what produces it.

What Value
Agent account, testnet Pending: PREFLIGHT_ACCOUNT_ID once funded
Agent account, mainnet Pending: PREFLIGHT_MAINNET_ACCOUNT_ID once funded
Service Pending: PUBLIC_BASE_URL once deployed
Ledger Pending: <service>/v1/ledger once deployed
HCS topic Pending: HCS_TOPIC_ID, the public topic for policy changes, ledger rows and receipts once HCS posting is live
ERC-8004 identity (testnet) Pending: the agent ID pnpm identity:register --send prints
HCS-14 UAID (mainnet) Pending: the UAID pnpm identity:uaid prints
Directory listing Pending: the HOL link pnpm directory:register --send prints
ENS preflight.eth on Sepolia, pending registration
npm preflight-agent, pending publish
Label set Pending v1 (see Label set)
  • Pre-event plan: docs/planning/
  • AI usage: documented per file in AI_USAGE.md (added during the build)

Integrate it

import { preflightAgentPlugin } from "preflight-agent";
import { HederaLangchainToolkit } from "@hashgraph/hedera-agent-kit-langchain";
const toolkit = new HederaLangchainToolkit({ client, configuration: { plugins: [preflightAgentPlugin] } });

The npm package preflight-agent is a Hedera Agent Kit plugin (check_token, check_address) plus a plain fetch client for teams without the kit. Each check is paid over x402 from the caller's own account.

Run it

Node 24 and pnpm.

pnpm install
cp env.example .env           # set PREFLIGHT_ACCOUNT_ID to the agent's testnet account
pnpm start                    # reads .env if present

POST /v1/check/token with {"tokenId":"0.0.429274"} (or /v1/check/address with {"address":"0.0.x"}) returns HTTP 402 and x402 payment terms. Paid, it returns the check result. Payment settles in USDC on Hedera testnet through x402.org/facilitator, with Blocky402 testnet as backup. A second instance runs on Hedera mainnet, settling real USDC (0.0.456858) through Blocky402 (api.blocky402.com), with its own account, keys and ledger; the testnet one stays up for free integration (docs/deploy.md).

Paid flow: verify → claim the payment's transaction ID → run the check → settle → respond. A replayed payment gets the cached result and does no new work. Rate limits run per IP before the 402 and per payer after it.

Architecture

One TypeScript service (Node 24, Express) holds the agent's account and runs everything. Its only outside dependencies are the x402 facilitators, the Hedera mirror node, the LLM providers and the data sellers it pays.

flowchart LR
  buyer["Buyer agent"] -->|"POST /v1/check/token"| rl["Per-IP rate limit"]
  rl --> pay["x402 paywall<br/>verify · claim · settle"]
  pay <-->|"verify, settle"| fac["x402 facilitator<br/>x402.org, Blocky402"]
  pay --> engine["Token check<br/>rules set verdict and score"]
  engine -->|"token, keys, fees, holders"| mirror["Hedera mirror node"]
  engine -->|"Standard: reasons only"| llm["DeepSeek on DeepInfra<br/>Claude Haiku fallback"]
  engine --> sign["Ed25519 signer<br/>holds no funds"]
  sign -->|"signed result"| buyer
  pay -->|"revenue row, same transaction"| db[("SQLite<br/>ledger · consumed payments<br/>spend cap · HCS outbox")]
  llm -.->|"debit cap first, then cost row"| db
  host["Hosting accrual"] -->|"one cost row per day"| db
  spend["pnpm buy: x402 data"] -->|"debit cap first"| db
  spend -->|"USDC on Hedera"| seller["Data seller<br/>hbar402"]
  db -->|"GET /v1/ledger"| public["Anyone"]
  alert["Balance monitor"] -->|"below one day of costs"| ntfy["ntfy alert"]
  policy["Adaptive policy<br/>runway mode, demand price"] -->|"USDC balance"| mirror
  policy -->|"mode and live price"| pay
  policy -->|"each change"| db
Loading
  • Payment before work. The paywall verifies the payment, claims its transaction ID, runs the check, settles, then responds. A failed settle means no answer and no revenue row.
  • Rules decide; the model explains. The LLM never sets the verdict or the score.
  • Every spend debits the hourly cap first, in one conditional UPDATE.
  • Identity is static. The agent card, ERC-8004 entry, HOL listing and ENS name all point at the same service and payee (see Identity).

Token check

Ask it before you buy or accept an HTS token. Send {"tokenId": "0.0.x", "tier": "quick"} or "tier": "standard"; Quick is the default.

Tier What runs Price
Quick Rules on mirror-node data: admin, freeze, wipe, supply, pause, KYC and fee-schedule keys; fixed, fractional and royalty fees; top-10 holder share; token age; deleted or paused $0.005
Standard The same rules and score, with reasons written by DeepSeek V4.1 Flash (Claude Haiku 5.5 as fallback), which also reads the name and memo for scam patterns $0.02

The rules alone set the verdict and score; the model only writes the reasons. The response holds verdict (allow / warn / block), score (risk, 0–100), confidence, reasons, findings, evidence (HashScan and mirror-node links), checkId, labelSetVersion, llm (the model that wrote the reasons, not_used, or unavailable) and signature. A clean token gets "no evidence of risk", never "safe".

  • Signature. Ed25519 over the canonical JSON of the result without signature, from a key that holds no funds. Check it with verifySignedResult in src/signing.ts.
  • LLM down. If both providers are down, a Standard request gets 503 with an offer of Quick at the Quick price, and the payment is not settled. The same holds when no LLM key is set, and when this hour's spend cap refuses the LLM call; the message then names the cap.
  • LLM answers badly. If a model answers but its reasons fail to parse twice (bad JSON, a link, or the word "safe"), the rules' reasons are served with llm: "unavailable" at the Standard price, since the model calls were made. A token ID that does not exist gets its rules answer on either tier with no model call.
  • Token counts. Every LLM call logs an llm_usage line with its input and output tokens.

The buyer snippet is at the top, under Use it.

Address check

Ask it before you pay an account. POST /v1/check/address with {"address": "0.0.x"} or a 0x EVM address, and an optional tier. Same tiers, prices, signature and failure handling as the token check.

Tier What runs Price
Quick Rules on mirror-node data: account age; key structure (no key yet, key list or threshold key); recent activity (none, or dormant 180+ days); smart contract or not; deleted; label-set hits; past Preflight verdicts on the account $0.005
Standard The same rules and score, with reasons written by the same models, which also sum up the pattern of the last 25 transactions $0.02
  • Label evidence decides first. A tier 1–3 label-set hit blocks. Tier 5 (exposure) warns at least, and blocks when other signals add up. Tier 4 (owner-attested clean) allows, unless a tier 1–3 or tier 5 hit or a deleted account outranks it. Every hit is listed in labels with its tier, label, category, source, source URL and the set version. Run with LABEL_SET_VERSION=none and the response says labelSetVersion: "none", confidence drops to medium, and a reason says no lists were checked.
  • Past verdicts are reported, never scored, so one verdict cannot feed the next.
  • Unknown addresses. An unknown 0.0.x, or its long-zero 0x form, blocks: a payment to it would fail. An unknown EVM alias warns: a payment would create a new account with no history. Label hits still count there, since a sanctioned ETH address usually has no Hedera account yet. As with an unknown token, an unknown address gets its rules answer on either tier with no model call, at the price of the tier asked.
  • Standard reasons. Label-set and critical findings keep the rules' own wording, and the model is told which reads failed, so it cannot call unread data clean.
  • The response carries account: {id, evmAddress} in place of token; everything else matches.

For a buyer agent, reuse preflightToken above with the URL /v1/check/address and the body { address, tier }.

Transaction check (Deep)

Ask it before you sign. POST /v1/check/tx with {"transaction": "<bytes>"}, where the bytes are a frozen, unsigned Hedera transaction in hex (with or without 0x) or base64. That is what the Hedera Agent Kit returns in RETURN_BYTES mode. Deep is the only tier, at $0.10 (PRICE_DEEP_USD). Bytes that do not decode get a 400 before the paywall, so they are never charged.

  • Decode. The Hiero SDK reads the payer, memo, fee cap, HBAR, token and NFT transfers, allowances, key changes, treasury moves, account deletion and contract calls. The rules read every entry. The response and the model see the first 25 of each list, and the response says when it cut one.
  • Rules. An account key change or an account deletion blocks. Allowance grants warn: HBAR, token, an effectively unlimited amount, every serial of an NFT, or a contract call to approve, setApprovalForAll or increaseAllowance. A grant of named NFT serials is noted. Token key and treasury changes warn too. A transaction type that is not decoded in detail warns at low confidence, and so does a contract call whose effect is not decoded. A debit from an account other than the fee payer warns, since that account must sign too. Tokens and NFTs leaving the payer are stated as findings.
  • History. The payer's HBAR outflow is compared with the largest it sent in its last 25 transactions: more than 10 times that warns, a first outflow is noted. Token amounts are not compared, and the response says so. If the mirror node fails, the route answers 500 and does not settle; if the account body carries no history, the check runs at medium confidence.
  • Explanation. The model's first reason says what the transaction does; every scored finding keeps the rules' own wording. The decoded transaction and the payer's recent transactions go to the LLM provider, as an address check's do. If the model's answer will not parse, the rules' reasons are served with llm: "unavailable", charged at the Deep price as Standard is. If every model is down or the spend cap refuses, the route answers 503 and does not settle. No Quick tier is offered, since none exists for this check.
  • Binding. The signed result carries transaction.bytesSha256, the SHA-256 of the exact unsigned bytes submitted. Hash the bytes you are about to sign and compare, before signing: signatures change the bytes.
pnpm test     # unit and payment-flow tests
pnpm smoke    # one paid testnet call against the running service; prints the HashScan link

The smoke script pays from SMOKE_PAYER_ACCOUNT_ID, a funded testnet buyer account that holds testnet USDC, separate from the agent's account.

Agent check

Ask it before you pay another agent. Is it who it says it is, and does it deliver? POST /v1/check/agent takes exactly one of these, plus an optional tier:

  • {"agentId": 12}: an agent ID in the ERC-8004 IdentityRegistry on Hedera testnet (0x8004A818…BD9e). ERC-8004 has no Hedera mainnet deployment, so these reads go to testnet whichever network Preflight serves.
  • {"uaid": "uaid:aid:…"}: an HCS-14 UAID, resolved through the HOL Registry Broker.

Same prices, signature and paywall as the other checks. No model runs on this check.

Tier What runs Price
Quick The identity resolves: ERC-8004 ownerOf, tokenURI and agent wallet, plus whether the registration file is an ERC-8004 file that names this agent ID back; or the UAID's listing and status in the broker $0.005
Standard Adds, for ERC-8004: reputation feedback (getSummary over the agent's clients in the ReputationRegistry) and the USDC payments its wallet received in its last 100 transactions $0.02
  • An identity that does not resolve blocks. A file that names another agent, or an agent its own file marks inactive, warns. A file with no back-reference is noted, not warned on.
  • Reputation. An average under 50 warns; 50 to 80 is noted; no feedback at all is noted. The ERC-8004 registry needs a client list to summarise, so Preflight reads the agent's clients first and summarises over at most 100 of them. The result says how many it covered.
  • Paid jobs. Incoming USDC transfers to the agent wallet are the on-chain record of settled payments. None in the last 100 transactions is noted.
  • HCS-14 on Standard. The broker's own rating and interaction count are reported, never scored, and the result says on-chain reputation is read for ERC-8004 identities only.
  • A registry that cannot be read answers 500, so the payment is not settled. That includes Standard's reputation read, so Standard is never charged for a Quick answer. A failed read of the wallet's payments is reported in the result instead, at medium confidence. Only the broker's own "UAID not found" answer counts as an unregistered UAID; any other 404 is a failed read.
  • Registrant text is kept out of the verdict. Agent and listing names appear only in subject.name, with control and format characters removed, never in reasons. The registration URI is shown only as a short https or ipfs URI, and the UAID shown is the broker's canonical one.
  • The registration file is fetched carefully. Its URI is the registrant's choice. Preflight fetches https on port 443 only (an ipfs:// URI goes through a public gateway, and a data: URI is decoded locally), refuses hosts that resolve to private or reserved addresses, refuses redirects, and stops at 64 KB and 5 seconds.
  • The response carries subject (the agent checked) in place of token or account, and on Standard the raw reputation and payments reads. agent still names Preflight itself.

The books

GET /v1/ledger is free. It returns the latest 5,000 ledger rows, totals by kind over every row, and the current hour's spend cap. Each row has a timestamp, direction, counterparty, amount, asset, USD value, purpose and evidence.

  • Four kinds, kept apart: outside revenue, builder-controlled revenue (shown, never counted), costs, and internal transfers such as top-ups. Net is outside revenue minus costs.

  • On-chain rows link to HashScan. Each settled payment writes its revenue row in the same transaction that marks it settled. Payers listed in BUILDER_ACCOUNT_IDS count as builder revenue. If that row cannot be written, the payment still records as settled, the ledger shows it under unbookedPayments, and the next start writes the row. Revenue is booked only when the facilitator's settle names the payment's own transaction; any other answer fails the settle closed and leaves the payment for the reconcile sweep to check on the mirror node.

  • Off-chain rows carry their own evidence: token counts and a request ID for inference, or the invoice line for hosting. Hosting is pro-rated to one row per UTC day.

  • HCS fees: each closed UTC day gets one cost row (hcs-fees:<day>), booked ten minutes after midnight and dated at the day's last millisecond. It counts that day's posted messages at the spend cap's estimate of $0.0008 per 1024-byte chunk, and names the first and last message by transaction ID and sequence number. Failed, duplicate and unrecorded attempts are debited from the cap but not booked. One row per post would loop, since every ledger row posts its own HCS message; one row per day still posts, so every day carries at least one.

  • Hourly spend cap: every outbound spend must debit the hour first with one conditional UPDATE (remaining >= cost). Zero rows updated means the spend is refused and logged. SPEND_CAP_USD_PER_HOUR sets it; the default is $0.50. Every spend path calls debit() before it pays. Every LLM call goes through spendWithCap: it reserves its worst case on the cap before the call, then books the billed tokens as a cost row with the provider, request ID and token counts. A cap refusal answers 503 and does not settle; it offers Quick where the route sells it. A debit is never refunded. A cost row that cannot be written is logged (cost_row_failed) for manual repair; cost rows have no automatic backfill. A call whose token counts are missing is booked at its reserve with estimated: true. Other repair events: spend_unbooked (debited, nothing booked), cost_row_duplicate, and spend_over_reserve_uncapped (billed more than the reserve and the cap could not take it).

  • Data purchases (R4): the agent buys x402 data from Hedera-settled sellers with its own account, only data a check is built to read, and books each one as a cost row linked to HashScan. MAX_PURCHASE_USD caps one purchase. pnpm buy makes one by hand. Sellers and their fallback order: docs/sellers.md.

  • Treasury guard: the agent's treasury is a Bloxchain account on Sepolia. The agent can pay only listed vendors, up to a daily cap enforced on-chain. Only the owner's offline key, or the recovery key after a timelock, can withdraw or change the limits. The treasuryGuard block shows the cap, today's spend and the balance, read live; it is null until the GUARD_* variables are set. pnpm guard local demos it with no keys. See docs/bloxchain-guard.md.

The public dashboard

GET /books is the public dashboard, and GET /v1/books is its data. Both are free, and /v1/books is open to any origin. Each instance serves one network. Set BOOKS_PEER_URLS to the other network's instance, and the page shows both side by side, mainnet first.

  • Totals and runway: outside revenue, cost, net, and the current mode, balance and runway. Builder revenue is shown apart and never counted. Settled payments not yet booked are called out.
  • By day: outside revenue, cost, net and builder revenue for each UTC day of the period.
  • Paying agents: a payer is named only if it is listed in BOOKS_PUBLIC_PAYERS (0.0.8001=Team Alpha,...), which means it gave permission. Every other outside payer is counted, never named. The same rule holds in the recent checks.
  • Recent checks: the last 20 settled checks, with check type, tier, price and a HashScan link. What was checked, and the verdict bought, show only for named payers and builder accounts. The settlement ties each row to the payer's account in /v1/ledger, so anyone else's would reveal what they looked into.
  • Runway over time: the last 50 mode or price changes, each with the balance and runway it was decided on.
  • HCS posts pending: the same hcs block as /v1/ledger: how many messages have not posted, the oldest one and its failed attempts, receipts waiting for a batch, and the topic.

Published on HCS

Ledger rows and check receipts go to one public HCS topic (HCS_TOPIC_ID), so anyone can audit the books and prove a verdict was published.

  • Ledger rows: a database trigger queues every new ledger row for the topic in the same transaction as the insert, as a preflight.ledger message.
  • Receipts: each paid response carries receipt.checkHash: the SHA-256 of the result as canonical JSON (keys sorted at every level, no whitespace), without its receipt and signature fields. The receipt sits inside the signed payload. Once the payment settles, the hash waits for a batch. A batch seals at 50 receipts or when the oldest has waited 10 minutes; nothing posts while nothing waits. The batch's Merkle root goes out as one preflight.receipts message (leaf = sha256(0x00 ‖ checkHash), node = sha256(0x01 ‖ left ‖ right), an odd last node moves up unchanged).
  • GET /v1/receipts/:checkId is free. It serves the receipt's Merkle proof, then the topic and sequence number once the batch posts.
  • Outbox: every message sits in hcs_outbox with an hcs_posted flag and a retry count. Every 15 seconds the worker drains it in order, then seals due batches and drains again. A failed post backs off from 15 seconds up to 10 minutes. Every fifth failure raises an hcs_post_failing alert (log and ntfy); when that message finally posts, a preflight.gap notice goes to the topic with the outage window. Five failing worker cycles in a row raise hcs_cycle_failing. Each post debits the hourly spend cap first ($0.0008 per 1024-byte chunk); at the cap the queue waits for the next hour. /v1/ledger shows the topic and what has not posted yet under hcs, as counts only. A post that timed out after reaching the network is retried, so a message can appear twice: dedupe ledger rows by key (the row's dedupe key) and batches by root.
  • Keys: HCS_OPERATOR_ID and HCS_OPERATOR_KEY pay the fees, from an account other than PREFLIGHT_ACCOUNT_ID. Create the topic with a submit key, or anyone can post to it, and with no admin key, or one held off the box, so the service cannot change or delete it. HCS_SUBMIT_KEY signs each post when that key differs from the operator key. Until HCS_TOPIC_ID is set, messages queue and post later.
HCS_TOPIC_ID=<Preflight's topic> pnpm verify-receipt https://<service> <checkId> [response.json]

The verify script walks the proof to the batch root and reads the message at the receipt's sequence number on the topic you name, from a mirror node. It trusts nothing the service says about the topic. Given the saved check response, it also proves the receipt covers that exact verdict.

Schema version 4 rebuilt the HCS outbox and added receipt batches. A version-2 or 3 database upgrades in place at boot, keeps its waiting policy messages and queues its ledger rows for the topic. An older one refuses to open: delete ./data/preflight.sqlite and restart.

The adaptive policy

Every minute the agent reads its USDC balance from the mirror node. It computes runway as that balance divided by the trailing 24-hour net burn (costs minus outside revenue). When net burn is zero or negative, runway is unlimited. The runway sets the mode:

Mode Enter Leave Effect
Healthy runway > 16 days < 14 days normal prices
Lean 3–14 days > 16 or < 3 Standard and Deep prices +25%; Quick unchanged
Survival < 3 days > 4 days Quick checks only
Hibernate balance < 1 day of DAILY_FIXED_COST_USD > 2 days no new work
  • Hysteresis and hold. Each mode's enter and leave lines are apart. A mode also holds 15 minutes before it changes again, and the hold survives a restart. Entering Hibernate skips the hold: it is the floor that stops a drained agent taking work.
  • Fails closed. If the balance cannot be read for 10 minutes, the agent drops to Survival. Nothing is published until the first balance read sets a mode.
  • Demand pricing. Prices rise DEMAND_PRICE_UP_PCT (default 50%) while settled paid checks exceed DEMAND_RPM_THRESHOLD per minute (default 30). They fall back once that drops to half the threshold, after at least 5 minutes. Unpaid requests and builder payers never count.
  • A retry keeps its price. A retried payment that was already taken is quoted at the amount it was taken at, so a reprice in between never makes a buyer pay twice.
  • Refused work is never charged. A request the mode does not take gets a 503 before the 402. A paid replay of finished work is still answered from the payment record.
  • On HCS. Each mode or price change writes a policy_events row and an HCS outbox message in one transaction. Entering Hibernate carries a shutdown notice. The message waits in the outbox until HCS posting to HCS_TOPIC_ID is live.

GET /v1/policy is free. It returns the mode, runway, balance, net burn, demand rate and current prices. The agent card lists base prices; each 402 and /v1/policy carry the live one.

The demo instance

The stage demo drains a float to show Lean and Survival. It runs as a separate instance on its own account, never on the real agent. Use its own .env with a different PREFLIGHT_ACCOUNT_ID and DATABASE_PATH, plus:

PREFLIGHT_INSTANCE=demo
MAIN_AGENT_ACCOUNT_ID=0.0.<real agent>   # the demo refuses to start on this account or with its paying key

Run the demo on the real agent's network: it reads MAIN_AGENT_ACCOUNT_ID from its own mirror node.

Every HCS message carries instance, so the demo's changes are labelled as the demo's.

Economic model

Preflight earns on every paid check and pays its own costs. Most checks need no model call, so most of the price is margin. The figures below are estimates from list prices (DEEPINFRA_PRICE_USD_PER_MTOK, ANTHROPIC_PRICE_USD_PER_MTOK). The ledger books every model call's billed tokens as a cost row, so GET /v1/ledger holds the measured figures.

Revenue

Tier Price (USDC) Set by
Quick $0.005 PRICE_QUICK_USD
Standard $0.02 PRICE_STANDARD_USD
Deep $0.10 PRICE_DEEP_USD

These are base prices. The adaptive policy raises them under Lean mode or high demand, and GET /v1/policy shows the live ones. The break-even below uses base prices, so it is the conservative case.

Payments settle to the agent's own account through x402. A check paid by a builder account (BUILDER_ACCOUNT_IDS) is shown in the books but never counted as revenue.

Cost per check

Tier Variable cost Margin
Quick None. The rules run in process on free mirror-node data 100%
Standard One model call of about 3,000 tokens in and 400 out: about $0.00084 on DeepSeek V4.1 Flash ($0.20 / $0.60 per million), or $0.0005 on Claude Haiku 5.5 ($0.10 / $0.50) about 96%

The worst Standard case is two Claude Haiku calls that each hit its 2,000-token output cap: about $0.0026, which still leaves a margin of 87%.

Fixed cost per day

Item Per day Basis
VPS $0.20 Budgeted at $6 a month. HOSTING_USD_PER_MONTH books the real invoice as one row per UTC day
HCS messages up to $0.115 Once HCS posting is live: at most one receipt batch ($0.0008) per 10 minutes, none while idle, plus one per policy change. Counted now so the break-even stays conservative
Total up to $0.32

Data purchases ($0.003–0.005 each from hbar402, see docs/sellers.md) are booked as costs when they happen. No check needs one to answer, so they are not part of the per-check cost.

Break-even

Break-even checks per day = fixed cost per day ÷ average margin per check. Only outside revenue counts.

Mix Margin per check Break-even per day Over the event (4 days)
All Quick $0.0050 64 253
All Standard $0.0192 17 66
60% Quick, 40% Standard $0.0107 30 119

Every check past break-even adds its margin to net. The spend guards cap the downside: the hourly spend cap (SPEND_CAP_USD_PER_HOUR, default $0.50), a cap on one data purchase (MAX_PURCHASE_USD, default $0.01), and an alert when the agent's USDC falls below one day of costs (DAILY_FIXED_COST_USD, default $0.50, set above the $0.32 estimate on purpose).

Label set

The address check and label set v1 are being built. This is the method they follow.

The address check flags an account only on evidence Preflight holds itself. A third-party score can point at an address; it becomes a label only once a source below backs it. Every label cites its source, and every verdict names the label-set version it used.

Tier Evidence Hedera source Label
1 Government sanctions designation OFAC SDN Digital Currency Address entries and the UK Sanctions List, matched against a Hedera account's EVM alias sanctioned
2 Issuer or law-enforcement action HTS freezes and KYC revocations by a named issuer, from the mirror node issuer-frozen, illicit
3 Exploit or scam, checked on chain Public incident reports, kept only once the named transaction is confirmed on the mirror node illicit
4 Clean, attested by the owner Exchange proof-of-reserves lists, Preflight's own accounts, named DEX and bridge contracts must-pass
5 Exposure traced by Preflight Transfers 1–2 hops out from tier 1–3 accounts, stopping at exchanges, DEXs and bridges, ignoring transfers under $100 exposure-1hop, exposure-2hop

A tier 1–3 hit blocks, tier 5 warns with the hop path, and tier 4 allows. With no hit, behaviour signals decide, and the answer says "no evidence of risk", never "safe".

  • Versioned, frozen, hashed. Each version is one set.csv (address, label, category, tier, source, source_url, source_date, onchain_verified). A new listing makes a new version, never an edit. The file's SHA-256 is posted to HCS.
  • Rebuilds offline. Every source is saved as a snapshot with its fetch time and SHA-256, so anyone can rebuild the set to the same hash.
  • Counts are reported as they are. OFAC lists no HBAR addresses, so tier 1 holds only EVM aliases and may be empty. Tier 2 is Hedera's strongest native signal.
Label set Value
Version v1, frozen from the 2026-12-03 source snapshot
SHA-256 of set.csv ad65c2e7fde886ea837cacac0003637c47065508a9678d7beaac1cb743dc270a
HCS message holding the hash Queued on startup; the sequence number follows once the topic is live
Counts per tier (1 / 2 / 3 / 4 / 5) 134 / 0 / 0 / 9 / 0
Self-benchmark Tiers 1–3: 129 of 129 caught. Tier 4: 0 false alerts on 9 (details)

Sources, the must-pass list and how to rebuild or cut a version: labels/README.md.

Self-benchmark

Preflight grades its address check against its own frozen set. Every address in v1 goes through the Quick check on Hedera mainnet. A tier 1–3 address is caught when the verdict is block and the check matched its tier 1–3 label, so a block from another rule does not count. A tier 4 address raises a false alert when the verdict is anything but allow. Each share carries a 95% lower bound (Wilson score), which on a perfect score of n is n ÷ (n + 3.84). A group under 30 addresses is reported but too small to judge.

Run on 2026-12-03 against v1 (ad65c2e7…), public mainnet mirror node:

Group Pass means Addresses Passed Share 95% lower bound Judged
tier 1 block 129 129 100.0% 97.1% yes
tier 2 block 0 0 – – no addresses
tier 3 block 0 0 – – no addresses
tiers 1-3 block 129 129 100.0% 97.1% yes
tier 4 allow 9 9 100.0% 70.1% too small to judge
  • Tiers 1–3: 129 of 129 caught. The 134 tier 1 rows hold 129 distinct addresses; 5 are listed by both OFAC and the UK. None has a Hedera account today, so each answer is "no account", blocked on the label.
  • Tier 4: no false alerts, too few to judge. With 9 addresses, even a perfect score only shows the pass rate is above 70%.
  • What it shows. The check applies the evidence it holds, including to an EVM address that has no Hedera account yet. It says nothing about risk the set does not list. The Hedera set is small, and tiers 2 and 3 are empty in v1.
  • One slow read. A cold mirror-node read of 0.0.98 took 6.5 s, past the service's 4 s timeout; the same read took 0.03 s warm. The benchmark allows 30 s, since it grades verdicts, not latency.

Rerun it with pnpm labels:benchmark [version]. It writes labels/benchmarks/<version>.json and prints the table above.

Identity

GET /.well-known/agent-card.json is free. It is an ERC-8004 registration file that also lists the paid endpoints, prices, networks and the response-signing public key. Every response carries X-Agent-Card, plus X-Agent-ERC8004 and X-Agent-UAID once set, and a paid result carries the same identity in its agent field.

pnpm identity:register          # dry run: checks the live card, simulates on testnet
pnpm identity:register --send   # registers in the ERC-8004 IdentityRegistry on Hedera testnet
pnpm identity:uaid              # prints the HCS-14 UAID for the mainnet agent (no transaction)

Set PUBLIC_BASE_URL to the public https origin first; the card's URLs and the agentURI come from it. Registration is signed by a dedicated owner account (ERC8004_OWNER_ACCOUNT_ID), never the payment account. After registering, the script clears the registry's agentWallet, so the card's payTo is the only payee. Set the printed ERC8004_AGENT_ID and HCS14_UAID in the service's environment. With ERC8004_AGENT_ID already set, identity:register updates the agentURI instead.

ERC-8004 on Hedera testnet does not put Preflight in a directory: HOL's Registry Broker indexes ERC-8004 agents only on other chains. So Preflight registers with the broker directly:

pnpm directory:register          # dry run: checks the live card, quotes the credit cost
pnpm directory:register --send   # lists Preflight in the HOL Registry Broker (hol.org/registry)

The listing is built from the live card. The script logs in to the broker as the owner account; its key signs the login challenge locally and is never sent. Registration costs broker credits held by that account. The script never buys them, because the broker's purchase call takes the raw private key, so on a shortfall it prints how many to buy at hol.org/registry. It prints the listing link for the submission checklist. Before registering it searches the directory for Preflight's endpoint or card, so a re-run after success prints the existing listing. If a registration's outcome is unclear (a timeout, a partial result), it records the attempt in data/hol-register-attempt.json, prints links to check, and refuses --send until you delete that file.

Deploying to the VPS with Kamal: docs/deploy.md.

ENS: preflight.eth

Preflight's ENS name is preflight.eth on Sepolia (ENSv2). Its text records point at the service, so an agent that knows only the name can find the card, the price and the on-chain identity:

Record Value
url the public origin
agent-card /.well-known/agent-card.json
x402 the paid check endpoint, /v1/check/token
agent-registration[<ERC-7930 registry>][<agentId>] 1: the ENSIP-25 link to the ERC-8004 entry on Hedera testnet
pnpm ens:records           # prints the records to set on ENS_NAME, built from the agent card
pnpm ens:records --check   # reads each record back via ENS_SEPOLIA_RPC_URL; fails on any difference

The name is registered and its records set in the ENS app with the owner's own wallet; the script holds no key. With ENS_NAME set, the agent card lists the name as an ENS service and every response carries X-Agent-ENS.

ENS is also evidence, built for the address check, which does not exist yet. lookupPrimaryName (src/ens.ts) asks the ENS Universal Resolver, through ENS_RPC_URL, for a counterparty's primary name, and the resolver checks that the name resolves back to the same address. ensEvidence turns the answer into verdict reasons: a verified name is cited with a link. No name, a failed lookup, or a reverse record that claims a name it doesn't own is neutral, never a flag by itself. No paid check calls it yet; the address check will.

New work and reused parts

Preflight entered the "Building from Scratch" track. It uses no starter kit or template: the first commit is a README stub, and everything after it was written during the event. How it was written, and by whom, is in AI_USAGE.md.

New in this repo:

  • The service (src/): the paywall flow, the token, address, transaction and agent checks, the ledger, the spend cap, the adaptive policy, HCS publishing and the public dashboard.
  • The Agent Kit plugin and fetch client (packages/preflight-agent/) and the demo customer agent (packages/demo-agent/).
  • The treasury guard contract (contracts/AgentSpendGuard.sol).
  • The scripts (scripts/), the deploy config and the label set's curation (labels/).

Reused, as published libraries and data:

Part Used for
@x402/core, @x402/express, @x402/hedera, @x402/fetch x402 payments: the paywall, settling on Hedera, and paying sellers
@hiero-ledger/sdk Hedera keys, transactions and HCS
@hashgraph/hedera-agent-kit The kit the plugin targets (a peer dependency)
zod Tool schemas in the Agent Kit plugin (an optional peer dependency)
@bloxchain/contracts, @bloxchain/sdk The governed treasury account behind the guard
viem EVM calls for ERC-8004 identity and the guard
@anthropic-ai/sdk The Claude Haiku fallback writer
express The HTTP server
x402.org and Blocky402 facilitators Verifying and settling payments
Hedera mirror node Token, account and transaction data
OFAC SDN and UK sanctions lists Address-check evidence (labels/snapshots/)

License

MIT — see LICENSE.

About

The check agents run before they pay — x402-paid risk checks on Hedera (ETHGlobal Agentic Markets)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages