Docs · Reference

Program: accounts

Every public account of the mesa program with its seeds, size and byte layout, the four note states, the constants and packed codes a reader needs, and how batch times, drand rounds and heartbeat deadlines are computed.

The mesa program keeps seven kinds of public account and four kinds of note. This page gives each account's address, size and fields in byte order, each note's fields, and the arithmetic that ties them to the clock.

Encoding and units

Every account starts with an 8-byte ASCII discriminator and is written field by field with no padding. Integers are little-endian. A 32-byte address or mint is stored as its raw bytes. Offsets in the tables below are in bytes from the start of the account data.

ConstantValueUsed for
PRICE_SCALE1_000_000_000_000 (10^12)Prices: quote atoms per base atom, times PRICE_SCALE
WAD1_000_000_000_000_000_000 (10^18)Share prices, the borrow index, fill fractions, Pool.borrows
BPS_DENOM10_000Every field ending in _bps
FUNDING_BIAS2^62The value a perp market's funding index starts at
MAX_BATCH_TARGETS8Target records in one Batch
MAX_POOL_COLLATERAL4Collateral slots in one Pool

Amounts are integers in the mint's smallest unit, called atoms here. Times are Unix seconds.

A price of 150.00 USDC per SOL, with 6 and 9 decimals, is 150 × 10^6 / 10^9 × 10^12 = 150_000_000_000.

Addresses

Every account is a program-derived address of the mesa program. The program id is listed under Addresses.

AccountSeedsSize in bytesDiscriminator
Authority"authority"no datanone
Config"config"246MESACFG1
Market"market", id as u16 LE120MESAMKT1
Vault"vault", id as u16 LE126MESAVLT1
Pool"pool", id as u16 LE393MESAPOL1
PerpMarket"perp", id as u16 LE148MESAPRP1
Batch"batch", n as u64 LE891MESABCH1
Action"action", n as u64 LE, index as u32 LE259MESAACT1

Ids are assigned in order of creation from the counters in Config. Markets, pools and perp markets each count from 0. Vaults share one counter: a spot market's vault and a perp market's vault each take the next vault id.

The authority and its token accounts

The authority owns no data. It is the owner of every Mesa note in the Privacy Rings pool and the token authority of Mesa's public funds. For each mint Mesa holds, the funds sit in the authority's associated token account for that mint under the SPL Token program. There is one such account per mint, shared by every market, vault and pool that uses the mint. The reserves, cash and fee counters in the accounts below say how much of it belongs to each.

Config

One account. It holds the clock, the fee split and the external programs every instruction reads.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESACFG1
admin[u8; 32]8The address that may change Config and create markets, pools and perp markets
authority_bumpu840Bump of the authority address
pausedu8410 or 1. While 1, deposit and place of an order, a supply, a borrow, a perp open or a vault deposit are refused. Everything else runs.
protocol_share_bpsu1642The protocol's part of each spot and perp fee, in bps of the fee
max_actions_per_marketu1644The most actions one target can have opened in one batch
market_countu1646Spot markets created. The next market id.
vault_countu1648Vaults created. The next vault id.
pool_countu1650Pools created. The next pool id.
perp_countu1652Perp markets created. The next perp market id.
fee_recipient[u8; 32]54The wallet whose associated token accounts receive sweep_fees
pyth_receiver[u8; 32]86The program that must own every oracle account. See Oracle accounts.
batch_lenu64118Length of a batch, in seconds
open_windowu64126Seconds after a batch closes during which its actions can be opened
place_marginu64134Seconds before the close at which a batch stops taking actions. Less than batch_len.
heartbeatu64142Length of a heartbeat epoch, in seconds
max_oracle_ageu64150The most seconds an oracle price's publish time may differ from the clock
genesis_tsi64158The time batch 0 and heartbeat epoch 0 begin
drand_genesisu64166Genesis time of the drand beacon
drand_periodu64174Seconds between drand rounds
drand_chain_hash[u8; 32]182Chain hash of the drand beacon the batches are sealed to
vk_set_id[u8; 32]214Identifier of the verifying-key set

