manifest/validation/
loaders.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use std::{cell::Ref, slice::Iter};

use hypertree::{get_helper, trace};
use solana_program::{
    account_info::{next_account_info, AccountInfo},
    program_error::ProgramError,
    pubkey::Pubkey,
    system_program,
};

use crate::{
    program::ManifestError,
    require,
    state::{GlobalFixed, MarketFixed},
    validation::{EmptyAccount, MintAccountInfo, Program, Signer, TokenAccountInfo},
};

use super::{get_vault_address, ManifestAccountInfo, TokenProgram};

#[cfg(feature = "certora")]
use early_panic::early_panic;

/// CreateMarket account infos
pub(crate) struct CreateMarketContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub base_mint: MintAccountInfo<'a, 'info>,
    pub quote_mint: MintAccountInfo<'a, 'info>,
    pub base_vault: EmptyAccount<'a, 'info>,
    pub quote_vault: EmptyAccount<'a, 'info>,
    pub system_program: Program<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
    pub token_program_22: TokenProgram<'a, 'info>,
}

impl<'a, 'info> CreateMarketContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new_init(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        let base_mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;
        let quote_mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;
        let base_vault: EmptyAccount = EmptyAccount::new(next_account_info(account_iter)?)?;
        let quote_vault: EmptyAccount = EmptyAccount::new(next_account_info(account_iter)?)?;

        let (expected_base_vault, _base_vault_bump) =
            get_vault_address(market.key, base_mint.info.key);
        let (expected_quote_vault, _quote_vault_bump) =
            get_vault_address(market.key, quote_mint.info.key);

        require!(
            expected_base_vault == *base_vault.info.key,
            ManifestError::IncorrectAccount,
            "Incorrect base vault account",
        )?;
        require!(
            expected_quote_vault == *quote_vault.info.key,
            ManifestError::IncorrectAccount,
            "Incorrect quote vault account",
        )?;
        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        let token_program_22: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;

        Ok(Self {
            payer,
            market,
            base_vault,
            quote_vault,
            base_mint,
            quote_mint,
            token_program,
            token_program_22,
            system_program,
        })
    }
}

/// ClaimSeat account infos
pub(crate) struct ClaimSeatContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub system_program: Program<'a, 'info>,
}

impl<'a, 'info> ClaimSeatContext<'a, 'info> {
    #[cfg_attr(all(feature = "certora", not(feature = "certora-test")), early_panic)]
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        Ok(Self {
            payer,
            market,
            system_program,
        })
    }
}

/// ExpandMarketContext account infos
pub(crate) struct ExpandMarketContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub system_program: Program<'a, 'info>,
}

impl<'a, 'info> ExpandMarketContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        Ok(Self {
            payer,
            market,
            system_program,
        })
    }
}

/// Deposit into a market account infos
pub(crate) struct DepositContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub trader_token: TokenAccountInfo<'a, 'info>,
    pub vault: TokenAccountInfo<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
    pub mint: MintAccountInfo<'a, 'info>,
}

impl<'a, 'info> DepositContext<'a, 'info> {
    #[cfg_attr(all(feature = "certora", not(feature = "certora-test")), early_panic)]
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;

        let market_fixed: Ref<MarketFixed> = market.get_fixed()?;
        let base_mint: &Pubkey = market_fixed.get_base_mint();
        let quote_mint: &Pubkey = market_fixed.get_quote_mint();

        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;

        // Infer the mint key from the token account.
        let (mint, expected_vault_address) =
            if &token_account_info.try_borrow_data()?[0..32] == base_mint.as_ref() {
                (base_mint, market_fixed.get_base_vault())
            } else if &token_account_info.try_borrow_data()?[0..32] == quote_mint.as_ref() {
                (quote_mint, market_fixed.get_quote_vault())
            } else {
                return Err(ManifestError::InvalidWithdrawAccounts.into());
            };

