Web3 Work Orders
Give a network of agents the authority to commission work, delegate it, accept it, and settle what it owes.
On this page
A useful agent economy needs more than a successful tool call. Someone must select a provider, limit its authority, reserve the money, inspect what arrives, and recover when publication succeeds but its acknowledgement disappears. Build those responsibilities into a network of four Chio kernels.
This application executes real reviews of escrow obligations, native passport and federation flows, signed two-hop delegation, actual Solidity escrow transactions, and a standard x402 purchase. The operator, buyer, provider, specialist and auditor have distinct keys and responsibilities. Every accepted or refused kernel operation leaves a signed record.
Download the complete application · Browse the tested public source · Download the execution
Run the whole network
Install the matching Chio CLI, Rust 1.94 or newer, Node.js 22 or newer, Python 3.11 or newer, and uv. Extract the project anywhere:
cd web3-work-order
uv run --locked run.pyThe first run builds the native host and installs locked dependencies. The launcher starts four HTTP kernel hosts, a native federation service and a private local EVM, then completes the work orders and checks the refusal paths. It stops its processes when finished and retains a new .state directory for each run. No model API key, funded wallet, external blockchain or cluster is required.
The local chain uses test tokens with six decimal places. Amounts in this guide are integer base units; 200,000 units means 0.2 wUSD. The test asset has unrestricted minting for local development. The actual escrow and registry contracts come from Chio’s public source.
From authority to settlement
Inspect the completed work order.
Follow the retained decisions from provider admission through receipt-bound payment and independent audit.
- Signed operations
- 55
- Permitted
- 25
- Refused
- 27
- Interrupted
- 3
Admit a providerallow
A native passport and holder-bound presentation identify the provider. Completed work supplies its observed quality; a selected trust policy determines admission.
- Completed samples
- 1
- Observed quality ratio
- 1.0
- Signed kernel receipt
- 618f44d4cf41d04a2860bf263b55278f4772c3966be2d6d5642a4ce82bc719d8
Buyer, provider and escrow balances after this captured run.
- Buyer
- 650000
- Provider
- 350000
- Escrow
- 0
Captured results, independently verified before publication. Values are local test-token base units. Download the complete execution.
Make each responsibility explicit
| Kernel | Responsibility | Authority boundary |
|---|---|---|
Atlas | Quote, reserve, pay, recover and reconcile. | A durable 300,000-unit exposure limit and separate approval of exact financial terms. |
ProofWorks | Review a supplied escrow specification and commission a specialist check. | Review and scoped delegation. Payment tools are absent from its grant. |
CipherWorks | Check the proof-leaf obligations under a narrower child grant. | One review tool, fewer invocations and a bound ancestor chain. |
Meridian | Admit providers and audit retained work. | Selected issuers, holder-bound presentations, observed work quality and exact peer records. |
Connect authority, work and money
Each host persists admission state, receipts and business state independently. Requests carry a holder signature and a CA-verified workload certificate with a SPIFFE URI. A separate operator signs the installed application’s measurement and quarantine state. This example uses its own local CA and application measurement; it does not require a SPIRE deployment or a hardware enclave.
Start with actual work and selected trust
ProofWorks first reviews a concrete escrow specification. Chio creates a native passport from that host’s actual receipts, selecting the serving kernel explicitly. The attesting issuer can differ from the kernel that performed the work; the selected kernel’s signature and receipt content must still verify.
The application exports and imports bilateral evidence, then obtains a native federation-issued capability with a two-call limit. Two reviews succeed, a third is refused, and the refusal survives a host restart. The recursive subcontracting grant is issued separately with its own narrower scope.
{
"kernel": {
"max_capability_ttl": 3600
},
"capabilities": {
"default": {
"tools": [
{
"server": "proofworks",
"tool": "review",
"operations": [
"invoke"
],
"max_invocations": 2,
"ttl": 900
}
]
}
}
}Read native_trust.py · native passport, challenge and federation flow 287 lines · complete file
"""Native passports, bilateral evidence exchange and federated capability issuance.
All history comes from the serving kernel's actual receipt database. The operator
selects source keys and verifier policy before any presentation is accepted.
"""
import json
import os
import shutil
import socket
import subprocess
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path
from evidence import digest, read, write
def cli(*arguments, cwd, endpoint=None, token=None):
binary = os.environ.get("CHIO_WORK_ORDER_CLI") or shutil.which("chio")
if not binary:
raise ValueError("Install the Chio source candidate documented in README.md")
command = [binary, "--json"]
if endpoint:
command += ["--control-url", endpoint, "--control-token", token]
command += [str(value) for value in arguments]
result = subprocess.run(command, cwd=cwd, text=True, capture_output=True, timeout=30)
if result.returncode:
# Do not print commands: the service credential is a private argument.
raise ValueError("Native Chio operation failed: " + result.stderr[-1500:])
return json.loads(result.stdout) if result.stdout.strip() else None
def seed(path, value):
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "w") as stream:
stream.write(value + "\n")
class NativeTrust:
def __init__(self, app):
self.app = app
self.root = app.directory
self.directory = self.root / "meridian/native"
self.directory.mkdir(mode=0o700)
(self.directory / "challenges").mkdir(mode=0o700)
self.credentials = read(self.root / "credentials/provider.json")
self.subject = self.credentials["capability"]["subject"]
self.token = read(self.root / "operator/meridian.json")["token"]
self.issuer_seed = self.root / "operator/federation.seed"
self.holder_seed = self.root / "credentials/provider.seed"
seed(self.issuer_seed, read(self.root / "operator/issuer.json")["seed"])
seed(self.holder_seed, self.credentials["seed"])
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
address = "127.0.0.1:" + str(listener.getsockname()[1])
self.endpoint = "http://" + address
log = (self.root / "federation.log").open("a")
app.logs.append(log)
command = [
os.environ["CHIO_WORK_ORDER_CLI"],
"trust",
"serve",
"--listen",
address,
"--advertise-url",
self.endpoint,
"--service-token",
self.token,
"--receipt-db",
str(self.directory / "evidence.db"),
"--authority-seed-file",
str(self.issuer_seed),
"--verifier-challenge-db",
str(self.directory / "service-challenges.db"),
]
child = subprocess.Popen(
command, cwd=self.directory, stdin=subprocess.DEVNULL, stdout=log, stderr=log
)
app.children["federation"] = child
for _ in range(300):
if child.poll() is not None:
raise RuntimeError("Federation service stopped; inspect " + log.name)
try:
with urllib.request.urlopen(self.endpoint + "/health", timeout=1) as response:
if response.status == 200:
break
except (urllib.error.URLError, TimeoutError):
time.sleep(0.1)
else:
raise RuntimeError("Federation did not become ready; inspect " + log.name)
def establish(self, history):
passport = self.directory / "passport.json"
self.run(
"--receipt-db",
self.root / "proofworks/receipts.db",
"passport",
"create",
"--subject-public-key",
self.subject,
"--output",
passport,
"--signing-seed-file",
self.issuer_seed,
"--trusted-kernel-key",
read(self.root / "proofworks/config.json")["trusted_kernel"],
"--validity-days",
1,
)
document = read(passport)
# This one fresh work result is an observed sample, not long-term history.
evidence = document["credentials"][0]["evidence"]
if evidence["receiptIds"] != [history["receipt"]["id"]]:
raise ValueError("Passport evidence differs from the actual qualification work")
policy = {
"issuerAllowlist": [
"did:chio:" + read(self.root / "capabilities.json")["root"]["issuer"]
],
"minReceiptCount": 1,
"minLineageRecords": 1,
"maxAttestationAgeDays": 1,
}
write(self.directory / "verifier-policy.json", policy)
sharing = self.directory / "sharing-policy.json"
export = self.directory / "evidence-package"
self.run(
"evidence",
"federation-policy",
"create",
"--output",
sharing,
"--signing-seed-file",
self.issuer_seed,
"--issuer",
"ProofWorks",
"--partner",
"Meridian",
"--agent-subject",
self.subject,
"--admin-all",
"--expires-at",
int(time.time()) + 1800,
"--purpose",
"work-order-admission",
)
self.run(
"--receipt-db",
self.root / "proofworks/receipts.db",
"evidence",
"export",
"--output",
export,
"--federation-policy",
sharing,
"--admin-all",
)
verified = self.run("evidence", "verify", "--input", export)
imported = self.run("evidence", "import", "--input", export, remote=True)
write(
self.directory / "membership.json",
{
"subject": self.subject,
"passport_hash": digest(document),
"receipt_ids": evidence["receiptIds"],
"evidence_verification": verified,
"import": imported,
"sharing_policy": read(sharing),
},
)
return document
def run(self, *arguments, remote=False):
return cli(
*arguments,
cwd=self.directory,
endpoint=self.endpoint if remote else None,
token=self.token if remote else None,
)
def presentation(self, order_id, *, remote=False):
challenge = self.directory / "challenges" / (order_id + ".json")
if challenge.exists():
raise ValueError("A challenge already exists for this order")
arguments = [
"passport",
"challenge",
"create",
"--output",
challenge,
"--verifier",
self.endpoint if remote else "Meridian work-order admission",
"--policy",
self.directory / "verifier-policy.json",
]
if not remote:
arguments += ["--verifier-challenge-db", self.directory / "admission-challenges.db"]
self.run(*arguments, remote=remote)
response = challenge.with_suffix(".response.json")
self.run(
"passport",
"challenge",
"respond",
"--input",
self.directory / "passport.json",
"--challenge",
challenge,
"--holder-seed-file",
self.holder_seed,
"--output",
response,
)
return read(response)
def issue(self, order_id):
self.presentation(order_id, remote=True)
policy = self.directory / "capability-policy.json"
write(
policy,
{
"kernel": {"max_capability_ttl": 3600},
"capabilities": {
"default": {
"tools": [
{
"server": "proofworks",
"tool": "review",
"operations": ["invoke"],
"max_invocations": 2,
"ttl": 900,
}
]
}
},
},
)
result = self.run(
"trust",
"federated-issue",
"--presentation-response",
self.directory / "challenges" / (order_id + ".response.json"),
"--challenge",
self.directory / "challenges" / (order_id + ".json"),
"--capability-policy",
policy,
remote=True,
)
if (
result["verification"]["accepted"] is not True
or result["capability"]["subject"] != self.subject
):
raise ValueError("Native federation refused or changed the provider subject")
write(self.directory / "issued-capability.json", result)
return {**self.credentials, "capability": result["capability"]}
def verify_presentation(directory, data, *, consume=False):
native = directory / "native"
member = read(native / "membership.json")
presentation = data["presentation"]
if digest(presentation["passport"]) != member["passport_hash"]:
raise ValueError("Presentation does not carry the admitted native passport")
with tempfile.TemporaryDirectory(prefix="verify-", dir=native) as temporary:
response = Path(temporary) / "response.json"
write(response, presentation)
arguments = [
"passport",
"challenge",
"verify",
"--input",
response,
"--challenge",
native / "challenges" / (data["order_id"] + ".json"),
]
if consume:
arguments += ["--verifier-challenge-db", native / "admission-challenges.db"]
verified = cli(*arguments, cwd=native)
if verified["accepted"] is not True or verified["subject"] != "did:chio:" + member["subject"]:
raise ValueError("Native passport presentation did not pass the selected verifier policy")
return {
"verification": verified,
"evidence_import": member["import"],
"passport_hash": member["passport_hash"],
"receipt_ids": member["receipt_ids"],
}Select a provider you can admit
The RFQ compares price, signed provider identity and completed review history. Meridian rejects a provider without completed work and one whose price exceeds the budget. The selected provider presents a native holder-bound challenge response. Reusing the consumed presentation fails.
Quality is the observed ratio of complete reviews in the supplied signed sample. The page and artifact expose the sample count; there is no invented long-term reputation. An incomplete second review later lowers that ratio enough to refuse another admission.
Atlas then issues an expiring invoice. Its approval binds the order ID, invoice hash, amount and installed rail. A modified amount, missing approval or unsupported rail fails before funding.
if host == "atlas" and tool == "reserve":
quote = result_evidence(data["quote"], "atlas", "quote", trusted, order_id)
require(quote["expires_at"] > time.time(), "Quote expired")
require(data["invoice_hash"] == quote["invoice_hash"], "Invoice was changed after quote")
require(data["amount"] == quote["amount"], "Invoice amount was changed after quote")
require(data["rail"] == quote["rail"] == "chio-local-escrow", "Uninstalled settlement rail")
approval = verify_signed(data["approval"], trusted["approval_issuer"])
expected = {
"order_id": order_id,
"invoice_hash": quote["invoice_hash"],
"amount": quote["amount"],
"rail": quote["rail"],
"approved": True,
}
require(
all(approval.get(key) == value for key, value in expected.items()),
"Approval does not bind this exact order, invoice and amount",
)
require(approval["expires_at"] > time.time(), "Independent approval expired")
require(
db.execute("SELECT 1 FROM orders WHERE id=?", (order_id,)).fetchone() is None,
"Order already reserved; inspect status",
)
exposure = db.execute(
"SELECT COALESCE(SUM(amount),0) FROM orders WHERE state NOT IN ('refunded','released')"
).fetchone()[0]
exposure += db.execute(
"SELECT COALESCE(SUM(amount),0) FROM report_purchases WHERE state='prepared'"
).fetchone()[0]
require(
exposure + quote["amount"] <= trusted["treasury_limit"],
"Treasury exposure would exceed its durable limit",
)
return {"quote": quote}The reservation commits before the chain call. An ambiguous publication retains its exposure. A competing purchase cannot spend the same remaining allowance while the first order is unresolved.
Delegate authority that can only shrink
The provider’s holder signs a binding to the specialist’s exact child token; the selected issuer signs that token. The binding covers identity, scope, expiry and budget share. Chio verifies the chain against the stored ancestor snapshots before dispatch.
let delegate = |parent: &CapabilityToken,
holder: &Keypair,
subject: &Keypair,
tools: &[(&str, &str)],
calls,
share,
delegable|
-> Result<CapabilityToken> {
Ok(issue_delegated_capability(
parent,
DelegatedCapabilityRequest {
id: uuid::Uuid::new_v4().to_string(),
subject: subject.public_key(),
scope: scope(tools, calls, delegable),
issued_at: issued,
expires_at: issued + 1800,
budget_share_bps: Some(share),
nonce: *uuid::Uuid::new_v4().as_bytes(),
},
holder,
&issuer,
)?
.0)
};
let provider_cap = delegate(
&root,
&owner,
&provider,
&[("proofworks", "review"), ("cipherworks", "review")],
30,
6000,
true,
)?;
let specialist_cap = delegate(
&provider_cap,
&provider,
&specialist,
&[("cipherworks", "review")],
20,
2500,
false,
)?;CipherWorks checks the supplied chain ID, amount, deadline, beneficiary and nine named proof-leaf fields. ProofWorks binds that specialist receipt into its own completed result. Atlas requires both reviews to refer to the same specification before settlement.
def review(data):
# Validate concrete escrow obligations supplied as data. Never execute prose,
# caller code, filesystem paths, or commands from a provider's work packet.
spec = data["specification"]
required = {
"chain_id",
"token_decimals",
"amount",
"deadline_seconds",
"beneficiary",
"required_leaf_fields",
}
require(set(spec) == required, "Unknown or missing settlement specification field")
require(
type(spec["chain_id"]) is int and spec["chain_id"] == 31337,
"Only the local Chio escrow rail is installed",
)
require(
spec["token_decimals"] == 6
and type(spec["amount"]) is int
and 0 < spec["amount"] <= 300000,
"Invalid token amount or denomination",
)
require(
type(spec["deadline_seconds"]) is int and 60 <= spec["deadline_seconds"] <= 3600,
"Unsafe escrow deadline",
)
require(
isinstance(spec["beneficiary"], str)
and re.fullmatch(r"0x[0-9a-fA-F]{40}", spec["beneficiary"]) is not None,
"Invalid beneficiary",
)
expected = [
"chainId",
"escrow",
"escrowId",
"token",
"beneficiary",
"operatorKeyHash",
"receiptHash",
"amount",
"partial",
]
fields = spec["required_leaf_fields"]
require(
isinstance(fields, list)
and len(fields) <= 32
and all(isinstance(field, str) for field in fields)
and len(set(fields)) == len(fields),
"Proof fields must be distinct names",
)
missing = sorted(set(expected) - set(spec["required_leaf_fields"]))
extra = sorted(set(spec["required_leaf_fields"]) - set(expected))
return {
"order_id": data["order_id"],
"specification_hash": digest(spec),
"complete": not missing and not extra,
"missing_leaf_fields": missing,
"unknown_leaf_fields": extra,
"checked_fields": expected,
"amount": spec["amount"],
}Revoking the provider’s ancestor stops its specialist immediately and after restart. The scoped delegation helper also refuses parent caveats and multi-hop aggregate-budget families it cannot safely preserve. Atlas’s monetary exposure limit is enforced separately in its business ledger.
Settle against the accepted receipt
The application deploys ChioIdentityRegistry, ChioRootRegistry and ChioEscrow. Atlas funds a real escrow, publishes a root that binds the accepted review receipt, then submits the matching proof to release funds. Changed receipt hashes and beneficiaries are rejected by the actual contract, with unchanged balances.
| Work | Funded | Provider receives | Buyer recovers |
|---|---|---|---|
Complete review | 200,000 | 200,000 | 0 |
Partially accepted review | 200,000 | 140,000 | 60,000 |
x402 report purchase | Direct payment | 10,000 | 0 |
Recover a publication without repeating its effect
The run deliberately loses acknowledgement after funding, after root publication and after refund. Each interrupted operation keeps an incomplete receipt. The restarted payer reads the actual contract and its persisted intent, verifies the original terms, and either resumes the remaining step or records the transaction that already happened.
For partial work, a separate operator approves 140,000 against the specific review receipt. The remaining 60,000 stays in escrow until the local chain passes its deadline. The final partial-release and refund summaries point to the successful recovery operations; the original interrupted records remain in the audit.
Read chain.mjs · complete deployment, escrow proof and recovery implementation 676 lines · complete file
/** Local EVM execution using the actual Chio escrow and registry contracts. */
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { fileURLToPath } from "node:url";
import solc from "solc";
import {
AbiCoder,
Contract,
ContractFactory,
JsonRpcProvider,
NonceManager,
Wallet,
keccak256,
toUtf8Bytes,
} from "ethers";
const home = path.dirname(fileURLToPath(import.meta.url));
const mode = process.argv[2];
let ownedServer = null;
let stage = "initialize";
const directory = path.resolve(process.argv[3] ?? ".");
const load = (file) => JSON.parse(fs.readFileSync(file, "utf8"));
const sha = (text) => crypto.createHash("sha256").update(text).digest("hex");
function save(file, value) {
const temporary = file + "." + crypto.randomUUID();
const descriptor = fs.openSync(temporary, "wx", 0o600);
try {
fs.writeFileSync(descriptor, JSON.stringify(value, null, 2));
fs.fsyncSync(descriptor);
} finally {
fs.closeSync(descriptor);
}
fs.renameSync(temporary, file);
}
function compile() {
const root = fs.existsSync(path.join(home, "contracts/src"))
? path.join(home, "contracts")
: path.resolve(home, "../../../contracts");
const sources = {};
const visit = (relative) => {
for (const entry of fs.readdirSync(path.join(root, relative), {
withFileTypes: true,
})) {
const file = path.join(relative, entry.name);
if (entry.isDirectory()) visit(file);
else if (file.endsWith(".sol"))
sources[file] = {
content: fs.readFileSync(path.join(root, file), "utf8"),
};
}
};
visit("src");
sources["LocalPaymentToken.sol"] = {
content: fs.readFileSync(path.join(home, "LocalPaymentToken.sol"), "utf8"),
};
const input = {
language: "Solidity",
sources,
settings: {
optimizer: { enabled: true, runs: 200 },
evmVersion: "paris",
outputSelection: { "*": { "*": ["abi", "evm.bytecode.object"] } },
},
};
const result = JSON.parse(solc.compile(JSON.stringify(input)));
const failures =
result.errors?.filter((item) => item.severity === "error") ?? [];
if (failures.length)
throw Error(failures.map((item) => item.formattedMessage).join("\n"));
return {
source_hash: sha(JSON.stringify(sources)),
contracts: result.contracts,
};
}
async function connect() {
const config = load(path.join(directory, "chain.json"));
if (
!/^http:\/\/127\.0\.0\.1:\d+$/.test(config.endpoint) ||
config.chain_id !== 31337
)
throw Error("This application only executes its private local chain");
const provider = new JsonRpcProvider(config.endpoint, 31337, {
staticNetwork: true,
});
provider.pollingInterval = 50;
const wallets = load(path.join(directory, "chain-wallets.json")).map(
(seed) => new Wallet(seed, provider),
);
const signers = wallets.map((wallet) => new NonceManager(wallet));
const contracts = load(path.join(directory, "chain-contracts.json"));
const contract = (name, index) =>
new Contract(config.addresses[name], contracts[name].abi, signers[index]);
return { config, provider, wallets, signers, contract };
}
function transactionRecord(receipt) {
return {
transaction_hash: receipt.hash,
block_number: receipt.blockNumber,
block_hash: receipt.blockHash,
status: receipt.status,
logs: receipt.logs.map((log) => ({
address: log.address,
topics: [...log.topics],
data: log.data,
})),
};
}
function injectedInterruption(point) {
const file = path.join(directory, "chain-interruption.json");
if (fs.existsSync(file) && load(file).point === point) {
fs.unlinkSync(file);
throw Error(
"Qualification interruption after actual chain publication: " + point,
);
}
}
async function reconcile(order, file, context) {
const escrow = context.contract("ChioEscrow", 3);
const observed = await escrow.getEscrow(order.escrow_id);
const deposited = Number(observed.deposited),
released = Number(observed.released);
if (deposited > 0) {
for (const [key, value] of Object.entries(order.terms)) {
if (
String(observed.terms[key]).toLowerCase() !==
String(value).toLowerCase()
)
throw Error("Retained escrow intent differs from the on-chain terms");
}
const logs = await context.provider.getLogs({
address: context.config.addresses.ChioEscrow,
topics: [null, order.escrow_id],
fromBlock: 0,
toBlock: "latest",
});
for (const log of logs) {
if (
!order.transactions.some(
(item) => item.transaction_hash === log.transactionHash,
)
) {
const receipt = await context.provider.getTransactionReceipt(
log.transactionHash,
);
if (!receipt || receipt.status !== 1)
throw Error("Escrow event has no successful transaction");
order.transactions.push(transactionRecord(receipt));
}
}
order.state = observed.refunded
? "refunded"
: released === deposited
? "released"
: released > 0
? "partial"
: "funded";
}
order.observed = {
deposited,
released,
refunded: observed.refunded,
block_number: await context.provider.getBlockNumber(),
chain_id: context.config.chain_id,
escrow_contract: context.config.addresses.ChioEscrow,
source_hash: context.config.source_hash,
};
save(file, order);
return order;
}
async function recover(order, file, context) {
const previous = order.pending_action ?? order.state;
order.pending_action = previous;
await reconcile(order, file, context);
const { config, contract, signers } = context;
const escrow = contract("ChioEscrow", 3),
token = contract("MockERC20", 2);
// Resume only the already persisted intent; the caller cannot change terms,
// amount, receipt, beneficiary or checkpoint during recovery.
if (previous === "funding" && order.observed.deposited === 0) {
order.transactions.push(
await transact(
token.approve(config.addresses.ChioEscrow, order.terms.maxAmount),
),
);
save(file, order);
order.transactions.push(
await transact(escrow.connect(signers[2]).createEscrow(order.terms)),
);
order.state = "funded";
save(file, order);
} else if (previous === "releasing" && order.observed.released === 0) {
const release = order.release;
if (!release) throw Error("No persisted release intent to recover");
const registry = contract("ChioRootRegistry", 1);
const entry = await registry.getRoot(config.operator, release.sequence);
if (Number(entry.checkpointSeq) === 0) {
order.transactions.push(
await transact(
registry.publishRoot(
config.operator,
release.root,
release.sequence,
release.sequence,
release.sequence,
1,
config.operator_key_hash,
),
),
);
save(file, order);
} else if (
entry.merkleRoot !== release.root ||
entry.operatorKeyHash !== config.operator_key_hash
)
throw Error("Checkpoint differs from the persisted release intent");
const method = release.partial
? "partialReleaseWithProofDetailed"
: "releaseWithProofDetailed";
order.transactions.push(
await transact(
escrow[method](
order.escrow_id,
{ auditPath: [], leafIndex: 0, treeSize: 1 },
release.root,
"0x" + release.receipt_id,
release.amount,
),
),
);
order.state = release.partial ? "partial" : "released";
save(file, order);
} else if (previous === "refunding" && !order.observed.refunded) {
order.transactions.push(
await transact(escrow.connect(signers[2]).refund(order.escrow_id)),
);
order.state = "refunded";
save(file, order);
}
await reconcile(order, file, context);
delete order.pending_action;
order.recovery = {
previous_state: previous,
reconciled_state: order.state,
observed_block: order.observed.block_number,
};
save(file, order);
return order;
}
async function transact(transaction) {
const response = await transaction;
const receipt = await response.wait();
if (receipt.status !== 1)
throw Error("Transaction reverted: " + response.hash);
return transactionRecord(receipt);
}
async function serve() {
const { default: ganache } = await import("ganache");
const walletsFile = path.join(directory, "chain-wallets.json");
if (!fs.existsSync(walletsFile))
save(
walletsFile,
Array.from({ length: 4 }, () => Wallet.createRandom().privateKey),
);
const keys = load(walletsFile);
const server = ganache.server({
chain: { chainId: 31337 },
wallet: {
accounts: keys.map((secretKey) => ({
secretKey,
balance: "0x3635c9adc5dea00000",
})),
},
database: { dbPath: path.join(directory, "chain-db") },
logging: { quiet: true },
});
ownedServer = server;
await server.listen(0, "127.0.0.1");
const endpoint = "http://127.0.0.1:" + server.address().port;
const previous = path.join(directory, "chain.json");
if (fs.existsSync(previous)) {
const config = load(previous);
config.endpoint = endpoint;
save(previous, config);
} else {
const provider = new JsonRpcProvider(endpoint, 31337, {
staticNetwork: true,
});
provider.pollingInterval = 50;
const wallets = keys.map((key) => new Wallet(key, provider));
const signers = wallets.map((wallet) => new NonceManager(wallet));
const built = compile();
const selected = {};
for (const entries of Object.values(built.contracts))
for (const [name, value] of Object.entries(entries))
if (
[
"ChioIdentityRegistry",
"ChioRootRegistry",
"ChioEscrow",
"LocalPaymentToken",
].includes(name)
)
selected[name === "LocalPaymentToken" ? "MockERC20" : name] = value;
const transactions = [];
const addresses = {};
const deploy = async (name, args) => {
stage = "deploy " + name;
console.error(stage);
const value = await new ContractFactory(
selected[name].abi,
"0x" + selected[name].evm.bytecode.object,
signers[0],
).deploy(...args);
transactions.push(
await transact(Promise.resolve(value.deploymentTransaction())),
);
addresses[name] = await value.getAddress();
save(path.join(directory, "chain-setup-progress.json"), {
addresses,
transactions,
});
return value;
};
const identity = await deploy("ChioIdentityRegistry", [wallets[0].address]);
const registry = await deploy("ChioRootRegistry", [
await identity.getAddress(),
]);
const escrow = await deploy("ChioEscrow", [
await registry.getAddress(),
await identity.getAddress(),
wallets[0].address,
]);
const token = await deploy("MockERC20", []);
const kernel = load(path.join(directory, "config.json")).trusted_kernel;
const operatorKeyHash = "0x" + sha(Buffer.from(kernel, "hex"));
const binding = await wallets[0].signTypedData(
{
name: "ChioIdentityRegistry",
version: "1",
chainId: 31337,
verifyingContract: await identity.getAddress(),
},
{
ChioOperatorBinding: [
{ name: "operatorAddress", type: "address" },
{ name: "edKeyHash", type: "bytes32" },
{ name: "settlementKey", type: "address" },
],
},
{
operatorAddress: wallets[1].address,
edKeyHash: operatorKeyHash,
settlementKey: wallets[1].address,
},
);
stage = "register operator";
transactions.push(
await transact(
identity.registerOperator(
wallets[1].address,
operatorKeyHash,
wallets[1].address,
binding,
),
),
);
stage = "allow token";
transactions.push(
await transact(escrow.setTokenAllowed(await token.getAddress(), true)),
);
stage = "mint local token";
transactions.push(
await transact(token.mint(wallets[2].address, 1_000_000)),
);
save(path.join(directory, "chain-contracts.json"), selected);
save(previous, {
schema: "work-order.chain.v1",
chain_id: 31337,
endpoint,
addresses,
operator_key_hash: operatorKeyHash,
operator: wallets[1].address,
depositor: wallets[2].address,
beneficiary: wallets[3].address,
source_hash: built.source_hash,
setup_transactions: transactions,
});
provider.destroy();
}
save(path.join(directory, "chain-ready.json"), { endpoint });
console.error("Local Chio escrow chain listening at " + endpoint);
let closing = false;
const close = async () => {
if (closing) return;
closing = true;
await server.close();
process.exit(0);
};
process.on("SIGTERM", close);
process.on("SIGINT", close);
}
function leaf(config, escrowId, receipt, amount, partial) {
return keccak256(
AbiCoder.defaultAbiCoder().encode(
[
"bytes32",
"uint256",
"address",
"bytes32",
"address",
"address",
"bytes32",
"bytes32",
"uint256",
"bool",
],
[
keccak256(
toUtf8Bytes(
"ChioEscrowProof(uint256 chainId,address escrow,bytes32 escrowId,address token,address beneficiary,bytes32 operatorKeyHash,bytes32 receiptHash,uint256 amount,bool partial)",
),
),
31337,
config.addresses.ChioEscrow,
escrowId,
config.addresses.MockERC20,
config.beneficiary,
config.operator_key_hash,
receipt,
amount,
partial,
],
),
);
}
async function execute(input) {
const context = await connect();
const { config, provider, contract } = context;
try {
if (input.action === "buy_report") {
const { purchaseReport } = await import("./x402.mjs");
return await purchaseReport(context, input, directory, save);
}
const token = contract("MockERC20", 2);
const escrow = contract("ChioEscrow", input.action === "refund" ? 2 : 3);
const registry = contract("ChioRootRegistry", 1);
const location = path.join(directory, "chain-orders");
fs.mkdirSync(location, { recursive: true, mode: 0o700 });
if (!/^[a-zA-Z0-9-]{1,80}$/.test(input.order_id))
throw Error("Invalid work order ID");
const file = path.join(location, input.order_id + ".json");
if (input.action === "fund") {
if (fs.existsSync(file))
throw Error("Order already funded; inspect its retained transaction");
if (
!Number.isSafeInteger(input.amount) ||
input.amount < 1 ||
input.amount > 300000
)
throw Error("Amount outside bounded work order");
const block = await provider.getBlock("latest");
const terms = {
capabilityId: "0x" + sha(input.capability_id + ":" + input.order_id),
depositor: config.depositor,
beneficiary: config.beneficiary,
token: config.addresses.MockERC20,
maxAmount: input.amount,
deadline: block.timestamp + 300,
operator: config.operator,
operatorKeyHash: config.operator_key_hash,
};
const escrowId = await escrow.deriveEscrowId(terms);
// Persist intent before publishing. Recovery inspects this exact escrow;
// it never creates a second escrow or chooses a replacement order ID.
const order = {
order_id: input.order_id,
terms,
escrow_id: escrowId,
transactions: [],
state: "funding",
};
save(file, order);
order.transactions.push(
await transact(
token.approve(config.addresses.ChioEscrow, input.amount),
),
);
save(file, order);
order.transactions.push(
await transact(escrow.connect(context.signers[2]).createEscrow(terms)),
);
injectedInterruption("after-create");
order.state = "funded";
save(file, order);
return order;
}
const order = load(file);
if (input.action === "recover") return await recover(order, file, context);
if (input.action === "release") {
if (
!/^[0-9a-f]{64}$/.test(input.receipt_id) ||
!Number.isSafeInteger(input.amount) ||
input.amount < 1 ||
input.amount > order.terms.maxAmount
)
throw Error("Invalid exact receipt or amount");
if (order.state !== "funded")
throw Error("Order is not awaiting release");
const partial = input.amount < order.terms.maxAmount;
const receipt = "0x" + input.receipt_id;
const root = leaf(
config,
order.escrow_id,
receipt,
input.amount,
partial,
);
const sequenceFile = path.join(directory, "root-sequence.json");
const seq = fs.existsSync(sequenceFile) ? load(sequenceFile).next : 1;
save(sequenceFile, { next: seq + 1 });
order.state = "releasing";
order.release = {
receipt_id: input.receipt_id,
amount: input.amount,
partial,
root,
sequence: seq,
};
save(file, order);
order.transactions.push(
await transact(
registry.publishRoot(
config.operator,
root,
seq,
seq,
seq,
1,
config.operator_key_hash,
),
),
);
save(file, order);
injectedInterruption("after-root");
const method = partial
? "partialReleaseWithProofDetailed"
: "releaseWithProofDetailed";
const balanceBefore = (
await token.balanceOf(config.beneficiary)
).toString();
const controls = [];
for (const [name, action] of [
[
"altered receipt hash",
() =>
escrow[method].staticCall(
order.escrow_id,
{ auditPath: [], leafIndex: 0, treeSize: 1 },
root,
"0x" + "00".repeat(32),
input.amount,
),
],
[
"wrong beneficiary caller",
() =>
escrow
.connect(context.signers[2])
[
method
].staticCall(order.escrow_id, { auditPath: [], leafIndex: 0, treeSize: 1 }, root, receipt, input.amount),
],
]) {
let refused = false;
try {
await action();
} catch (error) {
if (error.code !== "CALL_EXCEPTION") throw error;
refused = true;
controls.push({
case: name,
result: "contract reverted",
error: error.revert?.name ?? error.shortMessage,
});
}
if (!refused)
throw Error("Contract admitted negative control: " + name);
}
const balanceAfter = (
await token.balanceOf(config.beneficiary)
).toString();
if (balanceBefore !== balanceAfter)
throw Error("A proof control changed the beneficiary balance");
order.proof_controls = {
calls: controls,
balance_before: balanceBefore,
balance_after: balanceAfter,
};
save(file, order);
order.transactions.push(
await transact(
escrow[method](
order.escrow_id,
{ auditPath: [], leafIndex: 0, treeSize: 1 },
root,
receipt,
input.amount,
),
),
);
injectedInterruption("after-release");
order.state = partial ? "partial" : "released";
save(file, order);
return order;
}
if (input.action === "refund") {
if (order.state !== "partial" && order.state !== "funded")
throw Error("Order has no refundable balance");
// Time travel is specific to this local test chain and is recorded.
const block = await provider.getBlock("latest");
const seconds = Math.max(0, order.terms.deadline - block.timestamp + 1);
await provider.send("evm_increaseTime", [seconds]);
await provider.send("evm_mine", []);
order.state = "refunding";
save(file, order);
order.transactions.push(await transact(escrow.refund(order.escrow_id)));
injectedInterruption("after-refund");
order.state = "refunded";
order.local_clock_advance_seconds = seconds;
save(file, order);
return order;
}
if (input.action === "status")
return {
...order,
source_hash: config.source_hash,
chain_id: config.chain_id,
escrow_contract: config.addresses.ChioEscrow,
beneficiary_balance: (
await token.balanceOf(config.beneficiary)
).toString(),
buyer_balance: (await token.balanceOf(config.depositor)).toString(),
escrow_balance: (
await token.balanceOf(config.addresses.ChioEscrow)
).toString(),
};
throw Error("Unknown local chain action");
} finally {
provider.destroy();
}
}
try {
if (mode === "serve") await serve();
else if (mode === "execute") {
let input = "";
for await (const chunk of process.stdin) {
input += chunk;
if (input.length > 262144) throw Error("Input too large");
}
console.log(JSON.stringify(await execute(JSON.parse(input))));
} else
throw Error(
"Usage: node chain.mjs serve HOST_DIRECTORY | execute HOST_DIRECTORY < request.json",
);
} catch (error) {
console.error(
JSON.stringify({
stage,
message: error.shortMessage ?? error.message,
detail: error.info ?? null,
}),
);
if (ownedServer) await ownedServer.close();
process.exitCode = 1;
}Buy a report with a standard x402 client
Atlas also purchases the original signed review through HTTP. Chio admits the exact price and separately approved report hash before the wallet signs. The official @x402/core and @x402/evm 2.25.0 client reads PAYMENT-REQUIRED, creates an EIP-3009 authorization for the standard exact scheme, then submits PAYMENT-SIGNATURE. The official facilitator verifies and settles the transfer before the resource server releases the report.
const client = new x402HTTPClient(
x402Client
.fromConfig({
schemes: [{ network, client: new ClientScheme(payer) }],
spendControls: {
allowedAssets: [
{
network,
asset: requirements.asset,
maxAmountPerPayment: "10000",
},
],
},
})
.registerPolicy((version, choices) =>
choices.filter(
(choice) =>
version === 2 &&
choice.network === network &&
choice.scheme === "exact" &&
choice.amount === "10000" &&
choice.asset === requirements.asset &&
choice.payTo === requirements.payTo,
),
),
);The response includes PAYMENT-RESPONSE and the actual transaction. Four changed-payment attempts fail; replay cannot pay or deliver twice. The client verifies the returned report bytes, the consumed authorization and both balances. This x402 payment is separate from Chio’s receipt-bound escrow protocol.
Read x402.mjs · complete standard client and local resource server 329 lines · complete file
/** Standard x402 v2 exact payment on the application's private EIP-3009 chain. */
import assert from "node:assert/strict";
import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import {
createPublicClient,
createWalletClient,
http as transport,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { x402Client, x402HTTPClient } from "@x402/core/client";
import {
encodePaymentRequiredHeader,
decodePaymentSignatureHeader,
encodePaymentResponseHeader,
} from "@x402/core/http";
import { ExactEvmScheme as ClientScheme } from "@x402/evm/exact/client";
import { ExactEvmScheme as FacilitatorScheme } from "@x402/evm/exact/facilitator";
import { toFacilitatorEvmSigner } from "@x402/evm";
export async function purchaseReport(context, input, directory, save) {
const { config, provider, contract } = context;
const file = path.join(directory, "x402-" + input.order_id + ".json");
if (fs.existsSync(file))
throw Error(
"Payment intent exists; inspect its nonce and retained transaction before retrying",
);
assert.equal(input.amount, 10000);
const body = input.report_json;
assert.equal(
crypto.createHash("sha256").update(body).digest("hex"),
input.report_hash,
);
const network = "eip155:31337";
const chain = {
id: 31337,
name: "Private work-order chain",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: { default: { http: [config.endpoint] } },
};
const keys = JSON.parse(
fs.readFileSync(path.join(directory, "chain-wallets.json"), "utf8"),
);
const payer = privateKeyToAccount(keys[2]);
const facilitatorAccount = privateKeyToAccount(keys[0]);
const publicClient = createPublicClient({
chain,
transport: transport(config.endpoint),
pollingInterval: 50,
});
const walletClient = createWalletClient({
account: facilitatorAccount,
chain,
transport: transport(config.endpoint),
});
const facilitator = new FacilitatorScheme(
toFacilitatorEvmSigner(
{
address: facilitatorAccount.address,
readContract: publicClient.readContract,
verifyTypedData: publicClient.verifyTypedData,
getCode: publicClient.getCode,
writeContract: walletClient.writeContract,
sendTransaction: walletClient.sendTransaction,
waitForTransactionReceipt: publicClient.waitForTransactionReceipt,
},
{ confirmationTimeoutMs: 15000 },
),
{ simulateInSettle: true },
);
const requirements = {
scheme: "exact",
network,
amount: String(input.amount),
asset: config.addresses.MockERC20,
payTo: config.beneficiary,
maxTimeoutSeconds: 1800,
extra: {
name: "Work order test dollars",
version: "1",
assetTransferMethod: "eip3009",
},
};
const client = new x402HTTPClient(
x402Client
.fromConfig({
schemes: [{ network, client: new ClientScheme(payer) }],
spendControls: {
allowedAssets: [
{
network,
asset: requirements.asset,
maxAmountPerPayment: "10000",
},
],
},
})
.registerPolicy((version, choices) =>
choices.filter(
(choice) =>
version === 2 &&
choice.network === network &&
choice.scheme === "exact" &&
choice.amount === "10000" &&
choice.asset === requirements.asset &&
choice.payTo === requirements.payTo,
),
),
);
let required;
let deliveries = 0;
let settling = false;
const acceptedNonces = new Set();
const exchanges = [];
const server = http.createServer(async (request, response) => {
const deny = (reason) => {
exchanges.push({ status: 402, reason });
response.writeHead(402, {
"PAYMENT-REQUIRED": encodePaymentRequiredHeader({
...required,
error: reason,
}),
"Content-Type": "application/json",
});
response.end(JSON.stringify({ error: reason }));
};
if (
request.method !== "GET" ||
request.url !== "/report/" + input.report_hash
) {
response.writeHead(404);
response.end();
return;
}
const header = request.headers["payment-signature"];
if (!header) {
deny("Payment authorization required");
return;
}
if (typeof header !== "string" || header.length > 12000) {
deny("Invalid payment header");
return;
}
let payload;
try {
payload = decodePaymentSignatureHeader(header);
assert.deepEqual(payload.accepted, requirements);
assert.deepEqual(payload.resource, required.resource);
assert.equal(payload.x402Version, 2);
} catch {
deny("Payment terms or resource changed");
return;
}
const nonce = payload.payload?.authorization?.nonce;
if (settling || acceptedNonces.has(nonce)) {
deny("Authorization already in use or delivered");
return;
}
settling = true;
try {
const verified = await facilitator.verify(payload, requirements);
if (!verified.isValid) {
deny(verified.invalidReason ?? "Invalid payment authorization");
return;
}
const settlement = await facilitator.settle(payload, requirements);
if (!settlement.success) {
deny(settlement.errorReason ?? "Payment not settled");
return;
}
acceptedNonces.add(nonce);
deliveries += 1;
exchanges.push({ status: 200, settlement });
response.writeHead(200, {
"PAYMENT-RESPONSE": encodePaymentResponseHeader(settlement),
"Content-Type": "application/json",
});
response.end(body);
} catch {
response.writeHead(503);
response.end(
JSON.stringify({ error: "Payment outcome requires reconciliation" }),
);
} finally {
settling = false;
}
});
await new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const url =
"http://127.0.0.1:" +
server.address().port +
"/report/" +
input.report_hash;
required = {
x402Version: 2,
resource: {
url,
description: "Signed review of actual escrow obligations",
mimeType: "application/json",
},
accepts: [requirements],
};
const token = contract("MockERC20", 2);
const balances = async () => ({
payer: String(await token.balanceOf(config.depositor)),
provider: String(await token.balanceOf(config.beneficiary)),
});
const request = (headers = {}) =>
fetch(url, {
headers,
redirect: "error",
signal: AbortSignal.timeout(20000),
});
try {
const before = await balances();
const challenge = await request();
assert.equal(challenge.status, 402);
const selected = client.getPaymentRequiredResponse((name) =>
challenge.headers.get(name),
);
await challenge.arrayBuffer();
const payload = await client.createPaymentPayload(selected);
save(file, { state: "prepared", report_hash: input.report_hash, payload });
// The official facilitator checks changed signed values. No delivery or balance change is allowed.
for (const [name, change] of [
[
"amount",
(value) => {
value.payload.authorization.value = "10001";
},
],
[
"beneficiary",
(value) => {
value.payload.authorization.to = config.depositor;
},
],
[
"signature",
(value) => {
value.payload.signature = "0x" + "00".repeat(65);
},
],
[
"network",
(value) => {
value.accepted.network = "eip155:1";
},
],
]) {
const changed = structuredClone(payload);
change(changed);
const response = await request(
client.encodePaymentSignatureHeader(changed),
);
assert.equal(response.status, 402, name);
await response.arrayBuffer();
assert.deepEqual(await balances(), before, name + " moved funds");
}
assert.equal(deliveries, 0);
const paid = await request(client.encodePaymentSignatureHeader(payload));
const content = await paid.text();
assert.equal(paid.status, 200, content);
assert.equal(content, body);
const settlement = client.getPaymentSettleResponse((name) =>
paid.headers.get(name),
);
assert.equal(settlement.success, true);
const transaction = await provider.getTransactionReceipt(
settlement.transaction,
);
assert.equal(transaction.status, 1);
const after = await balances();
assert.equal(BigInt(before.payer) - BigInt(after.payer), 10000n);
assert.equal(BigInt(after.provider) - BigInt(before.provider), 10000n);
const replay = await request(client.encodePaymentSignatureHeader(payload));
assert.equal(replay.status, 402);
await replay.arrayBuffer();
assert.deepEqual(await balances(), after);
assert.equal(
await token.authorizationState(
config.depositor,
payload.payload.authorization.nonce,
),
true,
);
assert.equal(
(await facilitator.verify(payload, requirements)).isValid,
false,
"Consumed authorization was accepted again on chain",
);
assert.equal(deliveries, 1);
const result = {
protocol: "x402",
version: 2,
scheme: "exact",
sdk: "@x402/core + @x402/evm 2.25.0",
network,
amount: "10000",
asset: requirements.asset,
payer: config.depositor,
pay_to: config.beneficiary,
report_hash: input.report_hash,
report: JSON.parse(content),
payment_required: selected,
payment_payload: payload,
settlement,
transaction: {
hash: transaction.hash,
block_hash: transaction.blockHash,
block_number: transaction.blockNumber,
status: transaction.status,
},
before,
after,
deliveries,
exchanges,
};
save(file, { state: "settled", ...result });
return result;
} finally {
await new Promise((resolve) => server.close(resolve));
}
}An uncertain x402 outcome retains its intent and nonce and stops automatic repurchase. The escrow recovery examples demonstrate their three named publication points; automatic recovery of the separate HTTP resource service remains an application responsibility.
Give the auditor the original operations
Meridian fetches each request and response directly from its configured serving host. It verifies the selected signer, signature, request identity, capability, arguments and exact output hash. A missing receipt or changed record hash refuses the audit. Its final signed record binds the complete ordered list, including refusals and interrupted work.
uv run --locked check_capture.pyThis selects the newest completed local run and reads its independently configured auditor key. The verifier checks all signed operations and financial summaries. Its mutation tests reject changed inputs, outputs, signer lists, capabilities, order IDs, contract source, payment summaries and omitted or reordered operations.
Read verify.py · complete independent artifact verifier 108 lines · complete file
"""Verify an execution capture against an independently selected auditor key."""
import argparse
from pathlib import Path
from evidence import digest, read, verify_result
def verify(capture, auditor_key):
audit = capture["audit"]
verify_result(audit, auditor_key)
if audit["receipt"]["tool_server"] != "meridian" or audit["receipt"]["tool_name"] != "audit":
raise ValueError("Selected auditor did not sign a work-order audit")
if audit["receipt"]["decision"]["verdict"] != "allow":
raise ValueError("The auditor refused this capture")
operations = capture["operations"]
if not operations or operations[-1]["result"] != audit:
raise ValueError("Final operation differs from the signed audit")
verify_result(audit, auditor_key, operations[-1]["request"])
audited_input = audit["receipt"]["action"]["parameters"]["data"]
for field in ["trusted_kernels", "capabilities"]:
if capture[field] != audited_input[field]:
raise ValueError("Published " + field + " differs from the auditor's verified input")
references = audited_input["records"]
if len(references) != len(operations) - 1:
raise ValueError("An operation was added or omitted after the audit")
for operation, reference in zip(operations[:-1], references, strict=True):
receipt = operation["result"]["receipt"]
if digest(operation) != reference["record_hash"]:
raise ValueError("Retained operation differs from the auditor's pinned record")
if reference["receipt_id"] != receipt["id"] or reference["host"] != receipt["tool_server"]:
raise ValueError("Audited receipt or serving host was substituted")
# The selected auditor binds this exact record, including its signed
# kernel identity. The capture cannot substitute its own trust list.
verify_result(operation["result"], receipt["kernel_key"], operation["request"])
receipts = [operation["result"]["receipt"]["id"] for operation in operations[:-1]]
if audit["output"]["verified_receipts"] != receipts or len(set(receipts)) != len(receipts):
raise ValueError("Auditor output does not match the complete operation sequence")
by_id = {operation["result"]["receipt"]["id"]: operation["result"] for operation in operations}
for field, state in [
("full_release_receipt", "released"),
("partial_release_receipt", "partial"),
("refund_receipt", "refunded"),
]:
result = by_id[capture[field]]
if (
result["receipt"]["decision"]["verdict"] != "allow"
or result["output"]["escrow"]["state"] != state
):
raise ValueError("Settlement summary is not bound to its actual signed result")
payment = by_id[capture["x402_receipt"]]
if (
payment["receipt"]["tool_name"] != "buy_report"
or payment["receipt"]["decision"]["verdict"] != "allow"
):
raise ValueError("x402 summary is not bound to a permitted purchase")
result = payment["output"]["payment"]
if (
result["protocol"] != "x402"
or result["scheme"] != "exact"
or result["deliveries"] != 1
or not result["settlement"]["success"]
):
raise ValueError("x402 purchase did not settle and deliver once")
if (
digest(result["report"]) != result["report_hash"]
or int(result["before"]["payer"]) - int(result["after"]["payer"]) != 10000
):
raise ValueError("x402 report or payment does not match its signed evidence")
status = [
operation["result"]["output"]
for operation in operations
if operation["request"]["tool_name"] == "status"
and operation["result"]["receipt"]["decision"]["verdict"] == "allow"
]
if not status or capture["balances"] != status[-1]["escrow"]:
raise ValueError("Published balances differ from the signed final observation")
if capture["chain_source_hash"] != capture["balances"]["source_hash"]:
raise ValueError("Contract source hash differs from the signed chain observation")
full = by_id[capture["full_release_receipt"]]["output"]["order_id"]
partial = by_id[capture["partial_release_receipt"]]["output"]["order_id"]
refunded = by_id[capture["refund_receipt"]]["output"]["order_id"]
if capture["orders"] != [full, partial] or full == partial or partial != refunded:
raise ValueError("Order summary differs from the signed settlements")
if (
int(capture["balances"]["buyer_balance"])
+ int(capture["balances"]["beneficiary_balance"])
+ int(capture["balances"]["escrow_balance"])
!= 1_000_000
):
raise ValueError("Local token balances do not reconcile")
return {
"verified_operations": len(operations),
"auditor_receipt": audit["receipt"]["id"],
"allowed": audit["output"]["allowed"],
"refused": audit["output"]["refused"],
"incomplete": audit["output"]["incomplete"],
}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("capture", type=Path)
parser.add_argument(
"--auditor-key", required=True, help="Selected independently of the capture being verified"
)
args = parser.parse_args()
print(verify(read(args.capture), args.auditor_key))Build on the application
The download includes every source file, dependency lock, contract and Python SDK source. Use the role boundaries as the starting point for your own network:
| Change | Start here | Preserve |
|---|---|---|
Use a different kind of work | Bounded input, concrete retained output and matching specialist evidence. | |
Add your own providers | Selected issuers, holder-bound challenges and evidence from actual work. | |
Change the authority tree | Signed attenuation, stored ancestry and revocation before dispatch. | |
Add operator review | A separate credential and approval of exact terms, outside the agent’s tools. | |
Connect a deployed payment service | Explicit network, asset, recipient, amount and transaction reconciliation. |
For your first modification, change the second specification in run.py and its expected acceptance result. Then replace the review function with your own bounded service. The default sequence is deterministic application code; adding a model should route its proposed operations through these same governed entrypoints.
Keep execution.json when sharing evidence. The surrounding .state directory contains private development identities and operator credentials. Each run has its own directory, so earlier work remains available for inspection.
Continue with the Agent Marketplace, compose a larger Agentic OS, or compare this settlement path with the Commerce Network’s durable purchasing ledger.