cow-settlement-interface 0.5.0

Account layouts, PDA derivations, and instruction builders for the CoW Protocol Solana settlement program.
Documentation
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! Off-chain builder and input parsing for the `BeginSettle` instruction.

use std::vec;

use solana_instruction::{AccountMeta, Instruction};
use solana_program_error::ProgramError;
use solana_pubkey::Pubkey;

use crate::instruction::InstructionInputParsing;
use crate::{SettlementError, SettlementInstruction};

use super::{
    recover_counterpart, MaybeMint, TokenProgram, INSTRUCTIONS_SYSVAR_ID, MINT_PLACEHOLDER,
};

/// A single transfer made when settling an order: `amount` tokens sent from the
/// order's sell token account to `destination`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Pull {
    pub destination: Pubkey,
    pub amount: u64,
}

/// Builder for a `BeginSettle` instruction settling the orders described by the
/// parallel lists:
/// - `order_pdas[i]` is the canonical order PDA (see [`crate::pda::order`])
/// - `sell_token_accounts[i]` is the order's sell token account,
/// - `sell_mints[i]` is the order's sell mint if its pulls use
///   `TransferChecked`, or `None` for plain `Transfer`,
/// - `pulls[i]` the list of [`Pull`]s to perform from that order's sell token
///   account, each sending an amount from the `i`-th order sell token account
///   to a destination.
///
/// The slices are assumed to have the same length but this is not enforced in
/// the builder.
///
/// Wire format (grouped, with `n` orders and `T` total transfers):
/// `[discriminator=0][finalize_ix_index: u16 LE][auction_id: i64 LE][n: u8]
/// [transfer_count×n][amount: u64 LE ×T]`.
/// Required accounts: `[solver (S,R), instructions_sysvar (R), state_pda (R),
/// spl_token_program (R), token_2022_program (R)]` followed, per order, by
/// `[order_pda (W), sell_token_account (W), sell_mint (R), destination (W)...]`.
/// The token
/// program accounts are there to allow CPI calls against the corresponding token
/// program, and are otherwise not parsed or validated, so it is possible to replace
/// these accounts with the system program (or any other program) if they are unused.
/// A `sell_mint` holding [`MINT_PLACEHOLDER`] makes the
/// order's pulls plain `Transfer`s; any other mint makes them `TransferChecked`.
///
/// `solver` must sign, and the solver must be registered in the state pda.
///
/// The program requires the order PDAs to be strictly increasing by address.
/// This builder establishes that ordering for the caller: it sorts the orders by
/// PDA address, carrying each order's sell token account, transfer count,
/// amounts, and destination metas before emitting them.
#[cfg_attr(any(test, feature = "test-fixtures"), derive(Default))]
pub struct BeginSettle<'a> {
    pub program_id: Pubkey,
    pub state_pda: Pubkey,
    pub solver: Pubkey,
    pub finalize_ix_index: u16,
    /// The off-chain auction this settlement executes. Carried in the
    /// instruction data so the settlement can be tied back to its auction
    /// off-chain, unused on-chain.
    pub auction_id: i64,
    /// The only token program this settlement's transfers are issued against,
    /// or `None` to name every supported one; see [`TokenProgram::ALL`].
    pub only_token_program: Option<TokenProgram>,
    pub order_pdas: &'a [Pubkey],
    pub sell_token_accounts: &'a [Pubkey],
    pub sell_mints: &'a [Option<Pubkey>],
    pub pulls: &'a [&'a [Pull]],
}

