Docs · Guides

Run a liquidator

Find positions that missed their deadline, liquidate the unhealthy ones for the bonus, and keep a liquidator running from a script.

A liquidator watches for positions that passed their deadline unrenewed and liquidates the ones that are unhealthy at the oracle price. On a borrow it repays the debt and receives the collateral plus the pool's bonus. On a perp it receives the market's bonus out of the collateral. Who can be liquidated and what each side receives is in Liquidation.

Anyone can run one. It needs a Mesa account, a balance to repay debts with, and a process that stays up.

Before you start

  • A Mesa account opened from a script. See Trade from code for openMesaScript and the key file.
  • A balance of each asset you will repay. Liquidating a borrow repays its whole debt, with interest, from one balance note of the pool's asset. Hold USDC to liquidate USDC borrows, SOL to liquidate SOL borrows. Perps need no balance.
  • One note large enough. If your balance of an asset is spread across several notes, merge them first with a consolidate:
ts
await mesa.mesa.run({ kind: 'consolidate', mint: usdcMint }, console.log)

Liquidations are relayed, so the script needs no SOL.

Find lapsed positions

lapsed.ts
import { openMesaScript } from '@mesa/sdk/node'

const mesa = await openMesaScript({
  apiUrl: 'https://api.mesa.markets',
  keyFile: './liquidator-key.json',
})

const lapsed = await mesa.lapsedPositions()
for (const p of lapsed) {
  console.log(p.id, p.kind, p.marketId, p.deadlineAt)
}
mesa.destroy()

lapsedPositions() returns every position whose deadline has passed and that has not been renewed, closed or liquidated since. It reads GET /v1/positions/lapsed.

FieldMeaning
idThe position
kindborrow or perp
marketIdThe pool or perp market the position is in
deadlineAtThe deadline it missed
tlockOpenWhether the drand round at the deadline is out, so the position's contents can be read
ciphertextBase64The position's timelock ciphertext
positionNoteHash, positionAccountThe note and account a liquidation spends

Many positions lapse while healthy and are renewed by their owner or the watcher. The SDK opens the ciphertext and checks health when you call liquidate.

Liquidate one position

ts
const result = await mesa.liquidate(lapsed[0])
console.log(result.signature)

liquidate opens the position's timelock, reads the chain clock to confirm the deadline has passed, reads the pool or market and its oracle, and checks the position's health at that price. If the position is unhealthy, it proves the liquidation and relays it. On a borrow, your repayment and the collateral you receive are fixed by the proof, and the rest of the collateral goes back to the owner.

From openMesaScript, liquidate throws when it cannot go ahead:

MessageMeaning
Position is healthy at the current oracle price.Not liquidatable. It can only be renewed.
The position has not lapsed past its deadline yet.The chain clock is still before the deadline. Try again shortly.
Position timelock is not open yet.The drand round at the deadline is not out yet
Lapsed position is already liquidated or renewed.Someone got there first
Insufficient spendable Mesa balance to repay …No single balance note of the pool's asset covers the debt. Deposit or consolidate.
ProofVerificationFailedThe oracle price or the pool's index moved between proving and landing. Try again.

On mesa.mesa, the same call returns the progress with stage: 'failed' and the message instead of throwing.

Keep a liquidator running

liquidator.ts
import { openMesaScript } from '@mesa/sdk/node'

const mesa = await openMesaScript({
  apiUrl: 'https://api.mesa.markets',
  keyFile: './liquidator-key.json',
})

const loop = mesa.liquidateLoop({
  intervalMs: 15_000,
  onLiquidate: (position, progress) => console.log('liquidated', position.id, progress.signature),
  onError: (id, error) => console.error('failed', id, error),
})

process.on('SIGINT', () => loop.stop())
await loop.done
mesa.destroy()

On each pass the loop refreshes your account, lists lapsed positions and tries each one. Positions that are healthy, not yet past their deadline or already taken are skipped without a call to onError. After a borrow liquidation it waits for the next pass, so the next repayment is made from your refreshed balance.

OptionDefaultMeaning
intervalMs15000Time between passes
signalAn AbortSignal that stops the loop
onLiquidateCalled with the position and its progress after each liquidation lands
onErrorCalled with the position id, or * for a pass that failed, and the error

It returns stop() and done, a promise that resolves when the loop has stopped.

What you receive

PositionYou payYou receive
BorrowThe debt with interest, in the pool's assetCollateral worth the debt plus liq_bonus_bps, or the whole collateral if it holds less
PerpNothingliq_bonus_bps of the position's collateral

What you receive lands in your account as a sealed balance. Check it with mesa.snapshot().balances or on Portfolio.

Each pool's and perp market's liq_bonus_bps is in GET /v1/pools and GET /v1/perps. See Markets, pools and their parameters.