Skip to main content

cow_settlement_interface/instruction/
mod.rs

1//! Off-chain instruction builders for the settlement program.
2//!
3//! Each submodule builds the [`solana_instruction::Instruction`] for specific
4//! settlement instructions, encoding their discriminator (see
5//! [`crate::SettlementInstruction`]) and laying out the required accounts.
6
7use solana_program_error::ProgramError;
8
9use crate::{recover_discriminator, SettlementInstruction};
10
11pub mod create_buffer;
12pub mod create_order;
13pub mod initialize;
14pub mod reclaim_order;
15pub mod settle;
16
17/// Shared components for parsing an instruction's input (data fields and
18/// accounts).
19///
20/// Implementations declare which [`SettlementInstruction`] discriminator they
21/// belong to and parse the remaining instruction data and accounts. The
22/// discriminator check is shared via the default [`Self::parse`] implementation;
23/// an impl only needs to provide [`Self::parse_body`].
24///
25/// Parsing accounts is purely positional: they are picked out by their index in
26/// the slice, never by inspecting them. The account type `A` is left generic so
27/// the same layout can be parsed from any account representation, on-chain
28/// (`solana_account_view::AccountView`) or off-chain.
29pub trait InstructionInputParsing<'a, A>: Sized {
30    const DISCRIMINATOR: SettlementInstruction;
31
32    fn parse_body(instruction_data: &'a [u8], accounts: &'a mut [A]) -> Result<Self, ProgramError>;
33
34    fn parse(instruction_data: &'a [u8], accounts: &'a mut [A]) -> Result<Self, ProgramError> {
35        match recover_discriminator(instruction_data)? {
36            (discriminator, remaining_data) if discriminator == Self::DISCRIMINATOR => {
37                Self::parse_body(remaining_data, accounts)
38            }
39            _ => Err(ProgramError::InvalidInstructionData),
40        }
41    }
42}
43
44/// Account-building scaffolding shared by the parser unit tests in this crate
45/// and the settlement program's own tests.
46///
47/// Exposed under the `test-fixtures` feature (and unconditionally for this
48/// crate's own `cargo test`) so both crates can build
49/// [`AccountView`](solana_account_view::AccountView)s without duplicating the
50/// unsafe initializer below.
51#[cfg(any(test, feature = "test-fixtures"))]
52pub mod fixtures {
53    use solana_account_view::{AccountView, RuntimeAccount};
54    use solana_address::Address;
55    use std::{mem, ptr};
56
57    /// Build an `AccountView` based on the input `RuntimeAccount` and whose
58    /// data region is empty.
59    ///
60    /// This is trickier to do than it should be. There's no safe initializer for
61    /// `AccountView` in Pinocchio. The only initializer is:
62    /// <https://docs.rs/solana-account-view/2.0.0/solana_account_view/struct.AccountView.html#method.new_unchecked>
63    ///
64    /// `AccountView::new_unchecked` requires (1) a pointer to an initialized
65    /// `RuntimeAccount`, (2) immediately followed by exactly `data_len` bytes of
66    /// data. We satisfy (1) via `Box::new(RuntimeAccount::default())` (every
67    /// field is zero-initialized, then we overwrite `address`), and (2) by
68    /// setting `data_len = 0` so the trailing-data clause is vacuously true
69    /// regardless of what's actually in memory after the box.
70    ///
71    /// [`Box::leak`] keeps the backing alive for the rest of the test process:
72    /// a dropped `Box` or a returned stack slot would leave the pointer
73    /// dangling. We ignore the memory leak since this function is only intended to
74    /// use in tests.
75    /// <https://doc.rust-lang.org/std/boxed/struct.Box.html#method.leak>
76    ///
77    /// Every `AccountView` method is safe to call on the result. Header
78    /// accessors read fields out of the `RuntimeAccount`. Data-region accessors
79    /// hand out a zero-length slice, which [`core::slice::from_raw_parts`] (the
80    /// primitive underneath them) defines as sound for any non-null, aligned
81    /// pointer. This is true for us because the pointer itself comes boxed data
82    /// and not some manual allocation.
83    /// <https://docs.rs/crate/solana-account-view/2.0.0/source/src/lib.rs#98-295>
84    /// <https://doc.rust-lang.org/beta/core/slice/fn.from_raw_parts.html>
85    pub fn fake_account_from(runtime_account: RuntimeAccount) -> AccountView {
86        let backing = Box::leak(Box::new(runtime_account));
87        unsafe { AccountView::new_unchecked(backing as *mut RuntimeAccount) }
88    }
89
90    /// Adapted from pinocchio's crate-private test helper; kept structurally
91    /// close for comparison:
92    /// <https://docs.rs/crate/pinocchio/0.11.1/source/src/sysvars/slot_hashes/test_utils.rs#120-160>
93    ///
94    /// Allocate a heap-backed `AccountView` whose data region is initialized with
95    /// `data`, whose address is `address`, and whose borrow flag is `borrow_state`.
96    ///
97    /// The function also returns the backing `Vec<u64>` so the caller can keep it
98    /// alive for the duration of the test (otherwise the memory would be freed and
99    /// the raw pointer inside `AccountView` would dangle).
100    ///
101    /// # Safety
102    /// The caller must ensure the returned `AccountView` is used only for reading
103    /// or according to borrow rules because the Solana runtime invariants are not
104    /// fully enforced in this hand-rolled representation.
105    #[allow(
106        clippy::arithmetic_side_effects,
107        reason = "the function is mostly vendored and we don't want to introduce unnecessary changes"
108    )]
109    pub unsafe fn make_account_view(
110        address: Address,
111        data: &[u8],
112        borrow_state: u8,
113    ) -> (AccountView, Vec<u64>) {
114        // pinocchio writes a hand-rolled `AccountLayout` mirror and casts the
115        // pointer to `*mut RuntimeAccount`, because inside that crate the
116        // account struct's fields are private and its tests cannot set them by
117        // name. Here we instead write a real `RuntimeAccount`, since
118        // `solana_account_view::RuntimeAccount` has public fields and a
119        // `Default` impl.
120        let hdr_size = mem::size_of::<RuntimeAccount>();
121        let total = hdr_size + data.len();
122        let words = total.div_ceil(8);
123        let mut backing: Vec<u64> = vec![0u64; words];
124        assert!(
125            mem::align_of::<u64>() >= mem::align_of::<RuntimeAccount>(),
126            "`backing` should be properly aligned to store a `RuntimeAccount` instance"
127        );
128
129        let hdr_ptr = backing.as_mut_ptr() as *mut RuntimeAccount;
130        ptr::write(
131            hdr_ptr,
132            RuntimeAccount {
133                address,
134                borrow_state,
135                data_len: data.len() as u64,
136                ..Default::default()
137            },
138        );
139
140        ptr::copy_nonoverlapping(
141            data.as_ptr(),
142            (hdr_ptr as *mut u8).add(hdr_size),
143            data.len(),
144        );
145
146        (AccountView::new_unchecked(hdr_ptr), backing)
147    }
148
149    /// Create an account view storing the input data.
150    pub fn fake_account_with_data(address: Address, data: &[u8]) -> AccountView {
151        let (account, backing) =
152            unsafe { make_account_view(address, data, solana_account_view::NOT_BORROWED) };
153        core::mem::forget(backing);
154        account
155    }
156
157    pub fn fake_account(address: Address) -> AccountView {
158        fake_account_with_data(address, &[])
159    }
160
161    pub fn fake_account_from_array(address_array: [u8; 32]) -> AccountView {
162        fake_account(Address::new_from_array(address_array))
163    }
164
165    /// Build `N` fake accounts with sequential addresses (`[1; 32]`, `[2; 32]`, …).
166    pub fn fake_sequential_accounts<const N: usize>() -> [AccountView; N] {
167        core::array::from_fn(|i| fake_account_from_array([(i as u8).wrapping_add(1); 32]))
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use crate::{AccountMeta, Pubkey};
175    use solana_account_view::AccountView;
176
177    #[track_caller]
178    pub(crate) fn assert_writable_signer(account: &AccountMeta, pubkey: Pubkey) {
179        assert_eq!(account.pubkey, pubkey, "unexpected account pubkey");
180        assert!(account.is_writable, "{} should be writable", account.pubkey);
181        assert!(account.is_signer, "{} should be a signer", account.pubkey);
182    }
183
184    #[track_caller]
185    pub(crate) fn assert_writable_nonsigner(account: &AccountMeta, pubkey: Pubkey) {
186        assert_eq!(account.pubkey, pubkey, "unexpected account pubkey");
187        assert!(account.is_writable, "{} should be writable", account.pubkey);
188        assert!(
189            !account.is_signer,
190            "{} should not be a signer",
191            account.pubkey
192        );
193    }
194
195    #[track_caller]
196    pub(crate) fn assert_readonly_signer(account: &AccountMeta, pubkey: Pubkey) {
197        assert_eq!(account.pubkey, pubkey, "unexpected account pubkey");
198        assert!(
199            !account.is_writable,
200            "{} should be read-only",
201            account.pubkey
202        );
203        assert!(account.is_signer, "{} should be a signer", account.pubkey);
204    }
205
206    #[track_caller]
207    pub(crate) fn assert_readonly_nonsigner(account: &AccountMeta, pubkey: Pubkey) {
208        assert_eq!(account.pubkey, pubkey, "unexpected account pubkey");
209        assert!(
210            !account.is_writable,
211            "{} should be read-only",
212            account.pubkey
213        );
214        assert!(
215            !account.is_signer,
216            "{} should not be a signer",
217            account.pubkey
218        );
219    }
220
221    #[test]
222    fn input_parsing_rejects_different_discriminator() {
223        struct TestInputParsing {}
224        impl<'a> InstructionInputParsing<'a, AccountView> for TestInputParsing {
225            const DISCRIMINATOR: SettlementInstruction = SettlementInstruction::BeginSettle;
226
227            fn parse_body(
228                _instruction_data: &'a [u8],
229                _accounts: &'a mut [AccountView],
230            ) -> Result<Self, ProgramError> {
231                Ok(Self {})
232            }
233        }
234
235        let mut data = [0; 42];
236        let different_discriminator = SettlementInstruction::CreateOrder;
237        assert_ne!(TestInputParsing::DISCRIMINATOR, different_discriminator);
238        data[0] = different_discriminator.discriminator();
239        assert_eq!(
240            TestInputParsing::parse(&data, &mut []).err(),
241            Some(ProgramError::InvalidInstructionData),
242        );
243    }
244}