cow-settlement-interface 0.4.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
//! Off-chain builder and input parsing for the `FinalizeSettle` instruction.

use std::vec;

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

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

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

/// The number of fixed accounts every `FinalizeSettle` carries before its push
/// accounts: the instructions sysvar, the settlement state PDA, and one slot per
/// supported token program.
pub const FINALIZE_FIXED_ACCOUNTS: usize = 4;

/// Split the instruction bytes from `FinalizeSettle` that remain after all
/// constant-size data has been extracted into the per-push bump bytes and the
/// raw little-endian amount chunks.
fn split_push_bytes(body: &[u8]) -> Result<(&[u8], &[[u8; 8]]), ProgramError> {
    // The body is `9 * n` bytes: `n` bump bytes followed by `n` little-endian
    // `u64` amounts. A body that isn't a whole number of these 9-byte pushes
    // can't be parsed into the push layout (and would otherwise leave `bumps`
    // and `amounts` with mismatched lengths).
    if !body.len().is_multiple_of(9) {
        return Err(ProgramError::InvalidInstructionData);
    }
    let push_count = body.len() / 9;
    let (bumps, amount_bytes) = body.split_at(push_count);
    let (amounts, []) = amount_bytes.as_chunks::<8>() else {
        return Err(ProgramError::InvalidInstructionData);
    };
    Ok((bumps, amounts))
}

/// Like [`split_push_bytes`], but yields the amounts already decoded as `u64`s
/// so callers streaming the amounts don't each re-decode the little-endian
/// bytes. The decoding is lazy, so nothing is allocated.
fn split_pushes(body: &[u8]) -> Result<(&[u8], impl Iterator<Item = u64> + '_), ProgramError> {
    let (bumps, amounts) = split_push_bytes(body)?;
    Ok((bumps, amounts.iter().copied().map(u64::from_le_bytes)))
}

/// The per-push data — each push's source-buffer `bump` paired with the `amount`
/// it pays — in push order, carried by a `FinalizeSettle` instruction and
/// recovered from its full instruction data alone (discriminator included, as
/// returned by instruction introspection).
///
/// This function doesn't otherwise check that the instruction is consistent
/// with a `FinalizeSettle` instruction. For example, the discriminator field is
/// ignored.
pub fn finalize_push_data(
    instruction_data: &[u8],
) -> Result<impl Iterator<Item = (u8, u64)> + '_, ProgramError> {
    let (_discriminator, rest) = recover_discriminator(instruction_data)?;
    let (_begin_ix_index, body) = recover_counterpart(rest)?;
    let (bumps, amounts) = split_pushes(body)?;
    Ok(bumps.iter().copied().zip(amounts))
}

/// Builder for a `FinalizeSettle` instruction pushing the funds described by the
/// parallel lists:
/// - `source_buffers[i]` is the buffer token account the funds come from,
/// - `destinations[i]` is the account the funds go to (an order's buy token
///   account),
/// - `bumps[i]` is the canonical bump of `source_buffers[i]`, so the program
///   re-derives the buffer PDA with one hash instead of searching,
/// - `amounts[i]` is the amount to push.
///
/// This instruction comes in pair with a `BeginSettle` instruction. The slices
/// are assumed to be built in parallel with the order information specified in
/// `BeginSettle`. Notably, (1) the source buffer is the one corresponding to
/// the order's buy token, and (2) the destinations must be the buy token
/// accounts specified in the corresponding order.
/// The slices are assumed to have the same length but this is not enforced by
/// the builder.
///
/// Wire format (with `n` total pushes):
/// `[discriminator=1][begin_ix_index: u16 LE][bump: u8 ×n][amount: u64 LE ×n]`.
/// Required accounts:
/// `[instructions_sysvar (R), state_pda (R), spl_token_program (R),
/// token_2022_program (R)]` followed, per push, by `[source_buffer (W),
/// destination (W)]`. The two token programs are the slots
/// [`TokenProgram::ALL`] describes, there to name the programs this
/// instruction's pushes are issued against; the matching `BeginSettle` carries
/// the ones its pulls need.
///
/// `FinalizeSettle` only executes the transfers. Every push is validated by
/// `BeginSettle`, which reads this instruction through introspection.
pub struct FinalizeSettle<'a> {
    pub program_id: Pubkey,
    pub state_pda: Pubkey,
    pub begin_ix_index: u16,
    /// 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 source_buffers: &'a [Pubkey],
    pub destinations: &'a [Pubkey],
    pub bumps: &'a [u8],
    pub amounts: &'a [u64],
}

