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.

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:

text
tag · arguments · [tlock_len: u16 · tlock ciphertext] · SPP transact data

The 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:

AccountFlagsWhat it is
payerwritable, signerPays the pool's fees for the transact
output_treewritableThe state tree the new notes go into
spp_programread-onlyThe Solana Privacy Program
system_programread-onlyThe System Program
input_treewritableThe tree of the notes being spent
nullifierwritableOne nullifier PDA per input note, in input order
owner_signersignerPresent in deposit only: the wallet that owns the Rings notes spent
mesa_authorityread-onlyThe Mesa authority. It is not a signer of the transaction: the program signs for it inside the CPI
public leg accountsThe token accounts of each public leg, as the client lists them

The program passes at most 24 accounts to the CPI.

Shared account rules

  • config is the PDA ["config"], owned by the program.
  • batch is the PDA ["batch", n] with n as a little-endian u64. action is the PDA ["action", n, index] with index as a little-endian u32.
  • 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], with id as a little-endian u16.
  • 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 oracle account is a Pyth PriceUpdateV2 account owned by the program named in Config.pyth_receiver, fully verified, carrying the feed id the target names, with a positive price and a publish_time no more than Config.max_oracle_age seconds from the clock in either direction. The program scales its price to PRICE_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.

KindValueTargetSide
Order1Market id0 buy, 1 sell
Supply2Pool id0 or 255
Redeem3Pool id0 or 255
Borrow4Pool id0
Perp open5Perp market id0 long, 1 short
Perp close6Perp market id0 long, 1 short
Vault deposit7Vault idnot read
Vault withdraw8Vault idnot 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.

ErrorWhen
InvalidAccountconfig is not the config PDA, or is not owned by the program
InvalidInstructionDataThe arguments or the transact data do not decode
ProofVerificationFailedMesa's proof does not verify against the public inputs the program computed
HashingFailedA public input could not be hashed
InvalidShieldedPoolProgramThe SPP accounts do not hold the SPP program
MissingMesaAuthorityThe 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.

AccountFlagsMust be
configread-onlyThe config PDA
ownersignerThe wallet that owns the Rings notes
SPP accountsSee The SPP accounts
FieldTypeMeaning
proof128 bytesProof of deposit
transact datato the endThe 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.

AccountFlagsMust be
configread-onlyThe config PDA
SPP accountsSee The SPP accounts
FieldTypeMeaning
proof128 bytesProof 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 datato the endThe 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.

AccountFlagsMust be
configread-onlyThe config PDA
SPP accountsSee The SPP accounts
FieldTypeMeaning
proof128 bytesProof of consolidate
transact datato the endThe 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:

text
n        = floor((now − genesis_ts) / batch_len)
close_ts = genesis_ts + (n + 1) · batch_len

It 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.

AccountFlagsMust be
payerwritable, signerFunds the Action account, and the Batch account if it does not exist yet
configread-onlyThe config PDA
batchwritableThe batch PDA of the current batch n
actionwritableThe 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_programread-onlyThe System Program
targetread-onlyBorrow and perp open only: the pool or perp market
oracleread-onlyBorrow and perp open only: the price account of the pool's chosen collateral, or of the perp market's base
SPP accountsSee The SPP accounts
FieldTypeMeaning
kindu8Selects the proof, see below
commitment[u8; 32]The hash of the action's terms
proof128 bytesThe place proof for the kind
collateral_indexu8Present for borrow and perp open only. For a borrow, the index of the collateral in the pool's collateral list
tlock_lenu16Length of the timelock ciphertext
tlock ciphertexttlock_len bytesThe action's terms and action holder keys, encrypted to the batch's drand round
transact datato the endThe SPP transact
kindActionCircuitNotes
1, 2, 7Order, supply, perps vault depositplace_lockOne balance note in, one action note holding the locked amount out, change back as a balance
3, 8Redeem, vault withdrawplace_shareOne share note in, an action note holding 0 out, the remaining shares back as a share note
4, 5Borrow, perp openplace_openCollateral balance in, a position holding the collateral and an action note holding 0 out
6Perp closeplace_closeA position in, an action note holding its collateral out
0x87Spot vault depositplace_pairA 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 inputBorrowPerp open
target_codeKind 4 and the pool id, side byte 0Kind 5 and the perp market id, side byte 0
collateral_assetHash of the chosen collateral mintHash of the market's quote mint
oracle_pricePrice of the collateral in the pool's assetPrice of the base in quote
indexThe pool's borrow_indexThe market's funding_index
param_acollateral_factor_bpsmax_leverage
param_b0maint_margin_bps
deadlineThe end of the next heartbeat epochThe 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.

