manifest/program/processor/
batch_update.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use std::cell::RefMut;

use crate::{
    logs::{emit_stack, CancelOrderLog, PlaceOrderLog},
    program::get_trader_index_with_hint,
    quantities::{BaseAtoms, PriceConversionError, QuoteAtomsPerBaseAtom, WrapperU64},
    require,
    state::{
        utils::get_now_slot, AddOrderToMarketArgs, AddOrderToMarketResult, MarketRefMut, OrderType,
        RestingOrder, MARKET_BLOCK_SIZE,
    },
    validation::loaders::BatchUpdateContext,
};
use borsh::{BorshDeserialize, BorshSerialize};

use hypertree::{get_helper, trace, DataIndex, PodBool, RBNode};
use solana_program::{
    account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
    pubkey::Pubkey,
};

use super::{expand_market_if_needed, shared::get_mut_dynamic_account};

use crate::validation::loaders::GlobalTradeAccounts;
#[cfg(feature = "certora")]
use {
    crate::certora::mocks_batch_update::{mock_cancel_order, mock_place_order},
    early_panic::early_panic,
    vectors::no_resizable_vec::NoResizableVec,
};

#[derive(Debug, BorshDeserialize, BorshSerialize, Clone)]
pub struct CancelOrderParams {
    order_sequence_number: u64,
    order_index_hint: Option<DataIndex>,
}

impl CancelOrderParams {
    pub fn new(order_sequence_number: u64) -> Self {
        CancelOrderParams {
            order_sequence_number,
            order_index_hint: None,
        }
    }
    pub fn new_with_hint(order_sequence_number: u64, order_index_hint: Option<DataIndex>) -> Self {
        CancelOrderParams {
            order_sequence_number,
            order_index_hint,
        }
    }
    pub fn order_sequence_number(&self) -> u64 {
        self.order_sequence_number
    }
    pub fn order_index_hint(&self) -> Option<DataIndex> {
        self.order_index_hint
    }
}

#[derive(Debug, BorshDeserialize, BorshSerialize, Clone)]
pub struct PlaceOrderParams {
    base_atoms: u64,
    price_mantissa: u32,
    price_exponent: i8,
    is_bid: bool,
    last_valid_slot: u32,
    order_type: OrderType,
}

impl PlaceOrderParams {
    pub fn new(
        base_atoms: u64,
        price_mantissa: u32,
        price_exponent: i8,
        is_bid: bool,
        order_type: OrderType,
        last_valid_slot: u32,
    ) -> Self {
        PlaceOrderParams {
            base_atoms,
            price_mantissa,
            price_exponent,
            is_bid,
            order_type,
            last_valid_slot,
        }
    }
    pub fn base_atoms(&self) -> u64 {
        self.base_atoms
    }

    pub fn try_price(&self) -> Result<QuoteAtomsPerBaseAtom, PriceConversionError> {
        QuoteAtomsPerBaseAtom::try_from_mantissa_and_exponent(
            self.price_mantissa,
            self.price_exponent,
        )
    }
    pub fn is_bid(&self) -> bool {
        self.is_bid
    }
    pub fn last_valid_slot(&self) -> u32 {
        self.last_valid_slot
    }
    pub fn order_type(&self) -> OrderType {
        self.order_type
    }
}

#[derive(BorshDeserialize, BorshSerialize)]
pub struct BatchUpdateParams {
    /// Optional hint for what index the trader's ClaimedSeat is at.
    pub trader_index_hint: Option<DataIndex>,
    #[cfg(not(feature = "certora"))]
    pub cancels: Vec<CancelOrderParams>,
    #[cfg(feature = "certora")]
    pub cancels: NoResizableVec<CancelOrderParams>,
    #[cfg(not(feature = "certora"))]
    pub orders: Vec<PlaceOrderParams>,
    #[cfg(feature = "certora")]
    pub orders: NoResizableVec<PlaceOrderParams>,
}

