09Solana program engineering
  1. 01Introduction
  2. 02System overview
  3. 03Cryptographic foundations
  4. 04The confidential Ledger
  5. 05Trusted execution and attestation
  6. 06Threshold keys and the Escape
  7. 07The Crossing engine
  8. 08Unlinkability
  9. 09Solana program engineering
  10. 10The Coprocessor and the off-chain stack
  11. 11Selective disclosure and Receipts
  12. 12Economics and $PRV

Chapter 9

Solana program engineering

The Pool is one Anchor program that custodies every deposited token, accepts each Commit, routes each Residual through Jupiter and pays every Exit and Escape. This chapter specifies it at audit depth: account layouts and seeds, each instruction with the accounts it locks and the checks it runs, the compute and byte budgets that set how much one Commit carries, and the write-lock design that keeps deposits, Intents and Commits parallel under Sealevel. The Ledger semantics are in Chapter 4, enclave registration in Chapter 5, the Escape protocol in Chapter 6 and the clearing math in Chapter 7. Solana constants are cited to current Solana and Agave sources; figures derived for Privium are marked “est.”.

Program architecture

One program owns four state families: the Pool (PoolConfig, one AssetState per mint, vault and deposit queue shards), the Ledger (LedgerRoot, one CrossingState per open Crossing), the Registry of admitted measurements and live enclave keys with their validity intervals (Chapter 5), and the CouncilConfig holding the Council key PCP_{\mathcal{C}}, the nn member verification keys SjS_j and the threshold tt (Chapter 6). Splitting them across programs would put a CPI on the Commit path for every cross-family read, and a CPI costs 1,000 CU plus 1 CU per 250 serialized bytes [1] and spends a level of a limited call depth (see the Jupiter section).

Every vault is a token account owned by the Pool authority, a program derived address with no private key. The only code that can sign for it is invoke_signed inside this program, and every such path is gated by an enclave signature, a Council threshold signature or a Merkle proof against a committed root.

Accounts, PDAs and seeds

