Z3RO
Docs · Run a keeper

Docs · For builders

Run a keeper

Filling limit orders, raising trailing stops, copying leaders for copy-vault followers and selling at their take profit or stop loss are all open to anyone, and most of them pay. The contracts check every condition themselves, so a keeper is a convenience, not a party anyone has to trust.

What pays

CallContractPays the caller
fill(id, part)LimitOrdersThe order's run fee, 0.04 ZRO per whole order by default, shared across its parts
fillBatch(ids, parts)LimitOrdersThe same, for each part that fills
poke(ids)LimitOrdersNothing. It raises trailing stops' highs
copyBuy(follower, leader, token)CopyVault0.04 ZRO, from the follower
copySell(follower, leader, token)CopyVault0.04 ZRO, from the follower
exit(follower, token)CopyVault0.04 ZRO, from the follower
claimFor(holder)HolderTokenNothing. Sends a holder's rewards to the holder
collectProtocolFees()LaunchpadNothing. Moves the treasury's fees to the treasury

An order's run fee is fixed when it is placed: the owner can raise it to at most 0.4 ZRO for new orders, never for open ones. A copy-vault run fee is a constant.

Filling orders

openIds(from, count) lists open orders in a range, getOrder(id) returns one, and available(id) says how much of it may trade now, which for a sale group is capped by what the group still holds.

KindFills whenChecked
0 LimitThe market pays at least the minimum, after fees and the run feeBy the trade itself
1 StopA part would fetch no more than its share of trigger, and still at least its minimumAfter the sale, against what it really fetched
2 TrailingWhat it fetches is trailBps below the high, per tokenAfter the sale
3 On graduationThe token has moved to its poolBefore trading
4 On dev saleThe creator holds trigger tokens or fewerBefore trading
5 DCAAt least interval seconds since the last part, and a part is at most total ÷ slicesBefore trading

An expired order can always be filled: the call closes it and refunds the owner, and pays nothing. A part's minimum and its run fee both scale with its size and round up. Every buy moves the price against the next, so a large order at a near level often fills only as far as its level allows. Find that amount by bisection, as Z3RO's keeper does, rather than trying the whole.

Simulate each fill on its own. fillBatch wraps each fill in try and catch, so estimating gas for a batch finds the least gas at which the batch succeeds, which can be too little for any fill to go through. Estimate fills one at a time and send the batch with their sum.

Trailing stops

A trailing stop's high only counts once it is on chain. poke(ids) raises each high to what its remaining tokens would fetch now. It pays nothing, so Z3RO's keeper pokes at most every ten seconds.

Running copies and exits

  1. Rebuild who follows whom from the vault's Followed, Unfollowed and ExitSet events.
  2. Watch the router's Routed events. When a followed leader buys or sells, call copyBuy or copySell for each follower within 30 blocks.
  3. For followers with an exit set, call exit on their positions now and then. It reverts unless take profit or stop loss has been reached, so simulate first: a simulation is free.

The vault checks everything again: that the leader really traded through the router for itself, that this trade wasn't copied already, the follower's limits, how far the price has moved from the leader's, and the slippage. Most attempts are a normal "no", which costs nothing when simulated.

Running Z3RO's keeper

The keeper in keeper/src/index.ts does all of the above in one loop: orders, then copies, then exits, every second. It reads the contract addresses from contracts/deployments/<chain id>.json. Its defaults point at a local test chain. On Zero's testnet set CHAIN_ID=1337 and RPC_URL=https://testnet.zero.layerzero.network.

VariableDefaultWhat
KEEPER_PRIVATE_KEYrequiredThe key that sends fills and earns the fees. Fund it with a little ZRO for gas
RPC_URLhttp://127.0.0.1:8546The node. Set it to Zero's, https://testnet.zero.layerzero.network
CHAIN_ID31337Which deployment file to read. Set it to 1337
KEEPER_POLL_MS1000Pause between rounds
LOG_LEVELinfopino log level
Windows PowerShell
npm.cmd install
$env:KEEPER_PRIVATE_KEY = "0x..."; npm.cmd run dev --workspace=keeper
macOS or Linux
npm install
KEEPER_PRIVATE_KEY=0x... npm run dev --workspace=keeper

It fills up to 32 orders per transaction, skips a part smaller than a twentieth of its order (its share of the run fee would not pay for the gas), and checks exits every five seconds.

Writing your own

Fill whatever can fill, one simulation each
import { createPublicClient, createWalletClient, http, parseAbi } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';

const chain = { id: 1337, name: 'Zero', nativeCurrency: { name: 'ZRO', symbol: 'ZRO', decimals: 18 }, rpcUrls: { default: { http: [RPC] } } };
const client = createPublicClient({ chain, transport: http(RPC) });
const wallet = createWalletClient({ chain, transport: http(RPC), account: privateKeyToAccount(KEY) });

const LIMITS = parseAbi([
  'function ordersCount() view returns (uint256)',
  'function openIds(uint256 from, uint256 count) view returns (uint256[])',
  'function available(uint256 id) view returns (uint256)',
  'function fill(uint256 id, uint256 part) returns (uint256, uint256)',
]);

const count = await client.readContract({ address: LIMIT_ORDERS, abi: LIMITS, functionName: 'ordersCount' });
const ids = await client.readContract({ address: LIMIT_ORDERS, abi: LIMITS, functionName: 'openIds', args: [0n, count] });
for (const id of ids) {
  const part = await client.readContract({ address: LIMIT_ORDERS, abi: LIMITS, functionName: 'available', args: [id] });
  try {
    const { request } = await client.simulateContract({ address: LIMIT_ORDERS, abi: LIMITS, functionName: 'fill', args: [id, part], account: wallet.account });
    await wallet.writeContract(request);
  } catch {
    // not yet: condition or minimum not met
  }
}

Costs and races

Gas is paid in ZRO. Z3RO's keeper adds 20% to each estimate, so a fill still lands if the state moves a little.

Anyone can run the same fill. The first to land gets the fee, and the others revert and pay their gas. A copy can only run once per leader trade per follower, and an order part only once. Simulate right before sending and stop when a simulation fails.

A runner whose address refuses ZRO doesn't block a copy: the vault holds the fee as runnerCredit, collected later with collectRunnerCredit(to). In LimitOrders the keeper's payment has a gas cap, so a keeper that refuses ZRO just can't fill.

Next: launching and trading from code is on Launch and trade from code, and the events behind all of this are on Events to index.