Smart contracts
The contracts, their roles, units and deployment.
Reference implementation of the on-chain half of the protocol, in contracts/. The
backend talks to these through the typed ABIs in src/chain/abis (generated by
pnpm contracts:compile).
Status: unaudited reference contracts. They are covered by the end-to-end suite and have had one internal security review (every finding is fixed and has a regression test in
test/e2e/audit.contracts.test.ts), but they have not been independently audited. Use them on local chains and testnet. Do not put real funds behind them before an independent audit and before the admin roles are held by a multisig / timelock.pnpm deploy:contractsrefuses to deploy to mainnet unlessCONFIRM_MAINNET_DEPLOY=yesis set for that reason.
#Contracts
| Contract | Purpose |
|---|---|
LendingPool | Markets, share-based supply/debt accounting, kinked interest model, caps, health checks, two-phase liquidation, emergency liquidation, bad-debt accounting. Holds collateral in escrow. |
HyperCoreRiskFeed | IPriceEngine implementation used until the HyperCore read precompile is live. Stores reporter-posted prices and haircuts and bounds every report. |
FeeDistributionEngine | The "Native Fee Distribution Engine". Receives fees, tracks revenue, converts through whitelisted adapters, splits between five modules, bounded allocation changes. |
InsuranceFund | Reserve drawn by the pool to cover liquidation deficits; can also fill bad debt later (permissionless). |
ProtocolOwnedLiquidity | Supplies its fee share to the pool. Also receives reserve-factor interest as supply shares. |
RewardsDistributor | Cumulative Merkle claims. Deployed twice: yield booster and borrow rebates. |
ModuleTreasury | Budget holder, deployed as the Liquidation Execution Fund. |
mocks/* | Test tokens and a fixed-rate swap adapter. Never deployed on mainnet. |
#Units
- Prices: USD per whole token, 1e18.
- Rates: per year, 1e18 = 100%. Interest is simple over each accrual interval and compounds whenever a market is touched.
- Percentages: basis points.
- Shares: Morpho-style virtual shares (1e6 virtual shares, 1 virtual asset), so the
first depositor cannot inflate the share price. Accounting uses tracked totals, not
balanceOf, so donations do not move the share price either.
#LendingPool
User functions: supply, withdraw (type(uint256).max = everything), borrow, repay
(anything ≥ the debt repays it fully), setCollateral.
Health:
collateralValue = Σ supplied × price (collateral-enabled supply)
borrowLimit = Σ supplied × price × (1 − borrowHaircut) × LTV (0 for frozen collateral)
liquidationLimit = Σ supplied × price × (1 − liqHaircut) × threshold
healthFactor = liquidationLimit / debtValueBorrowing and withdrawing collateral require fresh prices and debt ≤ borrowLimit.
Repaying and supplying never require fresh prices. A missing (zero) price is never a valid
price: it makes the account "not fresh", so nothing can be borrowed against or out of it.
A frozen collateral supports no new borrowing but still counts toward the liquidation
limit, so a flag alone never liquidates anyone.
Supply that is not flagged as collateral adds no borrowing power but can still be seized by a liquidation, so it cannot be withdrawn while the account is liquidatable. Supplying on someone else's behalf never changes their collateral set, and an asset without a current price is never flagged automatically (otherwise a speck of a halted asset could block an account's health checks).
Interest carries its sub-unit remainder between accruals (interestRemainder), so a market
touched every second accrues exactly what it would if touched once a day.
#Liquidation
beginLiquidation(user, collateral, debt, amount, maxSlippageBps, ttl, ref) LIQUIDATOR
requires fresh prices for the collateral and debt asset being liquidated, and healthFactor < 1
(other positions are valued at their last price, so a stale speck cannot shield an account)
any supply of the account can be seized, flagged as collateral or not
amount is capped at the close factor (50%; 100% when HF < 0.95 or the debt is dust)
locks the collateral shares, fixes minRate = referenceRate × (1 − maxSlippage)
one active liquidation per user; `ref` is single-use (liquidationByRef)
settleLiquidation(id, collateralSold, proceeds, receiveShares, finalize) LIQUIDATOR
requires proceeds ≥ collateralSold × minRate, and block.timestamp ≤ deadline
(the rate fixed at begin is not a free option the liquidator can exercise later)
pulls `proceeds` of the debt asset from the caller, pays the liquidation fee to the
execution fund, repays debt, credits any surplus to the borrower as a supply balance,
releases `collateralSold` to the caller; may be called several times (partial fills)
`finalize` returns unsold collateral to the borrower and closes the liquidation
cancelLiquidation(id) LIQUIDATOR at any time; ANYONE after the deadline; ANYONE early
when nothing is settled yet and the account is healthy again
returns all still-locked collateral to the borrower
netPosition(user, asset) LIQUIDATOR, account unhealthy
cancels supply against debt in the same asset (a liquidation needs two assets)While a liquidation is active the borrower cannot withdraw, borrow or toggle collateral,
but can still repay. After a liquidation closes, if the account still owes debt and has
nothing left (or only dust worth less than the debt), the remainder is realised as bad
debt: the insurance fund pays what it can and the rest is recorded in badDebt for that
market until it is covered (coverBadDebt, InsuranceFund.fillBadDebt) or, as a last
resort, written down against suppliers by governance (socializeBadDebt).
emergencyLiquidate is the atomic fallback for when the order-book venue is unavailable.
It only works while the guardian has switched emergencyMode on, accepts last-known
prices, and pays a fixed bonus instead of executing on the book. receiveShares takes the
collateral as a supply balance when its market has no cash.
#HyperCoreRiskFeed
A report is (asset, price, borrowHaircutBps, liqHaircutBps, coreTimeMs, frozen). The
contract, per asset:
- ignores reports that are not newer than the last one, older than
maxStaleness, or stamped more than 15 s in the future; - accepts at most one report per asset per
minPostIntervalof chain time (also within one batch), so the bounds below are bounds per unit of time, not per report; - clamps the move of a single report to
maxPriceStepBps, and keeps the price withinmaxWindowMoveBpsof where it stood at the start of the currentwindowSecwindow (defaults: 5% per report, 30% per 5 minutes); - when a report had to be clamped, the stored price is not the market price, so the asset is frozen for new borrowing until an unclamped report lands;
- caps both haircuts; the liquidation haircut may be raised by at most
maxLiqHaircutStepBpsonce perliqHaircutStepInterval, and lowered freely; - reports
fresh = falseonce the observation is older thanmaxStaleness; - returns price 0,
fresh = false,frozen = truefor an asset it does not know or has disabled.
The quote asset (USDC, HyperCore's unit of account) has a fixed price and is always fresh. The guardian can freeze any asset.
#FeeDistributionEngine
Make this contract the token's creator-fee recipient. It accepts ERC-20 transfers and native HYPE.
Montra. Creator fees accrue in Montra's LaunchHook, in native HYPE, per pool, and
only the pool's current recipient can claim them. The deploy script registers each token in
MONTRA_TOKENS with addFeeSource(hook, poolId, token). The token's recipient then calls
LaunchHook.updateRecipient(poolId, feeEngine); pnpm montra route does this. From then
on claimLaunchFees(i) / claimAllLaunchFees() (permissionless, paying only to the engine)
pull the HYPE in, and the fee keeper calls them automatically. Governance can hand a stream
to a new engine with moveLaunchRecipient, the migration path for upgrades.
sync(token)recognises new balance as revenue;distribute(token)(permissionless) splits everything pending between the five modules and records it. Rounding dust goes to the insurance fund.convert(...)(CONVERTER) swaps a non-reserve fee token into a reserve asset through a whitelistedISwapAdapter, with a minimum output. Revenue is counted once, under the token it arrived in.setAllocation(bps[5], regime)(ALLOCATOR): each module must stay inside its[min, max], move by at mostmaxStepBps, and changes are spaced byminAdjustInterval, except a genuine de-risking change (insurance up and none of liquidity, booster or rebates up), which is never delayed.
Default bounds are the envelope of the plan's three models: insurance 20–65%, liquidity 20–35%, booster 0–25%, rebates 0–15%, liquidation fund 5–15%.
Reward leaves are keccak256(keccak256(abi.encode(chainId, distributor, account, token, cumulativeAmount))): a proof is valid on one chain and one distributor only.
#Roles
| Role | Held by | Can |
|---|---|---|
DEFAULT_ADMIN_ROLE | governance (deployer at first) | grant roles, set module addresses, socialise bad debt, withdraw from treasuries |
RISK_ADMIN_ROLE | governance | list/update markets, liquidation parameters, feed configuration |
GUARDIAN_ROLE | fast-reacting multisig | pause flags, emergency mode, freeze an asset |
LIQUIDATOR_ROLE (pool) | liquidation keeper | begin / settle / cancel / emergency-liquidate, realise bad debt |
REPORTER_ROLE (feed) | risk reporter keeper | post observations (bounded) |
ALLOCATOR_ROLE, CONVERTER_ROLE (fee engine) | fee keeper | change allocation (bounded), convert fee tokens |
ROOT_UPDATER_ROLE (rewards) | fee keeper | publish Merkle roots |
A leaked keeper key is bounded by the contracts: the liquidator cannot liquidate a healthy account or take collateral below the slippage bound; the reporter cannot move a price by more than the clamp per post or raise the liquidation haircut faster than the rate limit; the allocator cannot leave the allocation bounds. What a keeper can do within those bounds is still worth protecting: keep each role on its own key.
#Build, test, deploy
pnpm contracts:compile # compile + regenerate src/chain/abis
pnpm test:e2e # deploys to a local chain and tests everything
pnpm chain:node # local chain
NETWORK=local pnpm deploy:contracts # writes deployments/local.json (git-ignored)
NETWORK=testnet DEPLOYER_PRIVATE_KEY=0x… KEEPER_PRIVATE_KEY=0x… pnpm deploy:contracts
# writes deployments/testnet.json — commit itpnpm deploy:contracts deploys every contract, lists the markets in src/config/markets.ts,
configures the feed, grants the keeper roles and writes the addresses and start block to
deployments/<network>.json, which the backend reads at startup. On test networks it
deploys mock tokens with an open mint; on mainnet only markets with a canonical token
address are listed.
Before mainnet: an audit; admin and guardian roles on multisigs (and the admin behind a timelock); a decision on real risk parameters per market; keeper keys in a secrets manager with one key per role.
#Changing the price source to the precompile
When Elysium publishes the read precompile:
- Write a contract that implements
IPriceEngine.getAssetRiskby reading the precompile (price, depth-derived haircuts, the HyperCore timestamp forfresh). LendingPool.setAddresses(newEngine, …)from governance.- Set
ENABLE_RISK_REPORTER=false.
The pool, the liquidation flow and the backend API do not change.