impl From<FinalizeSettle<'_>> for Instruction {
    fn from(builder: FinalizeSettle<'_>) -> Self {
        let FinalizeSettle {
            program_id,
            state_pda,
            begin_ix_index,
            only_token_program,
            source_buffers,
            destinations,
            bumps,
            amounts,
        } = builder;

        let data: Vec<u8> = core::iter::once(SettlementInstruction::FinalizeSettle.discriminator())
            .chain(begin_ix_index.to_le_bytes())
            .chain(bumps.iter().copied())
            .chain(amounts.iter().flat_map(|amount| amount.to_le_bytes()))
            .collect();

        let mut accounts = vec![
            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 (source, destination) in source_buffers.iter().zip(destinations) {
            accounts.push(AccountMeta::new(*source, false));
            accounts.push(AccountMeta::new(*destination, false));
        }

        Instruction {
            program_id,
            accounts,
            data,
        }
    }
}

/// A single fund push parsed from `FinalizeSettle`: move `amount` from
/// `source_buffer` to `destination`. `bump` is `source_buffer`'s claimed
/// canonical buffer bump, which the program re-derives against.
#[derive(Debug, PartialEq, Eq)]
pub struct Push<'a, A> {
    pub source_buffer: &'a A,
    pub destination: &'a A,
    pub bump: u8,
    pub amount: u64,
}

/// Struct storing accounts, bumps, and amounts from parsing the input of
/// `FinalizeSettle`, laid out as a flat list of `[source_buffer, destination]`
/// account pairs parallel to `bumps` and `amounts`. The parsing step that created
/// this struct guarantees `push_accounts.len() == 2 * amounts.len()` and
/// `bumps.len() == amounts.len()`, so the offsets below never run short.
pub struct Pushes<'a, A> {
    /// `[source_buffer, destination]` per push, flattened.
    push_accounts: &'a [A],
    bumps: &'a [u8],
    /// One push amount (little-endian `u64`) per push, parallel to `bumps`.
    amounts: &'a [[u8; 8]],
}

impl<'a, A> Pushes<'a, A> {
    /// Returns an iterator yielding one [`Push`] per step.
    #[allow(
        clippy::arithmetic_side_effects,
        reason = "offsets are bounded by tx limits"
    )]
    pub fn iter(&self) -> impl Iterator<Item = Push<'a, A>> + '_ {
        let push_count = self.bumps.len();
        let mut i = 0usize;
        let mut account_offset = 0usize;
        std::iter::from_fn(move || {
            if i >= push_count {
                return None;
            }
            let bump = self.bumps[i];
            let amount = u64::from_le_bytes(self.amounts[i]);
            i += 1;

            let source_buffer = &self.push_accounts[account_offset];
            let destination = &self.push_accounts[account_offset + 1];
            account_offset += 2;

            Some(Push {
                source_buffer,
                destination,
                bump,
                amount,
            })
        })
    }
}