Fixed-layout state uses Anchor zero-copy accounts (#[account(zero_copy)], repr(C)), so handlers read fields in place instead of decoding whole accounts. Sizes include the 8-byte discriminator.

Account Seeds Bytes Count
PoolConfig ["pool"] 160 1
Pool authority ["authority"] signer only 1
LedgerRoot ["ledger"] 2,696 1
Registry ["registry"] 656 1
CouncilConfig ["council"] 560 1
AssetState ["asset", mint] 200 per admitted mint
Vault shard 0 associated token account of the authority 165 Token, 170+ Token-2022 [16] per mint
Vault shard j≥1j \ge 1 ["vault", mint, j] as above S−1S-1 per mint
DepositQueue ["deposits", mint, j] 61,504 SS per mint
CrossingState ["crossing", k] 736 per open Crossing
ExitRecord / EscapeRecord ["exit", k, index] / ["escaped", leaf, mint] 9 per payout
EscapeState ["escape"] 913 1, created by trigger_escape
EscapeRequest ["escape-req", leaf, mint] 216 per Escape request

The shard count is S=2S = 2 (parameter): two shards double each asset’s write-lock headroom (Equation 9.4) while a Commit stays at five accounts per asset (Equation 9.3). Shard 0 is the authority’s associated token account, so Jupiter’s router can use it as swap source and destination directly.

#[account(zero_copy)]
#[repr(C)]
pub struct LedgerRoot {
    pub k: u64,                  // last committed Crossing
    pub last_commit_slot: u64,
    pub escape_from_slot: u64,   // 0 while commits are live
    pub root: [u8; 32],          // ρ^(k)
    pub da_commitment: [u8; 32], // hash of the Crossing's ciphertext diff
    pub mids_hash: [u8; 32],
    pub exit_ring_head: u32,
    pub registry_epoch: u32,
    pub exit_roots: [ExitRoot; 64], // { k: u64, root: [u8; 32] }
}

#[account(zero_copy)]
#[repr(C)]
pub struct AssetState {
    pub mint: Pubkey,
    pub token_program: Pubkey,
    pub oracle_feed: [u8; 32],   // Pyth feed id; zero when the pair always routes
    pub ledger_total: u64,       // T_a, attested at the last Commit
    pub pending_exits: u64,      // X_a, committed, not yet released
    pub gamma: [u8; 32],         // Gamma_a, sum of asset-a leaf commitments (Equation 4.7)
    pub consumed: [u64; 4],      // deposits credited per shard
    pub decimals: u8,
    pub bump: u8,
    pub flags: u8,               // admitted Token-2022 extensions
    pub _pad: [u8; 5],
}

PoolConfig holds the bumps, SS, the batch interval Δ\Delta (Chapter 7), the liveness window WW (Chapter 6), the Crossing lease (Chapter 10), the fee rate ϕ\phi and the fee recipient, the token’s launch wallet, whose associated token account in each asset receives every Commit’s fees (Chapter 12). Only the admin key the configuration names changes the rate or the recipient. LedgerRoot keeps the last 64 exits roots (parameter), so an Exit proves inclusion against the Crossing that created it without one account per Crossing; an Exit whose root leaves the ring unreleased is placed again in a later exits root, which the enclave knows from the on-chain ExitRecord accounts.

A DepositQueue is a ring of 512 entries (parameter, several Crossings of deposits at the Equation 9.4 ceiling) of 120 bytes each: amount, cumulative amount, slot, the source token account (where an Escape refunds it), the hash of the deposit’s encrypted note, and the running chain hash, for 8+56+512⋅120=61,5048 + 56 + 512 \cdot 120 = 61{,}504 bytes. An account may grow by at most 10,240 bytes inside one CPI (MAX_PERMITTED_DATA_INCREASE [1]), so Anchor’s init, which allocates through a CPI to the System program, cannot create it. The queue is allocated by a top-level CreateAccount in the same transaction, within the 10 MiB account ceiling [1], and initialized under Anchor’s zero constraint.

Rent for dd data bytes is (128+d)ϖ(128 + d)\varpi lamports, with ϖ\varpi moving from 6,960 to 696 lamports per byte in the five steps of SIMD-0437 [13]. At ϖ=6,960\varpi = 6{,}960 a queue holds 61,632⋅6,960=428,958,72061{,}632 \cdot 6{,}960 = 428{,}958{,}720 lamports (est.), a tenth of that at the final step, all refundable on close.

Instructions

Accounts are W (writable) or R (read-only).

Instruction Authorized by Accounts Checks
admit_asset governance W AssetState, vault shards; R mint Extension set admitted (Token-2022 section)
register_enclave attestation W Registry Quote and report-data binding (Chapter 5)
rotate_council Council tt-of-nn W CouncilConfig Threshold signatures on the new set (Chapter 6)
deposit trader W vault jj, queue jj, source; R AssetState, LedgerRoot No Escape; queue not full; credit = vault delta
post_intent any fee payer W fee payer only Blob length
open_crossing enclave W CrossingState; R LedgerRoot, Registry, per mid an AssetState and its Pyth price account k=LedgerRoot.k+1k = \texttt{LedgerRoot.k} + 1, at least Δ\Delta slots after last_commit_slot; sponsored price accounts; validity recorded
route_residual enclave W CrossingState, vault 0 of two mints, route accounts; R AssetState ×2 Route hash; deadline; spent ≤ signed input; Crossing’s total spent of the input ≤ its TaT_a; received ≥ signed minimum
log_diff relayer named at open_crossing W CrossingState Next chunk index; accumulator (4.10) not sealed
commit enclave W LedgerRoot, AssetState ×AA, CrossingState, vault 0 ×AA, fee recipient account ×AA; R other shards Order, prior root, opener, mids, fills, deposits, data availability; pays ΔFa\Delta F_a to the fee recipient; conservation (Equations 9.2 and 4.7)
release_exit anyone W AssetState, vault, recipient, ExitRecord; R LedgerRoot Inclusion in a ring root; first release
set_fee_rate, set_fee_recipient admin W PoolConfig Admin signature; rate at most 10,000 bps
trigger_escape anyone W LedgerRoot, EscapeState; R CrossingState Slot >last_commit_slot+W> \texttt{last\_commit\_slot} + W; records the open Crossing’s fills
refund_deposit anyone W queue jj, vault jj, source Escape active; entry past the stored cut; first refund
escape_request owner W EscapeRequest; R LedgerRoot Leaf in frozen root; owner tag opens to (Yu,ςu)(Y_u, \varsigma_u)
escape_share Council member W EscapeRequest; R CouncilConfig Share proof (6.7) against SjS_j; combine at tt
escape_claim owner W EscapeRequest, vaults, recipients, EscapeRecord; R AssetState, EscapeState Claim proof under YuY_u; first claim; settlement rule (6.10)

post_intent is the on-chain Intent path and it writes nothing but the fee payer. The Intent’s HPKE ciphertext travels as instruction data, the program checks its length, and the indexer reads it from the transaction. Transactions with different fee payers share no writable account, so Sealevel runs them all in parallel.

open_crossing is the Crossing’s lease and price anchor. It records the opening enclave key (only that key may route and commit kk until the lease passes; Chapter 10) and takes one AssetState and one Pyth price account per mid. The price account must be the one Pyth sponsors and keeps current for the asset’s feed [23]: the program derives the push oracle’s address from the seeds (shard 0 as a little-endian u16, oracle_feed) [28] and requires that exact account, owned by the Pyth receiver and holding a PriceUpdateV2 at verification level Full whose feed id equals oracle_feed [29], so a relayer can substitute neither another account nor another feed (Price). It then sets each price’s validity against its own Clock: positive, published no more than max_price_age seconds before it and no more than 1 second after, and with a confidence within κ\kappa of the price, the check of Equation 7.3 per feed. A price that fails is recorded as invalid rather than failing the open. The program stores price, confidence, exponent, publish time and validity per feed and their hash hmh_m, so the mids mπ(k)m^{(k)}_\pi the enclave crosses at are the ones the chain verified, and route_residual refuses a swap in a mint whose recorded mid is invalid.

Deposit

pub fn deposit(ctx: Context<Deposit>, shard: u8, amount: u64, note: Vec<u8>) -> Result<()> {
    require!(note.len() <= MAX_NOTE, PriviumError::NoteTooLong);
    require!(ctx.accounts.ledger.load()?.escape_from_slot == 0, PriviumError::EscapeActive);
    let asset = ctx.accounts.asset.load()?;
    let mut q = ctx.accounts.queue.load_mut()?;
    require!(q.head - asset.consumed[shard as usize] < QUEUE_CAP, PriviumError::QueueFull);

    let before = ctx.accounts.vault.amount;
    token_interface::transfer_checked(ctx.accounts.transfer_ctx(), amount, asset.decimals)?;
    ctx.accounts.vault.reload()?;
    let credited = ctx.accounts.vault.amount.checked_sub(before).ok_or(PriviumError::Math)?;

    let slot = Clock::get()?.slot;
    let note_hash = hashv(&[b"privium/note/v1", &note]).to_bytes();
    q.cum_amount = q.cum_amount.checked_add(credited).ok_or(PriviumError::Math)?;
    q.chain_hash = hashv(&[&q.chain_hash, &credited.to_le_bytes(), &slot.to_le_bytes(), &note_hash])
        .to_bytes();
    let i = (q.head % QUEUE_CAP) as usize;
    q.entries[i] = DepositEntry {
        amount: credited, cum_amount: q.cum_amount, slot,
        source: ctx.accounts.source.key(), note_hash, chain_hash: q.chain_hash,
    };
    q.head += 1;
    Ok(())
}

The credit is the measured vault delta, never the argument: under a transfer fee the vault receives less than was sent [17]. The note, which tells the Coprocessor which Ledger account to credit (Chapter 4), stays in transaction data and enters the chain hash through its digest.

Commit

The Commit has no payload of its own. Its message MkM_k of Equation 4.6 sits once, inside the Ed25519 precompile instruction before it, in this byte layout:

Mk=privium/commit/v1 ∥ program id ∥ e ∥ k ∥ ρ(k−1) ∥ ρ(k) ∥ δ(k) ∥ E(k) ∥ nE ∥ hm ∥ hF ∥ hD ∥ (minta,Ta,ΔXa,ΔFa,ca,0,ca,1,ΔΓa,Ra)a∈Ak(9.1)M_k = \texttt{privium/commit/v1} \,\|\, \text{program id} \,\|\, e \,\|\, k \,\|\, \rho^{(k-1)} \,\|\, \rho^{(k)} \,\|\, \delta^{(k)} \,\|\, E^{(k)} \,\|\, n_E \,\|\, h_m \,\|\, h_F \,\|\, h_D \,\|\, \big(\text{mint}_a, T_a, \Delta X_a, \Delta F_a, c_{a,0}, c_{a,1}, \Delta\Gamma_a, R_a\big)_{a \in \mathcal{A}_k} \tag{9.1}

with ee the signing key’s epoch, δ(k)\delta^{(k)} the data availability accumulator (4.10) over the Crossing’s ciphertext diff, E(k)E^{(k)} and nEn_E the exits root and count, hmh_m and hFh_F the hashes of the mids and Residual fills in CrossingState, hDh_D the digest of the deposit chain hashes at the consumed positions, Ak\mathcal{A}_k the touched assets, Ta=∑ubu,a(k)T_a = \sum_u b^{(k)}_{u,a} the attested Ledger total, ΔXa\Delta X_a the exits the Crossing adds, ΔFa\Delta F_a the fees it pays, ca,jc_{a,j} the deposits consumed from shard jj, and (ΔΓa,Ra)(\Delta\Gamma_a, R_a) the commitment delta and aggregate opening of Equation 4.5. After applying the deltas, the program checks for each a∈Aka \in \mathcal{A}_k:

Ta+Xa+∑j<S(Σa,jhead−Σa,j(c))=∑j<SVa,j=Va(k)(9.2)T_a + X_a + \sum_{j<S}\left(\Sigma^{\text{head}}_{a,j} - \Sigma^{(c)}_{a,j}\right) = \sum_{j<S} V_{a,j} = V^{(k)}_a \tag{9.2}

evaluated after the Commit has paid ΔFa\Delta F_a from vault shard 0 to the fee recipient’s token account, where Σa,jhead\Sigma^{\text{head}}_{a,j} is shard jj‘s cumulative deposited amount, Σa,j(c)\Sigma^{(c)}_{a,j} the cumulative amount at the consumed entry, and Va,jV_{a,j} the shard balance. This is the on-chain form of the conservation theorem of Chapter 4, exact in base units: at every committed root, every vault token is a committed balance, a committed Exit awaiting release or a deposit not yet credited; no fee stays in a vault past the Commit that charges it. Between Commits the open Crossing’s recorded fills also move the vaults; its Commit absorbs them into TaT_a, so none is outstanding at a committed root, and if commits stop with fills recorded the Escape settles them (Chapter 6). Releases landing between the enclave’s snapshot and the Commit keep (9.2) exact, because the enclave signs deltas and release_exit decrements XaX_a together with the vault; late deposits enter both sides through Σhead\Sigma^{\text{head}}. The commitment half of the check, Equation 4.7, runs in the same pass.

pub fn commit<'info>(ctx: Context<'_, '_, 'info, 'info, Commit<'info>>, k: u64) -> Result<()> {
    let slot = Clock::get()?.slot;
    let msg = enclave_message(&ctx.accounts.instructions, &ctx.accounts.registry.load()?, slot)?;
    let c = CommitMsg::parse(&msg)?;
    let mut ledger = ctx.accounts.ledger.load_mut()?;
    require!(ledger.escape_from_slot == 0, PriviumError::EscapeActive);
    require!(c.program_id == crate::ID && c.k == k && k == ledger.k + 1, PriviumError::OutOfOrder);
    require!(c.prev_root == ledger.root, PriviumError::StaleRoot);

    let mut crossing = ctx.accounts.crossing.load_mut()?;
    require!(crossing.k == k && c.signer == crossing.opener, PriviumError::NotOpener);
    require!(c.mids_hash == crossing.mids_hash, PriviumError::MidsMismatch);
    require!(c.fills_hash == crossing.fills_hash(), PriviumError::FillsMismatch);
    require!(c.da == crossing.da_digest && !crossing.da_sealed, PriviumError::DaMismatch);
    crossing.da_sealed = true;

    let pool = ctx.accounts.pool.load()?;
    let per_asset = 4 + 2 * SHARDS; // state, mint, vaults, queues, fee recipient, token program
    require!(ctx.remaining_accounts.len() == per_asset * c.assets.len(), PriviumError::Accounts);
    let mut chain = Vec::with_capacity(SHARDS * c.assets.len());
    let mut acc = ConserveAcc::new(&hash(&msg));
    for (a, group) in c.assets.iter().zip(ctx.remaining_accounts.chunks_exact(per_asset)) {
        conserve(a, group, &pool, &ctx.accounts.authority, &mut chain, &mut acc)?; // Chapter 4
    }
    acc.finish()?;                                           // Equation 4.7, one MSM
    let slices: Vec<&[u8]> = chain.iter().map(|h: &[u8; 32]| h.as_slice()).collect();
    require!(hashv(&slices).to_bytes() == c.deposits_digest, PriviumError::DepositsMismatch);

    ledger.k = k;
    ledger.root = c.root;
    ledger.da_commitment = c.da;
    ledger.mids_hash = c.mids_hash;
    ledger.last_commit_slot = slot;
    let h = ledger.exit_ring_head as usize % 64;
    ledger.exit_roots[h] = ExitRoot { k, root: c.exits_root };
    ledger.exit_ring_head = ledger.exit_ring_head.wrapping_add(1);
    Ok(())
}