impl From<BeginSettle<'_>> for Instruction {
    fn from(builder: BeginSettle<'_>) -> Self {
        let BeginSettle {
            program_id,
            state_pda,
            solver,
            finalize_ix_index,
            auction_id,
            only_token_program,
            order_pdas,
            sell_token_accounts,
            sell_mints,
            pulls,
        } = builder;

        // Sort the parallel lists together by order PDA address via a shared
        // permutation, so each order keeps its own sell token account and pulls
        // (transfer count, amounts, and destination metas).
        let mut order: Vec<usize> = (0..order_pdas.len()).collect();
        order.sort_by_key(|&i| order_pdas[i]);

        let counts: Vec<u8> = order.iter().map(|&i| pulls[i].len() as u8).collect();
        let amounts: Vec<u8> = order
            .iter()
            .flat_map(|&i| pulls[i].iter())
            .flat_map(|pull| pull.amount.to_le_bytes())
            .collect();
        let data = [
            &[SettlementInstruction::BeginSettle.discriminator()][..],
            &finalize_ix_index.to_le_bytes()[..],
            &auction_id.to_le_bytes()[..],
            &[order_pdas.len() as u8][..],
            &counts[..],
            &amounts[..],
        ]
        .concat();

        // The signing solver, followed by read-only accounts for instruction
        // introspection, settlement state, and one slot per supported token
        // program.
        let mut accounts = vec![
            AccountMeta::new_readonly(solver, true),
            AccountMeta::new_readonly(INSTRUCTIONS_SYSVAR_ID, false),
            AccountMeta::new_readonly(state_pda, false),
        ];
        // One account per supported token program. If `only_token_program`,
        // replace the other program in the instruction with an account that's
        // already present (and so doesn't take extra space in the tx).
        accounts.extend(TokenProgram::ALL.map(|program| {
            let address = if only_token_program.is_none_or(|only| only == program) {
                program.address()
            } else {
                INSTRUCTIONS_SYSVAR_ID
            };
            AccountMeta::new_readonly(address, false)
        }));
        for &i in &order {
            // Writable account for the order: `BeginSettle` updates its filled
            // amounts (`amount_withdrawn`/`amount_received`).
            accounts.push(AccountMeta::new(order_pdas[i], false));
            // Writable accounts settling the order: its sell token account and the
            // recipient of each transfer.
            accounts.push(AccountMeta::new(sell_token_accounts[i], false));
            // Read account for the sell token mint in case TransferChecked is needed
            accounts.push(AccountMeta::new_readonly(
                sell_mints[i].unwrap_or(MINT_PLACEHOLDER),
                false,
            ));
            for pull in pulls[i] {
                accounts.push(AccountMeta::new(pull.destination, false));
            }
        }

        Instruction {
            program_id,
            accounts,
            data,
        }
    }
}

/// A single settled order, resulted from parsing `BeginSettle`, together with
/// the funds to pull from its sell token account.
pub struct SettledOrder<'a, A> {
    pub order_pda: &'a A,
    pub sell_token_account: &'a A,
    /// The sell mint for this order's pulls: a real mint for `TransferChecked`,
    /// or the [`MINT_PLACEHOLDER`] for plain `Transfer`.
    pub sell_mint: MaybeMint<'a, A>,
    /// Destination accounts for this order's transfers.
    pub destinations: &'a [A],
    /// Transfer amounts (little-endian `u64`), one per destination.
    pub amounts: &'a [[u8; 8]],
}

/// Struct storing accounts, transfer counts, and amounts from parsing the
/// input of BeginSettle. The parsing step that created this struct guarantees
/// that there aren't missing elements or that they are assigned incorrectly.
pub struct SettledOrders<'a, A> {
    /// Order accounts, laid out per order as
    /// [order_accounts_1,  order_accounts_2, ...] where
    /// - each order_accounts is a series of accounts:
    ///   `order_pda_N, sell_token_account_N, sell_mint_N, destination_N_1, ..., destination_N_M`
    /// - and M is `counts[N]`
    order_accounts: &'a [A],
    /// One transfer count per order.
    counts: &'a [u8],
    /// Transfer amounts (little-endian `u64`), shared across orders and
    /// handed out `count` at a time.
    amounts: &'a [[u8; 8]],
}

impl<'a, A> SettledOrders<'a, A> {
    /// The number of settled orders.
    pub fn len(&self) -> usize {
        self.counts.len()
    }

    pub fn is_empty(&self) -> bool {
        self.counts.is_empty()
    }

