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, 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}
46
47/// What a template has refreshed at each probe pass before its probes are instantiated.
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
49#[serde(tag = "type", rename_all = "camelCase")]
50pub enum TemplateResolver {
51    /// The route data is replaced by the session's metis router's for the same one-step route,
52    /// for a venue whose stamp only its own router can issue. Needs the metis sidecar.
53    Requote,
54    /// The tick arrays are those the pool's price reads at the pass.
55    LiquidityArrays,
56}
57
58/// The template's single instruction, sent verbatim except the role slots' addresses and the
59/// amount bytes.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct TemplateInstruction {
62    /// The program the instruction calls; base58 `programId` on the wire.
63    pub program_id: Address,
64    /// Metas in program order. Flags are never touched by the server; duplicate addresses are
65    /// legal; a role slot's address is a placeholder (by convention the zero address).
66    pub accounts: Vec<TemplateAccount>,
67    /// The instruction data. On the wire it is `{"data": "<base64>", "encoding": "base64"}`.
68    pub data: Vec<u8>,
69}
70
71/// One account meta of a [`TemplateInstruction`].
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct TemplateAccount {
74    /// The account, base58. A placeholder in a role slot, since the probe rewrites it.
75    pub address: Address,
76    /// Whether the account is writable. Defaults to `false` when omitted.
77    pub writable: bool,
78    /// Whether the account signs. Defaults to `false` when omitted.
79    pub signer: bool,
80}
81
82/// The account slots a probe rewrites, as indices into `instruction.accounts`.
83///
84/// Each role is a list because one instruction can name the same account more than once: a
85/// router's own swap instruction carries the taker's token accounts for itself and again inside
86/// the venue's account run, and rewriting only the first leaves the venue pointed at the
87/// exemplar's accounts. Every role also takes a bare index, decoded as a one-element list.
88#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90pub struct TakerSlots {
91    /// Every slot rewritten to the original swap's fee payer. Non-empty; each must be a signer.
92    #[serde(with = "slot_list")]
93    pub user: Vec<u8>,
94    /// Rewritten to the fee payer's associated account for `inputMint` and seeded with the
95    /// trade. Non-empty; each must be writable.
96    #[serde(with = "slot_list")]
97    pub input_token_account: Vec<u8>,
98    /// Rewritten to the fee payer's associated account for `outputMint` and seeded to zero, so
99    /// what lands there is the fill. Non-empty; each must be writable.
100    #[serde(with = "slot_list")]
101    pub output_token_account: Vec<u8>,
102    /// Accounts a venue derives from the taker, re-derived for each probe's taker.
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub derived: Vec<DerivedAccount>,
105}
106
107/// A program address derived from `seeds` under `program`, written into every one of `slots`.
108#[serde_as]
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct DerivedAccount {
112    /// The program the address is derived under, base58.
113    #[serde_as(as = "DisplayFromStr")]
114    pub program: Address,
115    /// The seeds, in derivation order. 1 to 16 seeds of at most 32 bytes each.
116    pub seeds: Vec<Seed>,
117    /// Indices into `instruction.accounts` that receive the derived address. A bare index
118    /// decodes as a one-element list.
119    #[serde(with = "slot_list")]
120    pub slots: Vec<u8>,
121}
122
123/// One seed of a [`DerivedAccount`]: `{"utf8": "<text>"}` or `"user"` on the wire.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase")]
126pub enum Seed {
127    /// The UTF-8 bytes of a literal string.
128    Utf8(String),
129    /// The probe's fee payer, the address `user` slots are rewritten to.
130    User,
131}
132
133impl Seed {
134    /// The seed's bytes, with `user` as the address [`Seed::User`] stands for.
135    pub fn bytes<'a>(&'a self, user: &'a Address) -> &'a [u8] {
136        match self {
137            Self::Utf8(text) => text.as_bytes(),
138            Self::User => user.as_ref(),
139        }
140    }
141
142    fn len(&self) -> usize {
143        match self {
144            Self::Utf8(text) => text.len(),
145            Self::User => size_of::<Address>(),
146        }
147    }
148}
149
150/// One slot or a list of them on the wire, always a list in memory.
151mod slot_list {
152    use serde::{Deserialize, Deserializer, Serialize, Serializer};
153
154    #[derive(Deserialize)]
155    #[serde(untagged)]
156    enum OneOrMany {
157        One(u8),
158        Many(Vec<u8>),
159    }
160
161    pub(super) fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
162        Ok(match OneOrMany::deserialize(d)? {
163            OneOrMany::One(slot) => vec![slot],
164            OneOrMany::Many(slots) => slots,
165        })
166    }
167
168    pub(super) fn serialize<S: Serializer>(slots: &[u8], s: S) -> Result<S::Ok, S::Error> {
169        match slots {
170            [only] => only.serialize(s),
171            many => many.serialize(s),
172        }
173    }
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177#[serde(rename_all = "camelCase")]
178struct VenueTemplateWire {
179    label: String,
180    mode: SwapMode,
181    input_mint: String,
182    output_mint: String,
183    instruction: TemplateInstructionWire,
184    amount_offset: u32,
185    taker: TakerSlots,
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    resolve: Option<TemplateResolver>,
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192struct TemplateInstructionWire {
193    program_id: String,
194    accounts: Vec<TemplateAccountWire>,
195    data: EncodedBinary,
196}
197
198#[derive(Debug, Clone, Serialize, Deserialize)]
199#[serde(rename_all = "camelCase")]
200struct TemplateAccountWire {
201    address: String,
202    #[serde(default)]
203    writable: bool,
204    #[serde(default)]
205    signer: bool,
206}
207
208/// Why a supplied template could not be used.
209#[derive(Debug, thiserror::Error, PartialEq, Eq)]
210#[allow(missing_docs)]
211pub enum ParseVenueTemplateError {
212    /// A field holds a string that is not a base58 address.
213    #[error("invalid address {value} in template field {field}")]
214    Address {
215        /// The field's path, e.g. `instruction.accounts[2].address`.
216        field: String,
217        value: String,
218    },
219    /// `label` is empty or only whitespace.
220    #[error("a template's label must not be blank")]
221    BlankLabel,
222    /// `inputMint` equals `outputMint`.
223    #[error("a template must trade two different mints")]
224    SameMint,
225    /// The per-instruction runtime ceiling; an empty list names no slot to rewrite.
226    #[error("a template instruction must hold 1..=255 accounts, got {count}")]
227    AccountCount {
228        /// How many accounts the instruction holds.
229        count: usize,
230    },
231    /// `instruction.data` is not valid base64.
232    #[error("template instruction data is not valid base64: {0}")]
233    Data(#[from] Base64DecodeError),
234    /// The [`AMOUNT_WIDTH`]-byte amount at `amountOffset` runs past the end of the data.
235    #[error("amount offset {offset} leaves no room for an amount in {len} bytes of data")]
236    AmountOffset {
237        /// The template's `amountOffset`.
238        offset: u32,
239        /// The data length, in bytes.
240        len: usize,
241    },
242    /// `taker.user` is empty.
243    #[error("a template must name at least one user slot")]
244    NoUserSlot,
245    /// `taker.inputTokenAccount` or `taker.outputTokenAccount` is empty.
246    #[error("a template must name at least one slot for each token account")]
247    NoTokenAccountSlot,
248    /// A slot index is not below the number of instruction accounts.
249    #[error("{role} slot {slot} is past the instruction's accounts")]
250    SlotOutOfRange {
251        /// The role naming the slot: `user`, `inputTokenAccount`, `outputTokenAccount` or
252        /// `derived`.
253        role: &'static str,
254        slot: u8,
255    },
256    /// Two roles, or two entries of one role, name the same slot.
257    #[error("slot {slot} is named by more than one taker role")]
258    DuplicateRoleSlot { slot: u8 },
259    /// A `user` slot's account is not a signer.
260    #[error("user slot {slot} must be a signer")]
261    UserNotSigner { slot: u8 },
262    /// A token-account slot's account is not writable.
263    #[error("token account slot {slot} must be writable")]
264    TokenAccountReadOnly { slot: u8 },
265    /// A derived account has no seeds, too many seeds, or a seed that is too long.
266    #[error("a derived account must name 1..={MAX_SEEDS} seeds of at most {MAX_SEED_LEN} bytes")]
267    DerivedSeeds,
268    /// A derived account's `slots` is empty.
269    #[error("a derived account must name at least one slot")]
270    NoDerivedSlot,
271}
272
273impl TryFrom<VenueTemplateWire> for VenueTemplate {
274    type Error = ParseVenueTemplateError;
275
276    fn try_from(wire: VenueTemplateWire) -> Result<Self, Self::Error> {
277        let address = |field: String, value: &str| {
278            Address::from_str(value).map_err(|_| ParseVenueTemplateError::Address {
279                field,
280                value: value.to_owned(),
281            })
282        };
283        let accounts = wire
284            .instruction
285            .accounts
286            .iter()
287            .enumerate()
288            .map(|(index, account)| {
289                Ok(TemplateAccount {
290                    address: address(
291                        format!("instruction.accounts[{index}].address"),
292                        &account.address,
293                    )?,
294                    writable: account.writable,
295                    signer: account.signer,
296                })
297            })
298            .collect::<Result<Vec<_>, ParseVenueTemplateError>>()?;
299        let template = Self {
300            label: wire.label,
301            mode: wire.mode,
302            input_mint: address("inputMint".to_owned(), &wire.input_mint)?,
303            output_mint: address("outputMint".to_owned(), &wire.output_mint)?,
304            instruction: TemplateInstruction {
305                program_id: address(
306                    "instruction.programId".to_owned(),
307                    &wire.instruction.program_id,
308                )?,
309                accounts,
310                data: wire.instruction.data.decode()?,
311            },
312            amount_offset: wire.amount_offset,
313            taker: wire.taker,
314            resolve: wire.resolve,
315        };
316        template.validate()?;
317        Ok(template)
318    }
319}
320
321impl VenueTemplate {
322    /// The account slots a probe rewrites: every user slot, then the input and output token
323    /// accounts.
324    pub fn role_slots(&self) -> impl Iterator<Item = u8> {
325        self.taker
326            .user
327            .iter()
328            .chain(&self.taker.input_token_account)
329            .chain(&self.taker.output_token_account)
330            .copied()
331    }
332
333    /// Checks the rules deserialization enforces. Call it on a template built in code before
334    /// sending it.
335    ///
336    /// # Errors
337    ///
338    /// The first rule the template breaks, as a [`ParseVenueTemplateError`].
339    pub fn validate(&self) -> Result<(), ParseVenueTemplateError> {
340        use ParseVenueTemplateError as Error;
341
342        if self.label.trim().is_empty() {
343            return Err(Error::BlankLabel);
344        }
345        if self.input_mint == self.output_mint {
346            return Err(Error::SameMint);
347        }
348        let accounts = &self.instruction.accounts;
349        if !(1..=usize::from(u8::MAX)).contains(&accounts.len()) {
350            return Err(Error::AccountCount {
351                count: accounts.len(),
352            });
353        }
354        let len = self.instruction.data.len();
355        let end = usize::try_from(self.amount_offset)
356            .ok()
357            .and_then(|offset| offset.checked_add(AMOUNT_WIDTH));
358        if end.is_none_or(|end| end > len) {
359            return Err(Error::AmountOffset {
360                offset: self.amount_offset,
361                len,
362            });
363        }
364        if self.taker.user.is_empty() {
365            return Err(Error::NoUserSlot);
366        }
367        if self.taker.input_token_account.is_empty() || self.taker.output_token_account.is_empty() {
368            return Err(Error::NoTokenAccountSlot);
369        }
370        for derived in &self.taker.derived {
371            if !(1..=MAX_SEEDS).contains(&derived.seeds.len())
372                || derived.seeds.iter().any(|seed| seed.len() > MAX_SEED_LEN)
373            {
374                return Err(Error::DerivedSeeds);
375            }
376            if derived.slots.is_empty() {
377                return Err(Error::NoDerivedSlot);
378            }
379        }
380        let mut role_slots = HashSet::new();
381        fn labelled(role: &'static str, slots: &[u8]) -> impl Iterator<Item = (&'static str, u8)> {
382            slots.iter().map(move |&slot| (role, slot))
383        }
384        self.taker
385            .user
386            .iter()
387            .map(|&slot| ("user", slot))
388            .chain(labelled(
389                "inputTokenAccount",
390                &self.taker.input_token_account,
391            ))
392            .chain(labelled(
393                "outputTokenAccount",
394                &self.taker.output_token_account,
395            ))
396            .chain(
397                self.taker
398                    .derived
399                    .iter()
400                    .flat_map(|derived| labelled("derived", &derived.slots)),
401            )
402            .try_for_each(|(role, slot)| {
403                if usize::from(slot) >= accounts.len() {
404                    return Err(Error::SlotOutOfRange { role, slot });
405                }
406                role_slots
407                    .insert(usize::from(slot))
408                    .then_some(())
409                    .ok_or(Error::DuplicateRoleSlot { slot })
410            })?;
411        let flags_of = |slot: u8| accounts[usize::from(slot)];
412        if let Some(&slot) = self.taker.user.iter().find(|&&slot| !flags_of(slot).signer) {
413            return Err(Error::UserNotSigner { slot });
414        }
415        if let Some(&slot) = self
416            .taker
417            .input_token_account
418            .iter()
419            .chain(&self.taker.output_token_account)
420            .find(|&&slot| !flags_of(slot).writable)
421        {
422            return Err(Error::TokenAccountReadOnly { slot });
423        }
424        Ok(())
425    }
426}
427
428impl From<VenueTemplate> for VenueTemplateWire {
429    fn from(template: VenueTemplate) -> Self {
430        Self {
431            label: template.label,
432            mode: template.mode,
433            input_mint: template.input_mint.to_string(),
434            output_mint: template.output_mint.to_string(),
435            instruction: TemplateInstructionWire {
436                program_id: template.instruction.program_id.to_string(),
437                accounts: template
438                    .instruction
439                    .accounts
440                    .into_iter()
441                    .map(|account| TemplateAccountWire {
442                        address: account.address.to_string(),
443                        writable: account.writable,
444                        signer: account.signer,
445                    })
446                    .collect(),
447                data: EncodedBinary::from_bytes(&template.instruction.data, BinaryEncoding::Base64),
448            },
449            amount_offset: template.amount_offset,
450            taker: template.taker,
451            resolve: template.resolve,
452        }
453    }
454}
455
456#[cfg(test)]
457mod tests {
458    use rstest::rstest;
459
460    use super::*;
461
462    fn address(byte: u8) -> Address {
463        Address::from([byte; 32])
464    }
465
466    /// A SOL → USDC template shaped like a captured router swap: 16 router prefix slots, a
467    /// 13-account venue run, 37 data bytes.
468    fn template_json() -> serde_json::Value {
469        serde_json::json!({
470            "label": "venue/sol-usdc/sol-to-usdc",
471            "mode": "ExactIn",
472            "inputMint": "So11111111111111111111111111111111111111112",
473            "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
474            "instruction": {
475                "programId": address(1).to_string(),
476                "accounts": [
477                    {"address": "11111111111111111111111111111111", "writable": true, "signer": true},
478                    {"address": "11111111111111111111111111111111", "writable": true, "signer": true},
479                    {"address": address(2).to_string()},
480                    {"address": "11111111111111111111111111111111", "writable": true},
481                    {"address": "11111111111111111111111111111111", "writable": true},
482                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
483                    {"address": "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"},
484                    {"address": "11111111111111111111111111111111"},
485                    {"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"},
486                    {"address": address(1).to_string()},
487                    {"address": address(1).to_string()},
488                    {"address": address(1).to_string()},
489                    {"address": address(3).to_string(), "writable": true},
490                    {"address": address(4).to_string(), "writable": true},
491                    {"address": "So11111111111111111111111111111111111111112"},
492                    {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},
493                    {"address": address(2).to_string(), "writable": true},
494                    {"address": address(5).to_string(), "writable": true},
495                    {"address": address(3).to_string(), "writable": true},
496                    {"address": address(4).to_string(), "writable": true},
497                    {"address": address(6).to_string(), "writable": true},
498                    {"address": address(8).to_string(), "writable": true},
499                    {"address": "So11111111111111111111111111111111111111112"},
500                    {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},
501                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
502                    {"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"},
503                    {"address": address(9).to_string()},
504                    {"address": "Sysvar1nstructions1111111111111111111111111"},
505                    {"address": address(10).to_string()}
506                ],
507                "data": {"data": "KgAAAAAAAAAAAAAAAAAAAAAAMgACAAAAAQAAAFsAAAEAypo7DQ==", "encoding": "base64"}
508            },
509            "amountOffset": 2,
510            "taker": {"user": [0, 1], "inputTokenAccount": 3, "outputTokenAccount": 4}
511        })
512    }
513
514    #[test]
515    fn a_venue_template_round_trips_through_its_wire_shape() {
516        let json = template_json();
517
518        let template: VenueTemplate = serde_json::from_value(json.clone()).expect("decode");
519
520        assert_eq!(template.label, "venue/sol-usdc/sol-to-usdc");
521        assert_eq!(template.mode, SwapMode::ExactIn);
522        assert_eq!(
523            template.input_mint.to_string(),
524            "So11111111111111111111111111111111111111112"
525        );
526        assert_eq!(
527            template.output_mint.to_string(),
528            "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
529        );
530        assert_eq!(template.instruction.program_id, address(1));
531        assert_eq!(template.instruction.accounts.len(), 29);
532        assert_eq!(
533            template.instruction.accounts[0],
534            TemplateAccount {
535                address: Address::default(),
536                writable: true,
537                signer: true,
538            }
539        );
540        assert_eq!(
541            template.instruction.accounts[2],
542            TemplateAccount {
543                address: address(2),
544                writable: false,
545                signer: false,
546            }
547        );
548        assert_eq!(template.instruction.data.len(), 37);
549        assert_eq!(template.instruction.data[0], 42);
550        assert_eq!(template.instruction.data[2..10], [0; 8]);
551        assert_eq!(template.instruction.data[28], 91);
552        assert_eq!(template.amount_offset, 2);
553        assert_eq!(
554            template.taker,
555            TakerSlots {
556                user: vec![0, 1],
557                input_token_account: vec![3],
558                output_token_account: vec![4],
559                derived: Vec::new(),
560            }
561        );
562
563        let encoded = serde_json::to_value(&template).expect("encode");
564        assert_eq!(encoded["mode"], "ExactIn");
565        assert_eq!(encoded["amountOffset"], 2);
566        assert_eq!(encoded["instruction"]["data"], json["instruction"]["data"]);
567        assert_eq!(encoded["instruction"]["accounts"][2]["signer"], false);
568        assert_eq!(encoded["taker"]["inputTokenAccount"], 3);
569        assert_eq!(
570            serde_json::from_value::<VenueTemplate>(encoded).expect("decode again"),
571            template
572        );
573    }
574
575    #[rstest]
576    #[case::bare_index(serde_json::json!(3), vec![3], serde_json::json!(3))]
577    #[case::one_element_list(serde_json::json!([3]), vec![3], serde_json::json!(3))]
578    #[case::list(serde_json::json!([3, 5]), vec![3, 5], serde_json::json!([3, 5]))]
579    fn every_taker_role_takes_a_bare_index_or_a_list(
580        #[case] wire: serde_json::Value,
581        #[case] slots: Vec<u8>,
582        #[case] encoded: serde_json::Value,
583    ) {
584        let json = serde_json::json!({
585            "user": wire,
586            "inputTokenAccount": wire,
587            "outputTokenAccount": wire,
588        });
589
590        let taker: TakerSlots = serde_json::from_value(json).expect("decode");
591
592        assert_eq!(
593            taker,
594            TakerSlots {
595                user: slots.clone(),
596                input_token_account: slots.clone(),
597                output_token_account: slots,
598                derived: Vec::new(),
599            }
600        );
601        let reencoded = serde_json::to_value(&taker).expect("encode");
602        assert_eq!(
603            reencoded,
604            serde_json::json!({
605                "user": encoded,
606                "inputTokenAccount": encoded,
607                "outputTokenAccount": encoded,
608            })
609        );
610        assert_eq!(
611            serde_json::from_value::<TakerSlots>(reencoded).expect("decode again"),
612            taker
613        );
614    }
615
616    #[rstest]
617    #[case::none(None, None)]
618    #[case::requote(Some(serde_json::json!({"type": "requote"})), Some(TemplateResolver::Requote))]
619    #[case::liquidity_arrays(
620        Some(serde_json::json!({"type": "liquidityArrays"})),
621        Some(TemplateResolver::LiquidityArrays)
622    )]
623    fn a_templates_resolver_round_trips_and_is_omitted_when_absent(
624        #[case] wire: Option<serde_json::Value>,
625        #[case] expected: Option<TemplateResolver>,
626    ) {
627        let mut json = template_json();
628        if let Some(wire) = &wire {
629            json["resolve"] = wire.clone();
630        }
631
632        let template: VenueTemplate = serde_json::from_value(json).expect("decode");
633
634        assert_eq!(template.resolve, expected);
635        assert_eq!(
636            serde_json::to_value(&template).unwrap().get("resolve"),
637            wire.as_ref()
638        );
639    }
640
641    fn template_wire() -> VenueTemplateWire {
642        serde_json::from_value(template_json()).expect("wire shape")
643    }
644
645    fn derived(seeds: Vec<Seed>, slots: Vec<u8>) -> DerivedAccount {
646        DerivedAccount {
647            program: address(7),
648            seeds,
649            slots,
650        }
651    }
652
653    #[test]
654    fn a_derived_account_reads_its_seeds_from_the_wire() {
655        let mut json = template_json();
656        json["taker"]["derived"] = serde_json::json!([{
657            "program": address(11).to_string(),
658            "seeds": [{"utf8": "ban"}, "user"],
659            "slots": [26, 28],
660        }]);
661
662        let template: VenueTemplate = serde_json::from_value(json.clone()).expect("parses");
663
664        assert_eq!(
665            template.taker.derived,
666            vec![DerivedAccount {
667                program: address(11),
668                seeds: vec![Seed::Utf8("ban".to_owned()), Seed::User],
669                slots: vec![26, 28],
670            }]
671        );
672        assert_eq!(
673            serde_json::to_value(&template).unwrap()["taker"]["derived"],
674            json["taker"]["derived"]
675        );
676    }
677
678    /// Each case corrupts exactly one thing about the template, and the parse names it.
679    #[rstest]
680    #[case::address(
681        |wire: &mut VenueTemplateWire| wire.instruction.program_id = "not-base58".to_owned(),
682        ParseVenueTemplateError::Address {
683            field: "instruction.programId".to_owned(),
684            value: "not-base58".to_owned(),
685        }
686    )]
687    #[case::blank_label(
688        |wire: &mut VenueTemplateWire| wire.label = "  ".to_owned(),
689        ParseVenueTemplateError::BlankLabel
690    )]
691    #[case::same_mint(
692        |wire: &mut VenueTemplateWire| wire.output_mint = wire.input_mint.clone(),
693        ParseVenueTemplateError::SameMint
694    )]
695    #[case::no_accounts(
696        |wire: &mut VenueTemplateWire| wire.instruction.accounts.clear(),
697        ParseVenueTemplateError::AccountCount { count: 0 }
698    )]
699    #[case::too_many_accounts(
700        |wire: &mut VenueTemplateWire| {
701            let filler = wire.instruction.accounts[2].clone();
702            wire.instruction.accounts.resize(256, filler);
703        },
704        ParseVenueTemplateError::AccountCount { count: 256 }
705    )]
706    #[case::data(
707        |wire: &mut VenueTemplateWire| wire.instruction.data.data = "!!!".to_owned(),
708        ParseVenueTemplateError::Data(Base64DecodeError::InvalidByte(0, b'!'))
709    )]
710    #[case::amount_offset(
711        |wire: &mut VenueTemplateWire| wire.amount_offset = 30,
712        ParseVenueTemplateError::AmountOffset { offset: 30, len: 37 }
713    )]
714    #[case::no_user_slot(
715        |wire: &mut VenueTemplateWire| wire.taker.user.clear(),
716        ParseVenueTemplateError::NoUserSlot
717    )]
718    #[case::slot_out_of_range(
719        |wire: &mut VenueTemplateWire| wire.taker.output_token_account = vec![29],
720        ParseVenueTemplateError::SlotOutOfRange { role: "outputTokenAccount", slot: 29 }
721    )]
722    #[case::duplicate_role_slot(
723        |wire: &mut VenueTemplateWire| wire.taker.input_token_account = vec![1],
724        ParseVenueTemplateError::DuplicateRoleSlot { slot: 1 }
725    )]
726    #[case::user_not_signer(
727        |wire: &mut VenueTemplateWire| wire.instruction.accounts[1].signer = false,
728        ParseVenueTemplateError::UserNotSigner { slot: 1 }
729    )]
730    #[case::token_account_read_only(
731        |wire: &mut VenueTemplateWire| wire.instruction.accounts[4].writable = false,
732        ParseVenueTemplateError::TokenAccountReadOnly { slot: 4 }
733    )]
734    #[case::no_derived_seed(
735        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![], vec![26])],
736        ParseVenueTemplateError::DerivedSeeds
737    )]
738    #[case::derived_seed_too_long(
739        |wire: &mut VenueTemplateWire| {
740            wire.taker.derived = vec![derived(vec![Seed::Utf8("x".repeat(33))], vec![26])];
741        },
742        ParseVenueTemplateError::DerivedSeeds
743    )]
744    #[case::no_derived_slot(
745        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![])],
746        ParseVenueTemplateError::NoDerivedSlot
747    )]
748    #[case::derived_slot_out_of_range(
749        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![29])],
750        ParseVenueTemplateError::SlotOutOfRange { role: "derived", slot: 29 }
751    )]
752    #[case::derived_slot_names_a_role(
753        |wire: &mut VenueTemplateWire| wire.taker.derived = vec![derived(vec![Seed::User], vec![3])],
754        ParseVenueTemplateError::DuplicateRoleSlot { slot: 3 }
755    )]
756    fn a_malformed_template_is_refused_at_parse(
757        #[case] corrupt: fn(&mut VenueTemplateWire),
758        #[case] expected: ParseVenueTemplateError,
759    ) {
760        let mut wire = template_wire();
761        corrupt(&mut wire);
762
763        assert_eq!(VenueTemplate::try_from(wire), Err(expected));
764    }
765
766    #[test]
767    fn a_255_account_template_is_admitted() {
768        let mut wire = template_wire();
769        wire.instruction.accounts = (0..u8::MAX)
770            .map(|byte| TemplateAccountWire {
771                address: address(byte).to_string(),
772                writable: true,
773                signer: true,
774            })
775            .collect();
776        wire.taker.user = vec![0];
777
778        let template = VenueTemplate::try_from(wire).expect("at the bound");
779
780        assert_eq!(template.role_slots().collect::<Vec<_>>(), vec![0, 3, 4]);
781    }
782}