conserve, listed in Chapter 4, matches the AssetState mint to the message, pays ΔFa\Delta F_a from vault shard 0 to the fee recipient’s associated token account under the Pool authority’s seeds, checks each vault shard is a token account of that mint owned by the authority, reads each queue entry at index ca,j−1c_{a,j} - 1 for its chain hash and Σa,j(c)\Sigma^{(c)}_{a,j}, applies the deltas, evaluates Equation 9.2 and stages the asset’s terms of Equation 4.7. It derives one address per asset, the fee recipient’s associated token account from the recipient, the token program and the mint, and none of the Pool’s own: each Pool account was created by this program at its canonical address, and the owner check, discriminator and stored mint and shard fields identify it uniquely. At 1,500 CU per create_program_address [1], skipping five derivations per asset saves 45,000 CU (est.) on a six-asset Commit.

The set Ak\mathcal{A}_k may be empty. A heartbeat Commit (Chapter 10) carries no asset entry and takes no remaining account: the program checks its order, prior root, opener, mids, fills and data availability as for any Commit, Equation 4.7 is the empty sum, and hDh_D covers no cut. It advances the index, re-anchors the root and stores its slot, from which the liveness window of Chapter 6 runs again.

The digest hDh_D binds the deposits the enclave credited to the chain the program wrote. The enclave reads deposits through an untrusted RPC host (Chapter 10); a fabricated deposit yields a chain hash that matches no on-chain entry, and the Commit fails.

