Call Seesaw from another program (CPI)#
This guide shows how a Solana program that you own can place an order, cancel
an order, and redeem (claim) settled shares by calling Seesaw through a
cross-program invocation (CPI). The caller usually holds the position under a
program-derived address (PDA) and signs for it with invoke_signed.
A search of program/src finds no allow-list of caller programs. PlaceOrder,
CancelOrder, Redeem, and WithdrawFunds contain no stack-height or
Instructions sysvar check: the route table in program/src/abi_compaction.rs
selects the handler from the first data byte, and each handler validates its own
accounts. One route does restrict how it is called:
ReplaceMakerQuotes(0x64) must be a top-level instruction (stack height 1) and the last instruction of its transaction, and it reads the Instructions sysvar to check this (require_final_top_level_instructioninprogram/src/processor/replace_maker_quotes.rs). A search ofprogram/srcfinds no other stack-height or Instructions sysvar check. By source, a CPI into this route fails withInvalidInstructionData. No test shows that rejection, and non-SBF builds treat every call as top-level.
Verification status. The repository has no test that drives
PlaceOrder,CancelOrder,Redeem, orWithdrawFundsfrom a caller program. The account order, signer and writable flags, and data layouts below are read from the program parsers and the Rust SDK builders. How they behave behind a caller program follows from those grammars and from Solana runtime rules, and is not proven by a Seesaw test. The Rust sketch on this page is markedrust,no_runand has not been compiled or run. Test your wrapper against your own deployment (for example on a local validator) before relying on it.
For off-chain transaction building, use the Rust SDK or Building transactions. This page is for on-chain callers only.
What you need to know first#
- Pin the callee. The program ID is deployment-specific. The compact
instruction manifest records
SEEsawgSrxRsgtKRbaThZFEKrVqX3Y64hDipTWyi8F8(docs/reference/compact-instruction-manifest.json,programId); another deployment has a different ID. Compare the program account against a constant or your own config before every CPI. - Instruction data is a one-byte tag plus a fixed payload. There is no Anchor-style 8-byte discriminator.
- Most routes require a recorder tail. The route table marks 98 routes as
requiring it and 11 as not requiring it.
PlaceOrder,CancelOrder,Redeem, andWithdrawFundsall require it. The tail is the last two accounts, both read-only and non-signer: the Seesaw program itself (self_program), then the log authority PDA (["log"], no"seesaw"prefix, derived under the Seesaw program ID). Seesaw uses the pair to call itself and record events (see Instruction account lists and PDAs). A missing pair, a pair that is not last, or a pair account marked writable or signer fails withInvalidInstructionData(require_recorder_tailinprogram/src/events/recorder.rs). - What these four routes call. Their inner calls go to token programs, to the
System Program (position creation in
PlaceOrder), and to Seesaw itself (the recorder). None of them calls your program. Other routes can call other programs; maker-quote setup calls the Associated Token Account program.
Instruction reference#
Tags and payload sizes come from program/src/abi_compaction.rs. Payload sizes
exclude the tag byte. Account order comes from each processor's account parser.
See Instruction account lists for
every other route.
| Flow | Instruction | Tag | Payload | Total data | Required tail |
|---|---|---|---|---|---|
| Place | PlaceOrder | 0x0C | 84 bytes | 85 bytes | Yes |
| Cancel | CancelOrder | 0x11 | 8 bytes | 9 bytes | Yes |
| Claim | Redeem | 0x17 | 9 bytes | 10 bytes | Yes |
| Withdraw* | WithdrawFunds | 0x09 | 9 bytes | 10 bytes | Yes |
* WithdrawFunds returns quote tokens credited to your trader-ledger slot (for
example maker proceeds). Its payload is amount as a little-endian u64, then
one strategy byte, 0 when the owner signs for itself. It takes nine accounts,
plus market_meta on external markets, then the recorder tail; see
depositOrWithdrawFundsAccountMetas.
In the tables below, S is signer and W is writable, as the Rust SDK builders
send them.
PlaceOrder (0x0C)#
| # | Account | S | W | Notes |
|---|---|---|---|---|
| 0 | market | W | ||
| 1 | orderbook | W | ||
| 2 | user_position | W | Created on the first order for this market and user | |
| 3 | user_token_account | W | Settlement-token account owned by user | |
| 4 | vault | W | ||
| 5 | user | S | W | Order owner and rent payer for the position account |
| 6 | config | |||
| 7 | treasury_token_account | W | Must be an approved protocol recipient (see below) | |
| 8 | token_program | The market's settlement-token program | ||
| 9 | share_token_program | Classic SPL Token, for YES and NO shares | ||
| 10 | system_program | |||
| 11 | settlement_mint | |||
| 12 | yes_escrow | W | ||
| 13 | no_escrow | W | ||
| 14 | user_yes_ata | W | Initialized YES account owned by user | |
| 15 | user_no_ata | W | Initialized NO account owned by user | |
| 16 | yes_mint | W | ||
| 17 | no_mint | W | ||
| 18 | trader_ledger | W | ||
| 19+ | optional groups | Spline seats, Market Tick, referral, builder pair | ||
| n-2 | self_program | Recorder tail: the Seesaw program account | ||
| n-1 | log_authority | Recorder tail: PDA ["log"] under the Seesaw program |
Sources: PlaceOrderAccounts::parse in
program/src/processor/place_order.rs, the tail parser in
program/src/processor/place_order/trailing_layout.rs, and
place_order_with_splines in packages/sdk-rust/src/instructions.rs.
The optional groups sit between account 18 and the recorder tail, in this order:
- Spline seats, writable. Their number is the last data byte,
0..=8. The program reads exactly that many accounts as seats and rejects duplicates. - Market Tick, read-only, at its fixed address. It is recognized only when the seat count is nonzero.
- Referral binding, read-only.
- Builder pair: the builder approval (read-only), then the builder token
account (writable). It is rejected on a
PostOnlyorder.
The current market layout has no creator spline account and no spline feature
bit. A market reports spline liquidity through attached_seat_count > 0. The
wallet PlaceOrder parser takes its seat count from the instruction and does not
require a nonzero count on such a market. By source, an order sent with count 0
passes the tail parser and is given no spline seat to match against; no test of
that case behind a caller program exists. See
Spline market making to select seats. A
creatorSpline or creator_spline field that remains in a client builder is a
single-seat shorthand, not a separate account kind.
The 84-byte payload is the 83-byte order body (PlaceOrderArgs in
program/src/instruction.rs, PlaceOrderPayload in
packages/sdk-rust/src/compact.rs) followed by the seat count. All integers are
little-endian.
| Offset | Size | Field | Notes |
|---|---|---|---|
| 0 | 1 | outcome | 0 YES, 1 NO |
| 1 | 1 | intent | 0 Buy, 1 Sell |
| 2 | 2 | price_bps | 1..=9999 |
| 4 | 8 | quantity | nonzero |
| 12 | 1 | order_type | 0 Limit, 1 PostOnly, 2 ImmediateOrCancel |
| 13 | 2 | worst_price_bps | IOC slippage bound |
| 15 | 8 | min_fill | IOC minimum fill; 0 disables |
| 23 | 1 | match_limit | 0..=12 |
| 24 | 1 | self_trade | 0 Abort, 1 CancelProvide, 2 DecrementTake |
| 25 | 4 | max_resting_age | seconds; 0 uses the market close |
| 29 | 1 | reject_post_only | 0 or 1 |
| 30 | 1 | treasury_index | 0..8; see below |
| 31 | 16 | client_order_id | All zero means absent |
| 47 | 8 | execution_valid_until | i64, non-negative; 0 means absent |
| 55 | 8 | resting_expires_at | i64, non-negative; 0 means absent |
| 63 | 8 | max_quote_input | u64::MAX when unset in the SDK |
| 71 | 8 | min_quote_output | |
| 79 | 4 | expected_fee_epoch | 0 skips the epoch check |
| 83 | 1 | spline seat count | 0..=8; matches the supplied seat accounts |
PlaceOrderPayload::encode produces the first 83 bytes and rejects a price
outside 1..=9999, a zero quantity, an order_type above 2, a self_trade
above 2, a reject_post_only above 1, and negative deadlines. Prefer
building the payload off-chain with the SDK, or copy the layout above into your
program and add your own checks. The semantics of each field are in
PlaceOrderArgs in program/src/instruction.rs and in the
instruction reference.
CancelOrder (0x11)#
Payload: order_id as a little-endian u64 (8 bytes). The user account
signs but is read-only.
| # | Account | S | W |
|---|---|---|---|
| 0 | market | W | |
| 1 | orderbook | W | |
| 2 | user_position | W | |
| 3 | user_token_account | W | |
| 4 | vault | W | |
| 5 | user | S | |
| 6 | token_program | ||
| 7 | share_token_program | ||
| 8 | settlement_mint | ||
| 9 | yes_escrow | W | |
| 10 | no_escrow | W | |
| 11 | user_yes_ata | W | |
| 12 | user_no_ata | W | |
| 13 | yes_mint | W | |
| 14 | no_mint | W | |
| 15 | trader_ledger | W | |
| 16 | self_program | ||
| 17 | log_authority |
Sources: CancelOrderAccounts in program/src/processor/cancel_order.rs,
cancelOrderAccountMetas in
Instruction account lists,
and cancel_order in packages/sdk-rust/src/instructions.rs. Other cancel,
reduce, and reclaim routes have their own payloads and, in some cases, their own
account lists; check each one in
Instruction account lists.
Redeem (0x17)#
Payload: amount as a little-endian u64, then token_type (0 YES, 1 NO),
9 bytes in total.
| # | Account | S | W | Notes |
|---|---|---|---|---|
| 0 | market | W | ||
| 1 | yes_mint | W | ||
| 2 | no_mint | W | ||
| 3 | user_yes_ata | W | ||
| 4 | user_no_ata | W | ||
| 5 | user_stablecoin_ata | W | Settlement-token destination owned by user | |
| 6 | vault | W | ||
| 7 | user | S when amount > 0 | ||
| 8 | token_program | The market's settlement-token program | ||
| 9 | share_token_program | Classic SPL Token | ||
| 10 | settlement_mint | |||
| 11 | market_meta | External markets only; native omits it | ||
| next | user_position | W | Optional trio, all three or none | |
| next | orderbook | W | ||
| next | trader_ledger | W | ||
| n-2 | self_program | Recorder tail | ||
| n-1 | log_authority | Recorder tail |
With the recorder tail, a native market takes 13 accounts, or 16 with the trio. An external market takes 14, or 17 with the trio. On a native market the trio starts at index 11.
Sources: RedeemAccounts::parse in program/src/processor/redeem.rs,
buildRedeemIx in
Instruction account lists,
and redeem plus RedeemAccounts in packages/sdk-rust/src/instructions.rs.
amount == 0 requires the trio. An unsigned call can pay only the owner's
canonical associated settlement-token account, with no delegate. A native market
rejects market_meta, and an external market requires the canonical
MarketMeta PDA (load_redeem_market_meta in the processor).
Sign as a PDA with invoke_signed#
Your program owns a PDA and passes it as user. invoke_signed marks that PDA
as a signer for the inner call, and Seesaw sees an ordinary signed user.
Three details matter.
- The PDA is the position owner. Seesaw derives the position address from
the market and the
userkey (["seesaw", "position", market, user]), and token accounts must belong touser. Create the settlement-token account and the YES and NO associated token accounts for the PDA first. An ATA for an off-curve owner requires the allow-owner-off-curve option in your client library. - The PDA pays position rent on the first order.
PlaceOrdercreates the position account withuseras payer (create_account_cpiinprogram/src/utils/account.rs). The System Program only moves lamports out of an account that is system-owned and carries no data. Use a PDA assigned to the System Program foruser, and fund it with enough SOL for the position account rent. A PDA that your program owns and that stores data cannot pay. - Authenticate before you sign.
invoke_signedlets your program act with the PDA's authority. Require a signature from the wallet that owns this virtual account (or your own authorization) before every CPI, and derive the PDA from that wallet's key. Otherwise anyone who can call your program can trade, cancel, or redeem with the PDA's funds.
Do not let the end user choose the fee recipient or any creator field. The check
on treasury_token_account depends on the market's settlement mint
(program/src/validation/loaders.rs):
- Default settlement mint. The account must be one of the eight recipients in
the config account, otherwise Seesaw returns
TreasuryRecipientMismatch.treasury_indexis a preference: if the account matches a different slot, that slot is used. - Any other currency. The account must be that currency's protocol treasury
shard for the requested
treasury_index. There is no fallback to another slot.
An index of 8 or more returns TreasuryIndexOutOfRange. Derive the recipient
in your client from on-chain configuration and pass it through; never add a
free-form fee-recipient or creator argument to your wrapper.
Example wrapper#
This sketch uses solana-program. It receives the callee and the log authority
first, then the grammar accounts in Seesaw order, builds the inner metas from a
fixed flag table (so the end user's transaction cannot raise a privilege the
grammar does not request), and signs with the owner's PDA.
It covers only the shortest account lists. place_order fixes the spline seat
count at 0 and passes no seat, Market Tick, referral binding, or builder pair,
so it takes no spline liquidity and supplies no referral. Extend the flag table
and the account order if you need those groups. The sketch has not been compiled
or run.
use solana_program::{
account_info::AccountInfo,
entrypoint::ProgramResult,
instruction::{AccountMeta, Instruction},
program::invoke_signed,
program_error::ProgramError,
pubkey,
pubkey::Pubkey,
};
/// Program ID from the compact instruction manifest. Replace it for any other deployment.
const SEESAW_PROGRAM_ID: Pubkey = pubkey!("SEEsawgSrxRsgtKRbaThZFEKrVqX3Y64hDipTWyi8F8");
/// Your own seed. It is a PDA of this wrapper program, not of Seesaw.
const USER_SEED: &[u8] = b"seesaw-user";
const TAG_PLACE_ORDER: u8 = 0x0C;
const TAG_CANCEL_ORDER: u8 = 0x11;
const TAG_REDEEM: u8 = 0x17;
/// (is_signer, is_writable) for the grammar accounts, in Seesaw order.
const PLACE_ORDER_FLAGS: [(bool, bool); 19] = [
(false, true), // 0 market
(false, true), // 1 orderbook
(false, true), // 2 user_position
(false, true), // 3 user_token_account
(false, true), // 4 vault
(true, true), // 5 user
(false, false), // 6 config
(false, true), // 7 treasury_token_account
(false, false), // 8 token_program
(false, false), // 9 share_token_program
(false, false), // 10 system_program
(false, false), // 11 settlement_mint
(false, true), // 12 yes_escrow
(false, true), // 13 no_escrow
(false, true), // 14 user_yes_ata
(false, true), // 15 user_no_ata
(false, true), // 16 yes_mint
(false, true), // 17 no_mint
(false, true), // 18 trader_ledger
];
const CANCEL_ORDER_FLAGS: [(bool, bool); 16] = [
(false, true), // 0 market
(false, true), // 1 orderbook
(false, true), // 2 user_position
(false, true), // 3 user_token_account
(false, true), // 4 vault
(true, false), // 5 user
(false, false), // 6 token_program
(false, false), // 7 share_token_program
(false, false), // 8 settlement_mint
(false, true), // 9 yes_escrow
(false, true), // 10 no_escrow
(false, true), // 11 user_yes_ata
(false, true), // 12 user_no_ata
(false, true), // 13 yes_mint
(false, true), // 14 no_mint
(false, true), // 15 trader_ledger
];
/// Redeem accounts 0..=10. The user flag at index 7 is set per call.
fn redeem_flags(amount: u64) -> [(bool, bool); 11] {
[
(false, true), // 0 market
(false, true), // 1 yes_mint
(false, true), // 2 no_mint
(false, true), // 3 user_yes_ata
(false, true), // 4 user_no_ata
(false, true), // 5 user_stablecoin_ata
(false, true), // 6 vault
(amount > 0, false), // 7 user
(false, false), // 8 token_program
(false, false), // 9 share_token_program
(false, false), // 10 settlement_mint
]
}
/// Accounts: [seesaw_program, log_authority, ...grammar accounts in Seesaw order].
fn call_seesaw(
accounts: &[AccountInfo],
grammar_flags: &[(bool, bool)],
data: Vec<u8>,
owner: &Pubkey,
owner_bump: u8,
wrapper_program_id: &Pubkey,
user_index: usize,
) -> ProgramResult {
let [seesaw_program, log_authority, grammar @ ..] = accounts else {
return Err(ProgramError::NotEnoughAccountKeys);
};
if grammar.len() != grammar_flags.len() {
return Err(ProgramError::InvalidArgument);
}
// Pin the callee and the recorder authority.
if *seesaw_program.key != SEESAW_PROGRAM_ID || !seesaw_program.executable {
return Err(ProgramError::IncorrectProgramId);
}
let (expected_log, _) = Pubkey::find_program_address(&[b"log"], &SEESAW_PROGRAM_ID);
if *log_authority.key != expected_log {
return Err(ProgramError::InvalidSeeds);
}
// The PDA that will sign must be the `user` account.
let bump = [owner_bump];
let seeds: &[&[u8]] = &[USER_SEED, owner.as_ref(), &bump];
let user_pda = Pubkey::create_program_address(seeds, wrapper_program_id)
.map_err(|_| ProgramError::InvalidSeeds)?;
if *grammar[user_index].key != user_pda {
return Err(ProgramError::InvalidSeeds);
}
let mut metas = Vec::with_capacity(grammar.len() + 2);
let mut infos = Vec::with_capacity(grammar.len() + 2);
for (info, (signer, writable)) in grammar.iter().zip(grammar_flags) {
metas.push(if *writable {
AccountMeta::new(*info.key, *signer)
} else {
AccountMeta::new_readonly(*info.key, *signer)
});
infos.push(info.clone());
}
// Recorder tail: self_program, then log_authority. Both read-only, non-signer.
metas.push(AccountMeta::new_readonly(*seesaw_program.key, false));
metas.push(AccountMeta::new_readonly(*log_authority.key, false));
infos.push(seesaw_program.clone());
infos.push(log_authority.clone());
let instruction = Instruction {
program_id: SEESAW_PROGRAM_ID,
accounts: metas,
data,
};
invoke_signed(&instruction, &infos, &[seeds])
}
/// `owner` must have signed the wrapper transaction.
pub fn place_order(
wrapper_program_id: &Pubkey,
accounts: &[AccountInfo],
owner: &AccountInfo,
owner_bump: u8,
order_body: &[u8; 83],
) -> ProgramResult {
if !owner.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
let mut data = Vec::with_capacity(85);
data.push(TAG_PLACE_ORDER);
data.extend_from_slice(order_body);
data.push(0); // spline seat count: this sketch passes no seat accounts
call_seesaw(
accounts,
&PLACE_ORDER_FLAGS,
data,
owner.key,
owner_bump,
wrapper_program_id,
5,
)
}
pub fn cancel_order(
wrapper_program_id: &Pubkey,
accounts: &[AccountInfo],
owner: &AccountInfo,
owner_bump: u8,
order_id: u64,
) -> ProgramResult {
if !owner.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
let mut data = Vec::with_capacity(9);
data.push(TAG_CANCEL_ORDER);
data.extend_from_slice(&order_id.to_le_bytes());
call_seesaw(
accounts,
&CANCEL_ORDER_FLAGS,
data,
owner.key,
owner_bump,
wrapper_program_id,
5,
)
}
/// Native market, no position trio. For `amount == 0` or external markets,
/// extend the flag table with the optional accounts described above.
pub fn redeem(
wrapper_program_id: &Pubkey,
accounts: &[AccountInfo],
owner: &AccountInfo,
owner_bump: u8,
amount: u64,
token_type: u8, // 0 = YES, 1 = NO
) -> ProgramResult {
if !owner.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
if amount == 0 || token_type > 1 {
return Err(ProgramError::InvalidArgument);
}
let mut data = Vec::with_capacity(10);
data.push(TAG_REDEEM);
data.extend_from_slice(&amount.to_le_bytes());
data.push(token_type);
call_seesaw(
accounts,
&redeem_flags(amount),
data,
owner.key,
owner_bump,
wrapper_program_id,
7,
)
}
The matching client builds your wrapper's instruction with the same account
order. To obtain Seesaw's ordered account list and data, build the Seesaw
instruction with the Rust SDK and read instruction.accounts and
instruction.data; packages/sdk-rust/examples/build_place_order.rs shows that
call. For a PlaceOrder with no seats, order_body is data[1..84] and
data[84] is 0. Replace the user entry with your PDA, put the Seesaw program
and the log authority in front, and drop the SDK's trailing recorder pair (your
wrapper re-adds it). Whether seesaw-sdk can be linked into an on-chain build is
not verified here; copy the constants you need instead.
Pitfalls#
| Symptom or mistake | Cause and fix |
|---|---|
InvalidInstructionData on every call | Wrong data length (a PlaceOrder is 85 bytes), or a recorder pair that is missing, not last, writable, or signer. The program comes before the log authority. |
MissingSplineAccounts | The seat count does not match the seat accounts, a seat is invalid, or, with a nonzero count, a later optional account is malformed. |
| Right accounts, wrong behavior | An optional group (seats, Market Tick, referral, builder pair, market_meta, redeem trio) was added or omitted. Later indices shift; rebuild from the SDK. |
| Missing-signer failure | invoke_signed seeds do not derive the PDA you passed as user, or the PDA is not in the AccountInfo slice you gave to the CPI. |
| System Program error on the first order | user holds data or is owned by your program, so it cannot fund the new position account. Use a data-free, system-owned PDA with enough lamports. |
| Runtime privilege error | The outer transaction did not mark an account writable (or signer) that the inner call needs. The inner call can never exceed the outer privileges. |
TreasuryRecipientMismatch | treasury_token_account is not the approved recipient for this currency. Derive it from on-chain configuration; do not accept it from the end user. |
| A cancel or redeem signs when it should not | The wrapper did not check the owner's signature before invoke_signed. Authenticate first. |
| Wrong program called | The wrapper trusted a caller-supplied program ID. Compare against a pinned constant, and check executable. |
| Heap or compute budget exhausted | The program defines a 64 KiB heap frame (PLACE_ORDER_HEAP_FRAME_BYTES) for worst-case PlaceOrder flows. Request it and compute headroom on the outer transaction. Neither is measured behind a caller program. |
Seesaw errors reach your program as ProgramError::Custom(code). The code
table is in the errors array of
compact-instruction-manifest.json.
For example InvalidState is 0x1002.
Keep the account lists current#
The instruction set changes with the program. Do not copy account lists into your program from memory.
- The tag, payload length, and recorder-tail requirement of every route come
from
program/src/abi_compaction.rs, mirrored indocs/reference/compact-instruction-manifest.json. Check your tags, payload sizes, and tail flags against it. - The ordered account grammar is generated from the TypeScript builders into
Instruction account lists. After a
builder change,
node scripts/generate_docs_instruction_accounts.mjs --checkfails until the page is regenerated with the same command without--check. The Rust builders inpackages/sdk-rust/src/instructions.rscarry the same orders and are covered by the cross-language vectors inpackages/test-vectors. idl/seesaw.jsonholds an executable model of every route, with each accepted account list, andbun run --cwd idl validatefails when a model disagrees with the shared vectors or with the processors. The page in item 2 is still generated from the TypeScript builders, so regenerating the IDL does not refresh it. See ABI maintenance for the release gates (make idl-check,bun --filter @seesaw/client-gen generate:check,bun run --cwd idl validate).- A redeployment can change the program ID and the deployment-specific addresses. Re-pin them in your wrapper and re-run your wrapper tests against the new deployment.
Not covered#
- Whether the Seesaw indexer attributes an order sent through a wrapper program to the PDA owner is not verified in this guide. The recorder events are emitted by Seesaw regardless of the caller.
- Mirror, spline, maker-quote, and administrative routes. Each has its own account contract, and some do not require the recorder tail, so do not reuse the flows above for them. Use Instruction account lists.
- CPI depth when your wrapper is itself called by another program. A
PlaceOrder,CancelOrder,Redeem, orWithdrawFundscall makes one further level of calls (token program, System Program, or the recorder). Solana limits the total depth, so count the levels in your own call chain. No repository test exercises this.