    /// Returns an iterator yielding one [`SettledOrder`] per step.
    #[allow(
        clippy::arithmetic_side_effects,
        reason = "offsets are bounded by tx limits"
    )]
    pub fn iter(&self) -> impl Iterator<Item = SettledOrder<'a, A>> + '_ {
        let (counts, amounts) = (self.counts, self.amounts);
        // Cursor over the remaining order accounts; each step splits one order's
        // `[order_pda, sell_token_account, sell_mint, destinations..count]` off
        // the front.
        let mut rest: &'a [A] = self.order_accounts;
        let mut i = 0usize;
        let mut amount_offset = 0usize;
        std::iter::from_fn(move || {
            if i >= counts.len() {
                return None;
            }
            let count = usize::from(counts[i]);
            i += 1;

            let (order_pda, tail) = rest.split_first()?;
            let (sell_token_account, tail) = tail.split_first()?;
            let (sell_mint, tail) = tail.split_first()?;
            let (destinations, remainder) = tail.split_at(count);
            rest = remainder;

            let amount_end = amount_offset + count;
            let order_amounts = &amounts[amount_offset..amount_end];
            amount_offset = amount_end;

            Some(SettledOrder {
                order_pda,
                sell_token_account,
                sell_mint: MaybeMint::new(sell_mint),
                destinations,
                amounts: order_amounts,
            })
        })
    }
}

/// Parsed inputs of a `BeginSettle` instruction.
///
/// Strictly the raw extracted form. Fields are read from `instruction_data` and
/// `accounts` but **not validated** against runtime context except confirming
/// that the discriminator matches the desired input and that the number of
/// accounts and transfer counts is consistent.
pub struct BeginSettleInput<'a, A> {
    pub finalize_ix_index: u16,
    /// The off-chain auction this settlement executes, read from the instruction
    /// data. Not validated on-chain: it's carried only so the settlement can be
    /// tied back to its auction off-chain.
    pub auction_id: i64,
    pub solver_account: &'a A,
    pub instructions_sysvar_account: &'a A,
    pub state_pda_account: &'a A,
    pub orders: SettledOrders<'a, A>,
}

