Custos docs

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#

contracts
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)
  • PerpMarket is the HBAR-USD market, settled in USDC. It inherits MarginAccount (the position book and risk math) and ScheduledKeeper (the timer), and reads every price from PriceGuard.
  • PriceGuard uses Chainlink as the price and Supra as the cross-check. It reports Stale if either feed is older than maxStaleness (or dated more than 5 minutes in the future) and Deviated if they differ by more than maxDeviationBps. It never reverts on a broken feed.
  • LiquidityPool holds LP USDC and mints cUSDC-LP, a native Hedera token it created itself. It is every trader's counterparty.
  • HbarDepositZap is 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 MarginAccount give 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.

  1. The network calls tick()

    The previous tick booked a call to tick() at nextRunAt on the Schedule Service (0x16b). At that second Hedera executes it. tick() accepts up to 5 seconds early, because block.timestamp is the start of Hedera's ~2 s block.

  2. msg.sender is the contract itself

    When the Schedule Service runs a call the contract booked, msg.sender and tx.origin are the contract's own address. tick() accepts nothing else, so nobody can tick early, starve it of gas or make a booked run revert.

  3. Record the gas price

    Inside a scheduled run tx.gasprice is the network gas price in tinybars (82 to 84 on testnet). The tick stores it, so runCostEstimate() follows the real price. It also sets lastRunAt and increments runCount.

  4. runWork() as a self-call

    The job runs through this.runWork() with all gas except 1.6M. A revert inside is caught and reported in Ticked(run, workOk, reason), so it can't stop the next tick from being booked.

  5. Accrue funding

    The funding index is brought up to the current second.

  6. Read the guard

    guard.read() returns the price and a status: Ok, Stale or Deviated.

  7. Sweep up to 50 positions while gas lasts

    At an Ok price the market walks the trader list from cursor. 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, emits Swept(from, to, liquidated), and resumes from the cursor next tick.

  8. 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).

  9. At a bad price: SweepSkipped

    If the status is Stale or Deviated, nothing is liquidated and the tick emits SweepSkipped(status). Ticks 12 to 16 on the live deploy did this while Chainlink's testnet feed was hours old.

  10. 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).

  11. Book the next tick

    The keeper checks hasScheduleCapacity for now + interval (trying up to 10 consecutive seconds) and calls scheduleCall for tick() with the full gas limit. Booking costs about 1.41M gas, which is why 1.6M is always held back from the job.

Constants#

ConstantValue
Max leverage50x
Maintenance margin1% of notional
Open fee / close fee0.1% of notional each, to the pool
Manual liquidation reward0.5% of notional (network liquidations pay none)
Min hold before close300 s
Open interest cap50% of the pool's USDC
Funding0.1%/h × (long − short) / pool USDC; the heavy side pays, net to the pool
Sweep50 positions per tick, stops under 150,000 gas left, resumes next tick
Gas held back for booking1,600,000
Refuelbelow 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#

QuantityUnitNote
Position sizeHBAR, 1e18; + long, − shortFor another market, that asset's units
PriceUSD per HBAR, 1e18Chainlink (8 dp) and Supra (18 dp) are scaled to 1e18
MoneyUSDC, 6 dpsize × price / 1e30 = USDC
HBAR inside the EVMtinybars (1 HBAR = 1e8)msg.value, balances, tx.gasprice

Every function and event is listed in the Contract reference.