        trace!("trader token account {:?}", token_account_info.key);
        let trader_token: TokenAccountInfo =
            TokenAccountInfo::new_with_owner(token_account_info, mint, payer.key)?;

        trace!("vault token account {:?}", expected_vault_address);
        let vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            mint,
            &expected_vault_address,
            &expected_vault_address,
        )?;

        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        let mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;

        // Drop the market ref so it can be passed through the return.
        drop(market_fixed);
        Ok(Self {
            payer,
            market,
            trader_token,
            vault,
            token_program,
            mint,
        })
    }
}

/// Withdraw account infos
pub(crate) struct WithdrawContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub trader_token: TokenAccountInfo<'a, 'info>,
    pub vault: TokenAccountInfo<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
    pub mint: MintAccountInfo<'a, 'info>,
}

impl<'a, 'info> WithdrawContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;

        let market_fixed: Ref<MarketFixed> = market.get_fixed()?;
        let base_mint: &Pubkey = market_fixed.get_base_mint();
        let quote_mint: &Pubkey = market_fixed.get_quote_mint();

        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;

        let (mint, expected_vault_address) =
            if &token_account_info.try_borrow_data()?[0..32] == base_mint.as_ref() {
                (base_mint, market_fixed.get_base_vault())
            } else if &token_account_info.try_borrow_data()?[0..32] == quote_mint.as_ref() {
                (quote_mint, market_fixed.get_quote_vault())
            } else {
                return Err(ManifestError::InvalidWithdrawAccounts.into());
            };

        let trader_token: TokenAccountInfo =
            TokenAccountInfo::new_with_owner(token_account_info, mint, payer.key)?;
        let vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            mint,
            &expected_vault_address,
            &expected_vault_address,
        )?;

        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        let mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;

        // Drop the market ref so it can be passed through the return.
        drop(market_fixed);
        Ok(Self {
            payer,
            market,
            trader_token,
            vault,
            token_program,
            mint,
        })
    }
}

/// Swap account infos
pub(crate) struct SwapContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub trader_base: TokenAccountInfo<'a, 'info>,
    pub trader_quote: TokenAccountInfo<'a, 'info>,
    pub base_vault: TokenAccountInfo<'a, 'info>,
    pub quote_vault: TokenAccountInfo<'a, 'info>,
    pub token_program_base: TokenProgram<'a, 'info>,
    pub token_program_quote: TokenProgram<'a, 'info>,
    pub base_mint: Option<MintAccountInfo<'a, 'info>>,
    pub quote_mint: Option<MintAccountInfo<'a, 'info>>,

    // One for each side. First is base, then is quote.
    pub global_trade_accounts_opts: [Option<GlobalTradeAccounts<'a, 'info>>; 2],
}

impl<'a, 'info> SwapContext<'a, 'info> {
    #[cfg_attr(all(feature = "certora", not(feature = "certora-test")), early_panic)]
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;

        let market_fixed: Ref<MarketFixed> = market.get_fixed()?;
        let base_mint_key: Pubkey = *market_fixed.get_base_mint();
        let quote_mint_key: Pubkey = *market_fixed.get_quote_mint();

        let trader_base: TokenAccountInfo = TokenAccountInfo::new_with_owner(
            next_account_info(account_iter)?,
            &base_mint_key,
            payer.key,
        )?;
        let trader_quote: TokenAccountInfo = TokenAccountInfo::new_with_owner(
            next_account_info(account_iter)?,
            &quote_mint_key,
            payer.key,
        )?;
        let base_vault_address: &Pubkey = market_fixed.get_base_vault();
        let quote_vault_address: &Pubkey = market_fixed.get_quote_vault();