Market

One per spot market.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESAMKT1
idu168Market id
vault_idu1610Id of the market's liquidity vault
fee_bpsu1612Fee taken from the output of each fill
pausedu8140 or 1. While 1, orders for the market open as Invalid and are reclaimed.
bumpu815Bump of this address
base_mint[u8; 32]16Mint of the base asset
quote_mint[u8; 32]48Mint of the quote asset
last_clearing_priceu6480Clearing price of the last batch cleared for this market, at PRICE_SCALE. At creation, the price of the vault's initial reserves.
cumulative_base_volumeu12888Sum of matched_base over every cleared batch, in base atoms
cumulative_quote_volumeu128104Sum of matched_quote over every cleared batch, in quote atoms

Vault

One per spot market and one per perp market. kind says which.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESAVLT1
idu168Vault id
market_idu1610Id of the spot market (kind 0) or of the perp market (kind 1) the vault backs
kindu8120 spot liquidity, 1 perps
bumpu813Bump of this address
base_mint[u8; 32]14Base mint. All zero for a perps vault.
quote_mint[u8; 32]46Quote mint
base_reserveu6478Base atoms that belong to the vault's shares. 0 for a perps vault.
quote_reserveu6486Quote atoms that belong to the vault's shares
total_sharesu6494Shares outstanding
admin_seed_sharesu64102Shares minted for the reserves the vault was created with, less any the admin has withdrawn
protocol_fees_baseu64110Base atoms of protocol fee owed, outside base_reserve, until sweep_fees pays them out
protocol_fees_quoteu64118Quote atoms of protocol fee owed, outside quote_reserve, until sweep_fees pays them out

A spot vault is created with total_shares = isqrt(initial_base · initial_quote). A perps vault is created with one share per quote atom. A spot vault's own price is quote_reserve · PRICE_SCALE / base_reserve.

Pool

One per lending pool.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESAPOL1
idu168Pool id
bumpu810Bump of this address
collateral_countu811Collateral slots in use, 1 to 4
decimalsu812Decimals of the pool's mint
mint[u8; 32]13The asset supplied and borrowed
cashu6445Atoms the pool holds that are not lent out. Includes reserves.
borrowsu12853Total debt with interest, in atoms times WAD
borrow_indexu12869Cumulative borrow index. Starts at WAD and grows with interest. Never above u64::MAX.
supply_sharesu6485Shares outstanding
admin_seed_sharesu6493Shares minted for the cash the pool was created with, less any the admin has withdrawn
reservesu64101The protocol's part of accrued interest, in atoms, until sweep_fees pays it out
base_rate_bpsu16109Annual borrow rate at zero utilization
slope1_bpsu16111Annual rate added between zero utilization and the kink
slope2_bpsu16113Annual rate added between the kink and full utilization
kink_bpsu16115The utilization at which the curve turns
collateral_factor_bpsu16117The most debt a new borrow may take, as a part of its collateral's value
liq_threshold_bpsu16119The part of its collateral's value a debt must stay within to renew
liq_bonus_bpsu16121The liquidator's bonus
reserve_factor_bpsu16123The part of accrued interest added to reserves
last_accruali64125Time interest was last accrued
collateral_mints[[u8; 32]; 4]133Mint of each collateral slot
collateral_oracles[[u8; 32]; 4]261Pyth feed id of each collateral slot
collateral_decimals[u8; 4]389Decimals of each collateral mint

Only the first collateral_count slots are read. An instruction names a collateral by its slot index.

A pool accrues interest when it clears a batch. With borrowed = borrows / WAD:

text
utilization = borrowed / (cash + borrowed)

rate = base_rate + slope1 · utilization / kink                        utilization ≤ kink
rate = base_rate + slope1 + slope2 · (utilization − kink) / (1 − kink)   utilization > kink