ErrorWhen
ProtocolPausedConfig.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.
InvalidBatchTimeThe clock is before genesis_ts or past close_ts − place_margin
InvalidAccountbatch or action is not the PDA the program derived. Another place landing first moves action_count and has this effect
AlreadyInitializedThe action account already exists
InvalidInstructionDatakind is none of the values above, or the data is cut short
UnsupportedCollateralBorrow: collateral_index is not below the pool's collateral_count
MarketPausedPerp open: the perp market is paused
InvalidOracle, StaleOracleBorrow 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.

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
actionwritableAn action PDA of that batch, in state Sealed
targetread-onlyThe 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:

FieldTypeMeaning
codeu32Kind, side and target id
batchu64The batch the action was made for
asset[u8; 32]The mint the action is in
amountu64Order: the amount locked. Supply: the amount supplied. Redeem and vault withdraw: shares. Vault deposit: the quote leg. Perp close: the position's collateral
amount_bu64Borrow: the principal. Perp open and close: the size in base atoms. Spot vault deposit: the base leg
limitu64Order: the limit price at PRICE_SCALE, 0 for a market order. Perp close: the funding index at entry
paramu64Perp 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:

KindShape required
OrderSide 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, redeemSide 0 or 255, amount > 0, amount_b = 0, asset equal to the pool's mint
BorrowSide 0, amount = 0, amount_b > 0, asset equal to the pool's mint
Perp openSide 0 or 1, amount = 0, amount_b > 0, asset equal to its quote mint
Perp closeSide 0 or 1, amount > 0, amount_b > 0, asset equal to its quote mint
Vault depositSpot vault: amount > 0 and amount_b > 0. Perps vault: amount > 0 and amount_b = 0. asset equal to the vault's quote mint
Vault withdrawamount > 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.

ErrorWhen
InvalidAccountbatch 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
InvalidActionStateThe action is not Sealed
BatchNotClosednow < close_ts
OpenWindowClosednow ≥ close_ts + open_window
InvalidInstructionDataThe data is not exactly 173 bytes
CommitmentMismatchThe fields do not hash to the stored commitment
TargetAlreadyClearedThe action's target is already cleared in this batch
ActionLimitExceededThe target already has max_actions_per_market opened actions in this batch
BatchTargetsFullThe action would add a ninth target to the batch
HashingFailedThe 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:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
marketwritableThe market
vaultwritableThe market's liquidity vault
actionsread-onlyThe market's opened orders

Pool:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
poolwritableThe pool
actionswritableThe pool's opened supplies, redeems and borrows

Perp market:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
perpwritableThe perp market
vaultwritableThe market's perps vault
oracleread-onlyThe price account of the market's base
actionswritableThe market's opened perp opens and closes

Vault:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
vaultwritableThe vault
actionswritableThe 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_base or protocol_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_accrual to now: the borrow rate at the pool's utilization grows borrows and borrow_index, and reserve_factor_bps of the interest is added to reserves. 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 marked Refused. Borrows take cash in index order, and a borrow larger than the cash left is marked Refused. The record keeps the share price, the borrow index and the net change in cash.
  • Perp market. Reads the oracle once and moves funding_index for 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 leave quote_reserve, or, when quote_reserve cannot pay them, the close is marked Refused and the position stays open, a loss enters it less the protocol share, and the protocol share is added to protocol_fees_quote. Each open is added to the open interest of its side while that stays within max_oi, and is marked Refused otherwise. 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 marked Refused, and its owner takes the shares back with reclaim. 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.

