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#
revive()books the firsttick()on the Schedule Service,intervalseconds out.- At that second the network calls
tick(). The call runs as the contract itself, sotick()accepts onlymsg.sender == address(this): nobody else can tick early or starve it of gas. tick()records the gas price, runs_work()in a self-call (a revert there is caught and reported inTicked), then books the next tick if_keepGoing()says so.- The contract pays for each run from its own HBAR balance.
The ScheduledKeeper API#
What you implement
| Member | What 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 virtual | The 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
| Function | What 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() payable | Tops 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
| Constant | Value | Why |
|---|---|---|
SCHEDULE_GAS_RESERVE | 1,600,000 | Gas held back from _work() so booking the next tick always fits (scheduleCall costs about 1.41M) |
TIMESTAMP_TOLERANCE | 5 s | block.timestamp is the start of Hedera's ~2 s block, so a run can look a second or two early |
CAPACITY_PROBES | 10 | If a second is full, try the next one, up to 10 seconds |
MAX_GAS_PRICE | 1,000,000 | Gas 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)).
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#
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#
Deploy, fund, revive
bashforge 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> --legacyThe same tools
custos.jsuses:forge createandcast sendwith legacy transactions (forge scriptcan't deploy through the Hedera relay).--value 10ethersends 10 HBAR.revive()needs a high gas limit because it books a schedule.Watch it run
The schedule
revive()booked appears on HashScan (nextSchedule()is its address). Afterintervalseconds it executes, emitsTicked, and the next schedule appears. If the chain ever stops (empty reserve, no capacity),fund()it and callrevive()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 withINSUFFICIENT_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 afterSCHEDULE_GAS_RESERVE: keep it undergasLimit − 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, asPerpMarket._sweepdoes.
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.
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._sweepfor paging, so a big book spreads over several ticks. - Copy
LiquidityPool.createShareTokenand its_mint/_burn/_sendif 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:
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.