Exit and Escape

An Exit leaf is H(0x02 ∥ k ∥ index ∥ mint ∥ recipient ∥ amount ∥ release slot)\mathsf{H}(\texttt{0x02} \,\|\, k \,\|\, \text{index} \,\|\, \text{mint} \,\|\, \text{recipient} \,\|\, \text{amount} \,\|\, \text{release slot}) under the root E(k)E^{(k)}, so the delay the enclave samples for each piece (Chapter 8) is enforced on chain. release_exit is permissionless: it verifies the path against the ring entry for kk, requires the current slot to be at or past the release slot, creates the ExitRecord (whose existence blocks a second release), decrements XaX_a and pays the recipient, which is any address the trader named, a Helius Ring included (Chapter 8).

trigger_escape sets escape_from_slot once WW slots pass without a Commit and writes EscapeState: the frozen index k⋆k^\star and, when Crossing k⋆+1k^\star + 1 is open, the fills its CrossingState recorded, leg by leg (input mint, output mint, spent, got). Commits, opens, routes and deposits then fail. refund_deposit returns each queue entry past the stored cut to the source the entry records, and release_exit keeps paying committed Exits. An owner opens an EscapeRequest with the leaf, its Merkle path to the frozen root and the opening (Yu,ςu)(Y_u, \varsigma_u) of its owner tag, which the program checks against the leaf’s version. Council members post re-encryption shares with escape_share, each verified against the member’s key SjS_j in CouncilConfig, and the tt-th valid share stores the combined pair. escape_claim verifies the owner’s proof for the amount, creates the EscapeRecord for (leaf, mint), whose existence blocks a second claim, and pays by the settlement rule (6.10): in full in the leaf’s asset when the open Crossing spent none of it, otherwise partly in the output assets of the legs that did. Chapter 6 gives the protocol and its safety theorem.