ErrorWhen
InvalidAccountFewer 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
BatchNotClosednow < close_ts
OpenWindowStillActiveSome action is still Sealed and the open window has not ended
TargetAlreadyClearedThe target is already cleared in this batch
BatchTargetsFullThe target has no record yet and the batch already has 8
InvalidActionAccountsThe action accounts are not exactly the target's opened actions in increasing index
MarketNotClearedVault: its market has a record in this batch and is not cleared
InsufficientVaultLiquidityA reserve is empty, the fills would take a whole reserve, or a withdrawal names more shares than the vault has in total
InvalidOracle, StaleOraclePerp market: the oracle account fails its checks
MathOverflowA 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:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
actionwritableThe action PDA, in state Opened
marketread-onlyThe market the order names
vaultread-onlyThe market's liquidity vault
rent_payerwritableThe rent payer recorded in the action
mesa_programread-onlyThe mesa program
SPP accountsSee 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:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch PDA
actionwritableThe action PDA, in state Opened
targetread-onlyThe pool, perp market or vault the action names
rent_payerwritableThe rent payer recorded in the action
mesa_programread-onlyThe mesa program
SPP accountsSee The SPP accounts. For a perp open, the Mesa authority alone
FieldTypeMeaning
proof128 bytesThe settle proof for the case
transact datato the endThe 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.

ActionCircuitPublic legsPublic inputs after mesa_identity and commitment
Order with a fillsettleAmount filled to Mesa, output after fee from Mesato_vault, from_vault
Order with no fillsettle_refundNoneNone
Supplysettle_supplyAmount supplied to Mesato_vault, share_target, shares
Redeemsettle_payoutShares at the recorded share price, from Mesafrom_vault
Borrowsettle_payoutThe principal, from Mesafrom_vault
Perp openNoneNone
Perp close, gainsettle_payoutThe gain, from Mesafrom_vault
Perp close, losssettle_lossThe loss, to Mesato_vault
Perp close, neithersettle_refundNoneNone
Spot vault depositsettle_pairBase used and quote used, to Mesaused_base, used_quote, share_target, shares
Perps vault depositsettle_supplyAmount deposited, to Mesato_vault, share_target, shares
Spot vault withdrawsettle_splitBase out and quote out, from Mesabase_out, quote_out
Perps vault withdrawsettle_payoutQuote out, from Mesafrom_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.

ErrorWhen
InvalidAccountbatch 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
InvalidActionStateThe action is Sealed or Invalid
InvalidRentPayerrent_payer is not the address recorded in the action
TargetNotClearedThe action's target has no cleared record in the batch
InvalidInstructionDataA perp open sent with data, or another kind sent without a proof and transact
MissingMesaAuthorityThe Mesa authority is not among the trailing accounts
MathOverflowA 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.

AccountFlagsMust be
configread-onlyThe config PDA
batchwritable for a Refused action, read-only otherwiseThe batch PDA
actionwritableThe action PDA, in state Sealed or Invalid, or a Refused redeem, vault withdraw or perp close
rent_payerwritableThe rent payer recorded in the action
SPP accountsSee The SPP accounts
FieldTypeMeaning
proof128 bytesProof of reclaim, reclaim_pair, reclaim_share or reclaim_position
transact datato the endThe 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.

ErrorWhen
InvalidAccountbatch or action is not a PDA of the program, or the action is of another batch
InvalidActionStateThe action is not Sealed or Invalid, and is not a Refused redeem, vault withdraw or perp close
InvalidRentPayerrent_payer is not the address recorded in the action
OpenWindowStillActiveA 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.

AccountFlagsMust be
configread-onlyThe config PDA
targetwritableThe pool of a borrow, or the perp market of a perp
oracleread-onlyThe price account of the borrow's collateral, or of the perp market's base
SPP accountsSee The SPP accounts
FieldTypeMeaning
kindu84 for a borrow, 5 for a perp
collateral_indexu8Borrow: the index of the collateral in the pool's list
old_deadlineu64The deadline of the position being renewed, unix seconds
proof128 bytesProof of renew
tlock_lenu16Length of the timelock ciphertext
tlock ciphertexttlock_len bytesThe renewed position's contents and keys, encrypted to the drand round at its new deadline
transact datato the endThe 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.