        let base_vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            &base_mint_key,
            &base_vault_address,
            &base_vault_address,
        )?;
        let quote_vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            &quote_mint_key,
            &quote_vault_address,
            &quote_vault_address,
        )?;
        drop(market_fixed);

        let token_program_base: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        let mut base_mint: Option<MintAccountInfo> = None;

        let mut current_account_info_or: Result<&AccountInfo<'info>, ProgramError> =
            next_account_info(account_iter);

        // Possibly includes base mint.
        if current_account_info_or
            .as_ref()
            .is_ok_and(|f| *f.owner == spl_token::id() || *f.owner == spl_token_2022::id())
        {
            let current_account_info: &AccountInfo<'info> = current_account_info_or?;
            base_mint = Some(MintAccountInfo::new(current_account_info)?);
            current_account_info_or = next_account_info(account_iter);
        }

        // Clone is not a problem since we are deserializing token program
        // anyways, so at most this is one more.
        let mut token_program_quote: TokenProgram = token_program_base.clone();
        let mut quote_mint: Option<MintAccountInfo> = None;
        let mut global_trade_accounts_opts: [Option<GlobalTradeAccounts<'a, 'info>>; 2] =
            [None, None];

        // Possibly includes quote token program.
        if current_account_info_or
            .as_ref()
            .is_ok_and(|f| *f.key == spl_token::id() || *f.key == spl_token_2022::id())
        {
            let current_account_info: &AccountInfo<'info> = current_account_info_or?;
            token_program_quote = TokenProgram::new(current_account_info)?;
            current_account_info_or = next_account_info(account_iter);
        }
        // Possibly includes quote mint if the quote token program was token22.
        if current_account_info_or
            .as_ref()
            .is_ok_and(|f| *f.owner == spl_token::id() || *f.owner == spl_token_2022::id())
        {
            let current_account_info: &AccountInfo<'info> = current_account_info_or?;
            quote_mint = Some(MintAccountInfo::new(current_account_info)?);
            current_account_info_or = next_account_info(account_iter);
        }

        if current_account_info_or.is_ok() {
            let current_account_info: &AccountInfo<'info> = current_account_info_or?;

            // It is possible that the global account does not exist. Do not
            // throw an error. This will happen when users just blindly include
            // global accounts that have not been initialized.
            if !current_account_info.data_is_empty() {
                let global: ManifestAccountInfo<'a, 'info, GlobalFixed> =
                    ManifestAccountInfo::<GlobalFixed>::new(current_account_info)?;
                let global_data: Ref<&mut [u8]> = global.data.borrow();
                let global_fixed: &GlobalFixed = get_helper::<GlobalFixed>(&global_data, 0_u32);
                let global_mint_key: &Pubkey = global_fixed.get_mint();
                let expected_global_vault_address: &Pubkey = global_fixed.get_vault();

                let global_vault: TokenAccountInfo<'a, 'info> =
                    TokenAccountInfo::new_with_owner_and_key(
                        next_account_info(account_iter)?,
                        global_mint_key,
                        &expected_global_vault_address,
                        &expected_global_vault_address,
                    )?;

                let index: usize = if *global_mint_key == base_mint_key {
                    0
                } else {
                    require!(
                        quote_mint_key == *global_mint_key,
                        ManifestError::MissingGlobal,
                        "Unexpected global accounts",
                    )?;
                    1
                };

                drop(global_data);
                global_trade_accounts_opts[index] = Some(GlobalTradeAccounts {
                    mint_opt: if index == 0 {
                        base_mint.clone()
                    } else {
                        quote_mint.clone()
                    },
                    global,
                    global_vault_opt: Some(global_vault),
                    market_vault_opt: if index == 0 {
                        Some(base_vault.clone())
                    } else {
                        Some(quote_vault.clone())
                    },
                    token_program_opt: if index == 0 {
                        Some(token_program_base.clone())
                    } else {
                        Some(token_program_quote.clone())
                    },
                    gas_payer_opt: None,
                    gas_receiver_opt: Some(payer.clone()),
                    market: *market.info.key,
                    // System program not included because does not rest an order.
                    system_program: None,
                });
            }
        }

        Ok(Self {
            payer,
            market,
            trader_base,
            trader_quote,
            base_vault,
            quote_vault,
            token_program_base,
            token_program_quote,
            base_mint,
            quote_mint,
            global_trade_accounts_opts,
        })
    }
}