impl BatchUpdateParams {
    pub fn new(
        trader_index_hint: Option<DataIndex>,
        #[cfg(not(feature = "certora"))] cancels: Vec<CancelOrderParams>,
        #[cfg(feature = "certora")] cancels: NoResizableVec<CancelOrderParams>,
        #[cfg(not(feature = "certora"))] orders: Vec<PlaceOrderParams>,
        #[cfg(feature = "certora")] orders: NoResizableVec<PlaceOrderParams>,
    ) -> Self {
        BatchUpdateParams {
            trader_index_hint,
            cancels,
            orders,
        }
    }
}

#[derive(BorshDeserialize, BorshSerialize)]
pub struct BatchUpdateReturn {
    /// Vector of tuples of (order_sequence_number, DataIndex)
    pub orders: Vec<(u64, DataIndex)>,
}

#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub enum MarketDataTreeNodeType {
    // 0 is reserved because zeroed byte arrays should be empty.
    Empty = 0,
    #[default]
    ClaimedSeat = 1,
    RestingOrder = 2,
}

pub(crate) fn process_batch_update(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
    data: &[u8],
) -> ProgramResult {
    let params: BatchUpdateParams = BatchUpdateParams::try_from_slice(data)?;
    process_batch_update_core(program_id, accounts, params)
}

#[cfg(not(feature = "certora"))]
fn batch_cancel_order(
    dynamic_account: &mut MarketRefMut,
    trader_index: DataIndex,
    order_sequence_number: u64,
    global_trade_accounts_opts: &[Option<GlobalTradeAccounts>; 2],
) -> ProgramResult {
    dynamic_account.cancel_order(
        trader_index,
        order_sequence_number,
        &global_trade_accounts_opts,
    )
}

#[cfg(feature = "certora")]
fn batch_cancel_order(
    dynamic_account: &mut MarketRefMut,
    trader_index: DataIndex,
    order_sequence_number: u64,
    global_trade_accounts_opts: &[Option<GlobalTradeAccounts>; 2],
) -> ProgramResult {
    mock_cancel_order(
        &dynamic_account,
        trader_index,
        order_sequence_number,
        &global_trade_accounts_opts,
    )
}

#[cfg(not(feature = "certora"))]
fn batch_place_order(
    dynamic_account: &mut MarketRefMut,
    args: AddOrderToMarketArgs,
) -> Result<AddOrderToMarketResult, ProgramError> {
    dynamic_account.place_order(args)
}

#[cfg(feature = "certora")]
fn batch_place_order(
    dynamic_account: &mut MarketRefMut,
    args: AddOrderToMarketArgs,
) -> Result<AddOrderToMarketResult, ProgramError> {
    mock_place_order(dynamic_account, args)
}