ErrorWhen
InvalidBatchTimeThe new deadline is not later than old_deadline, or the clock is before genesis_ts
InvalidInstructionDatakind is neither 4 nor 5
InvalidAccounttarget is not a pool or perp market of the program
UnsupportedCollateralBorrow: collateral_index is not below the pool's collateral_count
InvalidOracle, StaleOracleThe 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.

AccountFlagsMust be
configread-onlyThe config PDA
targetwritableThe pool, or in mode 1 the pool or the perp market
oracleread-onlyThe price account of the borrow's collateral, or of the perp market's base
SPP accountsSee The SPP accounts
FieldTypeMeaning
modeu80 repay, 1 change collateral
kindu84 for a borrow, 5 for a perp. Mode 0 takes 4 only
collateral_indexu8Borrow: the index of the collateral in the pool's list
repaidu64Mode 0: the amount repaid, above zero. Not read in mode 1
proof128 bytesThe proof for the mode
tlock_lenu16Length of the timelock ciphertext
tlock ciphertexttlock_len bytesThe updated position, encrypted to the drand round at its new deadline
transact datato the endThe SPP transact
ModeCircuitPublic legPublic inputs after mesa_identity
0adjust_repayrepaid of the pool's mint, to Mesatarget_code, collateral_asset, oracle_price, index, threshold_bps, new_deadline, repaid
1adjust_collateralNonetarget_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.

ErrorWhen
InvalidInstructionDatamode 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
InvalidBatchTimeThe clock is before genesis_ts
InvalidAccounttarget is not a pool or perp market of the program
UnsupportedCollateralBorrow: collateral_index is not below the pool's collateral_count
InvalidOracle, StaleOracleThe 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:

AccountFlagsMust be
configread-onlyThe config PDA
poolwritableThe pool borrowed from
SPP accountsSee The SPP accounts

Mode 1:

AccountFlagsMust be
configread-onlyThe config PDA
batchwritableThe batch of the refused action
actionwritableThe action PDA: Refused, or Sealed or Invalid after the open window
rent_payerwritableThe rent payer recorded in the action
SPP accountsSee The SPP accounts
FieldTypeMeaning
modeu80 repay in full, 1 close a refused position
repaidu64Mode 0: the debt at the pool's stored borrow index, above zero. Not read in mode 1
proof128 bytesThe proof for the mode
transact datato the endThe SPP transact
ModeCircuitPublic legPublic inputs after mesa_identity
0close_positionrepaid of the pool's mint, to Mesatarget_code, index, repaid
1close_refusedNonerefused_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.

ErrorWhen
InvalidInstructionDatamode is neither 0 nor 1, or mode 0 with repaid of zero
InvalidAccountpool is not a pool of the program, or batch and action are not PDAs of the program and of one batch
InvalidActionStateMode 1: the action is Opened, or it is Sealed or Invalid and the open window has not ended
InvalidRentPayerMode 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:

AccountFlagsMust be
configread-onlyThe config PDA
poolwritableThe pool borrowed from
oracleread-onlyThe price account of the position's collateral
SPP accountsSee The SPP accounts

Perp:

AccountFlagsMust be
configread-onlyThe config PDA
perpwritableThe perp market
vaultwritableThe market's perps vault
oracleread-onlyThe price account of the market's base
SPP accountsSee The SPP accounts
FieldTypeMeaning
kindu84 for a borrow, 5 for a perp
sideu8Perp: 0 long, 1 short
collateral_indexu8Borrow: the index of the collateral in the pool's list
old_deadlineu64The lapsed position's deadline, unix seconds
amountu64Borrow: the debt repaid. Perp: the amount paid to the perps vault. Above zero
sizeu64Perp: the position's size in base atoms. 0 for a borrow
proof128 bytesThe proof for the kind
transact datato the endThe SPP transact
KindCircuitPublic legPublic inputs after mesa_identity
Borrowliquidate_borrowamount of the pool's mint, to Mesatarget_code, collateral_asset, oracle_price, index, liq_threshold_bps, liq_bonus_bps, old_deadline, repaid
Perpliquidate_perpamount of the market's quote mint, to Mesatarget_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.

