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.
| Entry | For | Opens with |
|---|---|---|
@mesa/sdk/node | Scripts and services, on Node 22 | openMesaScript |
@mesa/sdk/browser | Web apps | createMesa |
npm install @mesa/sdkOpen an account from a script
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.
| Option | Type | Meaning |
|---|---|---|
apiUrl | string | The Mesa API's base URL, https://api.mesa.markets |
keyFile | string | Path to a key file. See The key file. |
masterSecret | Uint8Array | string | A 32-byte master secret, in place of keyFile |
wallet | WalletAdapter | Uint8Array | string | A wallet adapter or a Solana secret key, in place of keyFile |
onProgress | (p: ActionProgress) => void | Called at every stage of every action |
circuitsDir | string | A local folder of circuit files. Without it the SDK downloads them from the API. |
rpcUrl, indexerUrl, proverUrl | string | Your own Solana RPC, Privacy Rings indexer and Rings prover. Each defaults to the one GET /v1/config names. |
fetch | typeof fetch | A replacement for the global fetch |
One of keyFile, masterSecret or wallet is required.
The key file
A key file holds one of two things.
| Contents | The account it opens | Can deposit |
|---|---|---|
| A 64-byte Solana keypair | The account of that wallet, the same one the app opens when that wallet connects | Yes |
| A 32-byte master secret | The account of that secret | No. 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.
| Method | Goes through a batch | Resolves with |
|---|---|---|
deposit | No | |
withdraw | No | |
swap | Yes | order |
supply | Yes | share |
redeem | Yes | |
borrow | Yes | position |
repay | No | position |
perp | Yes | position |
close | A perp: yes. A borrow: no. | |
renew | No | position |
vaultDeposit | Yes | share |
vaultWithdraw | Yes |
Every result also carries:
| Field | Type | Meaning |
|---|---|---|
progress | ActionProgress | The last stage reached: settled, or placed |
signature | string | null | The Solana signature of the action's transaction |
batchNumber | number | null | The 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
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
const { order, batchNumber } = await mesa.swap({
marketId: 'SOL-USDC',
side: 'buy',
amount: 1_850_000_000n,
limitPrice: '185.00',
})| Parameter | Type | Meaning |
|---|---|---|
marketId | string | The spot market |
side | 'buy' | 'sell' | Buy or sell the base asset |
amount | bigint | How much of the asset you give up to lock: quote for a buy, base for a sell |
limitPrice | string, optional | The 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
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
const { position } = await mesa.borrow({
poolId: 'USDC',
collateralMint: SOL,
collateral: 10_000_000_000n,
amount: 1_000_000_000n,
})| Parameter | Type | Meaning |
|---|---|---|
poolId | string | The pool to borrow from |
collateralMint | string | The collateral asset. It must be one the pool accepts. |
collateral | bigint | How much collateral to lock in the position |
amount | bigint | How 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
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
const { position } = await mesa.perp({
marketId: 'SOL-PERP',
side: 'long',
collateral: 500_000_000n,
sizeBase: 10_000_000_000n,
})| Parameter | Type | Meaning |
|---|---|---|
marketId | string | The perp market |
side | 'long' | 'short' | The direction |
collateral | bigint | Collateral, in the market's collateral asset |
sizeBase | bigint | The position's size, in the base asset |
close
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
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
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.
const account = mesa.mesa
await account.run({ kind: 'add_collateral', positionId, amount: 1_000_000_000n }, console.log)| Action | Fields | Does |
|---|---|---|
register | Registers a Rings private wallet for the wallet | |
rings_deposit | mint, amount | Public balance to Rings private balance |
rings_withdraw | mint, amount | Rings private balance to public balance |
consolidate | mint | Merges the balance notes of one asset |
reclaim | orderId | Takes 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_collateral | positionId, amount | Adds collateral to a position |
remove_collateral | positionId, amount | Removes collateral from a position |
enrol_watcher | positionId | Hands a position's key to the watcher |
remove_watcher | positionId | Takes 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
const account = mesa.snapshot()| Field | Type | Meaning |
|---|---|---|
status | string | ready once the account is read. Otherwise no-wallet, not-registered, locked, reading or failed. |
address | string | null | The wallet's address |
readOnly | boolean | True when the account was opened from a read-only key |
balances | Balance[] | Per asset: mesa (free), locked (in orders and batches), rings, wallet |
orders | OwnOrder[] | Each with state: sealed, opening, filled, partially_filled, unfilled, reclaimable or reclaimed |
positions | OwnPosition[] | 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. |
shares | OwnShare[] | 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. |
history | HistoryItem[] | Every deposit, order, fill, renewal and withdrawal, with its batch and signature |
readAt | string | null | When the account was last read |
error | string | null | Why 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
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.
| Stage | Meaning |
|---|---|
signing | The action is being built, and the wallet signs if the action needs it |
proving | The proof is being generated. proof runs from 0 to 1 when the prover reports it. |
retrying | The 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". |
relaying | The transaction is on its way to the chain |
placed | The action is in batch batchNumber, sealed |
settled | The action is done |
failed | It 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:
| Message | Cause |
|---|---|
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
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.donerenewLoop 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.
| Option | Type | Default | Meaning |
|---|---|---|---|
intervalMs | number | 60000 | Time between passes |
marginSeconds | number | A third of the heartbeat | Renew a position when its deadline is within this many seconds |
positionIds | string[] | All positions | Renew only these |
onRenew | function | Called after each renewal with the position and the result | |
onError | function | Called with a position id and the error. The loop goes on. | |
signal | AbortSignal | Stops 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
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),
})| Method | Returns | Does |
|---|---|---|
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.
| Option | Type | Default | Meaning |
|---|---|---|---|
intervalMs | number | 15000 | Time between passes |
onLiquidate | function | Called with the position and its progress after each liquidation lands | |
onError | function | Called with a position id, or * for a failed pass, and the error. Healthy, early and already taken positions are skipped without it. | |
signal | AbortSignal | Stops the loop when aborted |
The whole task is in Run a liquidator.
In a browser
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.
| Member | Type | Meaning |
|---|---|---|
getAddress() | () => string | null | The connected address, or null |
signMessage(message) | (Uint8Array) => Promise<Uint8Array> | Signs bytes. unlock uses it once to derive the account. |
signTransaction(bytes) | optional | Signs a serialized transaction, for registration, Rings deposits and withdrawals, and deposits into Mesa |
subscribe(listener) | optional | Called 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.