Custos docs

Build with Custos

Contract reference

What each contract does, the external functions you will call, the events to index, and the units every number is in. The Solidity in packages/foundry/contracts is the source of truth; this page follows it.

Units#

Every amount in the contracts is an integer. Get these wrong and the numbers are off by powers of ten.

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 by PriceGuard
Money (collateral, PnL, fees, pool assets)USDC, 6 dpsize × price / 1e30 = USDC
cUSDC-LP shares6 dpOne share starts out worth one micro-USDC
HBAR inside the EVMtinybars (1 HBAR = 1e8)msg.value, balances, tx.gasprice, runCostEstimate()
Rates and limitsbasis points (10,000 = 100%)Fees, deviation, open-interest cap

PerpMarket#

The HBAR-USD perpetual, settled in USDC. It inherits MarginAccount (positions and risk math), ScheduledKeeper (the network tick), Ownable and ReentrancyGuard. Each tick accrues funding, liquidates up to 50 underwater positions at an Ok price, and refuels the keeper's HBAR reserve when it runs low.

Trading

FunctionWhat it does
open(bool isLong, uint256 collateral, uint256 leverage)Pulls collateral USDC (approve the market first) and opens collateral × leverage of notional. Needs an Ok price. Leverage 1 to 50.
openWithHbar(bool isLong, uint256 leverage, uint256 minCollateral_) payableSaucerSwap swaps msg.value HBAR to USDC collateral, then opens. minCollateral_ is the least USDC the swap may return.
close()Closes after the 300 s minimum hold and pays out USDC. Works in close-only mode at the worse fresh feed.
closeToHbar(uint256 minHbarOut) returns (uint256 hbarOut)Closes, then swaps the USDC payout to HBAR (tinybars) for the caller. Needs no USDC association.
addCollateral(uint256 amount)Adds USDC to an open position, moving its liquidation price away.
liquidate(address trader)Anyone can liquidate an underwater position at an Ok price and earn 0.5% of its notional.
accrueFunding()Brings funding up to date. The pool calls it before every deposit and withdrawal; anyone may.

Views

FunctionReturns
positionOf(address trader) returns (Position)size, collateral, entryPrice, entryNotional, fundingIndex, openedAt
liquidationPrice(address trader) returns (uint256)Price (1e18) at which the position becomes liquidatable; 0 if none
equity(address trader, uint256 price) returns (int256)Collateral + PnL − funding, gain capped at entry notional (USDC)
closePrice(address trader) returns (uint256)The price a close would settle at now; 0 means the close waits
quoteHbarToUsdc(uint256 hbar) returns (uint256)USDC SaucerSwap gives for hbar tinybars
quoteUsdcToHbar(uint256 usdcAmount) returns (uint256)Tinybars SaucerSwap gives for usdcAmount
requiredLiquidity() returns (uint256)USDC the pool must keep: 2 × open notional
traderCount() / totalOpenNotional()Open positions, and long + short notional in USDC
minCollateral() / MAX_LEVERAGE() / MIN_HOLD_SECONDS()1 USDC on the testnet deploy / 50 / 300

Events

EventWhen
Opened(address indexed trader, bool isLong, int256 size, uint256 collateral, uint256 price, uint256 leverage, uint256 fee)A position opens
Closed(address indexed trader, uint256 price, int256 pnl, int256 funding, uint256 payout, uint256 fee)A position closes
Liquidated(address indexed trader, uint256 price, bool byNetwork, address indexed by, uint256 reward)byNetwork is true and by is zero when a tick did it
Swept(uint256 from, uint256 to, uint256 liquidated)A tick checked one page of positions
SweepSkipped(PriceGuard.Status status)A tick skipped the sweep: price Stale (1) or Deviated (2)
Refueled(uint256 usdcIn, uint256 hbarOut, uint256 runsBefore)The keeper swapped pool USDC to HBAR
CollateralAdded(address indexed trader, uint256 amount)addCollateral
SwappedHbarForCollateral / SwappedPayoutForHbarThe SaucerSwap legs of openWithHbar and closeToHbar

LiquidityPool#

USDC in, cUSDC-LP out. The shares are a native Hedera token the pool creates and mints, and the pool is every trader's counterparty. Shares are priced at the pool's USDC minus what traders are up on open positions. To receive shares an account must be associated with the share token; to redeem or withdraw it must approve the pool on it.

FunctionWhat it does
deposit(uint256 assets, address receiver) returns (uint256 shares)Pulls assets USDC (approve the pool first) and sends the minted shares to receiver
redeem(uint256 shares, address receiver) returns (uint256 assets)Burns the caller's shares and sends the USDC they are worth
withdraw(uint256 assets, address receiver) returns (uint256 shares)Sends exactly assets USDC, burning the shares that costs
totalAssets() returns (uint256)What the pool is worth in USDC, net of traders' open gains
freeAssets() returns (uint256)USDC that can leave now (balance above requiredLiquidity())
maxWithdraw(address) / maxRedeem(address)The most an LP can take out right now
previewDeposit / previewRedeem / previewWithdrawWhat each action would give or burn now
convertToShares(uint256) / convertToAssets(uint256)Rounded-down conversions at the current price
shareToken() / asset() / market()cUSDC-LP address, USDC address, the linked market
balanceOf(address) / totalSupply()Shares held, and shares in existence (including 1,000 dead shares)

