Architecture
How every part of the protocol is implemented, and what waits for Elysium's HyperCore upgrade.
How the master plan (readme.md) is implemented, what runs today, and what waits for
Elysium's HyperCore upgrade.
#The one constraint that shapes everything
Elysium is Kinetiq's Hyperliquid L2 (Arbitrum Orbit, chain id 99901, testnet 99801). Per
the official docs, its HyperCore
read precompile and ElysiumCoreWriter ship in an ArbOS upgrade after mainnet. As
of 2026-11-28 neither is live and no address, ABI or event signature has been published.
HyperEVM's precompile addresses (0x…0800, 0x3333…3333) return empty data on Elysium.
So the two things the plan wants on-chain — reading HyperCore prices and placing HyperCore orders — cannot be done on-chain yet by anyone. The design therefore puts each of them behind one narrow interface, with an implementation that works today and a slot for the native one:
| Capability | Interface | Works today | When the upgrade ships |
|---|---|---|---|
| Prices, depth, haircuts on-chain | IPriceEngine (Solidity) | HyperCoreRiskFeed: the backend derives everything from HyperCore's order book and posts it; the contract bounds every report | a precompile-backed engine implementing the same interface; the pool is unchanged and the reporter job is switched off |
| HyperCore market data off-chain | HyperCoreClient | HyperCore info API | same shapes from the precompile / RPC |
| Liquidation execution | ExecutionVenue (TypeScript) | SimulatedVenue (paper fills against the live book, default) and HyperliquidVenue (real orders through an agent wallet) | CoreWriterVenue: order intents through the predeploy, outcome by callback |
Nothing above those interfaces changes. In particular the liquidation engine already
separates submitting an order from confirming it and settles only on confirmed fills,
which is exactly the non-atomic model the Elysium docs describe for ElysiumCoreWriter.
#Components
HyperCore (order books, prices)
│ info API today / precompile later
┌──────────────▼───────────────┐
│ Price engine │ mid, bid/ask, spread, depth, TWAP,
│ src/price │ volatility, manipulation-resistant
└──────────────┬───────────────┘ reference price, status flags
┌──────────────▼───────────────┐
│ Risk engine │ liquidity + volatility + concentration
│ src/risk │ haircuts, freezes, cap recommendations
└───────┬───────────────┬──────┘
risk reporter │ │ health monitor
(bounded posts) ▼ ▼
┌─────────────────────────┐ ┌───────────────────────┐ ┌──────────────────┐
│ Contracts on Elysium │◄──┤ Liquidation engine ├───►│ Execution venue │
│ LendingPool, RiskFeed, │ │ src/liquidation │ │ (HyperCore book) │
│ FeeEngine, Insurance, │ └───────────────────────┘ └──────────────────┘
│ Rewards, POL │◄── fee engine (src/fees), rewards (src/rewards)
└───────────┬─────────────┘
│ events ┌───────────────────────────┐
▼ │ HTTP + WebSocket API │◄── frontend
Indexer (src/indexer) ──► Postgres ◄─┤ src/api (SIWE auth, │
│ unsigned tx builder) │
└───────────────────────────┘Processes: ROLE=api (stateless, scale horizontally) and ROLE=worker (polls HyperCore,
indexes, runs keepers). ROLE=all runs both in one process. Workers coordinate through
row leases in Postgres, so extra replicas are safe standbys, not duplicates.
#Master plan coverage
| § | Requirement | Where | Status |
|---|---|---|---|
| 2 | Supply, borrow, repay, withdraw, collateral | contracts/LendingPool.sol; unsigned transactions from /v1/tx/* | working, tested end to end |
| 2 | Pools, debt accounting, interest model, utilisation rates, LTV, thresholds, caps | LendingPool.sol; mirrored in src/lending/math.ts (tests assert equality with the chain) | working |
| 2 | Health factor, rates, thresholds for users | /v1/accounts/:address, /v1/markets, previews | working |
| 2 | Bad debt accounting | LendingPool._realizeBadDebtIfInsolvent, badDebt, coverBadDebt, socializeBadDebt | working |
| 3 | Prices, best bid/ask, spread, depth, liquidity, execution estimates, volatility from HyperCore | src/price, src/hypercore/book.ts; /v1/prices/* | working on live data; source is the info API until the precompile ships |
| 3 | No external oracle | no third-party price feed anywhere; every input is HyperCore's own book / marks | working |
| 3 | Manipulation resistance, liquidity requirements, freshness, conservative valuation, safeguards | reference = median of spot mid, time-weighted spot mid and HyperCore perp oracle; STALE / THIN / WIDE_SPREAD / DEVIATION flags; on-chain staleness bound, per-post price clamp, guardian freeze | working |
| 4 | Executable vs theoretical collateral value | haircut = cost of selling a stress size into the live book; executableCollateralUsd, liquidityAdjustedHealthFactor | working |
| 4 | Slippage, position size, volatility, concentration, execution costs | src/risk/engine.ts (assess) | working |
| 4 | Dynamic, bounded parameters that manipulation cannot use to force liquidations | borrow haircut reacts at once (limits new risk only); liquidation haircut is a median over a window, scaled down, and its increases are capped and rate-limited on-chain | working |
| 5 | Detect → size → check liquidity → order → fill → repay → update → insurance | src/liquidation/engine.ts + LendingPool two-phase liquidation | working (simulated venue by default) |
| 5 | Partial / full liquidation, slippage protection | close factor + full-liquidation threshold; rate bound fixed on-chain at beginLiquidation, enforced at settleLiquidation | working |
| 5 | Order tracking, partial fills, failed orders, retries | order rows, per-leg retry with fresh book, cancel + unlock when nothing fills | working |
| 5 | Debt settled only on confirmed fills | settlement amounts are computed from reconciled fills only | working |
| 5 | Duplicate-execution protection | one open liquidation per account (DB + pool), single-use on-chain reference, deterministic order ids written before sending | working, crash-tested |
| 5 | Emergency procedures | guardian emergency mode → atomic emergencyLiquidate; pause flags; anyone can cancel after the deadline | working |
| 5 | Orders through ElysiumCoreWriter | CoreWriterVenue | pending the Elysium upgrade |
| 6 | Self-custody with enforceable collateral restrictions | see Custody model | escrow implemented |
| 7 | Fee engine: receive, track, convert, allocate, distribute, record, expose, bounded adjustments | contracts/FeeDistributionEngine.sol, src/fees, /v1/fees* | working |
| 7 | No team wallet in the path | fees are paid to the contract; distribute is permissionless | working |
| 7 | Collection compatible with the launchpad | Montra: the fee engine becomes the pool's creator-fee recipient on Montra's LaunchHook (pnpm montra route) and claims the HYPE itself (claimLaunchFees, run by the fee keeper); also accepts plain transfers | working; rehearsed on a mainnet fork with a live Montra token |
| 8 | 40 / 25 / 15 / 10 / 10 split and what each module does | InsuranceFund, ProtocolOwnedLiquidity, 2 × RewardsDistributor, ModuleTreasury | working |
| 8 | Rewards based on actual revenue | epochs split only what a distributor has actually received (src/rewards/service.ts) | working |
| 9 | Normal / stress / growth allocation driven by protocol condition | src/fees/allocator.ts (regime + hysteresis), bounded on-chain | working |
#Design decisions worth knowing
All money is integer math. bigint everywhere: WAD (1e18) for prices and USD, basis
points for percentages, base units for tokens. Floats are used only for volatility
statistics. src/lending/math.ts and src/risk/health.ts reproduce the contract's
formulas operation for operation; the end-to-end suite asserts they agree with the chain.
The reference price needs two sources to move. With three HyperCore sources (spot mid, time-weighted spot mid, perp oracle) the reference is their median. A spoofed spot book moves one of them; a real move moves two. When the spot price disagrees with the others, the confirming sources are re-read immediately so a genuine move is followed within one polling tick.
Two haircuts, on purpose. Tightening what can be borrowed is always safe, so the
borrow haircut follows the order book immediately. Tightening who can be liquidated is
not, so the liquidation haircut is the median of the raw haircut over ten minutes, halved,
and the contract will only raise it by a bounded step per interval. Thinning the book for
a few seconds cannot make a healthy position liquidatable. (Tested:
test/unit/risk.test.ts, "manipulation resistance of the liquidation haircut".)
Only collateral that secures debt counts as exposure. A lender with no borrows can never be liquidated, so their balance does not enter the stress size.
Liquidation is a persisted state machine. planned → locked → executing → settling → settled | cancelled | failed. Each step is written before the next begins and every
external action is idempotent:
- the on-chain reference maps to the liquidation it started (
liquidationByRef), so a keeper that crashed after sendingbeginLiquidationfinds and adopts it; - order ids are derived from (reference, leg, attempt) and the order row is written before the order is sent, so a lost response is reconciled by id, never re-sent blind;
- debt changes only in
settleLiquidation, with amounts computed from confirmed fills.
The user is never charged more collateral than the bound allows. The slippage bound is fixed on-chain when collateral is locked. Order limits include the venue fee, and if proceeds still fell short the engine settles fewer collateral units; the remainder goes back to the borrower.
The indexer is exactly-once and reorg-safe. A block range's events, their effects and the cursor commit in one transaction. The hash of the last processed block is re-checked every pass; on a mismatch the indexer rewinds and rebuilds the position mirror by replay. A reconciliation job compares the mirror with the chain as a safety net.
The backend never has custody. It builds calldata; wallets sign. Keeper keys can only do what their on-chain role allows, and those roles are bounded by the contracts.
#Custody model
The plan asks for self-custody "wherever the underlying infrastructure permits it", with collateral that cannot be withdrawn while it secures debt, and says that if unrestricted self-custody is incompatible with secure lending, a non-custodial smart contract escrow must be used.
What HyperCore permits today: an agent (API wallet) can place and cancel orders on an account but can never withdraw or transfer. That is enough to let a protocol sell a borrower's collateral in place, but nothing stops the account owner from withdrawing the collateral first, and the agent cannot move the sale proceeds to repay the debt. So agent permissions alone do not give an enforceable restriction.
Therefore: collateral is held in a non-custodial smart-contract escrow (LendingPool).
No person or key can move a user's collateral except through the rules in the contract:
the user (while the position stays within its limit), or a liquidation that proves the
position is unhealthy, is bounded by the slippage limit, and returns everything it does
not sell. That is the plan's fallback, and it is the strongest guarantee available.
The interim execution path follows from that. Selling on HyperCore needs the asset on
HyperCore, and the Elysium → HyperEVM bridge has a ~24 hour challenge period. So the
liquidation engine sells from inventory it already holds on HyperCore and settles
on-chain from inventory it holds on Elysium (funded by the Liquidation Execution
Fund); the seized collateral replenishes that inventory. From the pool's and the
borrower's point of view the guarantees are the ones in the plan: nothing is repaid until
a fill is confirmed, at a rate no worse than the bound. When ElysiumCoreWriter and the
account-binding it brings are live, the pool can hold its own HyperCore trading account
and this inventory hop disappears.
#Repository layout
contracts/ reference Solidity contracts (see docs/CONTRACTS.md)
src/config environment, networks, market definitions and risk parameters
src/lib fixed-point maths, errors, logging, metrics
src/hypercore HyperCore client and order-book maths
src/price price engine
src/risk risk model, account health, on-chain reporter, health monitor
src/lending lending maths and the API read model
src/chain viem clients, typed ABIs, pool reader, tx builder, keeper sender
src/indexer event indexer and position mirror
src/liquidation planner, engine, execution venues
src/fees allocation model and fee keeper
src/rewards reward epochs and Merkle trees
src/auth Sign-In with Ethereum and sessions
src/api HTTP routes, schemas, WebSocket feed
src/workers job scheduler and job list
src/db schema and client (Postgres / embedded PGlite)
scripts deploy, migrate, seed, smoke test, OpenAPI export
test/unit pure logic
test/integration database-backed (embedded Postgres, no services needed)
test/e2e compiled contracts on a local chain + database + fake HyperCore