Getting started
How it works
Custos is three reusable contracts and a market built from them. Traders put collateral in the market, a liquidity pool takes the other side, and the Hedera Schedule Service calls the market on a timer to charge funding and liquidate.
The parts#
Trader --open / close / closeToHbar--> PerpMarket --read() / prices()--> PriceGuard
| ^ | |-- Chainlink HBAR/USD
payTrader / | | | '-- Supra HBAR/USDT
payKeeper v | '--swap HBAR <-> USDC--> SaucerSwap V1
LP --deposit / redeem--> LiquidityPool |
| | tick() at nextRunAt; each tick books the next
| Hedera Schedule Service (0x16b)
'--mints / burns--> cUSDC-LP (HTS token)PerpMarketis the HBAR-USD market, settled in USDC. It inheritsMarginAccount(the position book and risk math) andScheduledKeeper(the timer), and reads every price fromPriceGuard.PriceGuarduses Chainlink as the price and Supra as the cross-check. It reportsStaleif either feed is older thanmaxStaleness(or dated more than 5 minutes in the future) andDeviatedif they differ by more thanmaxDeviationBps. It never reverts on a broken feed.LiquidityPoolholds LP USDC and mints cUSDC-LP, a native Hedera token it created itself. It is every trader's counterparty.HbarDepositZapis optional periphery: it swaps an LP's HBAR to USDC on SaucerSwap and deposits it in one transaction.
How the money moves#
- Collateral sits in the market; the pool backs every position. On close the market pays the collateral back and the pool covers any profit above it, or keeps any loss. On liquidation the collateral goes to the pool, minus a 0.5% reward if a person liquidated, and nothing if the network did.
- Open interest is capped at 50% of the pool's USDC. Each position's gain is capped at its entry notional, and LPs can't withdraw below twice the open interest, so the pool can always pay every position's largest possible gain.
- The pool is priced at what it is really worth: its USDC minus what traders are up on open positions, or plus what they are down. Running sums in
MarginAccountgive that number in O(1). Without it, anyone could deposit just before a loss lands in the pool and withdraw just after. - Funding is charged to the heavier side and the net goes to the pool. The pool calls
accrueFunding()before every deposit and withdrawal so funding is measured against the assets that were really there.
A liquidation, end to end#
This is what one network tick does. Tick 4 on the live deploy (0x7c37d2a7…de59a9(opens in a new tab)) followed exactly these steps and liquidated a 50x short with nobody signing.
The network calls tick()
The previous tick booked a call to
tick()atnextRunAton the Schedule Service (0x16b). At that second Hedera executes it.tick()accepts up to 5 seconds early, becauseblock.timestampis the start of Hedera's ~2 s block.msg.sender is the contract itself
When the Schedule Service runs a call the contract booked,
msg.senderandtx.originare the contract's own address.tick()accepts nothing else, so nobody can tick early, starve it of gas or make a booked run revert.Record the gas price
Inside a scheduled run
tx.gaspriceis the network gas price in tinybars (82 to 84 on testnet). The tick stores it, sorunCostEstimate()follows the real price. It also setslastRunAtand incrementsrunCount.runWork() as a self-call
The job runs through
this.runWork()with all gas except 1.6M. A revert inside is caught and reported inTicked(run, workOk, reason), so it can't stop the next tick from being booked.Accrue funding
The funding index is brought up to the current second.
Read the guard
guard.read()returns the price and a status:Ok,StaleorDeviated.Sweep up to 50 positions while gas lasts
At an
Okprice the market walks the trader list fromcursor. A position is liquidatable when its equity (collateral + PnL − funding) is below its maintenance margin, 1% of notional. The sweep stops after 50 positions or when less than 150,000 gas is left, emitsSwept(from, to, liquidated), and resumes from the cursor next tick.Liquidate with byNetwork = true, reward 0
The position is removed and all its collateral goes to the pool. The event is
Liquidated(trader, price, byNetwork = true, by = 0x0, reward = 0).At a bad price: SweepSkipped
If the status is
StaleorDeviated, nothing is liquidated and the tick emitsSweepSkipped(status). Ticks 12 to 16 on the live deploy did this while Chainlink's testnet feed was hours old.Refuel if the reserve is low (optional)
If the HBAR reserve covers fewer than 12 runs, the tick tries
refuel(): the pool pays up to 50 USDC that no position needs, and SaucerSwap swaps it to HBAR. The swap must fill within 3% of the oracle price, and a failure is caught so it never undoes the sweep. On testnet it fails closed (see The keeper).Book the next tick
The keeper checks
hasScheduleCapacityfornow + interval(trying up to 10 consecutive seconds) and callsscheduleCallfortick()with the full gas limit. Booking costs about 1.41M gas, which is why 1.6M is always held back from the job.
Constants#
| Constant | Value |
|---|---|
| Max leverage | 50x |
| Maintenance margin | 1% of notional |
| Open fee / close fee | 0.1% of notional each, to the pool |
| Manual liquidation reward | 0.5% of notional (network liquidations pay none) |
| Min hold before close | 300 s |
| Open interest cap | 50% of the pool's USDC |
| Funding | 0.1%/h × (long − short) / pool USDC; the heavy side pays, net to the pool |
| Sweep | 50 positions per tick, stops under 150,000 gas left, resumes next tick |
| Gas held back for booking | 1,600,000 |
| Refuel | below 12 runs, back up to 48, at most 50 USDC, within 3% of the oracle |
| Min collateral (testnet deploy) | 1 USDC |
| Keeper (testnet deploy) | interval 1,800 s, gas limit 3,000,000, starting gas price 82 tinybar/gas |
| PriceGuard (HBAR-USD) | max staleness 43,200 s (12 h), max deviation 500 bps |
Units#
| Quantity | Unit | Note |
|---|---|---|
| Position size | HBAR, 1e18; + long, − short | For another market, that asset's units |
| Price | USD per HBAR, 1e18 | Chainlink (8 dp) and Supra (18 dp) are scaled to 1e18 |
| Money | USDC, 6 dp | size × price / 1e30 = USDC |
| HBAR inside the EVM | tinybars (1 HBAR = 1e8) | msg.value, balances, tx.gasprice |
Every function and event is listed in the Contract reference.