Documentation
Technical

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:contracts refuses to deploy to mainnet unless CONFIRM_MAINNET_DEPLOY=yes is set for that reason.

#Contracts

ContractPurpose
LendingPoolMarkets, share-based supply/debt accounting, kinked interest model, caps, health checks, two-phase liquidation, emergency liquidation, bad-debt accounting. Holds collateral in escrow.
HyperCoreRiskFeedIPriceEngine implementation used until the HyperCore read precompile is live. Stores reporter-posted prices and haircuts and bounds every report.
FeeDistributionEngineThe "Native Fee Distribution Engine". Receives fees, tracks revenue, converts through whitelisted adapters, splits between five modules, bounded allocation changes.
InsuranceFundReserve drawn by the pool to cover liquidation deficits; can also fill bad debt later (permissionless).
ProtocolOwnedLiquiditySupplies its fee share to the pool. Also receives reserve-factor interest as supply shares.
RewardsDistributorCumulative Merkle claims. Deployed twice: yield booster and borrow rebates.
ModuleTreasuryBudget 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:

text
collateralValue      = Σ supplied × price                                  (collateral-enabled supply)
borrowLimit          = Σ supplied × price × (1 − borrowHaircut) × LTV      (0 for frozen collateral)
liquidationLimit     = Σ supplied × price × (1 − liqHaircut) × threshold
healthFactor         = liquidationLimit / debtValue

Borrowing 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

text
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 minPostInterval of 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 within maxWindowMoveBps of where it stood at the start of the current windowSec window (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 maxLiqHaircutStepBps once per liqHaircutStepInterval, and lowered freely;
  • reports fresh = false once the observation is older than maxStaleness;
  • returns price 0, fresh = false, frozen = true for 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 whitelisted ISwapAdapter, 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 most maxStepBps, and changes are spaced by minAdjustInterval, 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

RoleHeld byCan
DEFAULT_ADMIN_ROLEgovernance (deployer at first)grant roles, set module addresses, socialise bad debt, withdraw from treasuries
RISK_ADMIN_ROLEgovernancelist/update markets, liquidation parameters, feed configuration
GUARDIAN_ROLEfast-reacting multisigpause flags, emergency mode, freeze an asset
LIQUIDATOR_ROLE (pool)liquidation keeperbegin / settle / cancel / emergency-liquidate, realise bad debt
REPORTER_ROLE (feed)risk reporter keeperpost observations (bounded)
ALLOCATOR_ROLE, CONVERTER_ROLE (fee engine)fee keeperchange allocation (bounded), convert fee tokens
ROOT_UPDATER_ROLE (rewards)fee keeperpublish 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

bash
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 it

pnpm 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:

  1. Write a contract that implements IPriceEngine.getAssetRisk by reading the precompile (price, depth-derived haircuts, the HyperCore timestamp for fresh).
  2. LendingPool.setAddresses(newEngine, …) from governance.
  3. Set ENABLE_RISK_REPORTER=false.

The pool, the liquidation flow and the backend API do not change.