factor       = rate · elapsed_seconds / 31_536_000
borrows      = borrows + borrows · factor
borrow_index = borrow_index + borrow_index · factor
reserves     = reserves + interest · reserve_factor_bps / 10_000

share price  = (cash + borrowed − reserves) · WAD / supply_shares

The share price is WAD while supply_shares is 0. A borrow of principal taken at index entry owes ceil(principal · borrow_index / entry).

PerpMarket

One per perp market.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESAPRP1
idu168Perp market id
vault_idu1610Id of the perps vault that is the market's counterparty
max_leverageu1612The most size a new position may take, as a multiple of its collateral: collateral · max_leverage ≥ size · price
maint_margin_bpsu1614The margin a position must keep, in bps of its size at the oracle price
liq_bonus_bpsu1616The liquidator's bonus
open_fee_bpsu1618Fee on the position's size at its entry price
close_fee_bpsu1620Fee on the position's size at its closing price
funding_rate_bps_per_houru1622The hourly funding rate at full imbalance. See The funding index.
bumpu824Bump of this address
pausedu8250 or 1. While 1, place of a perp open is refused. Closes, renewals and clears run.
base_decimalsu826Decimals of the base asset
quote_decimalsu827Decimals of the quote mint
base_oracle[u8; 32]28Pyth feed id of the base asset's price
quote_mint[u8; 32]60The mint of collateral, fees and settlement
open_interest_longu6492Sum of long sizes, in base atoms
open_interest_shortu64100Sum of short sizes, in base atoms
funding_indexu128108Cumulative funding per base atom at PRICE_SCALE, offset by FUNDING_BIAS. Never above u64::MAX.
max_oiu64124The most open interest each side may reach, in base atoms
last_funding_tsi64132Time funding was last accrued
last_oracle_priceu64140The oracle price read at the last clear, at PRICE_SCALE

Batch

One per batch that has at least one action. The first place in batch n creates it.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESABCH1
nu648Batch number
close_tsi6416Time the batch closes
roundu6424The drand round the batch is sealed to
stateu832See Batch states
bumpu833Bump of this address
target_countu834Target records in use, 0 to 8
action_countu3235Actions placed. The index the next action gets.
opened_countu3239Actions recorded as Opened
invalid_countu3243Actions recorded as Invalid
settled_countu3247Opened actions that are finished: settled, or refused and then closed
targets[BatchTargetRecord; 8]51One record per market, pool, perp market or vault the batch touched, 105 bytes each

n, close_ts and round follow from Batch time.

Target record

Record i starts at offset 51 + 105 · i. Only the first target_count records are in use. A record is added when the first action for its target opens, or when clear runs for a target that has none. Offsets below are from the start of the record.

FieldTypeOffsetMeaning
target_kindu801 spot market, 2 pool, 3 perp market, 4 vault
clearedu810 until clear has run for this target, then 1
target_idu162Id of the market, pool, perp market or vault
opened_countu324Actions opened for this target. clear requires exactly this many action accounts.
clearing_priceu648Depends on the target kind, below
matched_baseu6416Depends on the target kind, below
matched_quoteu6424Depends on the target kind, below
vault_base_deltai6432Spot market: change of the vault's base_reserve in this clear, signed
vault_quote_deltai6440Spot market: change of the vault's quote_reserve in this clear, signed
partial_fill_wadu12848Spot market: the fraction, at WAD, filled of each order whose limit equals the clearing price on partial_fill_side
partial_fill_sideu864Spot market: 0 buys are rationed, 1 sells are rationed, 255 neither. 255 for every other target kind.
share_price_wadu12865Pool: the share price after accrual, at WAD
borrow_index_wadu12881Depends on the target kind, below
pool_net_cashi6497Pool: supplies, less redeems paid, less borrows paid, in atoms

The fields that depend on the target kind:

FieldSpot marketPoolPerp marketVault
clearing_priceThe clearing price, at PRICE_SCALE0The oracle price read at the clear, at PRICE_SCALE0
matched_baseBase atoms traded00The vault's base_reserve before this batch's deposits and withdrawals
matched_quoteQuote atoms traded00The vault's quote_reserve before this batch's deposits and withdrawals
borrow_index_wad0The pool's borrow_index after accrualThe market's funding_index after accrualThe vault's total_shares before this batch's deposits and withdrawals

settle computes every payout from these records and the action's opened fields:

  • A spot order fills whole when its limit is strictly better than clearing_price or is 0, fills partial_fill_wad of its amount when its limit equals the price and its side is partial_fill_side, fills whole at the price on the other side, and fills nothing when its limit is worse. A buy receives filled · PRICE_SCALE / clearing_price base atoms and a sell receives filled · clearing_price / PRICE_SCALE quote atoms, each less fee_bps of that output.
  • A supply mints amount · WAD / share_price_wad shares. A redeem pays shares · share_price_wad / WAD.
  • A perp close settles at clearing_price and the funding index in borrow_index_wad.
  • A vault deposit or withdrawal is priced against the reserves and total shares the record holds.

For a spot market, matched_base is the larger of the base the buys received before fees and the base the sells gave, and matched_quote is the larger of the quote the buys gave and the quote the sells received before fees. A market cleared with no orders records the vault's own price, zero volume, and a partial_fill_wad of WAD.

Batch states

ValueNameThe batch is in it when
0OPENIt has been created and no action has been opened
1OPENINGAt least one action has been recorded as Opened or Invalid
2CLEARINGAt least one target has cleared
3SETTLEDEvery target record is cleared and settled_count equals opened_count

The API reports its own states, open, sealed, opening, cleared and settled, read from these and the clock. sealed is an OPEN batch past close_ts. See Batches.

Action

One per action, created by place at index action_count of its batch.

FieldTypeOffsetMeaning
discriminator[u8; 8]0MESAACT1
batchu648The batch number n
indexu3216Position of the action in its batch, from 0
stateu820See Action states
bumpu821Bump of this address
commitment[u8; 32]22Hash of the action's fields, fixed at place
rent_payer[u8; 32]54The address that paid for the account and receives its lamports when it closes
fields173 bytes86The opened fields. All zero while the action is Sealed.

Opened fields

open writes these after checking that they hash to commitment.

FieldTypeOffsetMeaning
codeu3286Kind, side and target id, packed. See Action code.
batchu6490The batch the action was made for. An action whose value differs from the account's batch is Invalid.
asset[u8; 32]98Mint of the action note
amountu64130By kind, below
amount_bu64138By kind, below
limitu64146By kind, below
paramu64154By kind, below
recipient_owner_hash[u8; 32]162Owner hash of the receive holder the action settles to
recipient_view[u8; 33]194Viewing public key of the receive holder: a tag byte, then 32 key bytes
recipient_auth[u8; 32]227The spend authorization every note settled to the recipient carries

Fields by kind

Kindassetamountamount_blimitparam
1 order, buyThe market's quote mintQuote atoms locked, the most the order spends0Limit price at PRICE_SCALE, 0 for a market order0
1 order, sellThe market's base mintBase atoms locked0Limit price at PRICE_SCALE, 0 for a market order0
2 supplyThe pool's mintAtoms supplied0UnusedUnused
3 redeemThe pool's mintShares redeemed0UnusedUnused
4 borrowThe pool's mint0Principal borrowed, in atomsUnusedThe pool's borrow index when the action was placed
5 perp openThe market's quote mint0Size, in base atomsUnusedThe oracle price when the action was placed
6 perp closeThe market's quote mintThe position's collateral, in quote atomsThe position's size, in base atomsThe position's entry funding indexThe position's entry price
7 vault deposit, spotThe vault's quote mintQuote atoms lockedBase atoms lockedUnusedUnused
7 vault deposit, perpsThe vault's quote mintQuote atoms locked0UnusedUnused
8 vault withdrawThe vault's quote mintShares withdrawn0UnusedUnused

An action whose fields do not fit its row, or that names a target that does not exist, is recorded as Invalid.

