Skip to main content

simulator_api/
venue.rs

1//! Caller-supplied venue templates: one instruction the server rewrites per probe.
2//!
3//! Split from the crate root because the wire shape, its parse errors and its round-trip
4//! tests are one subject, and `lib.rs` is long enough that adding a ninth unrelated block
5//! to it makes every one of them harder to find.
6
7use std::{collections::HashSet, str::FromStr};
8
9use serde::{Deserialize, Serialize};
10use serde_with::{DisplayFromStr, base64::Base64, serde_as};
11use solana_address::{Address, MAX_SEED_LEN, MAX_SEEDS};
12
13use crate::{Base64DecodeError, BinaryEncoding, EncodedBinary, SwapMode};
14
15/// The width of the little-endian amount a template's `amountOffset` addresses.
16pub const AMOUNT_WIDTH: usize = 8;
17
18/// One instruction the caller serialized, with the slots the server rewrites per probe and the
19/// offset it writes the amount at. Matches hops of `mode` originals trading `inputMint` →
20/// `outputMint` and is priced against each such hop's realized fill.
21///
22/// Every floor, fee, direction and venue payload is the caller's: the server writes the amount,
23/// rewrites the taker, funds, simulates and reads the fill.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(try_from = "VenueTemplateWire", into = "VenueTemplateWire")]
26pub struct VenueTemplate {
27    /// The template's identity on rows, events, notifications, report groups and stats keys.
28    /// Unique per session, non-blank after trim.
29    pub label: String,
30    /// Which originals match, and whether the hop's input (`ExactIn`) or output (`ExactOut`)
31    /// amount is written.
32    pub mode: SwapMode,
33    /// The mint the matched hops sell; base58 `inputMint` on the wire.
34    pub input_mint: Address,
35    /// The mint the matched hops buy; base58 `outputMint` on the wire.
36    pub output_mint: Address,
37    /// The instruction each probe runs.
38    pub instruction: TemplateInstruction,
39    /// Offset of the [`AMOUNT_WIDTH`]-byte little-endian amount in `instruction.data`.
40    pub amount_offset: u32,
41    /// The account slots rewritten to each probe's taker.
42    pub taker: TakerSlots,
43    /// How the instruction is brought up to date with the state each probe pass runs at.
44    pub resolve: Option<TemplateResolver>,
45    /// The transaction each probe fires in place of `instruction`, which then names only the venue
46    /// program.
47    pub frame: Option<TemplateFrame>,
48}
49
50/// A landed transaction fired whole as `taker.fixedUser`, its fee payer, for a venue that refuses
51/// any caller but its own router. Only `patches` are rewritten per probe.
52#[serde_as]
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(rename_all = "camelCase")]
55pub struct TemplateFrame {
56    /// The transaction, bincode; base64 on the wire.
57    #[serde_as(as = "Base64")]
58    pub transaction: Vec<u8>,
59    /// The bytes each probe rewrites.
60    pub patches: Vec<FramePatch>,
61    /// The taker's token account of the mint that is not SOL.
62    #[serde_as(as = "DisplayFromStr")]
63    pub quote_account: Address,
64    /// Where the fill is read.
65    pub read: FrameRead,
66}
67
68/// A little-endian u64 in the data of one top-level instruction.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70pub struct FramePatch {
71    /// The instruction's index in the message.
72    pub ix: u8,
73    /// The u64's offset in the instruction's data.
74    pub offset: u16,
75    /// What the u64 is set to.
76    pub field: FrameField,
77}
78
79/// What a [`FramePatch`] is set to.
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
81#[serde(rename_all = "camelCase")]
82pub enum FrameField {
83    /// The probe's amount.
84    Amount,
85    /// Zero, so the router takes any output.
86    MinOut,
87}
88
89/// Where a frame's fill lands.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(tag = "type", rename_all = "camelCase")]
92pub enum FrameRead {
93    /// `quoteAccount`, for SOL in.
94    Token,
95    /// The taker's lamports, net of `fixed` lamports the transaction pays whatever it trades and of
96    /// `feeBps` its router keeps of the output.
97    #[serde(rename_all = "camelCase")]
98    #[expect(missing_docs, reason = "self-explanatory")]
99    Lamports { fee_bps: u16, fixed: u64 },
100}
101
102/// What a template has refreshed at each probe pass before its probes are instantiated.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(tag = "type", rename_all = "camelCase")]
105pub enum TemplateResolver {
106    /// The route data is replaced by the session's metis router's for the same one-step route,
107    /// for a venue whose stamp only its own router can issue. Needs the metis sidecar.
108    Requote,
109    /// The tick arrays are those the pool's price reads at the pass.
110    LiquidityArrays,
111}
112
113/// The template's single instruction, sent verbatim except the role slots' addresses and the
114/// amount bytes.
115#[derive(Debug, Clone, PartialEq, Eq)]
116pub struct TemplateInstruction {
117    /// The program the instruction calls; base58 `programId` on the wire.
118    pub program_id: Address,
119    /// Metas in program order. Flags are never touched by the server; duplicate addresses are
120    /// legal; a role slot's address is a placeholder (by convention the zero address).
121    pub accounts: Vec<TemplateAccount>,
122    /// The instruction data. On the wire it is `{"data": "<base64>", "encoding": "base64"}`.
123    pub data: Vec<u8>,
124}
125
126/// One account meta of a [`TemplateInstruction`].
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub struct TemplateAccount {
129    /// The account, base58. A placeholder in a role slot, since the probe rewrites it.
130    pub address: Address,
131    /// Whether the account is writable. Defaults to `false` when omitted.
132    pub writable: bool,
133    /// Whether the account signs. Defaults to `false` when omitted.
134    pub signer: bool,
135}
136
137/// The account slots a probe rewrites, as indices into `instruction.accounts`.
138///
139/// Each role is a list because one instruction can name the same account more than once: a
140/// router's own swap instruction carries the taker's token accounts for itself and again inside
141/// the venue's account run, and rewriting only the first leaves the venue pointed at the
142/// exemplar's accounts. Every role also takes a bare index, decoded as a one-element list.
143#[serde_as]
144#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(rename_all = "camelCase")]
146pub struct TakerSlots {
147    /// Every slot rewritten to the probe's taker (see `fixedUser`). Non-empty; each must be a
148    /// signer.
149    #[serde(with = "slot_list")]
150    pub user: Vec<u8>,
151    /// Rewritten to the probe taker's associated account for `inputMint` and seeded with the
152    /// trade. Non-empty; each must be writable.
153    #[serde(with = "slot_list")]
154    pub input_token_account: Vec<u8>,
155    /// Rewritten to the probe taker's associated account for `outputMint` and seeded to zero, so
156    /// what lands there is the fill. Non-empty; each must be writable.
157    #[serde(with = "slot_list")]
158    pub output_token_account: Vec<u8>,
159    /// Accounts a venue derives from the taker, re-derived for each probe's taker.
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    pub derived: Vec<DerivedAccount>,
162    /// The taker every probe fires as, base58, for a venue that quotes only for the taker it was
163    /// validated as; absent, a requoted route fires as the probe taker and any other as the
164    /// original swap's fee payer.
165    #[serde_as(as = "Option<DisplayFromStr>")]
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    pub fixed_user: Option<Address>,
168}
169
170/// A program address derived from `seeds` under `program`, written into every one of `slots`.
171#[serde_as]
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173#[serde(rename_all = "camelCase")]
174pub struct DerivedAccount {
175    /// The program the address is derived under, base58.
176    #[serde_as(as = "DisplayFromStr")]
177    pub program: Address,
178    /// The seeds, in derivation order. 1 to 16 seeds of at most 32 bytes each.
179    pub seeds: Vec<Seed>,
180    /// Indices into `instruction.accounts` that receive the derived address. A bare index
181    /// decodes as a one-element list.
182    #[serde(with = "slot_list")]
183    pub slots: Vec<u8>,
184}
185
186/// One seed of a [`DerivedAccount`]: `{"utf8": "<text>"}` or `"user"` on the wire.
187#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
188#[serde(rename_all = "camelCase")]
189pub enum Seed {
190    /// The UTF-8 bytes of a literal string.
191    Utf8(String),
192    /// The probe's fee payer, the address `user` slots are rewritten to.
193    User,
194}
195
196impl Seed {
197    /// The seed's bytes, with `user` as the address [`Seed::User`] stands for.
198    pub fn bytes<'a>(&'a self, user: &'a Address) -> &'a [u8] {
199        match self {
200            Self::Utf8(text) => text.as_bytes(),
201            Self::User => user.as_ref(),
202        }
203    }
204
205    fn len(&self) -> usize {
206        match self {
207            Self::Utf8(text) => text.len(),
208            Self::User => size_of::<Address>(),
209        }
210    }
211}
212
213/// One slot or a list of them on the wire, always a list in memory.
214mod slot_list {
215    use serde::{Deserialize, Deserializer, Serialize, Serializer};
216
217    #[derive(Deserialize)]
218    #[serde(untagged)]
219    enum OneOrMany {
220        One(u8),
221        Many(Vec<u8>),
222    }
223
224    pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
225        Ok(match OneOrMany::deserialize(d)? {
226            OneOrMany::One(slot) => vec![slot],
227            OneOrMany::Many(slots) => slots,
228        })
229    }
230
231    pub(super) fn serialize<S: Serializer>(slots: &[u8], s: S) -> Result<S::Ok, S::Error> {
232        match slots {
233            [only] => only.serialize(s),
234            many => many.serialize(s),
235        }
236    }
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize)]
240#[serde(rename_all = "camelCase")]
241struct VenueTemplateWire {
242    label: String,
243    mode: SwapMode,
244    input_mint: String,
245    output_mint: String,
246    instruction: TemplateInstructionWire,
247    amount_offset: u32,
248    taker: TakerSlots,
249    #[serde(default, skip_serializing_if = "Option::is_none")]
250    resolve: Option<TemplateResolver>,
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    frame: Option<TemplateFrame>,
253}
254
255#[derive(Debug, Clone, Serialize, Deserialize)]
256#[serde(rename_all = "camelCase")]
257struct TemplateInstructionWire {
258    program_id: String,
259    accounts: Vec<TemplateAccountWire>,
260    data: EncodedBinary,
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
264#[serde(rename_all = "camelCase")]
265struct TemplateAccountWire {
266    address: String,
267    #[serde(default)]
268    writable: bool,
269    #[serde(default)]
270    signer: bool,
271}
272
273/// Why a supplied template could not be used.
274#[derive(Debug, thiserror::Error, PartialEq, Eq)]
275#[expect(missing_docs, reason = "self-explanatory")]
276pub enum ParseVenueTemplateError {
277    /// A field holds a string that is not a base58 address.
278    #[error("invalid address {value} in template field {field}")]
279    Address {
280        /// The field's path, e.g. `instruction.accounts[2].address`.
281        field: String,
282        value: String,
283    },
284    /// `label` is empty or only whitespace.
285    #[error("a template's label must not be blank")]
286    BlankLabel,
287    /// `inputMint` equals `outputMint`.
288    #[error("a template must trade two different mints")]
289    SameMint,
290    /// The per-instruction runtime ceiling; an empty list names no slot to rewrite.
291    #[error("a template instruction must hold 1..=255 accounts, got {count}")]
292    AccountCount {
293        /// How many accounts the instruction holds.
294        count: usize,
295    },
296    /// `instruction.data` is not valid base64.
297    #[error("template instruction data is not valid base64: {0}")]
298    Data(#[from] Base64DecodeError),
299    /// The [`AMOUNT_WIDTH`]-byte amount at `amountOffset` runs past the end of the data.
300    #[error("amount offset {offset} leaves no room for an amount in {len} bytes of data")]
301    AmountOffset {
302        /// The template's `amountOffset`.
303        offset: u32,
304        /// The data length, in bytes.
305        len: usize,
306    },
307    /// `taker.user` is empty.
308    #[error("a template must name at least one user slot")]
309    NoUserSlot,
310    /// `taker.inputTokenAccount` or `taker.outputTokenAccount` is empty.
311    #[error("a template must name at least one slot for each token account")]
312    NoTokenAccountSlot,
313    /// A slot index is not below the number of instruction accounts.
314    #[error("{role} slot {slot} is past the instruction's accounts")]
315    SlotOutOfRange {
316        /// The role naming the slot: `user`, `inputTokenAccount`, `outputTokenAccount` or
317        /// `derived`.
318        role: &'static str,
319        slot: u8,
320    },
321    /// Two roles, or two entries of one role, name the same slot.
322    #[error("slot {slot} is named by more than one taker role")]
323    DuplicateRoleSlot { slot: u8 },
324    /// A `user` slot's account is not a signer.
325    #[error("user slot {slot} must be a signer")]
326    UserNotSigner { slot: u8 },
327    /// A token-account slot's account is not writable.
328    #[error("token account slot {slot} must be writable")]
329    TokenAccountReadOnly { slot: u8 },
330    /// A derived account has no seeds, too many seeds, or a seed that is too long.
331    #[error("a derived account must name 1..={MAX_SEEDS} seeds of at most {MAX_SEED_LEN} bytes")]
332    DerivedSeeds,
333    /// A derived account's `slots` is empty.
334    #[error("a derived account must name at least one slot")]
335    NoDerivedSlot,
336    /// A frame template is `ExactOut` or names a resolver.
337    #[error("a frame template must be ExactIn with no resolver")]
338    FrameMode,
339    /// A frame template names no fixed user, or a slot or instruction account to rewrite.
340    #[error("a frame template must name its fixed user and no slots or instruction accounts")]
341    FrameTaker,
342    /// A frame template patches no amount.
343    #[error("a frame template must patch its amount")]
344    FrameAmount,
345}
346
347impl TryFrom<VenueTemplateWire> for VenueTemplate {
348    type Error = ParseVenueTemplateError;
349
350    fn try_from(wire: VenueTemplateWire) -> Result<Self, Self::Error> {
351        let address = |field: String, value: &str| {
352            #[expect(
353                clippy::map_err_ignore,
354                reason = "error reports the field path and invalid address string"
355            )]
356            Address::from_str(value).map_err(|_| ParseVenueTemplateError::Address {
357                field,
358                value: value.to_owned(),
359            })
360        };
361        let accounts = wire
362            .instruction
363            .accounts
364            .iter()
365            .enumerate()
366            .map(|(index, account)| {
367                Ok(TemplateAccount {
368                    address: address(
369                        format!("instruction.accounts[{index}].address"),
370                        &account.address,
371                    )?,
372                    writable: account.writable,
373                    signer: account.signer,
374                })
375            })
376            .collect::<Result<Vec<_>, ParseVenueTemplateError>>()?;
377        let template = Self {
378            label: wire.label,
379            mode: wire.mode,
380            input_mint: address("inputMint".to_owned(), &wire.input_mint)?,
381            output_mint: address("outputMint".to_owned(), &wire.output_mint)?,
382            instruction: TemplateInstruction {
383                program_id: address(
384                    "instruction.programId".to_owned(),
385                    &wire.instruction.program_id,
386                )?,
387                accounts,
388                data: wire.instruction.data.decode()?,
389            },
390            amount_offset: wire.amount_offset,
391            taker: wire.taker,
392            resolve: wire.resolve,
393            frame: wire.frame,
394        };
395        template.validate()?;
396        Ok(template)
397    }
398}
399
400impl VenueTemplate {
401    /// The account slots a probe rewrites: every user slot, then the input and output token
402    /// accounts.
403    pub fn role_slots(&self) -> impl Iterator<Item = u8> {
404        self.taker
405            .user
406            .iter()
407            .chain(&self.taker.input_token_account)
408            .chain(&self.taker.output_token_account)
409            .copied()
410    }
411
412    /// Checks the rules deserialization enforces. Call it on a template built in code before
413    /// sending it.
414    ///
415    /// # Errors
416    ///
417    /// The first rule the template breaks, as a [`ParseVenueTemplateError`].
418    pub fn validate(&self) -> Result<(), ParseVenueTemplateError> {
419        use ParseVenueTemplateError as Error;
420
421        if self.label.trim().is_empty() {
422            return Err(Error::BlankLabel);
423        }
424        if self.input_mint == self.output_mint {
425            return Err(Error::SameMint);
426        }
427        if let Some(frame) = &self.frame {
428            return self.validate_frame(frame);
429        }
430        let accounts = &self.instruction.accounts;
431        if !(1..=usize::from(u8::MAX)).contains(&accounts.len()) {
432            return Err(Error::AccountCount {
433                count: accounts.len(),
434            });
435        }
436        let len = self.instruction.data.len();
437        let end = usize::try_from(self.amount_offset)
438            .ok()
439            .and_then(|offset| offset.checked_add(AMOUNT_WIDTH));
440        if end.is_none_or(|end| end > len) {
441            return Err(Error::AmountOffset {
442                offset: self.amount_offset,
443                len,
444            });
445        }
446        if self.taker.user.is_empty() {
447            return Err(Error::NoUserSlot);
448        }
449        if self.taker.input_token_account.is_empty() || self.taker.output_token_account.is_empty() {
450            return Err(Error::NoTokenAccountSlot);
451        }
452        for derived in &self.taker.derived {
453            if !(1..=MAX_SEEDS).contains(&derived.seeds.len())
454                || derived.seeds.iter().any(|seed| seed.len() > MAX_SEED_LEN)
455            {
456                return Err(Error::DerivedSeeds);
457            }
458            if derived.slots.is_empty() {
459                return Err(Error::NoDerivedSlot);
460            }
461        }
462        let mut role_slots = HashSet::new();
463        fn labelled(role: &'static str, slots: &[u8]) -> impl Iterator<Item = (&'static str, u8)> {
464            slots.iter().map(move |&slot| (role, slot))
465        }
466        self.taker
467            .user
468            .iter()
469            .map(|&slot| ("user", slot))
470            .chain(labelled(
471                "inputTokenAccount",
472                &self.taker.input_token_account,
473            ))
474            .chain(labelled(
475                "outputTokenAccount",
476                &self.taker.output_token_account,
477            ))
478            .chain(
479                self.taker
480                    .derived
481                    .iter()
482                    .flat_map(|derived| labelled("derived", &derived.slots)),
483            )
484            .try_for_each(|(role, slot)| {
485                if usize::from(slot) >= accounts.len() {
486                    return Err(Error::SlotOutOfRange { role, slot });
487                }
488                role_slots
489                    .insert(usize::from(slot))
490                    .then_some(())
491                    .ok_or(Error::DuplicateRoleSlot { slot })
492            })?;
493        let flags_of = |slot: u8| accounts[usize::from(slot)];
494        if let Some(&slot) = self.taker.user.iter().find(|&&slot| !flags_of(slot).signer) {
495            return Err(Error::UserNotSigner { slot });
496        }
497        if let Some(&slot) = self
498            .taker
499            .input_token_account
500            .iter()
501            .chain(&self.taker.output_token_account)
502            .find(|&&slot| !flags_of(slot).writable)
503        {
504            return Err(Error::TokenAccountReadOnly { slot });
505        }
506        Ok(())
507    }
508
509    fn validate_frame(&self, frame: &TemplateFrame) -> Result<(), ParseVenueTemplateError> {
510        use ParseVenueTemplateError as Error;
511
512        if self.mode != SwapMode::ExactIn || self.resolve.is_some() {
513            return Err(Error::FrameMode);
514        }
515        if self.taker.fixed_user.is_none()
516            || self.role_slots().next().is_some()
517            || !self.taker.derived.is_empty()
518            || !self.instruction.accounts.is_empty()
519        {
520            return Err(Error::FrameTaker);
521        }
522        if !frame
523            .patches
524            .iter()
525            .any(|patch| patch.field == FrameField::Amount)
526        {
527            return Err(Error::FrameAmount);
528        }
529        Ok(())
530    }
531}
532
533impl From<VenueTemplate> for VenueTemplateWire {
534    fn from(template: VenueTemplate) -> Self {
535        Self {
536            label: template.label,
537            mode: template.mode,
538            input_mint: template.input_mint.to_string(),
539            output_mint: template.output_mint.to_string(),
540            instruction: TemplateInstructionWire {
541                program_id: template.instruction.program_id.to_string(),
542                accounts: template
543                    .instruction
544                    .accounts
545                    .into_iter()
546                    .map(|account| TemplateAccountWire {
547                        address: account.address.to_string(),
548                        writable: account.writable,
549                        signer: account.signer,
550                    })
551                    .collect(),
552                data: EncodedBinary::from_bytes(&template.instruction.data, BinaryEncoding::Base64),
553            },
554            amount_offset: template.amount_offset,
555            taker: template.taker,
556            resolve: template.resolve,
557            frame: template.frame,
558        }
559    }
560}
561
562#[cfg(test)]
563mod tests {
564    use rstest::rstest;
565
566    use super::*;
567
568    fn address(byte: u8) -> Address {
569        Address::from([byte; 32])
570    }
571
572    /// A SOL → USDC template shaped like a captured router swap: 16 router prefix slots, a
573    /// 13-account venue run, 37 data bytes.
574    fn template_json() -> serde_json::Value {
575        serde_json::json!({
576            "label": "venue/sol-usdc/sol-to-usdc",
577            "mode": "ExactIn",
578            "inputMint": "So11111111111111111111111111111111111111112",
579            "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
580            "instruction": {
581                "programId": address(1).to_string(),
582                "accounts": [
583                    {"address": "11111111111111111111111111111111", "writable": true, "signer": true},
584                    {"address": "11111111111111111111111111111111", "writable": true, "signer": true},
585                    {"address": address(2).to_string()},
586                    {"address": "11111111111111111111111111111111", "writable": true},
587                    {"address": "11111111111111111111111111111111", "writable": true},
588                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
589                    {"address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"},
590                    {"address": "11111111111111111111111111111111"},
591                    {"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"},
592                    {"address": address(1).to_string()},
593                    {"address": address(1).to_string()},
594                    {"address": address(1).to_string()},
595                    {"address": address(3).to_string(), "writable": true},
596                    {"address": address(4).to_string(), "writable": true},
597                    {"address": "So11111111111111111111111111111111111111112"},
598                    {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},
599                    {"address": address(2).to_string(), "writable": true},
600                    {"address": address(5).to_string(), "writable": true},
601                    {"address": address(3).to_string(), "writable": true},
602                    {"address": address(4).to_string(), "writable": true},
603                    {"address": address(6).to_string(), "writable": true},
604                    {"address": address(8).to_string(), "writable": true},
605                    {"address": "So11111111111111111111111111111111111111112"},
606                    {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},
607                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
608                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
609                    {"address": address(9).to_string()},
610                    {"address": "Sysvar1nstructions1111111111111111111111111"},
611                    {"address": address(10).to_string()}
612                ],
613                "data": {"data": "KgAAAAAAAAAAAAAAAAAAAAAAMgACAAAAAQAAAFsAAAEAypo7DQ==", "encoding": "base64"}
614            },
615            "amountOffset": 2,
616            "taker": {"user": [0, 1], "inputTokenAccount": 3, "outputTokenAccount": 4}
617        })
618    }
619
620    #[test]
621    fn a_venue_template_round_trips_through_its_wire_shape() {
622        let json = template_json();
623
624        let template: VenueTemplate = serde_json::from_value(json.clone()).expect("decode");
625
626        assert_eq!(template.label, "venue/sol-usdc/sol-to-usdc");
627        assert_eq!(template.mode, SwapMode::ExactIn);
628        assert_eq!(
629            template.input_mint.to_string(),
630            "So11111111111111111111111111111111111111112"
631        );
632        assert_eq!(
633            template.output_mint.to_string(),
634            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
635        );
636        assert_eq!(template.instruction.program_id, address(1));
637        assert_eq!(template.instruction.accounts.len(), 29);
638        assert_eq!(
639            template.instruction.accounts[0],
640            TemplateAccount {
641                address: Address::default(),
642                writable: true,
643                signer: true,
644            }
645        );
646        assert_eq!(
647            template.instruction.accounts[2],
648            TemplateAccount {
649                address: address(2),
650                writable: false,
651                signer: false,
652            }
653        );
654        assert_eq!(template.instruction.data.len(), 37);
655        assert_eq!(template.instruction.data[0], 42);
656        assert_eq!(template.instruction.data[2..10], [0; 8]);
657        assert_eq!(template.instruction.data[28], 91);
658        assert_eq!(template.amount_offset, 2);
659        assert_eq!(
660            template.taker,
661            TakerSlots {
662                user: vec![0, 1],
663                input_token_account: vec![3],
664                output_token_account: vec![4],
665                derived: Vec::new(),
666                fixed_user: None,
667            }
668        );
669
670        let encoded = serde_json::to_value(&template).expect("encode");
671        assert_eq!(encoded["mode"], "ExactIn");
672        assert_eq!(encoded["amountOffset"], 2);
673        assert_eq!(encoded["instruction"]["data"], json["instruction"]["data"]);
674        assert_eq!(encoded["instruction"]["accounts"][2]["signer"], false);
675        assert_eq!(encoded["taker"]["inputTokenAccount"], 3);
676        assert_eq!(encoded.get("frame"), None);
677        assert_eq!(
678            serde_json::from_value::<VenueTemplate>(encoded).expect("decode again"),
679            template
680        );
681    }
682
683    fn frame_json() -> serde_json::Value {
684        serde_json::json!({
685            "label": "axiom/9zSnXyFg/sol-to-usdc/direct",
686            "mode": "ExactIn",
687            "inputMint": "So11111111111111111111111111111111111111112",
688            "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
689            "instruction": {
690                "programId": address(1).to_string(),
691                "accounts": [],
692                "data": {"data": "", "encoding": "base64"}
693            },
694            "amountOffset": 0,
695            "taker": {"user": [], "inputTokenAccount": [], "outputTokenAccount": [], "fixedUser": address(9).to_string()},
696            "frame": {
697                "transaction": "AQID",
698                "patches": [{"ix": 1, "offset": 1, "field": "amount"}, {"ix": 1, "offset": 9, "field": "minOut"}],
699                "quoteAccount": address(5).to_string(),
700                "read": {"type": "lamports", "feeBps": 100, "fixed": 305000}
701            }
702        })
703    }
704
705    #[test]
706    fn a_frame_template_encodes_back_to_the_json_it_was_read_from() {
707        let template: VenueTemplate = serde_json::from_value(frame_json()).expect("decode");
708
709        assert_eq!(
710            serde_json::to_value(&template).expect("encode"),
711            frame_json()
712        );
713    }
714
715    #[rstest]
716    #[case::exact_out(|wire: &mut VenueTemplateWire| wire.mode = SwapMode::ExactOut, ParseVenueTemplateError::FrameMode)]
717    #[case::resolved(|wire: &mut VenueTemplateWire| wire.resolve = Some(TemplateResolver::Requote), ParseVenueTemplateError::FrameMode)]
718    #[case::no_fixed_user(|wire: &mut VenueTemplateWire| wire.taker.fixed_user = None, ParseVenueTemplateError::FrameTaker)]
719    #[case::a_slot(|wire: &mut VenueTemplateWire| wire.taker.user = vec![0], ParseVenueTemplateError::FrameTaker)]
720    #[case::an_account(
721        |wire: &mut VenueTemplateWire| wire.instruction.accounts = template_wire().instruction.accounts,
722        ParseVenueTemplateError::FrameTaker
723    )]
724    #[case::no_amount(
725        |wire: &mut VenueTemplateWire| wire.frame.as_mut().unwrap().patches.retain(|patch| patch.field != FrameField::Amount),
726        ParseVenueTemplateError::FrameAmount
727    )]
728    fn a_malformed_frame_template_is_refused_at_parse(
729        #[case] corrupt: fn(&mut VenueTemplateWire),
730        #[case] expected: ParseVenueTemplateError,
731    ) {
732        let mut wire: VenueTemplateWire = serde_json::from_value(frame_json()).expect("wire shape");
733        corrupt(&mut wire);
734
735        assert_eq!(VenueTemplate::try_from(wire), Err(expected));
736    }
737
738    #[rstest]
739    #[case::bare_index(serde_json::json!(3), vec![3], serde_json::json!(3))]
740    #[case::one_element_list(serde_json::json!([3]), vec![3], serde_json::json!(3))]
741    #[case::list(serde_json::json!([3, 5]), vec![3, 5], serde_json::json!([3, 5]))]
742    fn every_taker_role_takes_a_bare_index_or_a_list(
743        #[case] wire: serde_json::Value,
744        #[case] slots: Vec<u8>,
745        #[case] encoded: serde_json::Value,
746    ) {
747        let json = serde_json::json!({
748            "user": wire,
749            "inputTokenAccount": wire,
750            "outputTokenAccount": wire,
751        });
752
753        let taker: TakerSlots = serde_json::from_value(json).expect("decode");
754
755        assert_eq!(
756            taker,
757            TakerSlots {
758                user: slots.clone(),
759                input_token_account: slots.clone(),
760                output_token_account: slots,
761                derived: Vec::new(),
762                fixed_user: None,
763            }
764        );
765        let reencoded = serde_json::to_value(&taker).expect("encode");
766        assert_eq!(
767            reencoded,
768            serde_json::json!({
769                "user": encoded,
770                "inputTokenAccount": encoded,
771                "outputTokenAccount": encoded,
772            })
773        );
774        assert_eq!(
775            serde_json::from_value::<TakerSlots>(reencoded).expect("decode again"),
776            taker
777        );
778    }
779
780    #[rstest]
781    #[case::none(None, None)]
782    #[case::requote(Some(serde_json::json!({"type": "requote"})), Some(TemplateResolver::Requote))]
783    #[case::liquidity_arrays(
784        Some(serde_json::json!({"type": "liquidityArrays"})),
785        Some(TemplateResolver::LiquidityArrays)
786    )]
787    fn a_templates_resolver_round_trips_and_is_omitted_when_absent(
788        #[case] wire: Option<serde_json::Value>,
789        #[case] expected: Option<TemplateResolver>,
790    ) {
791        let mut json = template_json();
792        if let Some(wire) = &wire {
793            json["resolve"] = wire.clone();
794        }
795
796        let template: VenueTemplate = serde_json::from_value(json).expect("decode");
797
798        assert_eq!(template.resolve, expected);
799        assert_eq!(
800            serde_json::to_value(&template).unwrap().get("resolve"),
801            wire.as_ref()
802        );
803    }
804
805    #[rstest]
806    #[case::absent(None, None)]
807    #[case::fixed(Some(serde_json::json!(address(9).to_string())), Some(address(9)))]
808    fn a_fixed_user_round_trips_and_is_omitted_when_absent(
809        #[case] wire: Option<serde_json::Value>,
810        #[case] expected: Option<Address>,
811    ) {
812        let mut json = template_json();
813        if let Some(wire) = &wire {
814            json["taker"]["fixedUser"] = wire.clone();
815        }
816
817        let template: VenueTemplate = serde_json::from_value(json.clone()).expect("decode");
818
819        assert_eq!(template.taker.fixed_user, expected);
820        assert_eq!(
821            serde_json::to_value(&template).unwrap()["taker"],
822            json["taker"]
823        );
824    }
825
826    fn template_wire() -> VenueTemplateWire {
827        serde_json::from_value(template_json()).expect("wire shape")
828    }
829
830    fn derived(seeds: Vec<Seed>, slots: Vec<u8>) -> DerivedAccount {
831        DerivedAccount {
832            program: address(7),
833            seeds,
834            slots,
835        }
836    }
837
838    #[test]
839    fn a_derived_account_reads_its_seeds_from_the_wire() {
840        let mut json = template_json();
841        json["taker"]["derived"] = serde_json::json!([{
842            "program": address(11).to_string(),
843            "seeds": [{"utf8": "ban"}, "user"],
844            "slots": [26, 28],
845        }]);
846
847        let template: VenueTemplate = serde_json::from_value(json.clone()).expect("parses");
848
849        assert_eq!(
850            template.taker.derived,
851            vec![DerivedAccount {
852                program: address(11),
853                seeds: vec![Seed::Utf8("ban".to_owned()), Seed::User],
854                slots: vec![26, 28],
855            }]
856        );
857        assert_eq!(
858            serde_json::to_value(&template).unwrap()["taker"]["derived"],
859            json["taker"]["derived"]
860        );
861    }
862
863    /// Each case corrupts exactly one thing about the template, and the parse names it.
864    #[rstest]
865    #[case::address(
866        |wire: &mut VenueTemplateWire| wire.instruction.program_id = "not-base58".to_owned(),
867        ParseVenueTemplateError::Address {
868            field: "instruction.programId".to_owned(),
869            value: "not-base58".to_owned(),
870        }
871    )]
872    #[case::blank_label(
873        |wire: &mut VenueTemplateWire| wire.label = "  ".to_owned(),
874        ParseVenueTemplateError::BlankLabel
875    )]
876    #[case::same_mint(
877        |wire: &mut VenueTemplateWire| wire.output_mint = wire.input_mint.clone(),
878        ParseVenueTemplateError::SameMint
879    )]
880    #[case::no_accounts(
881        |wire: &mut VenueTemplateWire| wire.instruction.accounts.clear(),
882        ParseVenueTemplateError::AccountCount { count: 0 }
883    )]
884    #[case::too_many_accounts(
885        |wire: &mut VenueTemplateWire| {
886            let filler = wire.instruction.accounts[2].clone();
887            wire.instruction.accounts.resize(256, filler);
888        },
889        ParseVenueTemplateError::AccountCount { count: 256 }
890    )]
891    #[case::data(
892        |wire: &mut VenueTemplateWire| wire.instruction.data.data = "!!!".to_owned(),
893        ParseVenueTemplateError::Data(Base64DecodeError::InvalidByte(0, b'!'))
894    )]
895    #[case::amount_offset(
896        |wire: &mut VenueTemplateWire| wire.amount_offset = 30,
897        ParseVenueTemplateError::AmountOffset { offset: 30, len: 37 }
898    )]
899    #[case::no_user_slot(
900        |wire: &mut VenueTemplateWire| wire.taker.user.clear(),
901        ParseVenueTemplateError::NoUserSlot
902    )]
903    #[case::slot_out_of_range(
904        |wire: &mut VenueTemplateWire| wire.taker.output_token_account = vec![29],
905        ParseVenueTemplateError::SlotOutOfRange { role: "outputTokenAccount", slot: 29 }
906    )]
907    #[case::duplicate_role_slot(
908        |wire: &mut VenueTemplateWire| wire.taker.input_token_account = vec![1],
909        ParseVenueTemplateError::DuplicateRoleSlot { slot: 1 }
910    )]
911    #[case::user_not_signer(
912        |wire: &mut VenueTemplateWire| wire.instruction.accounts[1].signer = false,
913        ParseVenueTemplateError::UserNotSigner { slot: 1 }
914    )]
915    #[case::token_account_read_only(
916        |wire: &mut VenueTemplateWire| wire.instruction.accounts[4].writable = false,
917        ParseVenueTemplateError::TokenAccountReadOnly { slot: 4 }
918    )]
919    #[case::no_derived_seed(
920        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![], vec![26])],
921        ParseVenueTemplateError::DerivedSeeds
922    )]
923    #[case::derived_seed_too_long(
924        |wire: &mut VenueTemplateWire| {
925            wire.taker.derived = vec![derived(vec![Seed::Utf8("x".repeat(33))], vec![26])];
926        },
927        ParseVenueTemplateError::DerivedSeeds
928    )]
929    #[case::no_derived_slot(
930        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![])],
931        ParseVenueTemplateError::NoDerivedSlot
932    )]
933    #[case::derived_slot_out_of_range(
934        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![29])],
935        ParseVenueTemplateError::SlotOutOfRange { role: "derived", slot: 29 }
936    )]
937    #[case::derived_slot_names_a_role(
938        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![3])],
939        ParseVenueTemplateError::DuplicateRoleSlot { slot: 3 }
940    )]
941    fn a_malformed_template_is_refused_at_parse(
942        #[case] corrupt: fn(&mut VenueTemplateWire),
943        #[case] expected: ParseVenueTemplateError,
944    ) {
945        let mut wire = template_wire();
946        corrupt(&mut wire);
947
948        assert_eq!(VenueTemplate::try_from(wire), Err(expected));
949    }
950
951    #[test]
952    fn a_255_account_template_is_admitted() {
953        let mut wire = template_wire();
954        wire.instruction.accounts = (0..u8::MAX)
955            .map(|byte| TemplateAccountWire {
956                address: address(byte).to_string(),
957                writable: true,
958                signer: true,
959            })
960            .collect();
961        wire.taker.user = vec![0];
962
963        let template = VenueTemplate::try_from(wire).expect("at the bound");
964
965        assert_eq!(template.role_slots().collect::<Vec<_>>(), vec![0, 3, 4]);
966    }
967}