/// Accounts needed to make a global trade. Scope is beyond just crate so
/// clients can place orders on markets in testing.
pub struct GlobalTradeAccounts<'a, 'info> {
    /// Required if this is a token22 token.
    pub mint_opt: Option<MintAccountInfo<'a, 'info>>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,

    // These are required when matching a global order, not necessarily when
    // cancelling since tokens dont move in that case.
    pub global_vault_opt: Option<TokenAccountInfo<'a, 'info>>,
    pub market_vault_opt: Option<TokenAccountInfo<'a, 'info>>,
    pub token_program_opt: Option<TokenProgram<'a, 'info>>,

    pub system_program: Option<Program<'a, 'info>>,

    // Trader is sending or cancelling the order. They are the one who will pay
    // or receive gas prepayments.
    pub gas_payer_opt: Option<Signer<'a, 'info>>,
    pub gas_receiver_opt: Option<Signer<'a, 'info>>,
    pub market: Pubkey,
}

/// BatchUpdate account infos
pub(crate) struct BatchUpdateContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub system_program: Program<'a, 'info>,

    // One for each side. First is base, then is quote.
    pub global_trade_accounts_opts: [Option<GlobalTradeAccounts<'a, 'info>>; 2],
}

impl<'a, 'info> BatchUpdateContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        // Certora version is not mutable.
        #[cfg(feature = "certora")]
        let global_trade_accounts_opts: [Option<GlobalTradeAccounts<'a, 'info>>; 2] = [None, None];
        #[cfg(not(feature = "certora"))]
        let mut global_trade_accounts_opts: [Option<GlobalTradeAccounts<'a, 'info>>; 2] =
            [None, None];

        #[cfg(not(feature = "certora"))]
        {
            let market_fixed: Ref<MarketFixed> = market.get_fixed()?;
            let base_mint: Pubkey = *market_fixed.get_base_mint();
            let quote_mint: Pubkey = *market_fixed.get_quote_mint();
            let base_vault: Pubkey = *market_fixed.get_base_vault();
            let quote_vault: Pubkey = *market_fixed.get_quote_vault();
            drop(market_fixed);

            for _ in 0..2 {
                let next_account_info_or: Result<&AccountInfo<'info>, ProgramError> =
                    next_account_info(account_iter);
                if next_account_info_or.is_ok() {
                    let mint: MintAccountInfo<'a, 'info> =
                        MintAccountInfo::new(next_account_info_or?)?;
                    let (index, expected_market_vault_address) = if base_mint == *mint.info.key {
                        (0, &base_vault)
                    } else {
                        require!(
                            quote_mint == *mint.info.key,
                            ManifestError::MissingGlobal,
                            "Unexpected global mint",
                        )?;
                        (1, &quote_vault)
                    };

                    let global_or: Result<
                        ManifestAccountInfo<'a, 'info, GlobalFixed>,
                        ProgramError,
                    > = ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?);

                    // If a client blindly fills in the global account and vault,
                    // then handle that case and allow them to try to work without
                    // the global accounts.
                    if global_or.is_err() {
                        let _global_vault: Result<&AccountInfo<'info>, ProgramError> =
                            next_account_info(account_iter);
                        let _market_vault: Result<&AccountInfo<'info>, ProgramError> =
                            next_account_info(account_iter);
                        let _token_program: Result<&AccountInfo<'info>, ProgramError> =
                            next_account_info(account_iter);
                        continue;
                    }
                    let global: ManifestAccountInfo<'a, 'info, GlobalFixed> = global_or.unwrap();
                    let global_data: Ref<&mut [u8]> = global.data.borrow();
                    let global_fixed: &GlobalFixed = get_helper::<GlobalFixed>(&global_data, 0_u32);
                    let expected_global_vault_address: &Pubkey = global_fixed.get_vault();

                    let global_vault: TokenAccountInfo<'a, 'info> =
                        TokenAccountInfo::new_with_owner_and_key(
                            next_account_info(account_iter)?,
                            mint.info.key,
                            &expected_global_vault_address,
                            &expected_global_vault_address,
                        )?;
                    drop(global_data);

                    let market_vault: TokenAccountInfo<'a, 'info> =
                        TokenAccountInfo::new_with_owner_and_key(
                            next_account_info(account_iter)?,
                            mint.info.key,
                            &expected_market_vault_address,
                            &expected_market_vault_address,
                        )?;
                    let token_program: TokenProgram<'a, 'info> =
                        TokenProgram::new(next_account_info(account_iter)?)?;

                    global_trade_accounts_opts[index] = Some(GlobalTradeAccounts {
                        mint_opt: Some(mint),
                        global,
                        global_vault_opt: Some(global_vault),
                        market_vault_opt: Some(market_vault),
                        token_program_opt: Some(token_program),
                        system_program: Some(system_program.clone()),
                        gas_payer_opt: Some(payer.clone()),
                        gas_receiver_opt: Some(payer.clone()),
                        market: *market.info.key,
                    })
                };
            }
        }

        Ok(Self {
            payer,
            market,
            system_program,
            global_trade_accounts_opts,
        })
    }
}