Action states

ValueNameMeaning
0SEALEDPlaced. The account holds the commitment and no fields.
1OPENEDThe fields are posted, hash to the commitment and can be executed
2INVALIDThe fields hash to the commitment and cannot be executed
3REFUSEDOpened, and its target could not take it at the clear: a borrow or a redeem beyond the pool's cash, a perp open beyond max_oi, a perp close whose gain the perps vault cannot pay, or a vault withdrawal its reserves cannot pay
4SETTLEDPaid out
5RECLAIMEDReturned to its owner

settle and reclaim close the account and send its lamports to rent_payer, and so does close_position for a refused action. An action that has settled or been reclaimed therefore has no account, and an account read from the chain is in one of states 0 to 3.

The commitment

The commitment is the hash of the action note's state. open recomputes it from the posted fields with Poseidon over twelve field elements:

text
Poseidon(
  discriminator,            // 0x90f169db4a88cbb0, the first 8 bytes of sha256("account:Action")
  code, batch,
  hash_bytes(asset),
  amount, amount_b, limit, param,
  recipient_owner_hash,
  recipient_view[0],                 // the tag byte
  hash_bytes(recipient_view[1..33]),
  recipient_auth
)

Each integer enters as a 32-byte big-endian value. recipient_owner_hash and recipient_auth enter as stored.

Packed codes

Action code

Action.code and Position.code pack three values into a u32:

text
code = kind | (side << 8) | (target_id << 16)

kind      = code & 0xff
side      = (code >> 8) & 0xff
target_id = (code >> 16) & 0xffff
KindValueTarget
Order1Spot market id
Supply2Pool id
Redeem3Pool id
Borrow4Pool id
Perp open5Perp market id
Perp close6Perp market id
Vault deposit7Vault id
Vault withdraw8Vault id
SideValueMeaning
SIDE_BUY0Buy, or long
SIDE_SELL1Sell, or short
SIDE_NONE255No side

An order and a perp carry side 0 or 1. A borrow carries 0. A supply and a redeem carry 0 or 255.

Target kinds

NameValue
TARGET_SPOT_MARKET1
TARGET_POOL2
TARGET_PERP_MARKET3
TARGET_VAULT4

Share target

Share.target packs the kind of target and its id, in the opposite order to an action code:

text
target = (target_kind << 16) | target_id

target_kind is 2 for a pool and 4 for a vault.

Note states

A Mesa note is an output in the Privacy Rings pool owned by the authority. The note's own asset and amount carry its value, and its data is one of four states. A state's fields are sealed with the note and are read by decrypting it. The tables give each state's fields in the order they are hashed and serialized. Field is a 32-byte field element.

Balance

The note's asset and amount are the balance.

FieldTypeMeaning
authFieldSpend authorization: Poseidon(spend key, nonce), with a fresh nonce per note

Share

A claim on a pool or a vault. The note holds 0 of the pool's mint or the vault's quote mint.

FieldTypeMeaning
authFieldSpend authorization
targetu32The pool or vault. See Share target.
sharesu64Number of shares

Action

A batch action. The note holds what the action locked: the amount for an order, a supply, a vault deposit or a perp close, and 0 for a redeem, a vault withdrawal, a borrow or a perp open. A spot vault deposit has two action notes under one state, one holding the base leg and one the quote leg.

FieldTypeMeaning
codeu32Kind, side and target id
batchu64The batch the action is placed into
asset[u8; 32]Mint of the action note
amountu64As in Fields by kind
amount_bu64As in Fields by kind
limitu64As in Fields by kind
paramu64As in Fields by kind
recipientUtxoOwnerThe receive holder everything the action settles into is paid to
recipient_view_tagu8Byte 0 of the recipient's 33-byte viewing public key
recipient_view[u8; 32]Bytes 1 to 32 of that key
recipient_authFieldSpend authorization of every note settled to the recipient

The Action account stores the same state in its opened form: recipient as its owner hash, and the two viewing-key fields as one 33-byte value.

