Docs · Reference
Program: instructions
Every instruction of the mesa program, with its tag, who may call it and when, its accounts in order, its data layout, the proof it verifies, what it changes, its measured compute units and the errors it raises.
The mesa program has 21 instructions. Ten of them move notes: each verifies a Groth16 proof and then calls the Solana Privacy Program (SPP) to spend and create the notes. The rest work on public accounts only. The accounts named here are laid out in Program: accounts, the proofs in Circuits, and the errors in Program: errors.
How an instruction is laid out
The tag byte and the arguments
The first byte of instruction data is the instruction's tag. The program reads it, then hands the remaining bytes to that instruction.
| Tag | Instruction | Tag | Instruction |
|---|---|---|---|
0 | init_config | 10 | create_pool |
1 | set_config | 11 | create_perp_market |
2 | create_market | 12 | sweep_fees |
3 | deposit | 13 | withdraw_seed_shares |
4 | withdraw | 14 | consolidate |
5 | place | 15 | renew |
6 | open | 16 | repay |
7 | clear | 17 | close_position |
8 | settle | 18 | liquidate |
9 | reclaim | 19 | set_paused |
255 | emit_event |
Empty data or any other tag fails with Solana's InvalidInstructionData.
Arguments follow the tag with no padding, in the order of the field tables on this page. Integers are little-endian at their fixed width, and byte arrays are written as they are. A proof is a compressed Groth16 proof of 128 bytes: a 32, b 64 and c 32.
Note-moving instructions
An instruction that moves notes carries two proofs. The first is Mesa's own, verified by the mesa program against public inputs the program computes itself from its accounts and the clock. The second is the SPP proof, carried inside the SPP transact data that ends the instruction data:
tag · arguments · [tlock_len: u16 · tlock ciphertext] · SPP transact dataThe bracketed part exists in place, renew and repay, and in reclaim of a perp close. tlock_len is the byte length of the timelock ciphertext that follows it. The program skips the ciphertext without reading it.
The program reads private_tx_hash from the transact data and verifies Mesa's proof against it, so the two proofs cover the same notes. When the instruction has public legs, the program builds the list of transfers (mint, direction, amount, Mesa's token account) from its own accounts and the amounts it computed, and the proof is verified against that list too. It then forwards the transact data unchanged to SPP transact by CPI, signed by the Mesa authority, the PDA with seed ["authority"].
The SPP accounts
Every note-moving instruction takes its own accounts first and the SPP accounts after them, to the end of the account list. The SPP accounts are what the Privacy Rings client builds for a transact CPI (Transact::cpi_accounts in Rust, transactCpiAccounts in TypeScript) with the Mesa authority as the one signing PDA:
| Account | Flags | What it is |
|---|---|---|
payer | writable, signer | Pays the pool's fees for the transact |
output_tree | writable | The state tree the new notes go into |
spp_program | read-only | The Solana Privacy Program |
system_program | read-only | The System Program |
input_tree | writable | The tree of the notes being spent |
nullifier | writable | One nullifier PDA per input note, in input order |
owner_signer | signer | Present in deposit only: the wallet that owns the Rings notes spent |
mesa_authority | read-only | The Mesa authority. It is not a signer of the transaction: the program signs for it inside the CPI |
| public leg accounts | The token accounts of each public leg, as the client lists them |
The program passes at most 24 accounts to the CPI.
Shared account rules
configis the PDA["config"], owned by the program.batchis the PDA["batch", n]withnas a little-endianu64.actionis the PDA["action", n, index]withindexas a little-endianu32.- A market, vault, pool or perp market account is the PDA of the id stored inside it:
["market", id],["vault", id],["pool", id],["perp", id], withidas a little-endianu16. - Mesa's token account for a mint is the associated token account of the Mesa authority for that mint. Every public vault of every market, pool and vault is one of these.
- An
oracleaccount is a PythPriceUpdateV2account owned by the program named inConfig.pyth_receiver, fully verified, carrying the feed id the target names, with a positive price and apublish_timeno more thanConfig.max_oracle_ageseconds from the clock in either direction. The program scales its price toPRICE_SCALE(10^12) quote atoms per base atom.
Kinds, sides and codes
An action's code is a u32: the kind in its low byte, the side in the next byte, and the target id in the two high bytes.
| Kind | Value | Target | Side |
|---|---|---|---|
| Order | 1 | Market id | 0 buy, 1 sell |
| Supply | 2 | Pool id | 0 or 255 |
| Redeem | 3 | Pool id | 0 or 255 |
| Borrow | 4 | Pool id | 0 |
| Perp open | 5 | Perp market id | 0 long, 1 short |
| Perp close | 6 | Perp market id | 0 long, 1 short |
| Vault deposit | 7 | Vault id | not read |
| Vault withdraw | 8 | Vault id | not read |
A share note's share_target is (target_kind << 16) | target_id, with target_kind 2 for a pool and 4 for a vault.
Who pays
The transaction's fee payer pays Solana's fee, and the payer of the SPP accounts pays the pool's fees. The relayer is both for every relayed action. Network costs has the amounts.
The program itself asks for a signature in three places: the owner of a deposit, the payer of a place, and the admin and payer of the authority-only instructions. No other instruction takes a signer of its own. What authorizes a spend is the proof.
place creates the action's Action account, and the batch's Batch account when the action is the first of its batch, with rent from its payer. The Action account records that address as its rent payer and returns the rent to it when the action is settled, reclaimed or closed as refused.
Compute units
Each instruction lists the compute units it used in the program's end-to-end tests. Solana's default limit of 200,000 units per instruction is below every proof-verifying instruction here, so a transaction that carries one sets its own compute unit limit.
Errors every note-moving instruction can raise
These apply to all ten and are not repeated under each one.
| Error | When |
|---|---|
InvalidAccount | config is not the config PDA, or is not owned by the program |
InvalidInstructionData | The arguments or the transact data do not decode |
ProofVerificationFailed | Mesa's proof does not verify against the public inputs the program computed |
HashingFailed | A public input could not be hashed |
InvalidShieldedPoolProgram | The SPP accounts do not hold the SPP program |
MissingMesaAuthority | The SPP accounts do not hold the Mesa authority |
A failure inside the CPI comes back as the Privacy Program's own error. See Errors from other programs.
Account instructions
deposit is refused with ProtocolPaused while Config.paused is set. withdraw and consolidate run whether or not the protocol is paused. None has a public leg: value enters and leaves Mesa as Rings notes.
deposit
Tag 3. Called by the person depositing, whose wallet signs because it owns the Rings notes being spent. Spends up to two of the wallet's Rings notes of one asset, creates a balance note for the account, and returns change to the wallet's Rings address.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
owner | signer | The wallet that owns the Rings notes |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
proof | 128 bytes | Proof of deposit |
| transact data | to the end | The SPP transact |
Public inputs: mesa_identity, and owner_pk_field, which the program computes from the owner address. A proof made for another wallet does not verify.
Measured: 244,908 to 247,261 compute units.
withdraw
Tag 4. Relayed, with no signer of its own. Spends one balance note, creates a plain Rings note for the recipient named in the data, and returns the change as a balance note.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
proof | 128 bytes | Proof of withdraw |
recipient_owner_hash | [u8; 32] | The owner hash of the recipient's Rings address |
recipient_viewing_pubkey | [u8; 33] | The recipient's viewing public key |
| transact data | to the end | The SPP transact |
Public inputs: mesa_identity, and recipient, the address hash the program computes from the two recipient fields.
Measured: 246,050 compute units.
consolidate
Tag 14. Relayed. Spends two balance notes of one asset and creates one balance note holding their sum.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
proof | 128 bytes | Proof of consolidate |
| transact data | to the end | The SPP transact |
Public input: mesa_identity.
Measured: 246,397 compute units.
Batch instructions
The path of an action through a batch is told in Batches. open, clear, settle and reclaim take no signer and run whether or not anything is paused, so every batch already placed finishes.
place
Tag 5. Relayed: the payer signs and funds the new accounts, and nobody's wallet signs. Puts one sealed action into the current batch.
The program computes the current batch from the clock:
n = floor((now − genesis_ts) / batch_len)
close_ts = genesis_ts + (n + 1) · batch_lenIt refuses the instruction when now is before genesis_ts or later than close_ts − place_margin. The proof is bound to n, so an action that misses the cutoff is proved again for the next batch.
| Account | Flags | Must be |
|---|---|---|
payer | writable, signer | Funds the Action account, and the Batch account if it does not exist yet |
config | read-only | The config PDA |
batch | writable | The batch PDA of the current batch n |
action | writable | The action PDA of n and the batch's current action_count (0 when the batch account does not exist yet). It must not exist |
system_program | read-only | The System Program |
target | read-only | Borrow and perp open only: the pool or perp market |
oracle | read-only | Borrow and perp open only: the price account of the pool's chosen collateral, or of the perp market's base |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
kind | u8 | Selects the proof, see below |
commitment | [u8; 32] | The hash of the action's terms |
proof | 128 bytes | The place proof for the kind |
collateral_index | u8 | Present for borrow and perp open only. For a borrow, the index of the collateral in the pool's collateral list |
tlock_len | u16 | Length of the timelock ciphertext |
| tlock ciphertext | tlock_len bytes | The action's terms and action holder keys, encrypted to the batch's drand round |
| transact data | to the end | The SPP transact |
kind | Action | Circuit | Notes |
|---|---|---|---|
1, 2, 7 | Order, supply, perps vault deposit | place_lock | One balance note in, one action note holding the locked amount out, change back as a balance |
3, 8 | Redeem, vault withdraw | place_share | One share note in, an action note holding 0 out, the remaining shares back as a share note |
4, 5 | Borrow, perp open | place_open | Collateral balance in, a position holding the collateral and an action note holding 0 out |
6 | Perp close | place_close | A position in, an action note holding its collateral out |
0x87 | Spot vault deposit | place_pair | A base balance and a quote balance in, two action notes under one action out. The action's code carries kind 7 |
Every place proof has the public inputs mesa_identity, batch (the n the program computed) and commitment. place_open adds values the program reads at that moment:
| Public input | Borrow | Perp open |
|---|---|---|
target_code | Kind 4 and the pool id, side byte 0 | Kind 5 and the perp market id, side byte 0 |
collateral_asset | Hash of the chosen collateral mint | Hash of the market's quote mint |
oracle_price | Price of the collateral in the pool's asset | Price of the base in quote |
index | The pool's borrow_index | The market's funding_index |
param_a | collateral_factor_bps | max_leverage |
param_b | 0 | maint_margin_bps |
deadline | The end of the next heartbeat epoch | The same |
The deadline is genesis_ts + (floor((now − genesis_ts) / heartbeat) + 2) · heartbeat.
The program creates the Batch account if needed (state Open, with its close_ts and drand round), creates the Action account in state Sealed with the commitment and the rent payer, raises the batch's action_count, verifies the proof and calls SPP. It does not read the action's terms, so the target of an order, supply, redeem, close or vault action is first checked at open.
Measured, in compute units: place_lock 250,796 to 259,911, place_share 251,743 to 259,391, place_open 263,592 to 266,370, place_close 251,418 to 252,353, place_pair 259,351.
| Error | When |
|---|---|
ProtocolPaused | Config.paused is set and the action is an order, a supply, a borrow, a perp open or a vault deposit. A redeem, a perp close and a vault withdrawal are placed while paused. |
InvalidBatchTime | The clock is before genesis_ts or past close_ts − place_margin |
InvalidAccount | batch or action is not the PDA the program derived. Another place landing first moves action_count and has this effect |
AlreadyInitialized | The action account already exists |
InvalidInstructionData | kind is none of the values above, or the data is cut short |
UnsupportedCollateral | Borrow: collateral_index is not below the pool's collateral_count |
MarketPaused | Perp open: the perp market is paused |
InvalidOracle, StaleOracle | Borrow and perp open: the oracle account fails its checks |
open
Tag 6. Anyone, from close_ts until close_ts + open_window. Posts the terms of one sealed action. The caller got them by decrypting the action's timelock ciphertext with the batch's drand round.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
action | writable | An action PDA of that batch, in state Sealed |
target | read-only | The PDA of the target the posted code names: ["market", id] for an order, ["pool", id] for supply, redeem and borrow, ["perp", id] for perp open and close, ["vault", id] for vault deposit and withdraw |
The data after the tag is exactly 173 bytes:
| Field | Type | Meaning |
|---|---|---|
code | u32 | Kind, side and target id |
batch | u64 | The batch the action was made for |
asset | [u8; 32] | The mint the action is in |
amount | u64 | Order: the amount locked. Supply: the amount supplied. Redeem and vault withdraw: shares. Vault deposit: the quote leg. Perp close: the position's collateral |
amount_b | u64 | Borrow: the principal. Perp open and close: the size in base atoms. Spot vault deposit: the base leg |
limit | u64 | Order: the limit price at PRICE_SCALE, 0 for a market order. Perp close: the funding index at entry |
param | u64 | Perp close: the entry price. Borrow: the borrow index at entry |
recipient_owner_hash | [u8; 32] | Owner hash of the receive holder |
recipient_view | [u8; 33] | Viewing public key of the receive holder |
recipient_auth | [u8; 32] | The auth of everything settled to the recipient |
The program hashes the fields with Poseidon by the rule that hashes an action note's state, and requires the result to equal the stored commitment. It then stores the fields and decides between Opened and Invalid. The action is Opened when its batch equals the batch's number, the target account exists, and the terms have the shape of their kind:
| Kind | Shape required |
|---|---|
| Order | Side 0 or 1, amount > 0, amount_b = 0, param = 0, the market not paused, asset equal to the quote mint for a buy or the base mint for a sell |
| Supply, redeem | Side 0 or 255, amount > 0, amount_b = 0, asset equal to the pool's mint |
| Borrow | Side 0, amount = 0, amount_b > 0, asset equal to the pool's mint |
| Perp open | Side 0 or 1, amount = 0, amount_b > 0, asset equal to its quote mint |
| Perp close | Side 0 or 1, amount > 0, amount_b > 0, asset equal to its quote mint |
| Vault deposit | Spot vault: amount > 0 and amount_b > 0. Perps vault: amount > 0 and amount_b = 0. asset equal to the vault's quote mint |
| Vault withdraw | amount > 0, amount_b = 0, asset equal to the vault's quote mint |
Any other terms, an unknown kind included, make the action Invalid. An Opened action is counted in the batch's record for its target, which the program adds on the target's first action. A batch holds records for at most 8 targets. The first open of a batch moves it from Open to Opening.
Measured: 23,744 to 72,302 compute units.
| Error | When |
|---|---|
InvalidAccount | batch or action is not a PDA of the program, the action is of another batch, or target is not the PDA of the id in code |
InvalidActionState | The action is not Sealed |
BatchNotClosed | now < close_ts |
OpenWindowClosed | now ≥ close_ts + open_window |
InvalidInstructionData | The data is not exactly 173 bytes |
CommitmentMismatch | The fields do not hash to the stored commitment |
TargetAlreadyCleared | The action's target is already cleared in this batch |
ActionLimitExceeded | The target already has max_actions_per_market opened actions in this batch |
BatchTargetsFull | The action would add a ninth target to the batch |
HashingFailed | The fields could not be hashed |
clear
Tag 7, no arguments. Anyone, once now ≥ close_ts and either every action of the batch is Opened or Invalid, or the open window has ended. Computes one target's result for the batch and writes it to the Batch account. The third account decides which kind of target is cleared.
The opened actions of the target follow the fixed accounts, in strictly increasing index, and there must be exactly as many as the batch's opened count for the target. A target with no opened actions is cleared with none.
Spot market:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
market | writable | The market |
vault | writable | The market's liquidity vault |
| actions | read-only | The market's opened orders |
Pool:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
pool | writable | The pool |
| actions | writable | The pool's opened supplies, redeems and borrows |
Perp market:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
perp | writable | The perp market |
vault | writable | The market's perps vault |
oracle | read-only | The price account of the market's base |
| actions | writable | The market's opened perp opens and closes |
Vault:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
vault | writable | The vault |
| actions | writable | The vault's opened deposits and withdrawals |
What each does:
- Spot market. Computes the clearing price from the opened orders and the vault's reserves, by the rule in Clearing at one price. Moves the vault's reserves by the sum of the per-order settlements, adds the protocol share of each fill's fee to the vault's
protocol_fees_baseorprotocol_fees_quote, and updates the market's last clearing price and cumulative volume. The record keeps the clearing price, the matched base and quote, the vault's change in each reserve, and the side and fraction of the orders filled pro rata at the price. - Pool. Accrues interest from
last_accrualto now: the borrow rate at the pool's utilization growsborrowsandborrow_index, andreserve_factor_bpsof the interest is added toreserves. This is the only place the borrow index moves. Supplies then add cash and mint shares at the share price after accrual. Redeems burn shares and remove cash at that price, and a redeem whose shares exceed the pool's or whose payout exceeds the cash left is markedRefused. Borrows take cash inindexorder, and a borrow larger than the cash left is markedRefused. The record keeps the share price, the borrow index and the net change in cash. - Perp market. Reads the oracle once and moves
funding_indexfor the time since the last clear. This is the only place the funding index moves. For each close it computes the settlement at that price and index, lowers the open interest of its side, and moves the result through the vault: a gain and the protocol share of its fees leavequote_reserve, or, whenquote_reservecannot pay them, the close is markedRefusedand the position stays open, a loss enters it less the protocol share, and the protocol share is added toprotocol_fees_quote. Each open is added to the open interest of its side while that stays withinmax_oi, and is markedRefusedotherwise. The record keeps the oracle price and the funding index. - Vault. If the vault's market has a record in this batch, the market must be cleared first. Every deposit and withdrawal is priced against the vault's reserves and total shares as they stand when the clear starts. A spot deposit mints shares for the smaller of its two legs at the reserves' ratio and takes the matching amount of the other. A perps vault deposit mints shares at
quote_reserve / total_shares. A withdrawal removes its pro rata part of each reserve. A withdrawal whose payout in a required asset rounds to zero, or exceeds the vault's reserves, is markedRefused, and its owner takes the shares back withreclaim. The record keeps the reserves and total shares used.
Perp fees are both charged here, at the close: open_fee_bps on the size at the entry price and close_fee_bps on the size at the clearing oracle price, taken together from the position's payout.
After writing the record the program sets the batch to Settled if every recorded target is cleared and every opened action is settled, and to Clearing otherwise.
Measured, in compute units: a spot market 112,156, a pool 13,723 to 20,543, a perp market 16,996 to 29,171. One transaction clearing a market and two vaults used 116,856, and one clearing two vaults used 34,542.
| Error | When |
|---|---|
InvalidAccount | Fewer than three accounts, a third account that is none of the four kinds, a batch that is not a PDA of the program, or a vault that is not the market's own |
BatchNotClosed | now < close_ts |
OpenWindowStillActive | Some action is still Sealed and the open window has not ended |
TargetAlreadyCleared | The target is already cleared in this batch |
BatchTargetsFull | The target has no record yet and the batch already has 8 |
InvalidActionAccounts | The action accounts are not exactly the target's opened actions in increasing index |
MarketNotCleared | Vault: its market has a record in this batch and is not cleared |
InsufficientVaultLiquidity | A reserve is empty, the fills would take a whole reserve, or a withdrawal names more shares than the vault has in total |
InvalidOracle, StaleOracle | Perp market: the oracle account fails its checks |
MathOverflow | A result does not fit its type |
settle
Tag 8. Anyone, once the action's target is cleared in its batch. Pays out one opened action. The program computes every public amount from the batch record and the action's stored terms, and the proof fixes every output note to the receive holder named in those terms.
For an order:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
action | writable | The action PDA, in state Opened |
market | read-only | The market the order names |
vault | read-only | The market's liquidity vault |
rent_payer | writable | The rent payer recorded in the action |
mesa_program | read-only | The mesa program |
| SPP accounts | See The SPP accounts |
For every other kind, one target account (the pool, perp market or vault the action names) stands in place of market and vault:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch PDA |
action | writable | The action PDA, in state Opened |
target | read-only | The pool, perp market or vault the action names |
rent_payer | writable | The rent payer recorded in the action |
mesa_program | read-only | The mesa program |
| SPP accounts | See The SPP accounts. For a perp open, the Mesa authority alone |
| Field | Type | Meaning |
|---|---|---|
proof | 128 bytes | The settle proof for the case |
| transact data | to the end | The SPP transact |
A perp open settles with no data after the tag: it moves no notes, since its position was created at place.
The case decides the circuit and the public legs. "To Mesa" is a leg from a note to Mesa's token account for the mint, and "from Mesa" is a leg from that token account into a note.
| Action | Circuit | Public legs | Public inputs after mesa_identity and commitment |
|---|---|---|---|
| Order with a fill | settle | Amount filled to Mesa, output after fee from Mesa | to_vault, from_vault |
| Order with no fill | settle_refund | None | None |
| Supply | settle_supply | Amount supplied to Mesa | to_vault, share_target, shares |
| Redeem | settle_payout | Shares at the recorded share price, from Mesa | from_vault |
| Borrow | settle_payout | The principal, from Mesa | from_vault |
| Perp open | None | None | |
| Perp close, gain | settle_payout | The gain, from Mesa | from_vault |
| Perp close, loss | settle_loss | The loss, to Mesa | to_vault |
| Perp close, neither | settle_refund | None | None |
| Spot vault deposit | settle_pair | Base used and quote used, to Mesa | used_base, used_quote, share_target, shares |
| Perps vault deposit | settle_supply | Amount deposited, to Mesa | to_vault, share_target, shares |
| Spot vault withdraw | settle_split | Base out and quote out, from Mesa | base_out, quote_out |
| Perps vault withdraw | settle_payout | Quote out, from Mesa | from_vault |
An order's fee is fee_bps of the fill's output, taken from that output. A perp close's gain or loss is its payout against its collateral, where the payout is collateral plus price result, minus funding owed, minus the open and close fees, floored at zero.
After the CPI the program emits the settlement as an emit_event, raises the batch's settled_count, sets the batch to Settled once every recorded target is cleared and every opened action is settled, and closes the Action account, returning its rent to the rent payer.
Called on a Refused action, settle succeeds and changes nothing. It reads only config, batch and action in that case.
Measured, in compute units: an order 295,211 to 301,309, a supply 277,048, a redeem 275,468, a borrow 273,127 to 273,379, a perp close with a gain 280,682 and with a loss 280,490, a spot vault deposit 303,573, a perps vault deposit 276,483, a spot vault withdraw 292,524, a perps vault withdraw 284,318, a refused action 9,459. Two perp opens settled in one transaction used 46,059.
| Error | When |
|---|---|
InvalidAccount | batch or action is not a PDA of the program, the action is of another batch, the target is not the one the action names, or mesa_program is not the program |
InvalidActionState | The action is Sealed or Invalid |
InvalidRentPayer | rent_payer is not the address recorded in the action |
TargetNotCleared | The action's target has no cleared record in the batch |
InvalidInstructionData | A perp open sent with data, or another kind sent without a proof and transact |
MissingMesaAuthority | The Mesa authority is not among the trailing accounts |
MathOverflow | A settlement amount does not fit its type |
reclaim
Tag 9. Once now ≥ close_ts + open_window, for an action that is still Sealed or was opened as Invalid. For a redeem, a vault withdraw or a perp close that its batch marked Refused, as soon as the target has cleared, with no wait. The instruction takes no signer, and its proof needs the owner's spend secret, so only the owner can produce it. Returns what the action locked: balances, for a redeem or vault withdraw the shares, or for a perp close the position.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable for a Refused action, read-only otherwise | The batch PDA |
action | writable | The action PDA, in state Sealed or Invalid, or a Refused redeem, vault withdraw or perp close |
rent_payer | writable | The rent payer recorded in the action |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
proof | 128 bytes | Proof of reclaim, reclaim_pair, reclaim_share or reclaim_position |
| transact data | to the end | The SPP transact |
An action that locked shares, a redeem or a vault withdraw, is verified as reclaim_share and returns as a share note of the same pool or vault and the same count. A transact with two inputs is verified as reclaim_pair, the two action notes of a spot vault deposit returning as two balances. Any other is verified as reclaim, one action note returning as one balance. Public inputs of all three: mesa_identity and the action's commitment.
The program closes the Action account and returns its rent to the rent payer. Reclaiming a Refused action also counts it as settled in the batch.
A refused borrow or perp open is not reclaimed here: its collateral is in a position, and close_position in mode 1 returns it.
For a perp close the proof is followed by a u16 length and the restored position's timelock ciphertext, laid out as in renew, and the position comes back with a new deadline at the end of the next heartbeat epoch.
Measured: 254,282 compute units for an order, 250,246 to 255,890 for refused shares, 255,299 for a refused perp close.
| Error | When |
|---|---|
InvalidAccount | batch or action is not a PDA of the program, or the action is of another batch |
InvalidActionState | The action is not Sealed or Invalid, and is not a Refused redeem, vault withdraw or perp close |
InvalidRentPayer | rent_payer is not the address recorded in the action |
OpenWindowStillActive | A Sealed or Invalid action, and now < close_ts + open_window |
Position instructions
Sealed positions and renewal and Liquidation explain what these are for. All four run whether or not the protocol or the market is paused, and none takes a signer of its own.
Each of them verifies its proof against the pool's borrow_index or the perp market's funding_index as stored in the account. Those indexes move only when the pool or market clears a batch, so a proof stays valid between clears as long as the oracle account it was made against is unchanged.
renew
Tag 15. Anyone who holds the position's keys: the owner's browser, the owner's script, or a watcher. Replaces a position with the same position and a later deadline.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
target | writable | The pool of a borrow, or the perp market of a perp |
oracle | read-only | The price account of the borrow's collateral, or of the perp market's base |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
kind | u8 | 4 for a borrow, 5 for a perp |
collateral_index | u8 | Borrow: the index of the collateral in the pool's list |
old_deadline | u64 | The deadline of the position being renewed, unix seconds |
proof | 128 bytes | Proof of renew |
tlock_len | u16 | Length of the timelock ciphertext |
| tlock ciphertext | tlock_len bytes | The renewed position's contents and keys, encrypted to the drand round at its new deadline |
| transact data | to the end | The SPP transact |
The program computes the new deadline, genesis_ts + (floor((now − genesis_ts) / heartbeat) + 2) · heartbeat, and requires it to be later than old_deadline. A position is therefore renewed at most once per heartbeat epoch, and one whose deadline has passed can still be renewed.
Public inputs after mesa_identity: target_code (the kind and target id, side byte 0), collateral_asset, oracle_price, index (the stored borrow or funding index), threshold_bps (liq_threshold_bps of the pool, or maint_margin_bps of the perp market), old_deadline and new_deadline. No account of the program changes.
Measured: 251,968 to 252,335 compute units.
| Error | When |
|---|---|
InvalidBatchTime | The new deadline is not later than old_deadline, or the clock is before genesis_ts |
InvalidInstructionData | kind is neither 4 nor 5 |
InvalidAccount | target is not a pool or perp market of the program |
UnsupportedCollateral | Borrow: collateral_index is not below the pool's collateral_count |
InvalidOracle, StaleOracle | The oracle account fails its checks |
repay
Tag 16. The owner, whose spend secret the proof needs. In mode 0 it repays part of a borrow. In mode 1 it adds collateral to a borrow or a perp, or removes some. Both prove the position healthy afterwards and set its deadline to the end of the next heartbeat epoch.
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
target | writable | The pool, or in mode 1 the pool or the perp market |
oracle | read-only | The price account of the borrow's collateral, or of the perp market's base |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
mode | u8 | 0 repay, 1 change collateral |
kind | u8 | 4 for a borrow, 5 for a perp. Mode 0 takes 4 only |
collateral_index | u8 | Borrow: the index of the collateral in the pool's list |
repaid | u64 | Mode 0: the amount repaid, above zero. Not read in mode 1 |
proof | 128 bytes | The proof for the mode |
tlock_len | u16 | Length of the timelock ciphertext |
| tlock ciphertext | tlock_len bytes | The updated position, encrypted to the drand round at its new deadline |
| transact data | to the end | The SPP transact |
| Mode | Circuit | Public leg | Public inputs after mesa_identity |
|---|---|---|---|
0 | adjust_repay | repaid of the pool's mint, to Mesa | target_code, collateral_asset, oracle_price, index, threshold_bps, new_deadline, repaid |
1 | adjust_collateral | None | target_code, collateral_asset, oracle_price, index, threshold_bps, new_deadline |
In mode 0 the program adds repaid to the pool's cash and takes it off borrows. Mode 1 changes no account of the program.
| Error | When |
|---|---|
InvalidInstructionData | mode is neither 0 nor 1, mode 0 with a kind other than 4 or with repaid of zero, or mode 1 with a kind that is neither 4 nor 5 |
InvalidBatchTime | The clock is before genesis_ts |
InvalidAccount | target is not a pool or perp market of the program |
UnsupportedCollateral | Borrow: collateral_index is not below the pool's collateral_count |
InvalidOracle, StaleOracle | The oracle account fails its checks |
close_position
Tag 17. The owner. In mode 0 it repays a borrow in full and returns its collateral as a balance. In mode 1 it unlocks the position of a borrow or perp open that never took effect, returning the whole collateral with nothing repaid: one its batch marked Refused, or one still Sealed or opened as Invalid once the batch's open window has ended. A perp that was opened closes through a batch, with a place of kind 6.
Mode 0:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
pool | writable | The pool borrowed from |
| SPP accounts | See The SPP accounts |
Mode 1:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
batch | writable | The batch of the refused action |
action | writable | The action PDA: Refused, or Sealed or Invalid after the open window |
rent_payer | writable | The rent payer recorded in the action |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
mode | u8 | 0 repay in full, 1 close a refused position |
repaid | u64 | Mode 0: the debt at the pool's stored borrow index, above zero. Not read in mode 1 |
proof | 128 bytes | The proof for the mode |
| transact data | to the end | The SPP transact |
| Mode | Circuit | Public leg | Public inputs after mesa_identity |
|---|---|---|---|
0 | close_position | repaid of the pool's mint, to Mesa | target_code, index, repaid |
1 | close_refused | None | refused_activation, the commitment stored in the action |
In mode 0 the program adds repaid to the pool's cash and takes it off borrows. In mode 1 it raises the batch's settled_count, sets the batch to Settled once every recorded target is cleared and every opened action is settled, and closes the Action account to its rent payer.
Measured: 265,719 compute units in mode 0, 249,810 in mode 1.
| Error | When |
|---|---|
InvalidInstructionData | mode is neither 0 nor 1, or mode 0 with repaid of zero |
InvalidAccount | pool is not a pool of the program, or batch and action are not PDAs of the program and of one batch |
InvalidActionState | Mode 1: the action is Opened, or it is Sealed or Invalid and the open window has not ended |
InvalidRentPayer | Mode 1: rent_payer is not the address recorded in the action |
liquidate
Tag 18. Anyone, once the clock is past the position's deadline. The liquidator read the position from its last timelock ciphertext, which opens at the deadline's drand round. The program checks the time, and the proof checks that the position is unhealthy at the oracle price and index the program supplies.
Borrow:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
pool | writable | The pool borrowed from |
oracle | read-only | The price account of the position's collateral |
| SPP accounts | See The SPP accounts |
Perp:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
perp | writable | The perp market |
vault | writable | The market's perps vault |
oracle | read-only | The price account of the market's base |
| SPP accounts | See The SPP accounts |
| Field | Type | Meaning |
|---|---|---|
kind | u8 | 4 for a borrow, 5 for a perp |
side | u8 | Perp: 0 long, 1 short |
collateral_index | u8 | Borrow: the index of the collateral in the pool's list |
old_deadline | u64 | The lapsed position's deadline, unix seconds |
amount | u64 | Borrow: the debt repaid. Perp: the amount paid to the perps vault. Above zero |
size | u64 | Perp: the position's size in base atoms. 0 for a borrow |
proof | 128 bytes | The proof for the kind |
| transact data | to the end | The SPP transact |
| Kind | Circuit | Public leg | Public inputs after mesa_identity |
|---|---|---|---|
| Borrow | liquidate_borrow | amount of the pool's mint, to Mesa | target_code, collateral_asset, oracle_price, index, liq_threshold_bps, liq_bonus_bps, old_deadline, repaid |
| Perp | liquidate_perp | amount of the market's quote mint, to Mesa | target_code (with the side), collateral_asset, oracle_price, index, maint_margin_bps, liq_bonus_bps, old_deadline, to_vault, size |
For a borrow, the liquidator's balance repays the debt, collateral worth the debt plus the bonus goes to the liquidator, and the rest goes to the position's home holder. The program adds amount to the pool's cash and takes it off borrows. For a perp, the collateral less the liquidator's bonus goes to the perps vault. The program adds amount to the vault's quote_reserve and takes size off the open interest of the position's side.
Measured: 273,866 compute units for a borrow.
| Error | When |
|---|---|
PositionNotLapsed | now ≤ old_deadline |
InvalidInstructionData | kind is neither 4 nor 5, amount is zero, or a perp's side is neither 0 nor 1 |
InvalidAccount | The pool or perp market is not the program's, or vault is not the perp market's own |
UnsupportedCollateral | Borrow: collateral_index is not below the pool's collateral_count |
InvalidOracle, StaleOracle | The oracle account fails its checks |
MathOverflow | A total does not fit its type |
Fee instruction
sweep_fees
Tag 12, no arguments, no signer. Anyone. Transfers the whole of a pool's reserves, or of a vault's protocol fees, from Mesa's token account to the associated token account of Config.fee_recipient, and sets the counter to zero. The second account decides the case. The program does not create the recipient's token accounts.
Pool:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
target | writable | The pool |
authority | read-only | The Mesa authority |
recipient_ata | writable | The fee recipient's token account for the pool's mint |
pool_ata | writable | Mesa's token account for the pool's mint |
token_program | read-only | The SPL Token program |
Spot liquidity vault:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
target | writable | The vault |
authority | read-only | The Mesa authority |
recipient_base_ata | writable | The fee recipient's token account for the base mint |
vault_base_ata | writable | Mesa's token account for the base mint |
recipient_quote_ata | writable | The fee recipient's token account for the quote mint |
vault_quote_ata | writable | Mesa's token account for the quote mint |
token_program | read-only | The SPL Token program |
Perps vault:
| Account | Flags | Must be |
|---|---|---|
config | read-only | The config PDA |
target | writable | The vault |
authority | read-only | The Mesa authority |
recipient_quote_ata | writable | The fee recipient's token account for the quote mint |
vault_quote_ata | writable | Mesa's token account for the quote mint |
token_program | read-only | The SPL Token program |
A pool's sweep lowers its cash by the amount swept. A spot vault with fees in one asset only transfers that one.
Measured: 17,293 compute units for a pool, 24,737 for a spot vault.
| Error | When |
|---|---|
NothingToSweep | The counter, or both counters of a spot vault, is zero |
InvalidAccount | authority is not the Mesa authority, target is neither a pool nor a vault, or a token account is not the associated token account expected |
InsufficientVaultLiquidity | Pool: cash is below reserves |
Authority-only instructions
These are signed by the address stored in Config.admin and are not part of any user's flow. Each fails with Unauthorized for any other signer, and with InvalidInstructionData when its arguments do not decode.
| Instruction | Tag | What it does | Measured |
|---|---|---|---|
init_config | 0 | Creates Config, once. The admin signer becomes Config.admin | 13,790 |
set_config | 1 | Rewrites the changeable fields of Config, the admin and the pause flag included | |
create_market | 2 | Creates a spot market and its liquidity vault, seeded from the admin's token accounts | 61,640 to 67,640 |
create_pool | 10 | Creates a lending pool, seeded from the admin's token account | 27,489 to 30,489 |
create_perp_market | 11 | Creates a perp market and its perps vault, seeded from the admin's token account | 28,049 to 37,137 |
withdraw_seed_shares | 13 | Redeems some of the admin's seed shares of a pool or vault | 38,069 for two vaults in one transaction |
set_paused | 19 | Pauses or unpauses one spot market or perp market | 14,872 for two markets in one transaction |
init_config
| Account | Flags | Must be |
|---|---|---|
payer | writable, signer | Funds the account |
admin | signer | The address that becomes the admin |
config | writable | The config PDA, not yet created |
authority | read-only | The Mesa authority |
system_program | read-only | The System Program |
| Field | Type |
|---|---|
fee_recipient | [u8; 32] |
pyth_receiver | [u8; 32] |
protocol_share_bps | u16 |
max_actions_per_market | u16 |
batch_len | u64 |
open_window | u64 |
place_margin | u64 |
heartbeat | u64 |
max_oracle_age | u64 |
genesis_ts | i64 |
drand_genesis | u64 |
drand_period | u64 |
drand_chain_hash | [u8; 32] |
vk_set_id | [u8; 32] |
Raises InvalidConfig when protocol_share_bps is above 10,000, when max_actions_per_market, batch_len, open_window or drand_period is zero, or when place_margin is not below batch_len. Raises AlreadyInitialized when Config exists, and InvalidAccount when config or authority is not the expected PDA.
set_config
| Account | Flags | Must be |
|---|---|---|
admin | signer | Config.admin |
config | writable | The config PDA |
| Field | Type |
|---|---|
admin | [u8; 32] |
fee_recipient | [u8; 32] |
pyth_receiver | [u8; 32] |
protocol_share_bps | u16 |
max_actions_per_market | u16 |
batch_len | u64 |
open_window | u64 |
place_margin | u64 |
heartbeat | u64 |
max_oracle_age | u64 |
paused | u8 |
drand_genesis | u64 |
drand_period | u64 |
drand_chain_hash | [u8; 32] |
vk_set_id | [u8; 32] |
Every field is written as sent. genesis_ts and the target counters are not among them. Raises InvalidConfig by the rules of init_config, and when paused is above 1.
create_market
The new market takes the id Config.market_count and its vault the id Config.vault_count.
| Account | Flags | Must be |
|---|---|---|
payer | writable, signer | Funds the accounts |
admin | signer | Config.admin, and the owner of the two source token accounts |
config | writable | The config PDA |
market | writable | The market PDA of the next market id, not yet created |
vault | writable | The vault PDA of the next vault id, not yet created |
authority | read-only | The Mesa authority |
base_mint | read-only | The base mint |
quote_mint | read-only | The quote mint, different from the base mint |
admin_base_ata | writable | The admin's base token account |
admin_quote_ata | writable | The admin's quote token account |
vault_base_ata | writable | Mesa's token account for the base mint, created if absent |
vault_quote_ata | writable | Mesa's token account for the quote mint, created if absent |
token_program | read-only | The SPL Token program |
ata_program | read-only | The Associated Token Account program |
system_program | read-only | The System Program |
| Field | Type | Meaning |
|---|---|---|
fee_bps | u16 | The market's fee, below 10,000 |
initial_base | u64 | Base reserve to seed, above zero |
initial_quote | u64 | Quote reserve to seed, above zero |
The vault starts with those reserves and isqrt(initial_base · initial_quote) shares, all recorded as admin_seed_shares. The market's last clearing price starts at the reserves' ratio. Raises InvalidConfig for the fee, InvalidSeedReserves for a zero reserve, price or share count, InvalidMarketMint for equal or zero mints, InvalidAccount for a wrong PDA or token account, and AlreadyInitialized when the market or vault account exists.
create_pool
The new pool takes the id Config.pool_count.
| Account | Flags | Must be |
|---|---|---|
payer | writable, signer | Funds the accounts |
admin | signer | Config.admin, and the owner of the source token account |
config | writable | The config PDA |
pool | writable | The pool PDA of the next pool id, not yet created |
authority | read-only | The Mesa authority |
mint | read-only | The pool's asset |
admin_ata | writable | The admin's token account for the mint |
pool_ata | writable | Mesa's token account for the mint, created if absent |
token_program | read-only | The SPL Token program |
ata_program | read-only | The Associated Token Account program |
system_program | read-only | The System Program |
| Field | Type | Meaning |
|---|---|---|
decimals | u8 | Decimals of the pool's asset |
collateral_count | u8 | Collaterals accepted, 1 to 4 |
collateral_mints | [[u8; 32]; 4] | Their mints |
collateral_decimals | [u8; 4] | Their decimals |
collateral_oracles | [[u8; 32]; 4] | Their Pyth feed ids |
base_rate_bps | u16 | Borrow rate at zero utilization |
slope1_bps | u16 | Rate added up to the kink |
slope2_bps | u16 | Rate added beyond the kink |
kink_bps | u16 | Above zero, below 10,000 |
reserve_factor_bps | u16 | At most 10,000 |
collateral_factor_bps | u16 | Above zero |
liq_threshold_bps | u16 | At least collateral_factor_bps, at most 10,000 |
liq_bonus_bps | u16 | Below 10,000 |
initial_cash | u64 | Cash to seed, above zero |
The pool starts with initial_cash cash, the same number of supply shares recorded as admin_seed_shares, no borrows, and a borrow index of 10^18. Raises InvalidSeedReserves, InvalidConfig, InvalidAccount and AlreadyInitialized as create_market does.
create_perp_market
The new perp market takes the id Config.perp_count and its vault the id Config.vault_count.
| Account | Flags | Must be |
|---|---|---|
payer | writable, signer | Funds the accounts |
admin | signer | Config.admin, and the owner of the source token account |
config | writable | The config PDA |
perp | writable | The perp market PDA of the next perp id, not yet created |
vault | writable | The vault PDA of the next vault id, not yet created |
authority | read-only | The Mesa authority |
base_mint | read-only | The base asset's mint. Not read |
quote_mint | read-only | The quote mint |
admin_quote_ata | writable | The admin's quote token account |
vault_quote_ata | writable | Mesa's token account for the quote mint, created if absent |
oracle | read-only | A current price account of the base feed |
token_program | read-only | The SPL Token program |
ata_program | read-only | The Associated Token Account program |
system_program | read-only | The System Program |
| Field | Type | Meaning |
|---|---|---|
base_decimals | u8 | Decimals of the base asset |
quote_decimals | u8 | Decimals of the quote asset |
base_oracle | [u8; 32] | The base's Pyth feed id |
max_leverage | u16 | Above zero |
maint_margin_bps | u16 | Above zero, below 10,000 |
liq_bonus_bps | u16 | Below 10,000 |
open_fee_bps | u16 | Below 10,000 |
close_fee_bps | u16 | Below 10,000 |
funding_rate_bps_per_hour | u16 | Funding rate at full imbalance |
max_oi | u64 | Open interest allowed per side, above zero |
initial_quote | u64 | Quote to seed the vault, above zero |
The vault starts with initial_quote in reserve and the same number of shares, recorded as admin_seed_shares. The funding index starts at 2^62. Raises the errors of create_market, and InvalidOracle or StaleOracle for the oracle account.
withdraw_seed_shares
Burns shares of the admin's seed shares and pays their part of the reserves by the same share arithmetic every other holder's withdrawal uses. The third account decides the case.
| Account | Flags | Must be |
|---|---|---|
admin | signer | Config.admin |
config | read-only | The config PDA |
target | writable | A pool or a vault |
authority | read-only | The Mesa authority |
| destination and source | writable | Pool: admin_ata, pool_ata. Spot vault: admin_base_ata, vault_base_ata, admin_quote_ata, vault_quote_ata. Perps vault: admin_quote_ata, vault_quote_ata. The source is Mesa's token account for the mint |
token_program | read-only | The SPL Token program |
| Field | Type | Meaning |
|---|---|---|
shares | u64 | Shares to burn, above zero |
Raises InsufficientVaultLiquidity when shares exceeds admin_seed_shares or the total, or when a pool's cash cannot pay the amount, and InvalidAccount for a wrong authority, target or source account.
set_paused
Tag 19. Sets the paused flag of one spot market or one perp market.
| Account | Flags | Must be |
|---|---|---|
admin | signer | Config.admin |
config | read-only | The config PDA |
target | writable | A Market or a PerpMarket of the program |
| Field | Type | Meaning |
|---|---|---|
paused | u8 | 1 to pause, 0 to unpause |
The pause of the whole protocol is Config.paused, set with set_config.
Event instruction
emit_event
Tag 255. Called only by the program on itself, from settle: its one account must sign, and it is the Mesa authority, a PDA only the program can sign for. Any other caller gets Unauthorized.
The instruction does nothing. Its data is the event, kept in the transaction's inner instructions where an indexer reads it.
| Account | Flags | Must be |
|---|---|---|
authority | signer | The Mesa authority |
The data is 73 bytes with the tag:
| Field | Type | Meaning |
|---|---|---|
batch | u64 | The batch number |
index | u32 | The action's index in the batch |
code | u32 | The action's kind, side and target id |
amount | u64 | The action's amount |
limit | u64 | The action's limit |
clearing_price | u64 | Order: the clearing price. Perp open and close: the oracle price of the clear. Otherwise 0 |
to_vault | u64 | What moved from the action's note to Mesa: an order's filled input, a supply or perps vault deposit, a spot vault deposit's quote used, a perp close's loss |
from_vault | u64 | What moved from Mesa into a note: an order's output after fee, a redeem's payout, a borrow's principal, a perp close's gain, a vault withdrawal's quote. For a supply or a vault deposit, the shares minted |
fee_total | u64 | Order and perp close: the whole fee. Otherwise 0 |
protocol_fee | u64 | Order and perp close: the protocol share of the fee. Otherwise 0 |