Signature verification by instruction introspection

Precompiles run as native code outside the sBPF VM and cannot be invoked by CPI [3]. A program learns that a signature was checked by reading the transaction’s top-level instructions through the Instructions sysvar, which exposes top-level instructions only [4]. The Ed25519 program (Ed25519SigVerify111111111111111111111111111) takes a signature count and, per signature, seven u16 offsets and instruction indices for signature, key and message, where u16::MAX means the precompile instruction itself; the transaction fails if any signature is invalid [3].

The flexibility is the classic hole: a precompile may verify a signature over bytes from some other instruction, so a program that checks only that an Ed25519 instruction names the right key can be fed a valid signature over an unrelated message. The Pool accepts exactly one shape:

pub fn enclave_message(ix_sysvar: &AccountInfo, reg: &Registry, slot: u64) -> Result<Vec<u8>> {
    let here = load_current_index_checked(ix_sysvar)? as usize;
    require!(here > 0, PriviumError::MissingSig);
    let ix = load_instruction_at_checked(here - 1, ix_sysvar)?;
    require!(ix.program_id == ed25519_program::ID, PriviumError::MissingSig);
    let d = &ix.data;
    require!(d.len() >= 112 && d[0] == 1, PriviumError::BadSigLayout); // one signature

    let f = |o: usize| u16::from_le_bytes([d[2 + o], d[3 + o]]) as usize;
    let this = u16::MAX as usize;
    require!(f(2) == this && f(6) == this && f(12) == this, PriviumError::BadSigLayout);
    require!(f(0) == 16 && f(4) == 80 && f(8) == 112, PriviumError::BadSigLayout);
    require!(112 + f(10) == d.len(), PriviumError::BadSigLayout);

    let pk: [u8; 32] = d[80..112].try_into().unwrap();
    let key = reg.find(&pk).ok_or(PriviumError::UnknownEnclave)?;
    require!(key.valid_from <= slot && slot < key.valid_until, PriviumError::KeyExpired);
    Ok(d[112..].to_vec())
}

Fixed offsets (2-byte header, 14-byte offsets record, signature, key, message to the end) mean the program parses one known layout instead of attacker-chosen offsets, and pinning the precompile to index here−1here - 1 gives each signed instruction its own. The domain tag and program id in Equation 9.1 stop a signature made for route_residual, open_crossing or another deployment from passing as a Commit. The same function with a tt-signature layout and CouncilConfig keys serves rotate_council; Escape shares and claims are sigma proofs that the program checks with the curve25519 syscalls instead.

Ed25519 carries the per-Commit signature because it is the cheapest precompile in the cost model: 2,280 CU per verification against 4,800 for secp256r1 and 6,690 for secp256k1 [10]. The secp256r1 program, which checks up to eight P-256 signatures per instruction with low-S enforced [3], is used at enclave registration for the attestation chain (Chapter 5).

The Residual route through Jupiter

The Coprocessor gets each Residual’s route from Jupiter’s Router path, GET /swap/v2/build, which returns raw Metis-routed instructions with no Jupiter swap fee, for integrators that compose or wrap the swap [21]. The program invokes the Jupiter aggregator (JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4) with the route’s accounts as remaining accounts, the pattern of Jupiter’s CPI example [22], and adds three guards.

pub fn route_residual<'info>(
    ctx: Context<'_, '_, 'info, 'info, RouteResidual<'info>>, data: Vec<u8>,
) -> Result<()> {
    let slot = Clock::get()?.slot;
    let msg = enclave_message(&ctx.accounts.instructions, &ctx.accounts.registry.load()?, slot)?;
    let r = RouteMsg::parse(&msg)?;
    let mut crossing = ctx.accounts.crossing.load_mut()?;
    require!(r.k == crossing.k && r.signer == crossing.opener, PriviumError::OutOfOrder);
    require!(slot <= r.deadline_slot, PriviumError::ResidualExpired);

    let authority = ctx.accounts.authority.key();
    let mut metas = Vec::with_capacity(ctx.remaining_accounts.len());
    let mut keys: Vec<&[u8]> = vec![JUPITER_ID.as_ref(), &data];
    for a in ctx.remaining_accounts {
        let is_signer = *a.key == authority;
        metas.push(AccountMeta { pubkey: *a.key, is_signer, is_writable: a.is_writable });
        keys.push(a.key.as_ref());
    }
    require!(hashv(&keys).to_bytes() == r.route_hash, PriviumError::RouteMismatch);

    let (in0, out0) = (ctx.accounts.vault_in.amount, ctx.accounts.vault_out.amount);
    let seeds: &[&[u8]] = &[b"authority", &[ctx.accounts.pool.load()?.authority_bump]];
    let ix = Instruction { program_id: JUPITER_ID, accounts: metas, data };
    invoke_signed(&ix, ctx.remaining_accounts, &[seeds])?;

    ctx.accounts.vault_in.reload()?;
    ctx.accounts.vault_out.reload()?;
    let spent = in0.checked_sub(ctx.accounts.vault_in.amount).ok_or(PriviumError::Math)?;
    let got = ctx.accounts.vault_out.amount.checked_sub(out0).ok_or(PriviumError::Math)?;
    require!(spent <= r.in_amount && got >= r.min_out, PriviumError::Slippage);
    require!(crossing.spent_of(&r.in_mint) + spent <= ctx.accounts.asset_in.load()?.ledger_total,
        PriviumError::RouteCap);                             // routes spend only committed balances
    crossing.record_fill(r.pair, spent, got)
}

