Docs · Reference

SDK

The TypeScript SDK in full: opening an account from a script or a browser, one call per action, the account snapshot, progress and errors, and the renew loop.

@mesa/sdk is the TypeScript package the app itself runs on. It derives an account's keys, reads the account by decrypting its notes, proves each action where the keys are, and sends it through the API. It has two entries.

EntryForOpens with
@mesa/sdk/nodeScripts and services, on Node 22openMesaScript
@mesa/sdk/browserWeb appscreateMesa
bash
npm install @mesa/sdk

Open an account from a script

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

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

console.log(mesa.snapshot().balances)

openMesaScript derives the keys, reads the account once, and returns a handle with one method per action. It throws if the account cannot be read.

OptionTypeMeaning
apiUrlstringThe Mesa API's base URL, https://api.mesa.markets
keyFilestringPath to a key file. See The key file.
masterSecretUint8Array | stringA 32-byte master secret, in place of keyFile
walletWalletAdapter | Uint8Array | stringA wallet adapter or a Solana secret key, in place of keyFile
onProgress(p: ActionProgress) => voidCalled at every stage of every action
circuitsDirstringA local folder of circuit files. Without it the SDK downloads them from the API.
rpcUrl, indexerUrl, proverUrlstringYour own Solana RPC, Privacy Rings indexer and Rings prover. Each defaults to the one GET /v1/config names.
fetchtypeof fetchA replacement for the global fetch

One of keyFile, masterSecret or wallet is required.

The key file

A key file holds one of two things.

ContentsThe account it opensCan deposit
A 64-byte Solana keypairThe account of that wallet, the same one the app opens when that wallet connectsYes
A 32-byte master secretThe account of that secretNo. A deposit is signed by a wallet.

With a keypair, the SDK signs the account message with it and derives the master secret from the signature, exactly as the app does. A keypair file written by solana-keygen works as it is.

Accepted encodings: a JSON array of bytes, a JSON object with secretKey or masterSecret, a hex, base58 or base64 string, or raw bytes.

Amounts and identifiers

Every amount is a bigint in the asset's smallest unit: 1_000_000_000n is 1 SOL at 9 decimals, 1_000_000n is 1 USDC at 6. A price is a decimal string in the market's quote asset per unit of base, such as '182.40'.

Markets, pools, perp markets and vaults are named by the ids the API returns: GET /v1/markets, /v1/pools, /v1/perps and /v1/vaults. Assets are named by mint address, listed with their decimals in GET /v1/config.

Actions

Each method proves the action, sends it, and resolves when it is done. For an action that goes through a batch, done means the batch has settled.

MethodGoes through a batchResolves with
depositNo
withdrawNo
swapYesorder
supplyYesshare
redeemYes
borrowYesposition
repayNoposition
perpYesposition
closeA perp: yes. A borrow: no.
renewNoposition
vaultDepositYesshare
vaultWithdrawYes

Every result also carries:

FieldTypeMeaning
progressActionProgressThe last stage reached: settled, or placed
signaturestring | nullThe Solana signature of the action's transaction
batchNumbernumber | nullThe batch the action went into

After each action the handle reads the account again, so snapshot() is current when the call returns.

deposit and withdraw

ts
await mesa.deposit({ mint: USDC, amount: 500_000_000n })
await mesa.withdraw({ mint: USDC, amount: 100_000_000n })

deposit moves an asset from the wallet's Rings private balance into Mesa. It is signed by the wallet, so the handle must have been opened with a keypair. withdraw moves it back to the wallet's Rings private balance and is relayed.

swap

ts
const { order, batchNumber } = await mesa.swap({
  marketId: 'SOL-USDC',
  side: 'buy',
  amount: 1_850_000_000n,
  limitPrice: '185.00',
})
ParameterTypeMeaning
marketIdstringThe spot market
side'buy' | 'sell'Buy or sell the base asset
amountbigintHow much of the asset you give up to lock: quote for a buy, base for a sell
limitPricestring, optionalThe worst clearing price the order accepts. Left out, the order is a market order.

The sample locks 1,850 USDC to buy SOL at no more than 185.00. It resolves with the account's order for that batch: its state is filled, partially_filled or unfilled, with filledBase, filledQuote and the batch's clearingPrice. Whatever did not fill is back in the balance.

supply and redeem

ts
const { share } = await mesa.supply({ poolId: 'USDC', amount: 5_000_000_000n })
await mesa.redeem({ poolId: 'USDC', shares: share!.shares })

supply resolves with the account's share of the pool. redeem takes a number of shares and pays the asset at the pool's share price of the batch.

borrow