/// Parsed inputs (instruction-data fields + relevant accounts) of a
/// `FinalizeSettle` 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 amounts is consistent.
pub struct FinalizeSettleInput<'a, A> {
    pub begin_ix_index: u16,
    pub instructions_sysvar_account: &'a A,
    pub state_pda_account: &'a A,
    pub pushes: Pushes<'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 FinalizeSettleInput<'a, A> {
    const DISCRIMINATOR: SettlementInstruction = SettlementInstruction::FinalizeSettle;

    fn parse_body(instruction_data: &'a [u8], accounts: &'a [A]) -> Result<Self, ProgramError> {
        let (begin_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 [instructions_sysvar_account, state_pda_account, _spl_token_program_account, _token_2022_program_account, push_accounts @ ..] =
            accounts
        else {
            return Err(ProgramError::NotEnoughAccountKeys);
        };

        let (bumps, amounts) = split_push_bytes(body)?;
        let push_count = bumps.len();

        // Each push contributes a source buffer and a destination account, so
        // the push-account count is `2 * n`.
        let expected_accounts = push_count
            .checked_mul(2)
            .ok_or(ProgramError::InvalidInstructionData)?;
        if push_accounts.len() != expected_accounts {
            return Err(SettlementError::AccountCountNotMatchingPushCount.into());
        }

        Ok(Self {
            begin_ix_index,
            instructions_sysvar_account,
            state_pda_account,
            pushes: Pushes {
                push_accounts,
                bumps,
                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;
    use crate::instruction::tests::assert_readonly_nonsigner;
    use crate::token_program::TokenProgram;
    use hex_literal::hex;
    use proptest::prelude::*;
    use solana_account_view::AccountView;
    use solana_address::Address;

    #[test]
    fn finalize_fixed_accounts_matches_builder() {
        // A no-push finalize carries exactly the fixed accounts, so the constant
        // must equal the account count the builder emits with no pushes.
        let ix = Instruction::from(FinalizeSettle {
            program_id: pubkey_from_seed("program id"),
            state_pda: pubkey_from_seed("state pda"),
            begin_ix_index: 0,
            only_token_program: None,
            source_buffers: &[],
            destinations: &[],
            bumps: &[],
            amounts: &[],
        });
        assert_eq!(ix.accounts.len(), FINALIZE_FIXED_ACCOUNTS);
    }

    #[test]
    fn expected_encoding_finalize_settle_no_pushes() {
        let program_id = pubkey_from_seed("program id");
        let state_pda = pubkey_from_seed("state pda");
        let Instruction {
            program_id: ix_program_id,
            accounts,
            data,
        } = FinalizeSettle {
            program_id,
            state_pda,
            begin_ix_index: 0x1337,
            only_token_program: None,
            source_buffers: &[],
            destinations: &[],
            bumps: &[],
            amounts: &[],
        }
        .into();
        assert_eq!(ix_program_id, program_id);
        assert_eq!(
            data,
            ix_data![
                [SettlementInstruction::FinalizeSettle.discriminator()],
                hex!("3713"), // counterpart index (little-endian)
            ],
        );
        // No orders: the fixed accounts (sysvar, state PDA, and a slot per token
        // program). They are all generic accounts that 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(), FINALIZE_FIXED_ACCOUNTS);
        assert_readonly_nonsigner(&accounts[0], INSTRUCTIONS_SYSVAR_ID);
        assert_readonly_nonsigner(&accounts[1], state_pda);
        assert_readonly_nonsigner(&accounts[2], TokenProgram::SplToken.address());
        assert_readonly_nonsigner(&accounts[3], 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 finalize_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 ix = Instruction::from(FinalizeSettle {
                program_id: Pubkey::new_unique(),
                state_pda: Pubkey::new_unique(),
                begin_ix_index: 0,
                only_token_program,
                source_buffers: &[],
                destinations: &[],
                bumps: &[],
                amounts: &[],
            });
            let slots: Vec<Pubkey> = ix.accounts[2..].iter().map(|meta| meta.pubkey).collect();
            assert_eq!(
                slots, expected,
                "{only_token_program:?} should name just the programs it settles against",
            );
        }
    }

    #[test]
    fn finalize_settle_encodes_pushes() {
        let program_id = pubkey_from_seed("program id");
        let state_pda = pubkey_from_seed("state pda");
        let source_a = Pubkey::new_from_array([0x01; 32]);
        let dest_a = Pubkey::new_from_array([0x02; 32]);
        let source_b = Pubkey::new_from_array([0x03; 32]);
        let dest_b = Pubkey::new_from_array([0x04; 32]);

        let ix = Instruction::from(FinalizeSettle {
            program_id,
            state_pda,
            begin_ix_index: 0x1337,
            only_token_program: None,
            source_buffers: &[source_a, source_b],
            destinations: &[dest_a, dest_b],
            bumps: &[0xa1, 0xb1],
            amounts: &[0x01020304, 0x05060708],
        });

        assert_eq!(
            ix.data,
            ix_data![
                [SettlementInstruction::FinalizeSettle.discriminator()],
                hex!("3713"), // counterpart index (little-endian)
                [0xa1, 0xb1], // bumps
                // amounts (little-endian)
                hex!("0403020100000000"),
                hex!("0807060500000000"),
            ],
        );

        let actual: Vec<Pubkey> = ix.accounts.iter().map(|meta| meta.pubkey).collect();
        assert_eq!(
            actual,
            vec![
                INSTRUCTIONS_SYSVAR_ID,
                state_pda,
                TokenProgram::SplToken.address(),
                TokenProgram::Token2022.address(),
                source_a,
                dest_a,
                source_b,
                dest_b,
            ],
        );
        // The fixed accounts are read-only; the source buffers and destinations
        // are writable for the transfers.
        let writable: Vec<Pubkey> = ix
            .accounts
            .iter()
            .filter(|meta| meta.is_writable)
            .map(|meta| meta.pubkey)
            .collect();
        assert_eq!(writable, vec![source_a, dest_a, source_b, dest_b]);
        assert!(ix.accounts.iter().all(|meta| !meta.is_signer));
    }

    #[test]
    fn finalize_settle_input_parses_no_pushes() {
        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 accounts = [
            fake_account(sysvar),
            fake_account(state),
            fake_account(spl_token_program),
            fake_account(token_2022_program),
        ];
        let data = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [0x37, 0x13], // begin index, little-endian
        ];
        let FinalizeSettleInput {
            begin_ix_index,
            instructions_sysvar_account,
            state_pda_account,
            pushes,
        } = FinalizeSettleInput::parse(&data, &accounts).expect("parse should succeed");
        assert_eq!(begin_ix_index, 0x1337);
        assert_eq!(instructions_sysvar_account.address(), &sysvar);
        assert_eq!(state_pda_account.address(), &state);
        assert_eq!(pushes.iter().count(), 0);
    }

    #[test]
    fn finalize_settle_input_parses_pushes() {
        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");
        // The same source buffer funds both pushes: parsing makes no uniqueness
        // assumption about source buffers.
        let source = pubkey_from_seed("source buffer");
        let dest0 = pubkey_from_seed("destination 0");
        let dest1 = pubkey_from_seed("destination 1");
        let accounts = [
            fake_account(sysvar),
            fake_account(state),
            fake_account(spl_token_program),
            fake_account(token_2022_program),
            fake_account(source),
            fake_account(dest0),
            fake_account(source),
            fake_account(dest1),
        ];
        let data = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [0x13, 0x37], // begin index
            [0xfe, 0xfd], // bumps
            0x1122u64.to_le_bytes(),
            0x3344u64.to_le_bytes(),
        ];

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

        let parsed: Vec<(&Address, &Address, u8, u64)> = pushes
            .iter()
            .map(|push| {
                (
                    push.source_buffer.address(),
                    push.destination.address(),
                    push.bump,
                    push.amount,
                )
            })
            .collect();
        assert_eq!(
            parsed,
            vec![
                (&source, &dest0, 0xfe, 0x1122),
                (&source, &dest1, 0xfd, 0x3344),
            ],
        );
    }

    #[test]
    fn finalize_settle_input_parses_many_pushes() {
        const PUSH_COUNT: usize = 16;

        struct ExpectedPush {
            source: Address,
            dest: Address,
            bump: u8,
            amount: u64,
        }
        let mut expected: Vec<ExpectedPush> = Vec::new();
        for i in 0..PUSH_COUNT {
            let source = pubkey_from_seed(&format!("source buffer {i}"));
            let dest = pubkey_from_seed(&format!("destination {i}"));
            let bump = (i + 2 * PUSH_COUNT) as u8;
            let amount = u64::from_le_bytes([(i + 3 * PUSH_COUNT) as u8; 8]);
            expected.push(ExpectedPush {
                source,
                dest,
                bump,
                amount,
            });
        }

        // The fixed accounts (`[0xff..]` down to `[0xfc..]`) differ from every
        // source/destination 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]),
        ];
        let mut bump_bytes = Vec::new();
        let mut amount_bytes = Vec::new();
        for push in &expected {
            accounts.push(fake_account(push.source));
            accounts.push(fake_account(push.dest));
            bump_bytes.push(push.bump);
            amount_bytes.extend_from_slice(&push.amount.to_le_bytes());
        }
        let data = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [0x13, 0x37], // begin index
            bump_bytes,
            amount_bytes,
        ];

        let parsed = FinalizeSettleInput::parse(&data, &accounts).expect("parse should succeed");
        let pushes: Vec<_> = parsed.pushes.iter().collect();

        assert_eq!(pushes.len(), PUSH_COUNT);
        for (push, expected) in pushes.iter().zip(&expected) {
            assert_eq!(push.source_buffer.address(), &expected.source);
            assert_eq!(push.destination.address(), &expected.dest);
            assert_eq!(push.bump, expected.bump);
            assert_eq!(push.amount, expected.amount);
        }
    }

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

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

    #[test]
    fn finalize_settle_input_rejects_account_count_mismatch() {
        // One push (a bump byte then a `u64` amount) needs exactly two push
        // accounts: its source buffer and destination.
        let data: Vec<u8> = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [13, 37], // begin index
            [0xff],   // the push's bump
            31337u64.to_le_bytes(),
        ];

        // Too few: only one push account follows the fixed accounts.
        let too_few = fake_sequential_accounts::<{ FINALIZE_FIXED_ACCOUNTS + 1 }>();
        assert_eq!(
            FinalizeSettleInput::parse(&data, &too_few).err(),
            Some(SettlementError::AccountCountNotMatchingPushCount.into()),
        );

        // Too many: three push accounts follow the fixed accounts.
        let too_many = fake_sequential_accounts::<{ FINALIZE_FIXED_ACCOUNTS + 3 }>();
        assert_eq!(
            FinalizeSettleInput::parse(&data, &too_many).err(),
            Some(SettlementError::AccountCountNotMatchingPushCount.into()),
        );
    }

    #[test]
    fn finalize_settle_input_rejects_partial_push() {
        // Four trailing bytes: not a whole number of 9-byte pushes (a bump plus a
        // `u64` amount), so the body can't be parsed into the push layout.
        let accounts = fake_sequential_accounts::<FINALIZE_FIXED_ACCOUNTS>();
        let data = ix_data![
            [SettlementInstruction::FinalizeSettle.discriminator()],
            [37, 13],                 // begin index
            [0xff],                   // the push's bump
            [0x11, 0x22, 0x33, 0x44], // a partial push (4 bytes)
        ];
        assert_eq!(
            FinalizeSettleInput::parse(&data, &accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn finalize_push_data_extracts_bumps_and_amounts() {
        let bumps = [0xa1, 0xb1];
        let amounts = [0x0102, 0x0304];
        let ix = Instruction::from(FinalizeSettle {
            program_id: pubkey_from_seed("program id"),
            state_pda: pubkey_from_seed("state pda"),
            begin_ix_index: 0x1337,
            only_token_program: None,
            source_buffers: &[
                pubkey_from_seed("source buffer 0"),
                pubkey_from_seed("source buffer 1"),
            ],
            destinations: &[
                pubkey_from_seed("destination 0"),
                pubkey_from_seed("destination 1"),
            ],
            bumps: &bumps,
            amounts: &amounts,
        });

        let recovered = finalize_push_data(&ix.data).expect("valid finalize data");
        let decoded: Vec<(u8, u64)> = recovered.collect();
        assert_eq!(decoded, [(0xa1, 0x0102), (0xb1, 0x0304)]);
    }

    #[test]
    fn finalize_push_data_handles_no_pushes() {
        let ix = Instruction::from(FinalizeSettle {
            program_id: pubkey_from_seed("program id"),
            state_pda: pubkey_from_seed("state pda"),
            begin_ix_index: 0,
            only_token_program: None,
            source_buffers: &[],
            destinations: &[],
            bumps: &[],
            amounts: &[],
        });
        let mut pushes = finalize_push_data(&ix.data).expect("valid empty finalize data");
        assert!(pushes.next().is_none());
    }

    #[test]
    fn finalize_push_data_rejects_incorrect_bytes() {
        let mut ix = Instruction::from(FinalizeSettle {
            program_id: pubkey_from_seed("program id"),
            state_pda: pubkey_from_seed("state pda"),
            begin_ix_index: 0,
            only_token_program: None,
            source_buffers: &[pubkey_from_seed("source buffer")],
            destinations: &[pubkey_from_seed("destination")],
            bumps: &[0xff],
            amounts: &[31337],
        });
        ix.data.pop();
        assert_eq!(
            finalize_push_data(&ix.data).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    /// An arbitrary well-formed `FinalizeSettle` instruction with `push_count`
    /// pushes.
    fn arb_finalize_instruction(
        push_count: impl Into<prop::collection::SizeRange>,
    ) -> impl Strategy<Value = Instruction> {
        (
            any::<[u8; 32]>().prop_map(Pubkey::new_from_array),
            any::<[u8; 32]>().prop_map(Pubkey::new_from_array),
            any::<u16>(),
            crate::instruction::settle::fixtures::arb_pushes(push_count),
        )
            .prop_map(
                |(
                    program_id,
                    state_pda,
                    begin_ix_index,
                    (source_buffers, destinations, bumps, amounts),
                )| {
                    Instruction::from(FinalizeSettle {
                        program_id,
                        state_pda,
                        begin_ix_index,
                        only_token_program: None,
                        source_buffers: &source_buffers,
                        destinations: &destinations,
                        bumps: &bumps,
                        amounts: &amounts,
                    })
                },
            )
    }

    proptest! {
        /// For any well-formed `FinalizeSettle`, the bumps and amounts
        /// `finalize_push_data` recovers from the instruction data alone (the way
        /// `BeginSettle` sees it through introspection) must equal what the full
        /// `FinalizeSettleInput` parser reads from the same data plus its accounts.
        #[test]
        fn finalize_push_data_matches_parser(ix in arb_finalize_instruction(0..=16usize)) {
            // Recovered from the instruction data alone.
            let recovered: Vec<(u8, u64)> =
                finalize_push_data(&ix.data).expect("well-formed finalize data").collect();

            // Read by the full parser from the same data plus its accounts.
            let accounts: Vec<AccountView> =
                ix.accounts.iter().map(|meta| fake_account(meta.pubkey)).collect();
            let parsed = FinalizeSettleInput::parse(&ix.data, &accounts)
                .expect("a well-formed finalize parses");
            let parsed_pushes: Vec<(u8, u64)> =
                parsed.pushes.iter().map(|push| (push.bump, push.amount)).collect();

            prop_assert_eq!(recovered, parsed_pushes);
        }
    }
}