/// Global create
pub(crate) struct GlobalCreateContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub global: EmptyAccount<'a, 'info>,
    pub system_program: Program<'a, 'info>,
    pub global_mint: MintAccountInfo<'a, 'info>,
    pub global_vault: EmptyAccount<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
}

impl<'a, 'info> GlobalCreateContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let global: EmptyAccount = EmptyAccount::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        let global_mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;
        // Address of the global vault is verified in the handler because the
        // create will only work if the signer seeds match.
        let global_vault: EmptyAccount = EmptyAccount::new(next_account_info(account_iter)?)?;
        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        Ok(Self {
            payer,
            global,
            system_program,
            global_mint,
            global_vault,
            token_program,
        })
    }
}

/// Global add trader
pub(crate) struct GlobalAddTraderContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,
    pub system_program: Program<'a, 'info>,
}

impl<'a, 'info> GlobalAddTraderContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let global: ManifestAccountInfo<GlobalFixed> =
            ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        Ok(Self {
            payer,
            global,
            system_program,
        })
    }
}

/// Global deposit
pub(crate) struct GlobalDepositContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,
    pub mint: MintAccountInfo<'a, 'info>,
    pub global_vault: TokenAccountInfo<'a, 'info>,
    pub trader_token: TokenAccountInfo<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
}

impl<'a, 'info> GlobalDepositContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let global: ManifestAccountInfo<GlobalFixed> =
            ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?)?;

        let mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;

        let global_data: Ref<&mut [u8]> = global.data.borrow();
        let global_fixed: &GlobalFixed = get_helper::<GlobalFixed>(&global_data, 0_u32);
        let expected_global_vault_address: &Pubkey = global_fixed.get_vault();

        let global_vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            mint.info.key,
            &expected_global_vault_address,
            &expected_global_vault_address,
        )?;
        drop(global_data);

        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;
        let trader_token: TokenAccountInfo =
            TokenAccountInfo::new_with_owner(token_account_info, mint.info.key, payer.key)?;
        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        Ok(Self {
            payer,
            global,
            mint,
            global_vault,
            trader_token,
            token_program,
        })
    }
}

/// Global withdraw
pub(crate) struct GlobalWithdrawContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,
    pub mint: MintAccountInfo<'a, 'info>,
    pub global_vault: TokenAccountInfo<'a, 'info>,
    pub trader_token: TokenAccountInfo<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
}

