Custos docs

Build with Custos

Write your own keeper job

ScheduledKeeper is the part of Custos that has nothing to do with perps: inherit it, override _work(), fund it with HBAR, and the Hedera Schedule Service runs your job every interval with no bot. Each run books the next one.

How it runs#

  1. revive() books the first tick() on the Schedule Service, interval seconds out.
  2. At that second the network calls tick(). The call runs as the contract itself, so tick() accepts only msg.sender == address(this): nobody else can tick early or starve it of gas.
  3. tick() records the gas price, runs _work() in a self-call (a revert there is caught and reported in Ticked), then books the next tick if _keepGoing() says so.
  4. The contract pays for each run from its own HBAR balance.

The ScheduledKeeper API#

What you implement

MemberWhat it is
constructor(uint256 interval_, uint256 gasLimit_, uint256 gasPrice_)Seconds between ticks; gas each tick is booked with (must exceed 1,600,000); starting gas price in tinybars per gas (ticks then record the real one)
function _work() internal virtualThe job. Required. Reverting is safe
function _keepGoing() internal view virtual returns (bool)Return false to stop after this tick. Default: run forever

What you get

FunctionWhat it does
tick()Network only. Runs the job and books the next tick
revive()Anyone. Books the first tick, or restarts a chain more than 2 × interval overdue
fund() payableTops up the HBAR reserve; a plain HBAR transfer works too
runCostEstimate()gasLimit × gasPrice, tinybars: what Hedera holds before each run
runsLeft()Balance / runCostEstimate(): runs the reserve covers at the full hold
canPayNextRun()False when Hedera would refuse to start the next run
nextRunAt() / lastRunAt() / runCount() / nextSchedule()The schedule: unix seconds, run count, schedule address
interval() / gasLimit() / gasPrice()Immutable settings; the last recorded gas price

Constants

ConstantValueWhy
SCHEDULE_GAS_RESERVE1,600,000Gas held back from _work() so booking the next tick always fits (scheduleCall costs about 1.41M)
TIMESTAMP_TOLERANCE5 sblock.timestamp is the start of Hedera's ~2 s block, so a run can look a second or two early
CAPACITY_PROBES10If a second is full, try the next one, up to 10 seconds
MAX_GAS_PRICE1,000,000Gas prices above this (tinybars per gas) are ignored

Start from Heartbeat#

packages/foundry/contracts/examples/Heartbeat.sol is the smallest keeper: it counts its own beats and stops after maxBeats (0 runs forever). One ran three times on testnet, 60 s apart, each run booked by the one before (0.0.10776628(opens in a new tab)).

examples/Heartbeat.sol
contract Heartbeat is ScheduledKeeper {
    uint256 public immutable maxBeats;
    uint256 public beats;

    event Beat(uint256 indexed beat, uint256 at);

    constructor(uint256 interval_, uint256 gasLimit_, uint256 gasPrice_, uint256 maxBeats_)
        ScheduledKeeper(interval_, gasLimit_, gasPrice_)
    {
        maxBeats = maxBeats_;
    }

    function _work() internal override {
        emit Beat(++beats, block.timestamp);
    }

    function _keepGoing() internal view override returns (bool) {
        return maxBeats == 0 || runCount < maxBeats;
    }
}

A minimal job#

contracts/MyJob.sol
import { ScheduledKeeper } from "./ScheduledKeeper.sol";

contract MyJob is ScheduledKeeper {
    // every 10 min, 2M gas, 82 tinybar/gas to start
    constructor() ScheduledKeeper(600, 2_000_000, 82) {}

    function _work() internal override {
        // the job: a revert here is caught, the next tick is still booked
    }

    function _keepGoing() internal view override returns (bool) {
        return true; // false ends the chain
    }
}

To add work to the perp market itself instead, extend PerpMarket._work(); it already accrues funding, sweeps and refuels.

Deploy and book the first tick#

  1. Deploy, fund, revive

    bash
    forge create contracts/MyJob.sol:MyJob --rpc-url https://testnet.hashio.io/api --account <keystore> --legacy --broadcast
    cast send <address> "fund()" --value 10ether --rpc-url https://testnet.hashio.io/api --account <keystore> --legacy
    cast send <address> "revive()" --gas-limit 2500000 --rpc-url https://testnet.hashio.io/api --account <keystore> --legacy

    The same tools custos.js uses: forge create and cast send with legacy transactions (forge script can't deploy through the Hedera relay). --value 10ether sends 10 HBAR. revive() needs a high gas limit because it books a schedule.

  2. Watch it run

    The schedule revive() booked appears on HashScan (nextSchedule() is its address). After interval seconds it executes, emits Ticked, and the next schedule appears. If the chain ever stops (empty reserve, no capacity), fund() it and call revive() once it is overdue.

Gas budgeting#

Two numbers decide whether a run starts and what it costs:

  • The hold. Hedera starts a scheduled run only if the payer holds the whole gasLimit × gasPrice. At 3,000,000 gas and 82 tinybar/gas that is 2.46 ℏ. A run that can't be held fails with INSUFFICIENT_PAYER_BALANCE, still costs about 0.018 ℏ, and stops the chain. runsLeft() counts full holds, so it never overstates.
  • The charge. Hedera then charges only the gas the run used. A Custos tick that sweeps a small book and books the next one uses about 1.6M gas, about 1.36 ℏ.
  • The work budget. _work() gets what is left after SCHEDULE_GAS_RESERVE: keep it under gasLimit − 1,600,000. A job that runs over reverts (caught; the next tick is still booked) and does nothing. For a big list, page through it with a cursor and a gas floor, as PerpMarket._sweep does.

A lower gas limit shrinks the hold but not the charge. More HBAR in the reserve, or a longer interval, makes it last longer. The keeper's HBAR can't be withdrawn: it only pays for runs.

Sketch: a lending market#

Keep ScheduledKeeper and PriceGuard and write the loan book. This is a sketch, not a contract in the repo: Loan and _accrueInterest are yours to write.

sketch
contract LendingMarket is ScheduledKeeper {
    PriceGuard public immutable guard;
    mapping(address => Loan) internal loans;
    address[] internal borrowers;

    constructor(PriceGuard guard_) ScheduledKeeper(3600, 3_000_000, 82) { guard = guard_; }

    function _work() internal override {
        (uint256 price, PriceGuard.Status status,,,) = guard.read();
        _accrueInterest();                          // the network charges interest every hour
        if (status != PriceGuard.Status.Ok) return; // never liquidate at a bad price
        // page through `borrowers` like PerpMarket._sweep, liquidating loans under their health factor
    }
}
  • Copy PerpMarket._sweep for paging, so a big book spreads over several ticks.
  • Copy LiquidityPool.createShareToken and its _mint / _burn / _send if lenders should hold a real HTS token, and its value-before-deposit logic (_syncMarket) to stop deposit/withdraw sandwiches.

Changing the interval#

interval is immutable: set it at deploy. For the perp market:

bash
KEEPER_INTERVAL=3600 yarn custos:deploy:testnet
  • Cost: each run is charged for the gas it uses, so halving the interval roughly doubles the HBAR spent: about 65 ℏ a day at 30 minutes.
  • Safety: at 50x a ~2% move wipes a position. A slower interval leaves underwater positions waiting longer; manual liquidators can still call liquidate() at any time for the 0.5% reward.
  • Funding accrues continuously; the interval only decides when it is booked.

KEEPER_GAS_LIMIT and KEEPER_GAS_PRICE set the other two constructor arguments the same way. More on costs and reviving in The keeper.