#[cfg_attr(all(feature = "certora", not(feature = "certora-test")), early_panic)]
pub(crate) fn process_batch_update_core(
    _program_id: &Pubkey,
    accounts: &[AccountInfo],
    params: BatchUpdateParams,
) -> ProgramResult {
    let batch_update_context: BatchUpdateContext = BatchUpdateContext::load(accounts)?;

    let BatchUpdateContext {
        market,
        payer,
        system_program,
        global_trade_accounts_opts,
    } = batch_update_context;

    let BatchUpdateParams {
        trader_index_hint,
        cancels,
        orders,
    } = params;

    let current_slot: Option<u32> = Some(get_now_slot());

    trace!("batch_update trader_index_hint:{trader_index_hint:?} cancels:{cancels:?} orders:{orders:?}");

    let trader_index: DataIndex = {
        let market_data: &mut RefMut<&mut [u8]> = &mut market.try_borrow_mut_data()?;

        let mut dynamic_account: MarketRefMut = get_mut_dynamic_account(market_data);
        let trader_index: DataIndex =
            get_trader_index_with_hint(trader_index_hint, &dynamic_account, &payer)?;

        for cancel_order_params in cancels {
            // Hinted is preferred because that is O(1) to find and O(log n) to
            // remove. Without the hint, we lookup by order_sequence_number and
            // that is O(n) lookup and O(log n) delete.
            match cancel_order_params.order_index_hint() {
                None => {
                    // Cancels must succeed otherwise we fail the tx.
                    batch_cancel_order(
                        &mut dynamic_account,
                        trader_index,
                        cancel_order_params.order_sequence_number(),
                        &global_trade_accounts_opts,
                    )?;
                }
                Some(hinted_cancel_index) => {
                    // Simple sanity check on the hint given. Make sure that it
                    // aligns with block boundaries. We do a check that it is an
                    // order owned by the payer inside the handler.
                    require!(
                        hinted_cancel_index % (MARKET_BLOCK_SIZE as DataIndex) == 0,
                        crate::program::ManifestError::WrongIndexHintParams,
                        "Invalid cancel hint index {}",
                        hinted_cancel_index,
                    )?;
                    require!(
                        get_helper::<RBNode<RestingOrder>>(
                            &dynamic_account.dynamic,
                            hinted_cancel_index,
                        )
                        .get_payload_type()
                            == MarketDataTreeNodeType::RestingOrder as u8,
                        crate::program::ManifestError::WrongIndexHintParams,
                        "Invalid cancel hint index {}",
                        hinted_cancel_index,
                    )?;
                    let order: &RestingOrder =
                        dynamic_account.get_order_by_index(hinted_cancel_index);
                    require!(
                        trader_index == order.get_trader_index(),
                        crate::program::ManifestError::WrongIndexHintParams,
                        "Invalid cancel hint index {}",
                        hinted_cancel_index,
                    )?;
                    require!(
                        cancel_order_params.order_sequence_number() == order.get_sequence_number(),
                        crate::program::ManifestError::WrongIndexHintParams,
                        "Invalid cancel hint sequence number index {}",
                        hinted_cancel_index,
                    )?;
                    dynamic_account
                        .cancel_order_by_index(hinted_cancel_index, &global_trade_accounts_opts)?;
                }
            };

            emit_stack(CancelOrderLog {
                market: *market.key,
                trader: *payer.key,
                order_sequence_number: cancel_order_params.order_sequence_number(),
            })?;
        }
        trader_index
    };

    // Result is a vector of (order_sequence_number, data_index)
    #[cfg(not(feature = "certora"))]
    let mut result: Vec<(u64, DataIndex)> = Vec::with_capacity(orders.len());
    #[cfg(feature = "certora")]
    let mut result = NoResizableVec::<(u64, DataIndex)>::new(10);
    for place_order_params in orders {
        {
            let base_atoms: BaseAtoms = BaseAtoms::new(place_order_params.base_atoms());
            let price: QuoteAtomsPerBaseAtom = place_order_params.try_price()?;
            let order_type: OrderType = place_order_params.order_type();
            let last_valid_slot: u32 = place_order_params.last_valid_slot();

            // Need to reborrow every iteration so we can borrow later for expanding.
            let market_data: &mut RefMut<&mut [u8]> = &mut market.try_borrow_mut_data()?;
            let mut dynamic_account: MarketRefMut = get_mut_dynamic_account(market_data);

            let add_order_to_market_result: AddOrderToMarketResult = batch_place_order(
                &mut dynamic_account,
                AddOrderToMarketArgs {
                    market: *market.key,
                    trader_index,
                    num_base_atoms: base_atoms,
                    price,
                    is_bid: place_order_params.is_bid(),
                    last_valid_slot,
                    order_type,
                    global_trade_accounts_opts: &global_trade_accounts_opts,
                    current_slot,
                },
            )?;

            let AddOrderToMarketResult {
                order_index,
                order_sequence_number,
                ..
            } = add_order_to_market_result;

            emit_stack(PlaceOrderLog {
                market: *market.key,
                trader: *payer.key,
                base_atoms,
                price,
                order_type,
                is_bid: PodBool::from(place_order_params.is_bid()),
                _padding: [0; 6],
                order_sequence_number,
                order_index,
                last_valid_slot,
            })?;
            result.push((order_sequence_number, order_index));
        }
        expand_market_if_needed(&payer, &market, &system_program)?;
    }

    // Formal verification does not cover return values.
    #[cfg(not(feature = "certora"))]
    {
        let mut buffer: Vec<u8> = Vec::with_capacity(
            std::mem::size_of::<BatchUpdateReturn>()
                + result.len() * 2 * std::mem::size_of::<u64>(),
        );
        let return_data: BatchUpdateReturn = BatchUpdateReturn { orders: result };
        return_data.serialize(&mut buffer).unwrap();
        solana_program::program::set_return_data(&buffer[..]);
    }

    Ok(())
}