02/Getting started

One cycle, end to end

Every 60 seconds the agent observes the market, scores it, plans, lets an optional LLM propose, and lets the risk kernel decide; the verdict is hashed and anchored to HCS before any swap is sent. The loop is runAgentCycle in apps/agent/src/index.ts. The gateway never decides anything: it serves the agent's latest state and sells it over x402.

The loop

  1. 01feeds.tsObservecollectMarketContext pulls the SaucerSwap V2 pool, Kraken 5-minute candles, CoinGecko, and the desk's balances from the Mirror Node. Every field gets a provenance label.
  2. 02quant-kernelScore and planscorePoolToxicity gives a 0 to 100 toxicity score and a regime; buildRebalancePlan ranks seven range widths by 24-hour expected value net of LVR and churn.
  3. 03strategist.tsProposegenerateStrategistProposal asks an OpenAI-compatible model for one JSON action, only when a key is set and the treasury is THRIVING. Otherwise the quant plan is the proposal.
  4. 04riskKernel.tsDisposeevaluateDecision runs eight guardrails, picks the final action and hashes the verdict with SHA-256.
  5. 05executor.tsAct and publishAnchor the verdict to HCS, swap if approved, commit and score forecasts, drive the Uniswap hook, book costs, and push the snapshot to the gateway.

The life of one decision

This follows a single cycle through the code in the order it runs. The timings are the defaults from apps/agent/src/config.ts. No run log ships with the repository, so there are no real transaction ids here; on a running deployment each step below shows up on the decision topic and in /app.

1. Read the market and the mandate, in parallel

collectMarketContext and readEnsMandate start together. The market side fetches /v2/pools from SaucerSwap and picks pool 0.0.3964804, whose mid price comes from sqrtPriceX96. Signals always come from the mainnet pool unless SIGNAL_NETWORK says otherwise, even when the desk trades on testnet. Kraken's HBARUSD 5-minute candles give 288 log returns (the last 24 hours, minus the candle still forming) and the volume for order flow; the reference price is the median of Kraken and CoinGecko. The fee APR comes from the pool's hourly volume and TVL over the last 24 hours, and the desk's HBAR and USDC come from the Mirror Node.

If the pool itself cannot be read, the cycle throws (no price, no decision) and the loop tries again after one poll interval. Anything else degrades out loud: no candles means the volatility prior of 25%, no fee data means a fee APR of 0, which keeps the desk out of the pool. Each fallback is written into provenance and warnings.

2. Work out the runway

computeTreasuryState values the balances at the pool mid and divides by the net daily burn of the last 24 hours, using the agent's own costs plus the revenue the gateway reported on the previous push. The result is a survival mode that decides whether the LLM may run and whether trading is allowed. See Survival economics.

3. Propose

The strategist builds the quant proposal first. It calls the model only if OPENAI_API_KEY is set and the treasury allows LLM spend, with temperature 0.1, JSON output and a 15-second timeout. The reply must pass a zod schema (slippage 1 to 200 bps, a rationale up to 600 characters); anything else falls back to the quant proposal. A call that returned is booked as an LLM_INFERENCE cost of LLM_CALL_COST_USD (default $0.0025), marked off-chain.

4. Dispose

evaluateDecision recomputes the quote and plan itself, so the LLM cannot feed it different numbers, then runs the eight checks. A failed mandate or pool check gives PAUSE_ON_MANDATE; any other failure gives HOLD. The result carries a decisionProofHash. Details on Risk kernel.

5. Anchor, then act

anchorDecision publishes parity.decision.v1 to the decision topic first. If the survival mode changed since the last cycle, a parity.mode.v1 message follows. Only then does executeApprovedAction run: it trades only an approved REBALANCE_RANGE or DELTA_HEDGE, sizes the swap toward 50/50 value, and stays a dry run unless LIVE_EXECUTION=true. On a live run it asks the SaucerSwap plugin for a quote, refuses if the quoted all-in cost is above the mandate's slippage cap, swaps with swap_v2_tool, reads the network fee back from the Mirror Node, books a SWAP_COST, and publishes parity.execution.v1.

6. Forecast, hook, books, push

  1. Forecasts whose one-hour horizon has passed are scored against the current reference price and published as parity.score.v1. If 15 minutes have passed since the last forecast and there are more than 10 returns, a new parity.prediction.v1 goes out.
  2. The Uniswap hook publisher sends setToxicityOracle(score, paused) when the score moved by 5 or more, the pause flag flipped, or 10 minutes passed.
  3. HCS fees are summed and booked as one HEDERA_GAS entry every 10 minutes; every new ledger entry is published as parity.pnl.v1.
  4. pushToGateway posts the snapshot, mandate, decision, ledger, forecasts, executions and hook status to /internal/snapshot. The gateway answers with the merged economics, track record, prices and its last 24 hours of revenue, which the agent uses on the next cycle.

The memory is saved to .parity/agent-state.json and the next cycle starts after POLL_INTERVAL_MS (60000) times the mode's cadence multiplier: 1, 2, 4 or 8.

The app at a glance

/app polls GET /status every 8 seconds. This is what that response holds, field by field (apps/x402-gateway/src/app.ts).

FieldWhat it holds
snapshotThe latest market snapshot, with a provenance label per input
latestDecisionQuote, plan, the eight checks, final action and proof hash
mandateThe ENS mandate as last read, plus ensSource and ensProfile
economicsRevenue, costs, margin, builder-excluded revenue, unique external payers
treasuryBalances, burn and revenue rates, runway, survival mode
pricingThe live x402 prices and the multipliers behind them
trackRecordHit rate, calibration gap, credibility; the last 50 predictions and scores
guaranteesIssued, cleared, claimed, honored and refunded counts; the last 50 clearances
executionsThe last 50 execution records (live, dry run or blocked)
ledgerThe last 100 ledger entries
hookThe last hook publish result: status, reason, tx hash, explorer link
agentOnline, bootstrapWhether the agent pushed recently, and whether any real data has arrived yet

agentOnline is true while the last push is younger than three poll intervals plus 30 seconds. Until the first push, bootstrap is true and every number is a placeholder.