The route is bound to the enclave: it signs H(Jupiter id ∥ data ∥ keys)\mathsf{H}(\text{Jupiter id} \,\|\, \text{data} \,\|\, \text{keys}) with (k,π,xin,ymin⁡)(k, \pi, x_{\text{in}}, y_{\min}) and the program recomputes the hash over what it invokes, so the relayer cannot substitute a route and the authority’s signature reaches only accounts the enclave approved; the message is the ResidualOrder of Chapter 7 under the domain tag privium/route/v1. The outcome is measured: input spent must be at most xinx_{\text{in}} and output received at least ymin⁡y_{\min}, the bound Chapter 7 derives from the oracle mid. The fill is recorded in CrossingState, the enclave settles on recorded fills, and hFh_F in the Commit binds them, so the Ledger credits exactly what the market delivered. The routes of one Crossing never spend more of an asset than its committed total TaT_a, so committed Exits and uncredited deposits stay in the vault whatever the route does, which the Escape’s solvency relies on (Chapter 6).

The authority enters the outer transaction as a non-signer; the program marks it signer in the CPI metadata and invoke_signed supplies its seeds. The /build request names the authority as taker, the relayer as payer so the PDA needs no SOL, output shard 0 as destinationTokenAccount, and wrapAndUnwrapSol=false, since vaults hold wrapped SOL as an ordinary mint [21].

The CPI runs the route one level deeper than a wallet swap. The maximum instruction stack depth is 5, height 1 being the top-level instruction [1][5]. Inside route_residual, Jupiter runs at height 2, each AMM at 3 and the Token program at 4, leaving one level for an AMM that makes a further CPI. SIMD-0268 raises the limit to 9 and is in development for Agave 4.4 [6]. A transaction also has 64 instructions in total, CPIs included (MAX_INSTRUCTION_TRACE_LENGTH [1]). The Coprocessor simulates each route before signing and rebuilds without the offending DEX when either limit is hit (Chapter 10).

Token and Token-2022 handling

Each vault uses the mint’s own token program, recorded in AssetState.token_program, and every transfer goes through token_interface::transfer_checked, which serves both programs and is the form Token-2022 extensions require. On the Token program, p-token (SIMD-0266, live on mainnet) runs TransferChecked in 105 CU, down from 6,200 [15]. admit_asset admits a mint when each of its extensions has a treatment:

Extension Treatment
TransferFeeConfig Credit measured vault deltas on deposit and route [17]
TransferHook Hook program on the admitted list; senders append the extra accounts every transfer of the mint requires [18]
ConfidentialTransfer Vaults hold the public balance; private entry and exit happen in the Ring or confidential account around the Pool [19]
InterestBearingConfig, ScaledUiAmount Raw base units; scaling is display only
PermanentDelegate, NonTransferable Not admitted: Equation 9.2 needs vault balances that move only through Pool instructions

Confidential Balances run on the ZK ElGamal proof program, restored on mainnet in June 2026 [20]. The Pool verifies no ZK ElGamal proof itself: Ledger confidentiality rests on the enclave and the Council (Chapters 4 to 6), and vaults move only public amounts.

Compute budget

A transaction may request up to 1,400,000 CU; one that requests nothing gets 200,000 CU per non-builtin instruction [1]. The estimates below use published unit costs: 1,500 CU per create_program_address, 1,000 CU per CPI plus 1 CU per 250 bytes, sol_sha256 at 85 CU plus, per slice, the larger of 10 CU and half the slice length, and for ristretto255 169 CU per point validation, 521 per addition and a multiscalar multiplication at 2,303 CU plus 788 per point beyond the first [1][11][12]. A Merkle node H(tag ∥ L ∥ R)\mathsf{H}(\text{tag} \,\|\, L \,\|\, R) therefore costs 85+10+16+16=12785 + 10 + 16 + 16 = 127 CU. Anchor dispatch and account validation get an allowance of 5,000 CU per instruction (est.), replaced by simulated figures before every send (Chapter 10).