ErrorWhen
PositionNotLapsednow ≤ old_deadline
InvalidInstructionDatakind is neither 4 nor 5, amount is zero, or a perp's side is neither 0 nor 1
InvalidAccountThe pool or perp market is not the program's, or vault is not the perp market's own
UnsupportedCollateralBorrow: collateral_index is not below the pool's collateral_count
InvalidOracle, StaleOracleThe oracle account fails its checks
MathOverflowA 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:

AccountFlagsMust be
configread-onlyThe config PDA
targetwritableThe pool
authorityread-onlyThe Mesa authority
recipient_atawritableThe fee recipient's token account for the pool's mint
pool_atawritableMesa's token account for the pool's mint
token_programread-onlyThe SPL Token program

Spot liquidity vault:

AccountFlagsMust be
configread-onlyThe config PDA
targetwritableThe vault
authorityread-onlyThe Mesa authority
recipient_base_atawritableThe fee recipient's token account for the base mint
vault_base_atawritableMesa's token account for the base mint
recipient_quote_atawritableThe fee recipient's token account for the quote mint
vault_quote_atawritableMesa's token account for the quote mint
token_programread-onlyThe SPL Token program

Perps vault:

AccountFlagsMust be
configread-onlyThe config PDA
targetwritableThe vault
authorityread-onlyThe Mesa authority
recipient_quote_atawritableThe fee recipient's token account for the quote mint
vault_quote_atawritableMesa's token account for the quote mint
token_programread-onlyThe 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.

ErrorWhen
NothingToSweepThe counter, or both counters of a spot vault, is zero
InvalidAccountauthority is not the Mesa authority, target is neither a pool nor a vault, or a token account is not the associated token account expected
InsufficientVaultLiquidityPool: 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.

InstructionTagWhat it doesMeasured
init_config0Creates Config, once. The admin signer becomes Config.admin13,790
set_config1Rewrites the changeable fields of Config, the admin and the pause flag included
create_market2Creates a spot market and its liquidity vault, seeded from the admin's token accounts61,640 to 67,640
create_pool10Creates a lending pool, seeded from the admin's token account27,489 to 30,489
create_perp_market11Creates a perp market and its perps vault, seeded from the admin's token account28,049 to 37,137
withdraw_seed_shares13Redeems some of the admin's seed shares of a pool or vault38,069 for two vaults in one transaction
set_paused19Pauses or unpauses one spot market or perp market14,872 for two markets in one transaction

init_config

AccountFlagsMust be
payerwritable, signerFunds the account
adminsignerThe address that becomes the admin
configwritableThe config PDA, not yet created
authorityread-onlyThe Mesa authority
system_programread-onlyThe System Program
FieldType
fee_recipient[u8; 32]
pyth_receiver[u8; 32]
protocol_share_bpsu16
max_actions_per_marketu16
batch_lenu64
open_windowu64
place_marginu64
heartbeatu64
max_oracle_ageu64
genesis_tsi64
drand_genesisu64
drand_periodu64
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

AccountFlagsMust be
adminsignerConfig.admin
configwritableThe config PDA
FieldType
admin[u8; 32]
fee_recipient[u8; 32]
pyth_receiver[u8; 32]
protocol_share_bpsu16
max_actions_per_marketu16
batch_lenu64
open_windowu64
place_marginu64
heartbeatu64
max_oracle_ageu64
pausedu8
drand_genesisu64
drand_periodu64
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.

