cow-settlement-interface 0.1.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
//! 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, INSTRUCTIONS_SYSVAR_ID, SPL_TOKEN_PROGRAM_ID};

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

/// 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 push amounts, in push order, carried by a `FinalizeSettle` instruction,
/// 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_amounts(
    instruction_data: &[u8],
) -> Result<impl Iterator<Item = u64> + '_, ProgramError> {
    let (_discriminator, rest) = recover_discriminator(instruction_data)?;
    let (_begin_ix_index, body) = recover_counterpart(rest)?;
    let (_bumps, amounts) = split_pushes(body)?;
    Ok(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), token_program (R)]` followed, per
/// push, by `[source_buffer (W), destination (W)]`.
///
/// `FinalizeSettle` validates that each source is the canonical buffer for its
/// destination's mint and executes the transfers; the order correspondence and
/// that each destination is an order's buy token account are `BeginSettle`'s
/// checks. So a push isn't aware of what orders are being paid, just the accounts
/// to move funds between, the source's bump, and the amount. The same buffer may
/// legitimately fund several pushes.
pub struct FinalizeSettle<'a> {
    pub program_id: Pubkey,
    pub state_pda: Pubkey,
    pub begin_ix_index: u16,
    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,
            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),
            AccountMeta::new_readonly(SPL_TOKEN_PROGRAM_ID, 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.
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 token_program_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 mut [A]) -> Result<Self, ProgramError> {
        let (begin_ix_index, body) = recover_counterpart(instruction_data)?;

        let [instructions_sysvar_account, state_pda_account, token_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,
            token_program_account,
            pushes: Pushes {
                push_accounts,
                bumps,
                amounts,
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    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 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::new_unique(),
            state_pda: Pubkey::new_unique(),
            begin_ix_index: 0,
            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::new_unique();
        let state_pda = Pubkey::new_unique();
        let Instruction {
            program_id: ix_program_id,
            accounts,
            data,
        } = FinalizeSettle {
            program_id,
            state_pda,
            begin_ix_index: 0x1337,
            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 three fixed accounts (sysvar, state PDA, 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).
        assert_eq!(accounts.len(), 3);
        assert_readonly_nonsigner(&accounts[0], INSTRUCTIONS_SYSVAR_ID);
        assert_readonly_nonsigner(&accounts[1], state_pda);
        assert_readonly_nonsigner(&accounts[2], SPL_TOKEN_PROGRAM_ID);
    }

    #[test]
    fn finalize_settle_encodes_pushes() {
        let program_id = Pubkey::new_unique();
        let state_pda = Pubkey::new_unique();
        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,
            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,
                SPL_TOKEN_PROGRAM_ID,
                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 = Address::new_from_array([0x42u8; 32]);
        // The state-PDA and token-program slots are reserved but not surfaced.
        let state = Address::new_from_array([0x43u8; 32]);
        let token_program = Address::new_from_array([0x44u8; 32]);
        let mut accounts = [
            fake_account(sysvar),
            fake_account(state),
            fake_account(token_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,
            token_program_account,
            pushes,
        } = FinalizeSettleInput::parse(&data, &mut 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!(token_program_account.address(), &token_program);
        assert_eq!(pushes.iter().count(), 0);
    }

    #[test]
    fn finalize_settle_input_parses_pushes() {
        let sysvar = Address::new_from_array([1u8; 32]);
        let state = Address::new_from_array([0xa1u8; 32]);
        let token_program = Address::new_from_array([0xa2u8; 32]);
        // The same source buffer funds both pushes: parsing makes no uniqueness
        // assumption about source buffers.
        let source = Address::new_from_array([3u8; 32]);
        let dest0 = Address::new_from_array([4u8; 32]);
        let dest1 = Address::new_from_array([5u8; 32]);
        let mut accounts = [
            fake_account(sysvar),
            fake_account(state),
            fake_account(token_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, &mut 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 = Address::new_from_array([i as u8; 32]);
            let dest = Address::new_from_array([(i + PUSH_COUNT) as u8; 32]);
            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 three fixed accounts (`[0xff..]`, `[0xfe..]`, `[0xfd..]`) 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]),
        ];
        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, &mut 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 mut accounts: [AccountView; 0] = [];
        assert_eq!(
            FinalizeSettleInput::parse(&data, &mut 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 mut accounts: [AccountView; 0] = [];
        assert_eq!(
            FinalizeSettleInput::parse(&data, &mut 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 mut too_few = fake_sequential_accounts::<{ FINALIZE_FIXED_ACCOUNTS + 1 }>();
        assert_eq!(
            FinalizeSettleInput::parse(&data, &mut too_few).err(),
            Some(SettlementError::AccountCountNotMatchingPushCount.into()),
        );

        // Too many: three push accounts follow the fixed accounts.
        let mut too_many = fake_sequential_accounts::<{ FINALIZE_FIXED_ACCOUNTS + 3 }>();
        assert_eq!(
            FinalizeSettleInput::parse(&data, &mut 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 mut 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, &mut accounts).err(),
            Some(ProgramError::InvalidInstructionData),
        );
    }

    #[test]
    fn finalize_push_amounts_extracts_amounts() {
        let amounts = [0x0102, 0x0304];
        let ix = Instruction::from(FinalizeSettle {
            program_id: Pubkey::new_unique(),
            state_pda: Pubkey::new_unique(),
            begin_ix_index: 0x1337,
            source_buffers: &[Pubkey::new_unique(), Pubkey::new_unique()],
            destinations: &[Pubkey::new_unique(), Pubkey::new_unique()],
            bumps: &[0xa1, 0xb1],
            amounts: &amounts,
        });

        let recovered = finalize_push_amounts(&ix.data).expect("valid finalize data");
        let decoded: Vec<u64> = recovered.collect();
        assert_eq!(decoded, amounts);
    }

    #[test]
    fn finalize_push_amounts_handles_no_pushes() {
        let ix = Instruction::from(FinalizeSettle {
            program_id: Pubkey::new_unique(),
            state_pda: Pubkey::new_unique(),
            begin_ix_index: 0,
            source_buffers: &[],
            destinations: &[],
            bumps: &[],
            amounts: &[],
        });
        let mut amounts = finalize_push_amounts(&ix.data).expect("valid empty finalize data");
        assert!(amounts.next().is_none());
    }

    #[test]
    fn finalize_push_amounts_rejects_incorrect_bytes() {
        let mut ix = Instruction::from(FinalizeSettle {
            program_id: Pubkey::new_unique(),
            state_pda: Pubkey::new_unique(),
            begin_ix_index: 0,
            source_buffers: &[Pubkey::new_unique()],
            destinations: &[Pubkey::new_unique()],
            bumps: &[0xff],
            amounts: &[31337],
        });
        ix.data.pop();
        assert_eq!(
            finalize_push_amounts(&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,
                        source_buffers: &source_buffers,
                        destinations: &destinations,
                        bumps: &bumps,
                        amounts: &amounts,
                    })
                },
            )
    }

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

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

            prop_assert_eq!(recovered, parsed_amounts);
        }
    }
}