Instruction Components CU (est.)
deposit allowance; 3 PDA checks 4,500; transfer CPI ≈ 1,110; hashes ≈ 320; writes ≈ 500 12,000
post_intent allowance 5,000
commit, A=2A = 2 measured on the built program, both fee transfers and the fee recipient’s address derivations included 73,214 to 78,518, measured
route_residual allowance; introspection ≈ 1,500; route hash ≈ 1,000; CPI ≈ 2,000; reloads ≈ 500 10,000 + route
release_exit, depth 12 allowance; path 12⋅12712 \cdot 127; record creation 2,500; transfer ≈ 1,110 10,200
escape_share allowance; (6.7) as one 11-point MSM 2,303+10⋅7882{,}303 + 10 \cdot 788; 6 point validations; challenge ≈ 300; at the tt-th share, (6.8) as two 5-point MSMs 10,910 16,500, or 27,400 at tt
escape_claim allowance; claim proof as one 6-point MSM 2,303+5⋅7882{,}303 + 5 \cdot 788; point work ≈ 1,500; record creation 2,500; transfer ≈ 1,110 per paid mint 16,400

The cost model adds 2,280 CU per Ed25519 verification [10], so a two-asset Commit, its fees paid, costs at most about 80,800 CU, near 5.8% of the transaction ceiling and below the 157,000 CU Encifher reports for a whole confidential swap [27]. It is cheap because the chain verifies and never recomputes: tree updates, netting and allocation happen once in the enclave, and the program checks one signature, one vault equation per asset and one multiscalar multiplication for all assets. The Jupiter route is the large item; the relayer simulates at 1,400,000 and sets 1.2 times the units consumed, as Jupiter prescribes for /build [21].

Transaction size and lookup tables

Legacy and v0 transactions hold 1,232 bytes. The v1 format, active on mainnet since epoch 1035 in September 2026, holds 4,096 bytes and inlines every address, with no lookup tables [2][7]. A lookup table stores up to 256 addresses that v0 references by 1-byte index, non-signers only [2]. Both formats lock at most 64 accounts; SIMD-0596, in development, raises v1 to 96 [1][8]. The Commit is laid out for v1.

The fixed part of a v1 Commit is 880 bytes (est.): 42 of prefix, header, config mask, blockhash and counts; ten addresses (fee payer, PoolConfig, LedgerRoot, Registry, CrossingState, Pool authority, Instructions sysvar, event authority, Ed25519 program, Pool program) at 320; 16 of config values; 8 of instruction headers; 112 of precompile header, signature and key plus a 294-byte fixed message; 24 of Commit indices and data; a 64-byte signature. Each asset adds eight addresses (its AssetState, mint, two vault shards, two deposit queues, the fee recipient’s token account and the token program), 136 message bytes and eight indices, 400 bytes:

880+400A≤4,096and10+8A≤64  ⟹  Amax⁡=6 (est.)(9.3)880 + 400A \le 4{,}096 \quad\text{and}\quad 10 + 8A \le 64 \;\Longrightarrow\; A_{\max} = 6 \text{ (est.)} \tag{9.3}

The account limit binds first, at six assets, where a Commit is 3,280 bytes; the byte limit alone would allow eight, the most one Commit message carries. At the 96 accounts of SIMD-0596 the byte limit binds, at eight (est.). A Crossing touching more assets commits as consecutive Crossings, each closed under the pairs it settles (Chapter 7).

A v1 transaction must state its compute limit and loaded-accounts data size: left unset, each is zero and the transaction fails, and ComputeBudget instructions in v1 run as 150 CU no-ops [2]. The relayer writes both into the message config from a simulation, rounding the data size up to the next 32 KiB page, the cost model’s unit [2].

Sealevel parallelism and write-lock design

Sealevel runs transactions in parallel when their write sets are disjoint, and Encifher shows that declared read and write sets order encrypted operations without a custom scheduler [27]. The Pool keeps its high-volume instructions on disjoint writable accounts.

Instruction Writes Reads Serializes with
deposit (shard jj) vault jj, queue jj, source AssetState, LedgerRoot deposits on shard jj; the Commit
post_intent fee payer none nothing
route_residual CrossingState, two vaults, AMM pools AssetState ×2 swaps on the same pools
log_diff CrossingState none the Crossing’s other stages
commit LedgerRoot, AssetState ×AA, CrossingState, vault 0 and the fee recipient’s account ×AA other shards of AA assets everything on those assets, once per Crossing
release_exit AssetState, vault, recipient LedgerRoot releases of the same asset

The binding limit for a hot asset is per account: one writable account absorbs at most 12,000,000 CU per block, inside a block limit of 100,000,000 CU since SIMD-0286 activated in July 2026 [9][10]. With the deposit cost cdepc_{\text{dep}} of the compute table,

Ndep≤S⋅12,000,000cdep=2⋅12,000,00012,000=2,000 per asset per block (est.)(9.4)N_{\text{dep}} \le S \cdot \frac{12{,}000{,}000}{c_{\text{dep}}} = 2 \cdot \frac{12{,}000{,}000}{12{,}000} = 2{,}000 \text{ per asset per block (est.)} \tag{9.4}

or 10,000 deposits per asset per second at the 200 ms slot time live on mainnet since SIMD-0525 [14] (est.); every other chapter converts slots to time with this figure. The SDK picks the shard uniformly at random, so load spreads without coordination. Releases of one asset serialize on AssetState at up to 12,000,000/10,200≈1,17612{,}000{,}000 / 10{,}200 \approx 1{,}176 per block (est.). The Commit’s read locks order it against deposits on its shards once per Crossing; deposits landing first are counted in Σhead\Sigma^{\text{head}} and credited at the next Crossing.