AccountFlagsMust be
payerwritable, signerFunds the accounts
adminsignerConfig.admin, and the owner of the two source token accounts
configwritableThe config PDA
marketwritableThe market PDA of the next market id, not yet created
vaultwritableThe vault PDA of the next vault id, not yet created
authorityread-onlyThe Mesa authority
base_mintread-onlyThe base mint
quote_mintread-onlyThe quote mint, different from the base mint
admin_base_atawritableThe admin's base token account
admin_quote_atawritableThe admin's quote token account
vault_base_atawritableMesa's token account for the base mint, created if absent
vault_quote_atawritableMesa's token account for the quote mint, created if absent
token_programread-onlyThe SPL Token program
ata_programread-onlyThe Associated Token Account program
system_programread-onlyThe System Program
FieldTypeMeaning
fee_bpsu16The market's fee, below 10,000
initial_baseu64Base reserve to seed, above zero
initial_quoteu64Quote 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.

AccountFlagsMust be
payerwritable, signerFunds the accounts
adminsignerConfig.admin, and the owner of the source token account
configwritableThe config PDA
poolwritableThe pool PDA of the next pool id, not yet created
authorityread-onlyThe Mesa authority
mintread-onlyThe pool's asset
admin_atawritableThe admin's token account for the mint
pool_atawritableMesa's token account for the mint, created if absent
token_programread-onlyThe SPL Token program
ata_programread-onlyThe Associated Token Account program
system_programread-onlyThe System Program
FieldTypeMeaning
decimalsu8Decimals of the pool's asset
collateral_countu8Collaterals 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_bpsu16Borrow rate at zero utilization
slope1_bpsu16Rate added up to the kink
slope2_bpsu16Rate added beyond the kink
kink_bpsu16Above zero, below 10,000
reserve_factor_bpsu16At most 10,000
collateral_factor_bpsu16Above zero
liq_threshold_bpsu16At least collateral_factor_bps, at most 10,000
liq_bonus_bpsu16Below 10,000
initial_cashu64Cash 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.

AccountFlagsMust be
payerwritable, signerFunds the accounts
adminsignerConfig.admin, and the owner of the source token account
configwritableThe config PDA
perpwritableThe perp market PDA of the next perp id, not yet created
vaultwritableThe vault PDA of the next vault id, not yet created
authorityread-onlyThe Mesa authority
base_mintread-onlyThe base asset's mint. Not read
quote_mintread-onlyThe quote mint
admin_quote_atawritableThe admin's quote token account
vault_quote_atawritableMesa's token account for the quote mint, created if absent
oracleread-onlyA current price account of the base feed
token_programread-onlyThe SPL Token program
ata_programread-onlyThe Associated Token Account program
system_programread-onlyThe System Program
FieldTypeMeaning
base_decimalsu8Decimals of the base asset
quote_decimalsu8Decimals of the quote asset
base_oracle[u8; 32]The base's Pyth feed id
max_leverageu16Above zero
maint_margin_bpsu16Above zero, below 10,000
liq_bonus_bpsu16Below 10,000
open_fee_bpsu16Below 10,000
close_fee_bpsu16Below 10,000
funding_rate_bps_per_houru16Funding rate at full imbalance
max_oiu64Open interest allowed per side, above zero
initial_quoteu64Quote 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.

AccountFlagsMust be
adminsignerConfig.admin
configread-onlyThe config PDA
targetwritableA pool or a vault
authorityread-onlyThe Mesa authority
destination and sourcewritablePool: 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_programread-onlyThe SPL Token program
FieldTypeMeaning
sharesu64Shares 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.

AccountFlagsMust be
adminsignerConfig.admin
configread-onlyThe config PDA
targetwritableA Market or a PerpMarket of the program
FieldTypeMeaning
pausedu81 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.

AccountFlagsMust be
authoritysignerThe Mesa authority

The data is 73 bytes with the tag:

FieldTypeMeaning
batchu64The batch number
indexu32The action's index in the batch
codeu32The action's kind, side and target id
amountu64The action's amount
limitu64The action's limit
clearing_priceu64Order: the clearing price. Perp open and close: the oracle price of the clear. Otherwise 0
to_vaultu64What 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_vaultu64What 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_totalu64Order and perp close: the whole fee. Otherwise 0
protocol_feeu64Order and perp close: the protocol share of the fee. Otherwise 0