13/Integrate

The gateway, route by route

The x402 gateway (apps/x402-gateway/src/app.ts, Hono) serves ten free routes, three paid x402 routes and one internal route the agent pushes to. The base URL is X402_GATEWAY_URL (default http://localhost:4020); this build points at https://parity.mrnetwork.tech. Types come from packages/quant-kernel/src/types.ts. CORS is open to every origin.

Every route

MethodPathPricePurpose
GET/healthFreeLiveness, network, operator, facilitator, whether HCS publishing is on, agent heartbeat
GET/statusFreeEverything the dashboard shows (below)
GET/agent.jsonFreeERC-8004 registration file
GET/.well-known/agent-registration.jsonFreeSame as /agent.json
GET/.well-known/ucpFreeUCP agent card: identity, audit topics, live prices, guarantee policy
GET/ucp.jsonFreeSame as /.well-known/ucp
GET/track-recordFreeTrack-record summary, the last 500 predictions and scores, topic id, Mirror Node hint
GET/guaranteesFreeThe last 200 clearances and guarantee stats
GET/guarantees/:idFreeOne clearance, or 404
POST/guarantee/claimFreeClaim the slippage guarantee for a cleared swap
GET/x402/toxicity-quotex402, 1× ($0.0100)Live toxicity quote
POST/x402/rebalance-planx402, 2× ($0.0200)EV-optimal range and hedge plan for your position
POST/x402/protected-executex402, 2.5× ($0.0250)Pre-trade clearance with a slippage guarantee
POST/internal/snapshotInternalAgent push; needs x-parity-secret when INTERNAL_SYNC_SECRET is set, loopback only when it is not

Paid prices are the calm-market defaults; see x402 endpoints and pricing for the formula. Paid routes use x402 v2, scheme exact, on hedera:mainnet, in USDC 0.0.456858.

Free routes

GET /health

responsejson
{
  "ok": true,
  "service": "parity-x402-gateway",
  "network": "hedera:mainnet",
  "operatorAccountId": "0.0.x",
  "facilitatorUrl": "https://api.blocky402.com",
  "hcsPublisherEnabled": true,
  "agentOnline": true,
  "agentHeartbeatMs": 1764849600000
}

GET /status

StatusResponsets
{
  network: string;                 // "hedera:mainnet" | "hedera:testnet"
  operatorAccountId: string;
  hashscanBase: string;            // "https://hashscan.io/mainnet"
  mirrorNodeUrl: string;
  topics: { decision: string | null; pnl: string | null; track: string | null };
  agentOnline: boolean;            // last push younger than 3 poll intervals + 30 s
  agentHeartbeatMs: number | null;
  bootstrap: boolean;              // true until the agent's first push: numbers are placeholders
  snapshot: MarketSnapshot;        // includes provenance
  mandate: EnsMandate;
  ensSource: string;               // "mainnet-live" | "sepolia-live" | "cached" | "unavailable" | "local-fallback" | "bootstrap"
  ensProfile: unknown | null;      // ENSIP-25/26/28/31 profile
  latestDecision: RiskDecision;
  economics: UnitEconomicsSnapshot;
  pricing: EndpointPricing;
  treasury: TreasuryState | null;
  trackRecord: TrackRecordSummary;
  guarantees: GuaranteeStats;      // issued, cleared, claimed, honored, refunded, refundedUsd, feesUsd
  predictions: Prediction[];       // last 50
  scores: PredictionScore[];       // last 50
  clearances: Clearance[];         // last 50
  executions: ExecutionRecord[];   // last 50
  ledger: LedgerEntry[];           // last 100
  hook: { status; reason; txHash?; explorerUrl?; chainId?; score? } | null;
}

GET /track-record

responsets
{
  summary: TrackRecordSummary;
  predictions: Prediction[];       // last 500
  scores: PredictionScore[];       // last 500
  topicId: string | null;
  verifyHint: string | null;       // "{mirror}/api/v1/topics/{topicId}/messages?order=desc&limit=100"
}

GET /guarantees and /guarantees/:id

/guarantees returns { clearances: Clearance[], stats: GuaranteeStats } with the last 200 clearances. /guarantees/:id returns one Clearance or 404 { "error": "Unknown clearance" }.

POST /guarantee/claim

requestbash
curl -s -X POST https://parity.mrnetwork.tech/guarantee/claim \
  -H 'content-type: application/json' \
  -d '{ "clearanceId": "clr_…", "transactionId": "0.0.1234@1764849600.123456789" }'
response (GuaranteeClaimResult)json
{
  "status": "REFUNDED",
  "reason": "Realized 92.4 bps > guaranteed 80 bps: fee refunded",
  "transactionId": "0.0.1234@1764849600.123456789",
  "fill": { "side": "SELL_HBAR", "hbarAmount": 10, "usdcAmount": 1.71, "executionPrice": 0.171 },
  "realizedSlippageBps": 92.4,
  "guaranteedMaxSlippageBps": 80,
  "refundAmountUsd": 0.025,
  "refundTx": "0.0.x@1764849607.000000000",
  "evaluatedAtMs": 1764849608000
}

The numbers in this example are illustrative. clearanceId is 1 to 64 characters; transactionId must look like 0.0.x@secs.nanos or 0.0.x-secs-nanos.

Before the agent's first push every paid route answers 503 "Risk agent warming up; you were not charged." Without a payment, each answers 402 with the challenge in the payment-required header.

GET /x402/toxicity-quote?pair=HBAR-USDC

responsets
{
  provider: string;                // the ENS name
  hederaAccountId: string;
  quote: ToxicityQuote;            // ewmaAnnualizedVolPct, crossVenueSkewBps, toxicityScore, regime,
                                   // recommendedDynamicFeeBps, recommendedTickHalfWidth, maxSafeSlippageBps,
                                   // recommendedSplitCount, estimated24hLvrUsd
  referencePrice: number;
  venuePrice: number;
  provenance: Record<string, string>;
  trackRecord: TrackRecordSummary;
  pricing: EndpointPricing;
  decisionProofHash: string;
}

The handler always quotes the desk's HBAR-USDC snapshot; the pair query is not read.

POST /x402/rebalance-plan

request (every field optional)jsonc
{
  "positionNotionalUsd": 2500,       // > 0, at most 10,000,000
  "positionDeltaRatio": 0.2,         // -1 to 1; (HBAR USD - USDC) / total
  "currentTick": -170000,
  "currentTickLower": -170480,
  "currentTickUpper": -169520
}

Your fields override the desk's snapshot, and the response is { provider, quote: ToxicityQuote, plan: RebalancePlan }. plan holds the recommended action, tick range, hedge size, projected fees, friction, LVR, expected net EV, lpEdgeDailyPct, all seven range candidates and a rationale.

POST /x402/protected-execute

requestjsonc
{
  "side": "SELL_HBAR",               // or "BUY_HBAR"
  "amountIn": 10,                    // display units of the input token, > 0
  "maxSlippageBps": 80,              // all-in, > 0 and at most 2000
  "pair": "HBAR-USDC",               // optional, the only value
  "callerAgentId": "my-agent"        // optional, up to 200 characters
}
response (ProtectedExecuteResponse)ts
{
  cleared: boolean;
  reasons: string[];               // why (not) cleared
  clearance: Clearance;            // payer and paymentTx are bound after settlement: fetch /guarantees/:id
  expectedCost: ImpactEstimate;    // side, amountIn, feeBps, priceImpactBps, allInCostBps, withinSingleRange
  toxicity: { score: number; regime: "CALM" | "ELEVATED" | "TOXIC" };
  recommendedSplitCount: number;
  guarantee: { maxSlippageBps: number; validUntilMs: number; claimUrl: "/guarantee/claim"; policy: string };
}

The response header x-parity-clearance-id carries the clearance id. Rules and claim flow are on Slippage guarantee.

Status codes

CodeRouteMeaning
400rebalance-plan, protected-execute, claimThe body failed validation; the error tree explains why
401/internal/snapshotMissing or wrong x-parity-secret
402/x402/*Payment required; read the payment-required header
404/guarantees/:id, claimUnknown clearance
409claimThe clearance payment has not settled, or a claim is already in progress
422claimThe claim was REJECTED; the clearance stays open
502claimA refund is owed but the transfer failed
503/x402/*Agent warming up, or the execution pool is unavailable; you are not charged

HCS message schemas

All messages are single JSON documents on the topics from pnpm init:topics.

SchemaTopicSent byCarries
parity.decision.v1decisionagent, every cyclepoolId, finalAction, approved, proposalSource, toxicityScore, regime, venuePx, refPx, expectedNetEvUsd, lpEdgeDailyPct, failed checks, decisionProofHash, ts
parity.execution.v1decisionagent, after a live swapaction, side, amountIn, quotedOut, costBps, tx, proof
parity.mode.v1decisionagent, on a mode changefrom, to, reason, runwayDays, ts
parity.agent-card.v1decisionagent, on start-upname, account, ens, erc8004, gateway, topics, ts
parity.prediction.v1trackagentPrediction
parity.score.v1trackagentPredictionScore
parity.pnl.v1pnlagent and gatewayLedgerEntry
parity.clearance.v1pnlgateway, after a clearance is paidid, payer, cleared, mid, guaranteedBps, notionalUsd, feeUsd, paymentTx, expiresAtMs, proof
parity.refund.v1pnlgateway, after a claimclearanceId, payer, status, swapTx, realizedSlippageBps, guaranteedMaxSlippageBps, refundTx, refundAmountUsd
read a topic from the Mirror Nodebash
curl -s "https://mainnet.mirrornode.hedera.com/api/v1/topics/<topicId>/messages?order=desc&limit=100" \
  | jq -r '.messages[].message | @base64d'