Upgrade authority policy

The Pool is deployed under the upgradeable loader: the upgrade authority can replace the bytecode from a buffer, and setting the authority to None makes the program immutable for good [24][25]. The authority is a multisig whose execution enforces a time lock longer than WW plus the release crank’s slots, so every pending upgrade is visible on chain for longer than any trader needs to Exit, or to Escape, under the code they deposited with. Each buffer’s hash is reproducible from the tagged source with the Solana Verify CLI in Docker, and its verification record lives in a PDA anyone can recheck [26].

Layouts carry a version byte and reserved space so upgrades extend state without migration. Once the instruction set has run unchanged through a Council rotation and an enclave re-attestation (Chapters 5 and 6), the authority is removed with solana program set-upgrade-authority <program-id> --final [25]. From then on the enclave changes by re-attestation in the Registry and the Council by threshold rotation, with the program fixed.

References

  1. “Constants Reference”, Solana Foundation, 2026. https://solana.com/docs/core/constants-reference
  2. “Versioned Transactions: legacy, v0 and v1”, Solana Foundation, 2026. https://solana.com/docs/core/transactions/versioned-transactions
  3. “Precompiled Programs”, Solana Foundation, 2026. https://solana.com/docs/core/programs/precompiles
  4. “Instruction Introspection”, Solana Foundation, 2026. https://solana.com/docs/core/instructions/instruction-introspection
  5. “CPI Execution and Privileges”, Solana Foundation, 2026. https://solana.com/docs/core/cpi/cpi-execution
  6. “Deeper CPI Nesting” (SIMD-0268), Solana Foundation, October 2026. https://solana.com/upgrades/cpi-nesting-depth
  7. “Larger Transaction Sizes” (transaction v1), Solana Foundation, September 2026. https://solana.com/upgrades/larger-transaction-sizes
  8. “More Accounts per Transaction” (SIMD-0596), Solana Foundation, October 2026. https://solana.com/upgrades/v1-account-limit
  9. “100M CU Blocks” (SIMD-0286), Solana Foundation, July 2026. https://solana.com/upgrades/100m-cu-blocks
  10. cost-model/src/block_cost_limits.rs, Agave v3.1.8, Anza. https://github.com/anza-xyz/agave/blob/v3.1.8/cost-model/src/block_cost_limits.rs
  11. program-runtime/src/execution_budget.rs, Agave v3.1.8, Anza. https://github.com/anza-xyz/agave/blob/v3.1.8/program-runtime/src/execution_budget.rs
  12. syscalls/src/lib.rs (hash syscall metering), Agave v3.1.8, Anza. https://github.com/anza-xyz/agave/blob/v3.1.8/syscalls/src/lib.rs
  13. “Reduced Rent” (SIMD-0437), Solana Foundation, September 2026. https://solana.com/upgrades/reduced-rent
  14. “Reduced Slot Times” (SIMD-0525), Solana Foundation, October 2026. https://solana.com/upgrades/reduced-slot-times
  15. “Optimized Token Program” (p-token, SIMD-0266), Solana Foundation, 2026. https://solana.com/upgrades/p-token
  16. “Create a Token Account”, Solana Foundation, 2026. https://solana.com/docs/tokens/basics/create-token-account
  17. “Transfer Fees”, Solana Foundation, 2026. https://solana.com/docs/tokens/extensions/transfer-fees
  18. “Transfer Hook Integration Guide”, Solana Foundation, 2026. https://solana.com/docs/tokens/extensions/transfer-hook-integration
  19. “Confidential Balances”, Solana Foundation, 2026. https://solana.com/docs/tokens/extensions/confidential-transfer
  20. “Confidential transfers return to Solana mainnet after year-long security pause”, Solana Compass, June 18, 2026. https://solanacompass.com/news/confidential-transfers-return-to-solana-mainnet-after-year-long-security-pause
  21. “Build” (Swap API V2 Router path), Jupiter, 2026. https://developers.jup.ag/docs/swap/build
  22. sol-swap-cpi, Jupiter, GitHub. https://github.com/jup-ag/sol-swap-cpi
  23. “Sponsored Feeds” (Solana), Pyth Network, 2026. https://docs.pyth.network/pro/sponsored-feeds#solana
  24. “Program Deployment”, Solana Foundation, 2026. https://solana.com/docs/core/programs/program-deployment
  25. “Deploying Programs”, Solana Foundation, 2026. https://solana.com/docs/programs/deploying
  26. “Verified Builds”, Solana Foundation, 2026. https://solana.com/docs/programs/verified-builds
  27. N. Lokhande et al., “Encifher: A Trusted-Execution Coprocessor for Confidential Computation on Solana”, IACR ePrint 2026/1504, July 2026. https://eprint.iacr.org/2026/1504
  28. programs/pyth-push-oracle/src/lib.rs (price feed account seeds), Pyth Network, GitHub. https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/solana/programs/pyth-push-oracle/src/lib.rs
  29. pyth_solana_receiver_sdk/src/price_update.rs (PriceUpdateV2, VerificationLevel), Pyth Network, GitHub. https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/solana/pyth_solana_receiver_sdk/src/price_update.rs