Docs · For builders
Run a keeper
What pays
| Call | Contract | Pays the caller |
|---|---|---|
fill(id, part) | LimitOrders | The order's run fee, 0.04 ZRO per whole order by default, shared across its parts |
fillBatch(ids, parts) | LimitOrders | The same, for each part that fills |
poke(ids) | LimitOrders | Nothing. It raises trailing stops' highs |
copyBuy(follower, leader, token) | CopyVault | 1% of the copy, at least 0.01 and at most 0.1 ZRO, from the follower |
copySell(follower, leader, token) | CopyVault | 1% of what the sale brought, 0.01 to 0.1 ZRO, from the follower |
exit(follower, token) | CopyVault | 1% of what the sale brought, 0.01 to 0.1 ZRO, from the follower |
claimFor(holder) | HolderToken | Nothing. Sends a holder's rewards to the holder |
collectProtocolFees() | Launchpad | Nothing. Moves the treasury's fees to the treasury |
claimFor(staker) | Staking | Nothing. Sends a staker's ZRO to the staker |
buyback, fundStaking | BuybackVault | Nothing, and only the keeper the owner names may call them |
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 set in the contract and keeps to the size of the run: a 5 ZRO copy pays 0.05 ZRO, and anything from 10 ZRO up pays 0.1 ZRO. runFeeFor(size) works it out.
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.
| Kind | Fills when | Checked |
|---|---|---|
| 0 Limit | The market pays at least the minimum, after fees and the run fee | By the trade itself |
| 1 Stop | A part would fetch no more than its share of trigger, and still at least its minimum | After the sale, against what it really fetched |
| 2 Trailing | What it fetches is trailBps below the high, per token | After the sale |
| 3 On graduation | The token has moved to its pool | Before trading |
| 4 On dev sale | The creator holds trigger tokens or fewer | Before trading |
| 5 DCA | At least interval seconds since the last part, and a part is at most total ÷ slices | Before 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 Submarine's keeper does, rather than trying the whole.
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 Submarine's keeper pokes at most every ten seconds.
Running copies and exits
- Rebuild who follows whom from the vault's
Followed,UnfollowedandExitSetevents. - Watch the router's
Routedevents. When a followed leader buys or sells, callcopyBuyorcopySellfor each follower within 30 blocks. - For followers with an exit set, call
exiton 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 and balance, the token's max wallet, how far the price has moved from the leader's, and the slippage. A copy that comes to less than 0.1 ZRO doesn't run. Most attempts are a normal "no", which costs nothing when simulated.
While copies are paused, copyBuy and copySell revert with Paused. exit keeps working, and still pays.
Running Submarine's keeper
The keeper in keeper/src/index.ts does all of the above. Its jobs, orders, copies and exits, run side by side once per new block, and at least once a second on a quiet chain, so copies never wait for an order batch. 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.
| Variable | Default | What |
|---|---|---|
KEEPER_PRIVATE_KEY | required | The key that sends fills and earns the fees. Fund it with a little ZRO for gas |
RPC_URL | http://127.0.0.1:8546 | The node. Set it to Zero's, https://testnet.zero.layerzero.network. Several, comma separated, and the next takes over when one stops answering |
CHAIN_ID | 31337 | Which deployment file to read. Set it to 1337 |
KEEPER_POLL_MS | 100 | How often to ask for a new block. Work runs once per new block |
BUYBACK | off | 1 runs the treasury's hourly round. Only for the key the treasury names as its keeper. See The hourly round |
KEEPER_HEALTH_PORT | 3023 | Answers GET /health on 127.0.0.1 with when the last round ran, for the status page. 0 turns it off |
LOG_LEVEL | info | pino log level |
npm.cmd install
$env:KEEPER_PRIVATE_KEY = "0x..."; npm.cmd run dev --workspace=keepernpm install
KEEPER_PRIVATE_KEY=0x... npm run dev --workspace=keeperIt 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), sends up to 5 copies at once, and checks exits every five seconds.
Writing your own
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. Submarine's keeper adds 20% to each copy's estimate and 25% to a batch of fills, so they still land 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.