Events: Deposit(sender, receiver, assets, shares), Withdraw(sender, receiver, assets, shares), TraderPaid(trader, amount), KeeperPaid(amount), ShareTokenCreated(token). Setup functions setMarket, createShareToken and associate are called once by the deploy and start scripts; payTrader and payKeeper are market-only.

PriceGuard#

The one place prices come from. Chainlink is the price, Supra is the cross-check: Stale (1) if either feed is older than maxStaleness, Deviated (2) if they differ by more than maxDeviationBps, otherwise Ok (0). Reading never reverts on a broken feed.

FunctionWhat it does
price() returns (uint256)Chainlink's price (1e18). Reverts PriceGuard__NotOk unless the status is Ok
status() returns (Status)Ok, Stale or Deviated right now
read() returns (uint256 price_, Status status_, uint256 chainlinkAt, uint256 supraAt, uint256 deviationBps)Everything a UI shows, never reverts
prices() returns (uint256 chainlinkPrice, uint256 supraPrice, Status status_)Both feeds at 1e18; a stale or missing feed reads 0
setParams(uint256 maxStaleness_, uint256 maxDeviationBps_)Owner only, bounded by MAX_STALENESS_LIMIT (1 day) and MAX_DEVIATION_LIMIT_BPS (2,000)
maxStaleness() / maxDeviationBps() / supraPair()43,200 s / 500 bps / 75 for HBAR-USD

Event: ParamsSet(maxStaleness, maxDeviationBps).

ScheduledKeeper#

Abstract. Runs _work() every interval seconds with no bot: each tick books the next one on the Hedera Schedule Service and pays for it from the contract's own HBAR. Writing your own job is covered in Write your own keeper job.

FunctionWhat it does
tick()Called by the Schedule Service at nextRunAt, and by nothing else (msg.sender must be the contract)
revive()Books the first tick, or restarts a chain more than 2 × interval overdue. Anyone can call
fund() payableTops up the HBAR reserve that pays for runs (sending HBAR plainly works too)
runCostEstimate() returns (uint256)gasLimit × gasPrice in tinybars: what Hedera holds before each run
runsLeft() returns (uint256)Runs the reserve covers, each counted at the full hold
canPayNextRun() returns (bool)False when Hedera would refuse to start the next run
nextRunAt() / lastRunAt() / runCount() / nextSchedule()The schedule: unix seconds, count, schedule address
interval() / gasLimit() / gasPrice()Immutable interval and gas limit; the last gas price a tick recorded

Events: Ticked(run, workOk, reason), TickScheduled(schedule, at), ScheduleFailed(responseCode, at), Revived(by), Funded(from, amount), Stopped(runs), GasPriceSet(tinybarsPerGas).

MarginAccount#

Abstract. The position book and risk math, with no tokens and no oracle: the child contract passes prices in. Running sums over all positions give the traders' combined PnL and funding in O(1). Every view below is public on PerpMarket.

FunctionReturns
pnl(address trader, uint256 price) returns (int256)Unrealised PnL in USDC, before funding and the gain cap
fundingOwed(address trader) returns (int256)Funding owed (negative: owed to the trader), USDC
maintenanceMargin(address trader) returns (uint256)1% of entry notional, USDC
isLiquidatable(address trader, uint256 price) returns (bool)Equity below maintenance margin
netTraderGain(uint256 price) returns (int256)All traders' PnL − funding, USDC; the pool books it against its assets
currentFundingIndex() returns (int256)Funding index including accrual up to now (1e18)
traders(uint256) / longNotional() / shortNotional() / totalCollateral()The book

Event: FundingAccrued(ratePerHour, index).

HbarDepositZap#

Periphery. LPs deposit with HBAR alone: SaucerSwap swaps it to USDC, and the zap deposits that USDC with the caller as receiver, in one transaction. It holds nothing between calls and needs no rights on the pool. The swap must fill within maxSwapDeviationBps of the oracle value. The caller must be associated with cUSDC-LP, as for any deposit.

FunctionWhat it does
depositWithHbar(uint256 minUsdc) payable returns (uint256 shares)Swaps msg.value HBAR to USDC and deposits it for the caller. The oracle floor applies on top of minUsdc
quote(uint256 hbar) returns (uint256)USDC SaucerSwap gives for hbar tinybars now
oracleFloor(uint256 hbar) returns (uint256)The least USDC the swap may return. Reverts unless the price is Ok

Event: DepositedWithHbar(lp, hbarIn, usdcOut, shares).

Live testnet addresses#

A deploy of your own writes its addresses to packages/foundry/deployments/296.json. Every flow on the live deployment is linked from Testnet proof.

Errors#

Every contract reverts with named custom errors such as PerpMarket__HoldTime(closeableAt) or PriceGuard__NotOk(status). Each one, what it means and what to do, is in Troubleshooting.