Documentation
Technical

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:

CapabilityInterfaceWorks todayWhen the upgrade ships
Prices, depth, haircuts on-chainIPriceEngine (Solidity)HyperCoreRiskFeed: the backend derives everything from HyperCore's order book and posts it; the contract bounds every reporta precompile-backed engine implementing the same interface; the pool is unchanged and the reporter job is switched off
HyperCore market data off-chainHyperCoreClientHyperCore info APIsame shapes from the precompile / RPC
Liquidation executionExecutionVenue (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

text
                         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

§RequirementWhereStatus
2Supply, borrow, repay, withdraw, collateralcontracts/LendingPool.sol; unsigned transactions from /v1/tx/*working, tested end to end
2Pools, debt accounting, interest model, utilisation rates, LTV, thresholds, capsLendingPool.sol; mirrored in src/lending/math.ts (tests assert equality with the chain)working
2Health factor, rates, thresholds for users/v1/accounts/:address, /v1/markets, previewsworking
2Bad debt accountingLendingPool._realizeBadDebtIfInsolvent, badDebt, coverBadDebt, socializeBadDebtworking
3Prices, best bid/ask, spread, depth, liquidity, execution estimates, volatility from HyperCoresrc/price, src/hypercore/book.ts; /v1/prices/*working on live data; source is the info API until the precompile ships
3No external oracleno third-party price feed anywhere; every input is HyperCore's own book / marksworking
3Manipulation resistance, liquidity requirements, freshness, conservative valuation, safeguardsreference = 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 freezeworking
4Executable vs theoretical collateral valuehaircut = cost of selling a stress size into the live book; executableCollateralUsd, liquidityAdjustedHealthFactorworking
4Slippage, position size, volatility, concentration, execution costssrc/risk/engine.ts (assess)working
4Dynamic, bounded parameters that manipulation cannot use to force liquidationsborrow 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-chainworking
5Detect → size → check liquidity → order → fill → repay → update → insurancesrc/liquidation/engine.ts + LendingPool two-phase liquidationworking (simulated venue by default)
5Partial / full liquidation, slippage protectionclose factor + full-liquidation threshold; rate bound fixed on-chain at beginLiquidation, enforced at settleLiquidationworking
5Order tracking, partial fills, failed orders, retriesorder rows, per-leg retry with fresh book, cancel + unlock when nothing fillsworking
5Debt settled only on confirmed fillssettlement amounts are computed from reconciled fills onlyworking
5Duplicate-execution protectionone open liquidation per account (DB + pool), single-use on-chain reference, deterministic order ids written before sendingworking, crash-tested
5Emergency proceduresguardian emergency mode → atomic emergencyLiquidate; pause flags; anyone can cancel after the deadlineworking
5Orders through ElysiumCoreWriterCoreWriterVenuepending the Elysium upgrade
6Self-custody with enforceable collateral restrictionssee Custody modelescrow implemented
7Fee engine: receive, track, convert, allocate, distribute, record, expose, bounded adjustmentscontracts/FeeDistributionEngine.sol, src/fees, /v1/fees*working
7No team wallet in the pathfees are paid to the contract; distribute is permissionlessworking
7Collection compatible with the launchpadMontra: 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 transfersworking; rehearsed on a mainnet fork with a live Montra token
840 / 25 / 15 / 10 / 10 split and what each module doesInsuranceFund, ProtocolOwnedLiquidity, 2 × RewardsDistributor, ModuleTreasuryworking
8Rewards based on actual revenueepochs split only what a distributor has actually received (src/rewards/service.ts)working
9Normal / stress / growth allocation driven by protocol conditionsrc/fees/allocator.ts (regime + hysteresis), bounded on-chainworking

#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 sending beginLiquidation finds 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

text
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