impl<'a, 'info> GlobalWithdrawContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let global: ManifestAccountInfo<GlobalFixed> =
            ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?)?;

        let mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;

        let global_data: Ref<&mut [u8]> = global.data.borrow();
        let global_fixed: &GlobalFixed = get_helper::<GlobalFixed>(&global_data, 0_u32);
        let expected_global_vault_address: &Pubkey = global_fixed.get_vault();

        let global_vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            mint.info.key,
            &expected_global_vault_address,
            &expected_global_vault_address,
        )?;
        drop(global_data);

        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;
        let trader_token: TokenAccountInfo =
            TokenAccountInfo::new_with_owner(token_account_info, mint.info.key, payer.key)?;
        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        Ok(Self {
            payer,
            global,
            mint,
            global_vault,
            trader_token,
            token_program,
        })
    }
}

/// Global evict
pub(crate) struct GlobalEvictContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,
    pub mint: MintAccountInfo<'a, 'info>,
    pub global_vault: TokenAccountInfo<'a, 'info>,
    pub trader_token: TokenAccountInfo<'a, 'info>,
    pub evictee_token: TokenAccountInfo<'a, 'info>,
    pub token_program: TokenProgram<'a, 'info>,
}

impl<'a, 'info> GlobalEvictContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let global: ManifestAccountInfo<GlobalFixed> =
            ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?)?;

        let mint: MintAccountInfo = MintAccountInfo::new(next_account_info(account_iter)?)?;

        let global_data: Ref<&mut [u8]> = global.data.borrow();
        let global_fixed: &GlobalFixed = get_helper::<GlobalFixed>(&global_data, 0_u32);
        let expected_global_vault_address: &Pubkey = global_fixed.get_vault();

        let global_vault: TokenAccountInfo = TokenAccountInfo::new_with_owner_and_key(
            next_account_info(account_iter)?,
            mint.info.key,
            &expected_global_vault_address,
            &expected_global_vault_address,
        )?;
        drop(global_data);

        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;
        let trader_token: TokenAccountInfo =
            TokenAccountInfo::new_with_owner(token_account_info, mint.info.key, payer.key)?;
        let token_account_info: &AccountInfo<'info> = next_account_info(account_iter)?;
        let evictee_token: TokenAccountInfo =
            TokenAccountInfo::new(token_account_info, mint.info.key)?;
        let token_program: TokenProgram = TokenProgram::new(next_account_info(account_iter)?)?;
        Ok(Self {
            payer,
            global,
            mint,
            global_vault,
            trader_token,
            evictee_token,
            token_program,
        })
    }
}

/// Global clean
pub(crate) struct GlobalCleanContext<'a, 'info> {
    pub payer: Signer<'a, 'info>,
    pub market: ManifestAccountInfo<'a, 'info, MarketFixed>,
    pub system_program: Program<'a, 'info>,
    pub global: ManifestAccountInfo<'a, 'info, GlobalFixed>,
}

impl<'a, 'info> GlobalCleanContext<'a, 'info> {
    pub fn load(accounts: &'a [AccountInfo<'info>]) -> Result<Self, ProgramError> {
        let account_iter: &mut Iter<AccountInfo<'info>> = &mut accounts.iter();

        let payer: Signer = Signer::new_payer(next_account_info(account_iter)?)?;
        let market: ManifestAccountInfo<MarketFixed> =
            ManifestAccountInfo::<MarketFixed>::new(next_account_info(account_iter)?)?;
        let system_program: Program =
            Program::new(next_account_info(account_iter)?, &system_program::id())?;
        let global: ManifestAccountInfo<GlobalFixed> =
            ManifestAccountInfo::<GlobalFixed>::new(next_account_info(account_iter)?)?;

        Ok(Self {
            payer,
            market,
            system_program,
            global,
        })
    }
}