Position

A borrow or a perp. The note's asset and amount are the collateral: one of the pool's collateral mints for a borrow, the market's quote mint for a perp.

FieldTypeMeaning
codeu32Kind 4 with side 0 and the pool id for a borrow. Kind 5 with the side and the perp market id for a perp.
debtu64Borrow: principal in atoms of the pool's mint, as of the index in entry. Perp: size in base atoms.
entryu64Borrow: the pool's borrow_index when the borrow was placed. Perp: the oracle price when the open was placed, at PRICE_SCALE.
fundingu64Perp: the market's funding_index when the open was placed. Borrow: 0.
deadlineu64The time the position must be renewed by. See Heartbeat deadlines.
activationFieldThe commitment of the action that opened the position
authFieldSpend authorization
homeUtxoOwnerThe account holder a liquidation's remainder is paid to
home_view_tagu8Byte 0 of the home holder's 33-byte viewing public key
home_view[u8; 32]Bytes 1 to 32 of that key

Batch time

place computes the batch from the clock. With now the cluster's Unix time:

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

Batch n covers [genesis_ts + n · batch_len, close_ts). The same numbers give the Batch address for any time, before the account exists.

InstructionRuns when
placenow ≤ close_ts − place_margin
openclose_ts ≤ now < close_ts + open_window
clearnow ≥ close_ts, and either opened_count + invalid_count = action_count or now ≥ close_ts + open_window
settleThe action's target record has cleared = 1
reclaimnow ≥ close_ts + open_window, for an action that is Sealed or Invalid

The drand round

A batch is sealed to the first drand round published at or after its close:

text
round = ceil((close_ts − drand_genesis) / drand_period) + 1

The round is 1 when close_ts is at or before drand_genesis. It is computed once, when the Batch account is created, and stored in round.

Heartbeat deadlines

Heartbeat epoch e covers [genesis_ts + e · heartbeat, genesis_ts + (e + 1) · heartbeat). Every instruction that writes a position sets its deadline to the end of the epoch after the current one:

text
e        = floor((now − genesis_ts) / heartbeat)
deadline = genesis_ts + (e + 2) · heartbeat

place uses this value for a new borrow or perp, and renew and repay use it for the position they write. renew requires the new deadline to be later than the old one. liquidate requires now to be later than the position's deadline.

The funding index

A perp market's funding_index starts at FUNDING_BIAS, so it can move both ways and stay positive. Each clear of the market moves it by

text
delta = oracle_price · funding_rate_bps_per_hour · elapsed_seconds · |oi_long − oi_short|
        / (10_000 · 3_600 · (oi_long + oi_short))

It rises by delta when longs are the larger side and falls when shorts are. A position that entered at funding owes, in quote atoms,

text
long:   size · (funding_index − funding) / PRICE_SCALE
short:  size · (funding − funding_index) / PRICE_SCALE

A negative result is an amount the position receives. Its profit is size · (price − entry) / PRICE_SCALE for a long and size · (entry − price) / PRICE_SCALE for a short.

Oracle accounts

An oracle account passed to the program is a Pyth PriceUpdateV2 account. The program accepts it when all of these hold:

  • its owner is Config.pyth_receiver;
  • it is at least 133 bytes and begins with the PriceUpdateV2 discriminator, 22 f1 23 63 9d 7e f4 cd in hex;
  • byte 40, the verification level, is 1 for full verification;
  • the feed id at bytes 41 to 72 equals the feed id the pool or perp market names;
  • the price is above 0;
  • the publish time is within max_oracle_age seconds of the clock, before or after.

The program reads the price as an i64 at byte 73, the exponent as an i32 at byte 89 and the publish time as an i64 at byte 93, and scales the price to PRICE_SCALE:

text
scaled = price · 10^(12 + exponent + quote_decimals − base_decimals)

For a perp market the decimals are its base_decimals and quote_decimals. For a pool's collateral, the base is the collateral with its collateral_decimals and the quote is the pool's mint with its decimals.