/// This implementation defines how instruction bytes and accounts are laid out
/// in the transaction. It's the source of truth for deciding where the data
/// is stored.
impl<'a, A> InstructionInputParsing<'a, A> for BeginSettleInput<'a, A> {
    const DISCRIMINATOR: SettlementInstruction = SettlementInstruction::BeginSettle;

    fn parse_body(instruction_data: &'a [u8], accounts: &'a [A]) -> Result<Self, ProgramError> {
        let (finalize_ix_index, body) = recover_counterpart(instruction_data)?;

        // The two token-program slots are skipped rather than read since they are only
        // used for program invocation.
        let [solver_account, instructions_sysvar_account, state_pda_account, _spl_token_program_account, _token_2022_program_account, order_accounts @ ..] =
            accounts
        else {
            return Err(ProgramError::NotEnoughAccountKeys);
        };

        // Fixed-width auction id, carried between the counterpart index and the
        // per-order pull layout so the settlement can be tied to its auction
        // off-chain.
        let (auction_id, body) = body
            .split_first_chunk::<8>()
            .ok_or(ProgramError::InvalidInstructionData)?;
        let auction_id = i64::from_le_bytes(*auction_id);

        // The leading byte is the order count `n`; the counts take `n` bytes and
        // the remaining bytes are the amounts. `T` (total transfers) is the
        // number of 8-byte amounts. Too few bytes for the order count or the
        // counts, or a trailing amount that isn't a whole `u64`, means the data
        // can't be parsed into the pull layout at all.
        let (&order_count, body) = body
            .split_first()
            .ok_or(ProgramError::InvalidInstructionData)?;
        let order_count = usize::from(order_count);
        let (counts, amount_bytes) = body
            .split_at_checked(order_count)
            .ok_or(ProgramError::InvalidInstructionData)?;
        let (amounts, []) = amount_bytes.as_chunks::<8>() else {
            return Err(ProgramError::InvalidInstructionData);
        };
        let transfer_count = amounts.len();

        // Each order contributes its order PDA, sell token account, sell mint,
        // and one destination per transfer, so the order accounts count is
        // `3n + T`.
        let expected_accounts = order_count
            .checked_mul(3)
            .and_then(|three_n| three_n.checked_add(transfer_count))
            .ok_or(ProgramError::InvalidInstructionData)?;
        if order_accounts.len() != expected_accounts {
            return Err(SettlementError::AccountCountNotMatchingOrderCount.into());
        }

        // The transfer counts must sum to `T` so that every destination account
        // is matched to exactly one amount and the order accounts are consumed
        // exactly by the iterator.
        let counts_sum: usize = counts.iter().map(|&c| usize::from(c)).sum();
        if counts_sum != transfer_count {
            return Err(SettlementError::TransferCountMismatch.into());
        }

        Ok(Self {
            finalize_ix_index,
            auction_id,
            instructions_sysvar_account,
            state_pda_account,
            solver_account,
            orders: SettledOrders {
                order_accounts,
                counts,
                amounts,
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fixtures::pubkey_from_seed;
    use crate::instruction::fixtures::{
        fake_account, fake_account_from_array, fake_sequential_accounts,
    };
    use crate::instruction::settle::tests::{ix_data, mint_address};
    use crate::instruction::tests::{assert_readonly_nonsigner, assert_readonly_signer};
    use crate::token_program::TokenProgram;
    use hex_literal::hex;
    use solana_account_view::AccountView;
    use solana_address::Address;

    /// The fixed accounts every `BeginSettle` carries before its order accounts:
    /// the signing solver, the instructions sysvar, the settlement state PDA, and
    /// one slot per supported token program.
    const FIXED_ACCOUNTS: usize = 5;

    /// A placeholder auction id for the tests where its specific value is
    /// incidental. The wire-layout tests spell out the literal bytes instead.
    const AUCTION_ID: i64 = 0x0102_0304_0506_0708;

    #[test]
    fn expected_encoding_begin_settle_no_orders() {
        let program_id = pubkey_from_seed("program id");
        let state_pda = pubkey_from_seed("state pda");
        let solver = pubkey_from_seed("solver");
        let Instruction {
            program_id: ix_program_id,
            accounts,
            data,
        } = BeginSettle {
            program_id,
            state_pda,
            solver,
            finalize_ix_index: 0x1337,
            auction_id: 0x0102_0304_0506_0708,
            ..Default::default()
        }
        .into();
        assert_eq!(ix_program_id, program_id);
        assert_eq!(
            data,
            ix_data![
                [SettlementInstruction::BeginSettle.discriminator()],
                hex!("3713"),             // counterpart index, little endian
                hex!("0807060504030201"), // auction id, little endian
                [0],                      // order count
            ],
        );
        // No orders: the fixed accounts (solver, sysvar, state PDA, and a slot
        // per token program). Only the solver signs; the rest don't play an
        // active role in the base instruction (the state PDA CPI signature isn't
        // relevant here). This settlement carries only the legacy program, so
        // Token-2022's slot holds the placeholder.
        assert_eq!(accounts.len(), FIXED_ACCOUNTS);
        assert_readonly_signer(&accounts[0], solver);
        assert_readonly_nonsigner(&accounts[1], INSTRUCTIONS_SYSVAR_ID);
        assert_readonly_nonsigner(&accounts[2], state_pda);
        assert_readonly_nonsigner(&accounts[3], TokenProgram::SplToken.address());
        assert_readonly_nonsigner(&accounts[4], TokenProgram::Token2022.address());
    }

    /// The token-program slots are the addresses the settlement's
    /// `only_token_program` names, in [`TokenProgram::ALL`] order, so a
    /// settlement can name both programs — or leave either one out.
    #[test]
    fn begin_settle_carries_the_token_program_slots_it_is_given() {
        for (only_token_program, expected) in [
            (
                None,
                [
                    TokenProgram::SplToken.address(),
                    TokenProgram::Token2022.address(),
                ],
            ),
            (
                Some(TokenProgram::SplToken),
                [TokenProgram::SplToken.address(), INSTRUCTIONS_SYSVAR_ID],
            ),
            (
                Some(TokenProgram::Token2022),
                [INSTRUCTIONS_SYSVAR_ID, TokenProgram::Token2022.address()],
            ),
        ] {
            let Instruction { accounts, .. } = Instruction::from(BeginSettle {
                program_id: Pubkey::new_unique(),
                state_pda: Pubkey::new_unique(),
                solver: Pubkey::new_unique(),
                only_token_program,
                ..Default::default()
            });
            let slots: Vec<Pubkey> = accounts[3..].iter().map(|meta| meta.pubkey).collect();
            assert_eq!(
                slots, expected,
                "{only_token_program:?} should name just the programs it settles against",
            );
        }
    }

    #[test]
    fn begin_settle_sorts_orders_by_pda() {
        let program_id = pubkey_from_seed("program id");
        let state_pda = pubkey_from_seed("state pda");
        let solver = pubkey_from_seed("solver");
        // Two orders supplied in descending PDA order. All the other parameters
        // are chosen to sort in the opposite order.
        let high_order_pda = Pubkey::new_from_array([0xbb; 32]);
        let high_sell_token_account = Pubkey::new_from_array([0xa0; 32]);
        let low_order_pda = Pubkey::new_from_array([0xaa; 32]);
        let low_sell_token_account = Pubkey::new_from_array([0xb0; 32]);
        let high_sell_mint = Pubkey::new_from_array([0xc0; 32]);
        let Instruction { data, accounts, .. } = BeginSettle {
            program_id,
            state_pda,
            solver,
            finalize_ix_index: 0x1337,
            auction_id: AUCTION_ID,
            order_pdas: &[high_order_pda, low_order_pda],
            sell_token_accounts: &[high_sell_token_account, low_sell_token_account],
            // Not set to `None` for one of the mints to be able to confirm the ordering of accounts
            sell_mints: &[Some(high_sell_mint), None],
            pulls: &[&[], &[]],
            ..Default::default()
        }
        .into();

        assert_eq!(
            data,
            ix_data![
                [SettlementInstruction::BeginSettle.discriminator()],
                hex!("3713"),             // counterpart index, little endian
                AUCTION_ID.to_le_bytes(), // auction id, little endian
                [2],                      // order count
                [0, 0],                   // transfer counts (both zero)
            ],
        );

        let expected: Vec<Pubkey> = vec![
            solver,
            INSTRUCTIONS_SYSVAR_ID,
            state_pda,
            TokenProgram::SplToken.address(),
            TokenProgram::Token2022.address(),
            low_order_pda,
            low_sell_token_account,
            MINT_PLACEHOLDER,
            high_order_pda,
            high_sell_token_account,
            high_sell_mint,
        ];
        let actual: Vec<Pubkey> = accounts.iter().map(|account| account.pubkey).collect();
        assert_eq!(actual, expected);
        // The fixed accounts and mints are read-only; the rest are writable and
        // should be sorted
        let writable: Vec<Pubkey> = accounts
            .iter()
            .filter(|account| account.is_writable)
            .map(|account| account.pubkey)
            .collect();
        assert_eq!(
            writable,
            vec![
                low_order_pda,
                low_sell_token_account,
                high_order_pda,
                high_sell_token_account,
            ],
        );
        // The solver is the sole signer; none of the order accounts signs.
        let (_fixed, order_accounts) = accounts.split_at(FIXED_ACCOUNTS);
        assert!(order_accounts.iter().all(|account| !account.is_signer));
    }

    #[test]
    fn begin_settle_encodes_grouped_transfers() {
        let program_id = pubkey_from_seed("program id");
        let state_pda = pubkey_from_seed("state pda");
        let solver = pubkey_from_seed("solver");
        let order_a = Pubkey::new_from_array([0x01; 32]);
        let sell_a = Pubkey::new_from_array([0x02; 32]);
        let order_b = Pubkey::new_from_array([0x03; 32]);
        let sell_b = Pubkey::new_from_array([0x04; 32]);
        let dest_a0 = Pubkey::new_from_array([0x05; 32]);
        let dest_a1 = Pubkey::new_from_array([0x06; 32]);
        let dest_b0 = Pubkey::new_from_array([0x07; 32]);
        let mint_b = Pubkey::new_from_array([0x08; 32]);

        // Order A has two transfers, order B has one.
        let Instruction { data, accounts, .. } = BeginSettle {
            program_id,
            state_pda,
            solver,
            finalize_ix_index: 0x1337,
            auction_id: AUCTION_ID,
            order_pdas: &[order_a, order_b],
            sell_token_accounts: &[sell_a, sell_b],
            sell_mints: &[None, Some(mint_b)],
            pulls: &[
                &[
                    Pull {
                        destination: dest_a0,
                        amount: 0x0102,
                    },
                    Pull {
                        destination: dest_a1,
                        amount: 0x0304,
                    },
                ],
                &[Pull {
                    destination: dest_b0,
                    amount: 0x0506,
                }],
            ],
            ..Default::default()
        }
        .into();

        assert_eq!(
            data,
            ix_data![
                [SettlementInstruction::BeginSettle.discriminator()],
                hex!("3713"),             // counterpart index, little endian
                AUCTION_ID.to_le_bytes(), // auction id, little endian
                [2],                      // order count
                [2, 1],                   // counts
                // amounts, little endian
                hex!("0201000000000000"),
                hex!("0403000000000000"),
                hex!("0605000000000000"),
            ],
        );

        let expected: Vec<Pubkey> = vec![
            solver,
            INSTRUCTIONS_SYSVAR_ID,
            state_pda,
            TokenProgram::SplToken.address(),
            TokenProgram::Token2022.address(),
            order_a,
            sell_a,
            MINT_PLACEHOLDER,
            dest_a0,
            dest_a1,
            order_b,
            sell_b,
            mint_b,
            dest_b0,
        ];
        let actual: Vec<Pubkey> = accounts.iter().map(|account| account.pubkey).collect();
        assert_eq!(actual, expected);
        // The fixed accounts and mints are read-only; the rest are writable.
        let writable: Vec<Pubkey> = accounts
            .iter()
            .filter(|account| account.is_writable)
            .map(|account| account.pubkey)
            .collect();
        assert_eq!(
            writable,
            vec![order_a, sell_a, dest_a0, dest_a1, order_b, sell_b, dest_b0,],
        );
        // The solver is the sole signer; none of the order accounts signs.
        let (_fixed, order_accounts) = accounts.split_at(FIXED_ACCOUNTS);
        assert!(order_accounts.iter().all(|account| !account.is_signer));
    }

    #[test]
    fn begin_settle_input_parses_valid_input() {
        let sysvar = pubkey_from_seed("sysvar");
        let state = pubkey_from_seed("state pda");
        let spl_token_program = pubkey_from_seed("spl token program");
        let token_2022_program = pubkey_from_seed("token 2022 program");
        let solver = pubkey_from_seed("solver");
        let accounts = [
            fake_account(solver),
            fake_account(sysvar),
            fake_account(state),
            fake_account(spl_token_program),
            fake_account(token_2022_program),
        ];
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0x37, 0x13],             // finalize index, little-endian
            hex!("0807060504030201"), // auction id, little-endian
            [0x00],                   // order count
        ];
        let BeginSettleInput {
            finalize_ix_index,
            auction_id,
            solver_account,
            instructions_sysvar_account,
            orders,
            state_pda_account,
        } = BeginSettleInput::parse(&data, &accounts).expect("parse should succeed");
        assert_eq!(finalize_ix_index, 0x1337);
        assert_eq!(auction_id, 0x0102_0304_0506_0708);
        assert_eq!(instructions_sysvar_account.address(), &sysvar);
        assert_eq!(orders.iter().count(), 0);
        assert_eq!(state_pda_account.address(), &state);
        assert_eq!(solver_account.address(), &solver);
    }

    #[test]
    fn begin_settle_input_rejects_different_discriminator() {
        let data = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [0, 0], // finalize index
        ];
        let accounts: [AccountView; 0] = [];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn begin_settle_input_rejects_empty_accounts() {
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0], // finalize index
        ];
        let accounts: [AccountView; 0] = [];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::NotEnoughAccountKeys),
        );
    }

    #[test]
    fn begin_settle_input_rejects_missing_auction_id() {
        // The body carries the finalize index but fewer than eight bytes for the
        // auction id, so parsing can't recover it.
        let accounts = fake_sequential_accounts::<FIXED_ACCOUNTS>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],             // finalize index
            [0x01, 0x02, 0x03], // a partial (3-byte) auction id
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn begin_settle_input_pairs_orders_with_their_accounts() {
        let sysvar = pubkey_from_seed("sysvar");
        let state = pubkey_from_seed("state pda");
        let spl_token_program = pubkey_from_seed("spl token program");
        let token_2022_program = pubkey_from_seed("token 2022 program");
        let solver = pubkey_from_seed("solver");
        let order_pda = pubkey_from_seed("order pda");
        let sell_token = pubkey_from_seed("sell token");
        let sell_mint = pubkey_from_seed("sell mint");
        let accounts = [
            fake_account(solver),
            fake_account(sysvar),
            fake_account(state),
            fake_account(spl_token_program),
            fake_account(token_2022_program),
            fake_account(order_pda),
            fake_account(sell_token),
            fake_account(sell_mint),
        ];
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0x37, 0x13],             // finalize index, little-endian
            AUCTION_ID.to_le_bytes(), // auction id, little-endian
            [0x01],                   // order count
            [0x00],                   // that order's transfer count
        ];
        let BeginSettleInput {
            finalize_ix_index,
            auction_id,
            solver_account,
            instructions_sysvar_account,
            orders,
            state_pda_account,
        } = BeginSettleInput::parse(&data, &accounts).expect("parse should succeed");
        assert_eq!(finalize_ix_index, 0x1337);
        assert_eq!(auction_id, AUCTION_ID);
        assert_eq!(instructions_sysvar_account.address(), &sysvar);
        assert_eq!(state_pda_account.address(), &state);
        assert_eq!(solver_account.address(), &solver);

        let mut orders = orders.iter();
        let order = orders.next().expect("one settled order");
        assert_eq!(order.order_pda.address(), &order_pda);
        assert_eq!(order.sell_token_account.address(), &sell_token);
        assert_eq!(mint_address(order.sell_mint), &sell_mint);
        assert_eq!(order.destinations.len(), 0);
        assert!(orders.next().is_none());
    }

    #[test]
    fn begin_settle_input_parses_transfers() {
        let sysvar = pubkey_from_seed("sysvar");
        let state = pubkey_from_seed("state pda");
        let spl_token_program = pubkey_from_seed("spl token program");
        let token_2022_program = pubkey_from_seed("token 2022 program");
        let solver = pubkey_from_seed("solver");
        let order_pda = pubkey_from_seed("order pda");
        let sell_token = pubkey_from_seed("sell token");
        let sell_mint = pubkey_from_seed("sell mint");
        let dest0 = pubkey_from_seed("destination 0");
        let dest1 = pubkey_from_seed("destination 1");
        let accounts = [
            fake_account(solver),
            fake_account(sysvar),
            fake_account(state),
            fake_account(spl_token_program),
            fake_account(token_2022_program),
            fake_account(order_pda),
            fake_account(sell_token),
            fake_account(sell_mint),
            fake_account(dest0),
            fake_account(dest1),
        ];
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0x37, 0x13],             // finalize index, little-endian
            AUCTION_ID.to_le_bytes(), // auction id, little-endian
            [0x01],                   // order count
            [0x02],                   // transfer count
            0x1122u64.to_le_bytes(),
            0x3344u64.to_le_bytes(),
        ];

        let BeginSettleInput { orders, .. } =
            BeginSettleInput::parse(&data, &accounts).expect("parse should succeed");

        let mut orders = orders.iter();
        let order = orders.next().expect("one settled order");
        assert_eq!(order.order_pda.address(), &order_pda);
        assert_eq!(order.sell_token_account.address(), &sell_token);
        assert_eq!(mint_address(order.sell_mint), &sell_mint);
        let transfers: Vec<(&Address, u64)> = order
            .destinations
            .iter()
            .zip(order.amounts)
            .map(|(destination, amount)| (destination.address(), u64::from_le_bytes(*amount)))
            .collect();
        assert_eq!(transfers, vec![(&dest0, 0x1122), (&dest1, 0x3344)]);
        assert!(orders.next().is_none());
    }

    #[test]
    fn begin_settle_input_pairs_every_order_with_its_sell_token_account() {
        const ORDER_COUNT: usize = 16;

        let mut expected: Vec<(Address, Address, Address)> = Vec::new();
        for i in 0..ORDER_COUNT {
            let order_pda = pubkey_from_seed(&format!("order pda {i}"));
            let sell_token = pubkey_from_seed(&format!("sell token {i}"));
            let sell_mint = pubkey_from_seed(&format!("sell mint {i}"));
            expected.push((order_pda, sell_token, sell_mint));
        }

        // The fixed accounts (`[0xff..]` down to `[0xfb..]`) differ from every
        // order/token address above.
        let mut accounts = vec![
            fake_account_from_array([0xff; 32]),
            fake_account_from_array([0xfe; 32]),
            fake_account_from_array([0xfd; 32]),
            fake_account_from_array([0xfc; 32]),
            fake_account_from_array([0xfb; 32]),
        ];
        for &(order_pda, sell_token, sell_mint) in &expected {
            accounts.push(fake_account(order_pda));
            accounts.push(fake_account(sell_token));
            accounts.push(fake_account(sell_mint));
        }
        // Grouped data: discriminator, finalize index, auction id, order count,
        // then all transfer counts (every order has zero transfers).
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0x37, 0x13],             // finalize index, little-endian
            AUCTION_ID.to_le_bytes(), // auction id, little-endian
            [ORDER_COUNT as u8],      // order count
            [0u8; ORDER_COUNT],
        ];

        let parsed = BeginSettleInput::parse(&data, &accounts).expect("parse should succeed");

        let actual: Vec<(Address, Address, Address)> = parsed
            .orders
            .iter()
            .map(|order| {
                assert_eq!(order.destinations.len(), 0);
                (
                    *order.order_pda.address(),
                    *order.sell_token_account.address(),
                    *mint_address(order.sell_mint),
                )
            })
            .collect();
        assert_eq!(actual, expected);
    }

    #[test]
    fn begin_settle_input_rejects_too_few_accounts() {
        // The body declares one order with no transfers, which needs three order
        // accounts (its order PDA, sell token account, and sell mint). Only two
        // are supplied after the fixed accounts, short of the `3n + T` the body
        // implies.
        let accounts = fake_sequential_accounts::<{ FIXED_ACCOUNTS + 2 }>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
            [0x01],                   // order count
            [0x00],                   // the order's transfer count
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(SettlementError::AccountCountNotMatchingOrderCount.into()),
        );
    }

    #[test]
    fn begin_settle_input_rejects_too_many_accounts() {
        // One order with one transfer takes four order accounts, but five are
        // supplied after the fixed accounts.
        let accounts = fake_sequential_accounts::<{ FIXED_ACCOUNTS + 5 }>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
            [0x01],                   // order count
            [0x01],                   // the order's transfer count
            0x1122u64.to_le_bytes(),
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(SettlementError::AccountCountNotMatchingOrderCount.into()),
        );
    }

    #[test]
    fn begin_settle_input_rejects_counts_not_summing_to_destinations() {
        // One order with two amounts (T = 2) and its five accounts (order PDA,
        // sell token account, sell mint, and two destinations), but the
        // transfer-count byte claims only one.
        let accounts = fake_sequential_accounts::<{ FIXED_ACCOUNTS + 5 }>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
            [0x01],                   // order count
            [0x01],                   // count says one, but two amounts/destinations exist
            0u64.to_le_bytes(),
            0u64.to_le_bytes(),
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(SettlementError::TransferCountMismatch.into()),
        );
    }

    #[test]
    fn begin_settle_input_rejects_missing_order_count() {
        // The body carries the finalize index and auction id but no order-count
        // byte, so the pull layout can't even begin to be parsed.
        let accounts = fake_sequential_accounts::<FIXED_ACCOUNTS>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn begin_settle_input_rejects_body_too_short_for_counts() {
        // The order count claims two orders, but only one transfer-count byte
        // follows, so the counts can't be split off.
        let accounts = fake_sequential_accounts::<FIXED_ACCOUNTS>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
            [0x02],                   // order count: two orders...
            [0x00],                   // ...but only one transfer-count byte
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn begin_settle_input_rejects_partial_amount() {
        // One order with no transfers, but four trailing bytes that don't form a
        // whole `u64` amount.
        let accounts = fake_sequential_accounts::<FIXED_ACCOUNTS>();
        let data = ix_data![
            [SettlementInstruction::BeginSettle.discriminator()],
            [0, 0],                   // finalize index
            AUCTION_ID.to_le_bytes(), // auction id
            [0x01],                   // order count
            [0x00],                   // transfer count
            [0x11, 0x22, 0x33, 0x44], // a partial (4-byte) amount
        ];
        assert_eq!(
            BeginSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }
}