ts
const { position } = await mesa.borrow({
  poolId: 'USDC',
  collateralMint: SOL,
  collateral: 10_000_000_000n,
  amount: 1_000_000_000n,
})
ParameterTypeMeaning
poolIdstringThe pool to borrow from
collateralMintstringThe collateral asset. It must be one the pool accepts.
collateralbigintHow much collateral to lock in the position
amountbigintHow much to borrow

It resolves with the new position, or with position: null if the batch refused the borrow because the pool had too little cash. The collateral of a refused borrow is returned by close.

repay

ts
await mesa.repay({ positionId: position.id, amount: 400_000_000n })

Repays part of a borrow from the balance of the borrowed asset and renews the position.

perp

ts
const { position } = await mesa.perp({
  marketId: 'SOL-PERP',
  side: 'long',
  collateral: 500_000_000n,
  sizeBase: 10_000_000_000n,
})
ParameterTypeMeaning
marketIdstringThe perp market
side'long' | 'short'The direction
collateralbigintCollateral, in the market's collateral asset
sizeBasebigintThe position's size, in the base asset

close

ts
await mesa.close({ positionId: position.id })

Closes a borrow by repaying its whole debt and returning the collateral, at once. Closes a perp through the next batch, and resolves when the result has settled against the perps vault.

renew

ts
await mesa.renew({ positionId: position.id })

Proves the position healthy at the current oracle price and moves its deadline one heartbeat on.

vaultDeposit and vaultWithdraw

ts
const { share } = await mesa.vaultDeposit({
  vaultId: 'vault-lp-sol-usdc',
  amount: 1_800_000_000n,
  amountBase: 10_000_000_000n,
  amountQuote: 1_800_000_000n,
})
await mesa.vaultWithdraw({ vaultId: 'vault-lp-sol-usdc', shares: share!.shares })

A spot liquidity vault takes both assets: amountBase and amountQuote, with amount equal to the quote leg. The perps vault takes one, in amount. vaultWithdraw takes a number of shares.

Actions without a method of their own

mesa.mesa is the underlying account controller. Its run takes any action, including the ones the handle has no method for.

ts
const account = mesa.mesa
await account.run({ kind: 'add_collateral', positionId, amount: 1_000_000_000n }, console.log)
ActionFieldsDoes
registerRegisters a Rings private wallet for the wallet
rings_depositmint, amountPublic balance to Rings private balance
rings_withdrawmint, amountRings private balance to public balance
consolidatemintMerges the balance notes of one asset
reclaimorderIdTakes back what an action locked: one never opened or opened as Invalid, or a redeem, vault withdrawal or perp close its batch refused. orderId is the order's id, or the actionId of a share's pending or a position's pendingClose.
add_collateralpositionId, amountAdds collateral to a position
remove_collateralpositionId, amountRemoves collateral from a position
enrol_watcherpositionIdHands a position's key to the watcher
remove_watcherpositionIdTakes it back

run resolves with the last ActionProgress and does not throw: check stage for failed. For an action that goes through a batch it resolves at placed.

Reading the account

ts
const account = mesa.snapshot()
FieldTypeMeaning
statusstringready once the account is read. Otherwise no-wallet, not-registered, locked, reading or failed.
addressstring | nullThe wallet's address
readOnlybooleanTrue when the account was opened from a read-only key
balancesBalance[]Per asset: mesa (free), locked (in orders and batches), rings, wallet
ordersOwnOrder[]Each with state: sealed, opening, filled, partially_filled, unfilled, reclaimable or reclaimed
positionsOwnPosition[]Each with collateral, debt or sizeBase, health, liquidationPrice, nextDeadlineAt, renewedBy and state: pending, sealed, due or lapsed. A perp being closed carries pendingClose: actionId, batchNumber and state, pending or reclaimable when its batch refused the close or never opened it.
sharesOwnShare[]Per vault: shares, valueQuote, and pending, a deposit or withdrawal not yet settled, with its kind, amount, batchNumber, actionId and state: pending, or refused when its batch refused it or its open window passed unopened. A refused one is taken back with reclaim and its actionId.
historyHistoryItem[]Every deposit, order, fill, renewal and withdrawal, with its batch and signature
readAtstring | nullWhen the account was last read
errorstring | nullWhy the read failed

A position's health is a decimal string: 1 is the liquidation threshold and above it is healthy.

mesa.refresh() reads the account again. mesa.mesa.subscribe(listener) calls listener each time the snapshot changes.

Read-only keys

ts
const key = await mesa.mesa.exportReadOnlyKey()

const viewer = createMesa({ apiUrl })
await viewer.openReadOnly(key)
console.log(viewer.snapshot().history)

exportReadOnlyKey returns the account's read-only key as a base58 string. openReadOnly opens an account from one. Every action on it fails with "This account is open with a read-only key."

Progress and errors

onProgress receives each stage as it is reached.

StageMeaning
signingThe action is being built, and the wallet signs if the action needs it
provingThe proof is being generated. proof runs from 0 to 1 when the prover reports it.
retryingThe batch closed before the action landed. It is proved again for the current batch, up to three attempts. The app reads "The batch closed first. Proving again for the next one".
relayingThe transaction is on its way to the chain
placedThe action is in batch batchNumber, sealed
settledThe action is done
failedIt did not happen. message says why and retryable says whether trying again can work.

A method of the handle throws an Error whose message is the failure's message. Where the API refused the request, that is the message of its error envelope, and where the program refused the transaction the API names the program error.

Messages the SDK raises itself:

MessageCause
Connect a wallet first.The action needs a wallet signature and the handle was opened from a master secret
Insufficient Mesa balance for <mint>: have <a>, need <b>.The free balance does not cover the amount
No unspent Mesa balance found for <mint>.The account holds none of the asset
No unspent share note covers the requested amount.No single share note holds that many shares
Repay applies only to borrow positions.repay was called on a perp
Unknown Mesa asset mint: <mint>The mint is not one GET /v1/config lists

The renew loop

ts
const loop = mesa.renewLoop({
  onRenew: (position) => console.log('renewed', position.id),
  onError: (id, error) => console.error(id, error),
})

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

renewLoop keeps positions sealed for as long as the process runs. On every pass it reads the account and renews each position whose deadline is near.

OptionTypeDefaultMeaning
intervalMsnumber60000Time between passes
marginSecondsnumberA third of the heartbeatRenew a position when its deadline is within this many seconds
positionIdsstring[]All positionsRenew only these
onRenewfunctionCalled after each renewal with the position and the result
onErrorfunctionCalled with a position id and the error. The loop goes on.
signalAbortSignalStops the loop when aborted

It returns stop() and done, a promise that resolves when the loop has stopped. A marginSeconds of your own stays below the heartbeat (heartbeatSeconds in GET /v1/config) and well above intervalMs, so each position is renewed once per heartbeat with passes to spare.

Liquidation

ts
const lapsed = await mesa.lapsedPositions()
if (lapsed[0]) await mesa.liquidate(lapsed[0])

const loop = mesa.liquidateLoop({
  onLiquidate: (position, progress) => console.log('liquidated', position.id, progress.signature),
  onError: (id, error) => console.error(id, error),
})
MethodReturnsDoes
lapsedPositions()Promise<LapsedPosition[]>Positions past their deadline and not yet renewed, closed or liquidated, from GET /v1/positions/lapsed
liquidate(position)Promise<ScriptActionResult>Opens the position's timelock, checks it is past its deadline and unhealthy at the oracle price, proves the liquidation and relays it. Throws when it cannot.
liquidateLoop(options){ stop(), done }Lists lapsed positions on every pass and liquidates each one it can

LapsedPosition carries id, kind (borrow or perp), marketId, targetAddress, collateralIndex, slot, deadlineAt, deadlineSeconds, tlockOpen, ciphertextBase64, positionNoteHash and positionAccount.

A borrow is repaid in full from one balance note of the pool's asset. On mesa.mesa, liquidate(position, onProgress) returns the progress instead of throwing.

OptionTypeDefaultMeaning
intervalMsnumber15000Time between passes
onLiquidatefunctionCalled with the position and its progress after each liquidation lands
onErrorfunctionCalled with a position id, or * for a failed pass, and the error. Healthy, early and already taken positions are skipped without it.
signalAbortSignalStops the loop when aborted

The whole task is in Run a liquidator.

In a browser

ts
import { createMesa } from '@mesa/sdk/browser'

const mesa = createMesa({ apiUrl, wallet })
mesa.subscribe(() => render(mesa.snapshot()))
await mesa.unlock()
await mesa.run({ kind: 'supply', poolId: 'USDC', amount: 5_000_000_000n }, onProgress)

wallet is a small adapter over the connected wallet.

MemberTypeMeaning
getAddress()() => string | nullThe connected address, or null
signMessage(message)(Uint8Array) => Promise<Uint8Array>Signs bytes. unlock uses it once to derive the account.
signTransaction(bytes)optionalSigns a serialized transaction, for registration, Rings deposits and withdrawals, and deposits into Mesa
subscribe(listener)optionalCalled when the wallet connects, switches account or disconnects

unlock() asks the wallet for one signature and reads the account. Proofs run in the page from the same WebAssembly module the Node entry uses, and the circuit files are fetched from the API on first use.

mesa.destroy() stops the controller's subscriptions and streams. Call it when a script is finished or a page unmounts.