cow-settlement-interface 0.3.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
//! Order PDA bodies and their canonical byte representation.
//!
//! The settlement program stores each authenticated order in a dedicated
//! program-derived account. That account's data area is laid out here.
//!
//! Two types live in this module:
//!
//! - [`OrderAccount`] is the idiomatic Rust representation. Every value is
//!   valid by construction: `cancelled` is a `bool`, `intent` is a fully
//!   decoded [`OrderIntent`].
//! - [`EncodedOrderAccount`] is its canonical byte representation, that is,
//!   the exact bytes written to/read from the PDA.
//!
//! Conversion is asymmetric: [`EncodedOrderAccount`]`::from(OrderAccount)`
//! is infallible; decoding raw bytes via [`OrderAccount`]`::try_from`
//! returns `Result` and rejects an out-of-range `cancelled` byte or any
//! intent byte the intent decoder rejects. There is no path that produces
//! an [`OrderAccount`] whose `cancelled` byte or `intent` slot was not
//! validated.

use core::mem::size_of;

use arrayref::{array_refs, mut_array_refs};
use derive_more::Deref;
use solana_account_view::AccountView;
use solana_address::Address;
use solana_hash::Hash;
use solana_program_error::ProgramError;
use solana_pubkey::Pubkey;

use crate::data::intent::{self, EncodedOrderIntent, OrderIntent, OrderKind};
use crate::pda::is_pda_with_signer_seeds;
use crate::pda::order::order_pda_signer_seeds;
use crate::{SettlementAccount, SettlementError};

/// Idiomatic representation of an order PDA's body.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct OrderAccount {
    /// Canonical bump of the PDA this account lives at. Written at creation
    /// time so callers don't need to supply it; see [`Self::load_from_pda`].
    pub bump: u8,

    /// `false` = the order is still active and can be filled; `true` = the
    /// order has been cancelled by the owner and must not be filled.
    pub cancelled: bool,

    /// Cumulative amount of the sell token withdrawn for this order
    /// across settlements. Starts at zero; monotonically increases.
    pub amount_withdrawn: u64,

    /// Cumulative amount of the buy token received for this order
    /// across settlements. Starts at zero; monotonically increases.
    pub amount_received: u64,

    /// Account that funded the rent for this PDA. The rent is refunded
    /// here when the order is cleared.
    pub created_by: Pubkey,

    /// The order intent stored in this PDA.
    pub intent: OrderIntent,
}

impl OrderAccount {
    /// Load and decode the order at the given PDA, and confirm the PDA is
    /// derivable from its own data: both the UID and the bump feeding the
    /// derivation come from the stored body.
    pub fn load_from_pda(
        order_pda: &AccountView,
        program_id: &Address,
    ) -> Result<Self, ProgramError> {
        let (account, uid) = {
            let data = order_pda.try_borrow()?;
            let bytes: &[u8; EncodedOrderAccount::SIZE] = (&*data)
                .try_into()
                .map_err(|_| ProgramError::InvalidAccountData)?;
            EncodedOrderAccount::decode_and_hash(bytes)?
        };

        if !is_pda_with_signer_seeds(
            order_pda.address(),
            program_id,
            order_pda_signer_seeds(&uid, &[account.bump]),
        ) {
            return Err(SettlementError::AccountNotDerivable.into());
        }

        Ok(account)
    }

    /// Whether the order has been filled to the full amount of its exact side,
    /// so no settlement can ever fill it again.
    pub fn is_fully_filled(&self) -> bool {
        let (filled, order_amount) =
            fill_progress(&self.intent, self.amount_withdrawn, self.amount_received);
        filled >= order_amount
    }
}

/// Extract the values relevant for understanding the fill of an order.
/// Returns a tuple. First return value is the amount currently filled, and the second return
/// value is the amount that has been requested to be filled by the intent.
pub fn fill_progress(
    intent: &OrderIntent,
    amount_withdrawn: u64,
    amount_received: u64,
) -> (u64, u64) {
    match intent.flags.kind {
        OrderKind::Sell => (amount_withdrawn, intent.sell_amount),
        OrderKind::Buy => (amount_received, intent.buy_amount),
    }
}

/// Canonical 264-byte representation of an [`OrderAccount`]. The bytes
/// written to/read from the order PDA's data area.
///
/// Layout: one character per byte, cell widths proportional to field size,
/// each divider belongs to the cell on its right. Integers are little-endian
/// (Anchor/Borsh convention). The intent slot holds a verbatim
/// [`EncodedOrderIntent`]; see that type's docs for its inner layout.
///
/// ```text
///  ┌───── discriminator
///  │┌──── bump
///  ││┌─── cancelled
///  ┌┬┬┬───────┬───────┬───────────────────────────────┬─────────────────...─────────────────┐
///  ││││amount_│amount_│                               │                                     │
///  ││││with-  │re-    │           created_by          │     intent (EncodedOrderIntent)     │
///  ││││drawn  │ceived │                               │                                     │
///  └┴┴┴───────┴───────┴───────────────────────────────┴─────────────────...─────────────────┘
/// 0 1 2 3      11      19                              51                ...               264
/// ```
#[derive(Clone, Debug, Deref, Eq, PartialEq)]
pub struct EncodedOrderAccount([u8; Self::SIZE]);

impl EncodedOrderAccount {
    // Per-field widths, derived from the `OrderAccount` field types.
    const W_DISCRIMINATOR: usize = size_of::<u8>();
    const W_BUMP: usize = size_of::<u8>();
    const W_CANCELLED: usize = size_of::<bool>();
    const W_AMOUNT_WITHDRAWN: usize = size_of::<u64>();
    const W_AMOUNT_RECEIVED: usize = size_of::<u64>();
    const W_CREATED_BY: usize = size_of::<Pubkey>();
    const W_INTENT: usize = EncodedOrderIntent::SIZE;

    pub const SIZE: usize = 264;

    /// Single-byte account discriminator. See [`SettlementAccount`].
    pub const DISCRIMINATOR: u8 = SettlementAccount::OrderAccount.discriminator();

    /// Decode the account body and compute the embedded intent's UID in one
    /// shot, mirroring [`EncodedOrderIntent::decode_and_hash`]. Decoding
    /// validates the discriminator and the intent; returns
    /// [`ProgramError::InvalidAccountData`] on a decode error.
    pub fn decode_and_hash(bytes: &[u8; Self::SIZE]) -> Result<(OrderAccount, Hash), ProgramError> {
        let order_account = OrderAccount::try_from(*bytes)?;
        // The order UID is the hash of the intent's canonical bytes. Decoding
        // succeeded, so the intent slot already holds those exact bytes: hash
        // them in place rather than using `intent.uid()` to avoid re-encoding.
        let (_, raw_intent) = array_refs![
            bytes,
            EncodedOrderAccount::SIZE - EncodedOrderAccount::W_INTENT,
            EncodedOrderAccount::W_INTENT
        ];
        let intent_uid = intent::hash_bytes(raw_intent);
        Ok((order_account, intent_uid))
    }
}

/// Writes the canonical [`EncodedOrderAccount`] encoding of the given fields
/// into `buffer`. `encoded_intent` must be a canonical [`EncodedOrderIntent`]
/// encoding: validating it is the caller's responsibility.
pub fn write_account(
    buffer: &mut [u8; EncodedOrderAccount::SIZE],
    bump: u8,
    cancelled: bool,
    amount_withdrawn: u64,
    amount_received: u64,
    created_by: &Pubkey,
    encoded_intent: &[u8; EncodedOrderIntent::SIZE],
) {
    let (
        discriminator_slot,
        bump_slot,
        cancelled_slot,
        amount_withdrawn_slot,
        amount_received_slot,
        created_by_slot,
        intent_slot,
    ) = mut_array_refs![
        buffer,
        EncodedOrderAccount::W_DISCRIMINATOR,
        EncodedOrderAccount::W_BUMP,
        EncodedOrderAccount::W_CANCELLED,
        EncodedOrderAccount::W_AMOUNT_WITHDRAWN,
        EncodedOrderAccount::W_AMOUNT_RECEIVED,
        EncodedOrderAccount::W_CREATED_BY,
        EncodedOrderAccount::W_INTENT
    ];
    *discriminator_slot = [EncodedOrderAccount::DISCRIMINATOR];
    *bump_slot = [bump];
    *cancelled_slot = [cancelled as u8];
    *amount_withdrawn_slot = amount_withdrawn.to_le_bytes();
    *amount_received_slot = amount_received.to_le_bytes();
    *created_by_slot = created_by.to_bytes();
    *intent_slot = *encoded_intent;
}

impl From<EncodedOrderAccount> for [u8; EncodedOrderAccount::SIZE] {
    fn from(encoded: EncodedOrderAccount) -> Self {
        encoded.0
    }
}

impl From<OrderAccount> for EncodedOrderAccount {
    fn from(account: OrderAccount) -> Self {
        let mut out = [0u8; Self::SIZE];
        write_account(
            &mut out,
            account.bump,
            account.cancelled,
            account.amount_withdrawn,
            account.amount_received,
            &account.created_by,
            &EncodedOrderIntent::from(&account.intent),
        );
        Self(out)
    }
}

impl TryFrom<[u8; EncodedOrderAccount::SIZE]> for OrderAccount {
    type Error = ProgramError;

    fn try_from(bytes: [u8; EncodedOrderAccount::SIZE]) -> Result<Self, Self::Error> {
        let (discriminator, bump, cancelled, amount_withdrawn, amount_received, created_by, intent) = array_refs![
            &bytes,
            EncodedOrderAccount::W_DISCRIMINATOR,
            EncodedOrderAccount::W_BUMP,
            EncodedOrderAccount::W_CANCELLED,
            EncodedOrderAccount::W_AMOUNT_WITHDRAWN,
            EncodedOrderAccount::W_AMOUNT_RECEIVED,
            EncodedOrderAccount::W_CREATED_BY,
            EncodedOrderAccount::W_INTENT
        ];

        if *discriminator != [EncodedOrderAccount::DISCRIMINATOR] {
            return Err(ProgramError::InvalidAccountData);
        }

        Ok(OrderAccount {
            bump: bump[0],
            cancelled: match cancelled {
                [0] => false,
                [1] => true,
                _ => return Err(ProgramError::InvalidAccountData),
            },
            amount_withdrawn: u64::from_le_bytes(*amount_withdrawn),
            amount_received: u64::from_le_bytes(*amount_received),
            created_by: Pubkey::new_from_array(*created_by),
            intent: OrderIntent::try_from(intent).map_err(|_| ProgramError::InvalidAccountData)?,
        })
    }
}

impl TryFrom<&[u8]> for OrderAccount {
    type Error = ProgramError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        let bytes: &[u8; EncodedOrderAccount::SIZE] = bytes
            .try_into()
            .map_err(|_| ProgramError::InvalidAccountData)?;
        OrderAccount::try_from(*bytes)
    }
}

impl TryFrom<EncodedOrderAccount> for OrderAccount {
    type Error = ProgramError;

    fn try_from(encoded: EncodedOrderAccount) -> Result<Self, Self::Error> {
        OrderAccount::try_from(encoded.0)
    }
}

#[cfg(any(test, feature = "test-fixtures"))]
pub mod fixtures {
    use proptest::prelude::*;

    use super::{OrderAccount, Pubkey};
    use crate::data::intent::fixtures::{arb_order_intent, sample_intent};

    // Hardcoded but verified in a sanity-check test.
    pub const DISCRIMINATOR_OFFSET: usize = 0;
    pub const CANCELLED_OFFSET: usize = 2;
    pub const INTENT_OFFSET: usize = 51;

    /// Hand-picked example order account wrapping [`sample_intent`].
    pub fn sample_account(cancelled: bool) -> OrderAccount {
        OrderAccount {
            bump: 0xfd,
            cancelled,
            amount_withdrawn: 0x0112_2334_4556_6778,
            amount_received: 0x899a_abbc_cdde_eff0,
            created_by: Pubkey::new_from_array([0x43; 32]),
            intent: sample_intent(Default::default()),
        }
    }

    /// Any valid [`OrderAccount`].
    pub fn arb_order_account() -> impl Strategy<Value = OrderAccount> {
        (
            any::<u8>(),
            any::<bool>(),
            any::<u64>(),
            any::<u64>(),
            any::<[u8; 32]>(),
            arb_order_intent(),
        )
            .prop_map(
                |(bump, cancelled, amount_withdrawn, amount_received, created_by, intent)| {
                    OrderAccount {
                        bump,
                        cancelled,
                        amount_withdrawn,
                        amount_received,
                        created_by: Pubkey::new_from_array(created_by),
                        intent,
                    }
                },
            )
    }
}

#[cfg(test)]
mod tests {
    use core::mem::size_of;

    use super::fixtures::{sample_account, CANCELLED_OFFSET, DISCRIMINATOR_OFFSET, INTENT_OFFSET};
    use super::*;
    use crate::data::intent::fixtures::{sample_intent, FLAGS_OFFSET};
    use crate::data::intent::Flags;

    // Pin each width to the size of the `OrderAccount` field it encodes. The
    // widths summing to `SIZE` is enforced separately, at compile time, by the
    // `array_refs!` / `mut_array_refs!` invocations in the codec.
    #[test]
    fn widths_match_field_sizes() {
        use core::mem::size_of_val;

        // Any `OrderAccount` works: `size_of_val` only consults the field
        // type, never the data.
        let OrderAccount {
            bump,
            cancelled,
            amount_withdrawn,
            amount_received,
            created_by,
            // `OrderAccount` decodes the intent, but the encoded order uses
            // `EncodedOrderIntent`, not `OrderIntent`.
            intent: _intent,
        } = sample_account(false);

        assert_eq!(EncodedOrderAccount::W_BUMP, size_of_val(&bump));
        assert_eq!(EncodedOrderAccount::W_CANCELLED, size_of_val(&cancelled));
        assert_eq!(
            EncodedOrderAccount::W_AMOUNT_WITHDRAWN,
            size_of_val(&amount_withdrawn)
        );
        assert_eq!(
            EncodedOrderAccount::W_AMOUNT_RECEIVED,
            size_of_val(&amount_received)
        );
        assert_eq!(EncodedOrderAccount::W_CREATED_BY, size_of_val(&created_by));

        assert_eq!(
            EncodedOrderAccount::W_INTENT,
            size_of::<EncodedOrderIntent>()
        );
    }

    #[test]
    fn roundtrip_both_cancelled_states() {
        for cancelled in [false, true] {
            let account = sample_account(cancelled);
            let encoded = EncodedOrderAccount::from(account.clone());
            let decoded = OrderAccount::try_from(encoded).expect("example must decode");
            assert_eq!(decoded, account);
        }
    }

    #[test]
    fn is_fully_filled_tracks_the_exact_side_only() {
        const SELL_AMOUNT: u64 = 1_000;
        const BUY_AMOUNT: u64 = 2_000;

        let account = |kind, amount_withdrawn, amount_received| OrderAccount {
            amount_withdrawn,
            amount_received,
            intent: OrderIntent {
                sell_amount: SELL_AMOUNT,
                buy_amount: BUY_AMOUNT,
                ..sample_intent(Flags {
                    kind,
                    ..Default::default()
                })
            },
            ..sample_account(false)
        };

        // (kind, withdrawn, received, expected)
        let cases = [
            (OrderKind::Sell, SELL_AMOUNT, 0, true), // fully filled SELL order (stolen money, generally impossible)
            (OrderKind::Buy, 0, BUY_AMOUNT, true),   // fully filled BUY order (free money)
            (OrderKind::Sell, u64::MAX, 0, true), // sell fill past the intent amount (should be impossible)
            (OrderKind::Sell, u64::MAX, u64::MAX, true), // sell fill past the intent amount (should be impossible)
            (OrderKind::Buy, 0, u64::MAX, true),         // buy fill past the intent amount
            (OrderKind::Buy, u64::MAX, u64::MAX, true),  // buy fill past the intent amount
            (OrderKind::Sell, 0, 0, false),              // unfilled order
            (OrderKind::Sell, SELL_AMOUNT - 1, BUY_AMOUNT, false), // not fully filled SELL order
            (OrderKind::Buy, SELL_AMOUNT, BUY_AMOUNT - 1, false), // not fully filled BUY order with fully filled sell side (generally should be impossible)
        ];
        for (kind, withdrawn, received, expected) in cases {
            assert_eq!(
                account(kind, withdrawn, received).is_fully_filled(),
                expected,
                "{kind:?} order withdrawn={withdrawn} received={received}",
            );
        }
    }

    #[test]
    fn sanity_check_offsets() {
        fn first_differing_byte(lhs: &[u8], rhs: &[u8]) -> Option<usize> {
            lhs.iter().zip(rhs).position(|(l, r)| l != r)
        }

        let mut sample_account_base = sample_account(false);
        let base: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account_base.clone()).into();
        let cancelled: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(true)).into();
        assert_eq!(
            first_differing_byte(&base, &cancelled).expect("should differ in the cancelled byte"),
            CANCELLED_OFFSET
        );

        // Differs only in the embedded intent.
        let encoded_intent: [u8; EncodedOrderIntent::SIZE] =
            (&EncodedOrderIntent::from(&sample_account_base.intent)).into();
        // Hack: xoring each byte makes sure all bytes are different.
        // In general, it isn't guaranteed that the result encodes to a
        // valid intent, but in this case we know it because the only byte
        // that may fail decoding is the flags byte, and `^0x01` only flips
        // its `created_on_chain` flag bits, never a reserved one.
        let bitwise_different_encoded_intent: [u8; EncodedOrderIntent::SIZE] =
            encoded_intent.map(|b| b ^ 0x01);
        sample_account_base.intent =
            OrderIntent::try_from(&bitwise_different_encoded_intent).expect("hack should work");
        let changed_intent: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account_base).into();
        assert_eq!(
            first_differing_byte(&base, &changed_intent).expect("should differ in the intent slot"),
            INTENT_OFFSET
        );
    }

    #[test]
    fn decode_rejects_wrong_discriminator() {
        let mut bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();
        bytes[0] ^= 0xff;
        let err = OrderAccount::try_from(bytes).expect_err("wrong discriminator must be rejected");
        assert_eq!(err, ProgramError::InvalidAccountData);
    }

    #[test]
    fn decode_rejects_non_boolean_cancelled() {
        let mut bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();
        for bad in 0x02u8..=0xff {
            bytes[CANCELLED_OFFSET] = bad;
            let err = OrderAccount::try_from(bytes)
                .expect_err("non-boolean cancelled byte must be rejected");
            assert_eq!(err, ProgramError::InvalidAccountData);
        }
    }

    #[test]
    fn decode_propagates_invalid_intent() {
        let mut bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();
        // Set a reserved bit of the flags byte inside the intent slot: the
        // intent decoder rejects it and the order-account decode surfaces
        // that failure as `InvalidAccountData`.
        bytes[INTENT_OFFSET + FLAGS_OFFSET] = 0xff;
        let err = OrderAccount::try_from(bytes)
            .expect_err("an invalid intent flags byte must propagate as a decode failure");
        assert_eq!(err, ProgramError::InvalidAccountData);
    }

    #[test]
    fn decode_and_hash_catches_errors() {
        let mut bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();
        // Corrupt the `cancelled` byte to an out-of-range value so the
        // underlying `try_from` rejects it.
        bytes[CANCELLED_OFFSET] = 0xff;
        let err = EncodedOrderAccount::decode_and_hash(&bytes)
            .expect_err("decode_and_hash must propagate the try_from error");
        assert_eq!(err, ProgramError::InvalidAccountData);
    }

    #[test]
    fn try_from_exact_length_slice_decodes() {
        let account = sample_account(false);
        let bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(account.clone()).into();

        let decoded = OrderAccount::try_from(&bytes[..]).expect("exact-length slice must decode");
        assert_eq!(decoded, account);
    }

    #[test]
    fn try_from_wrong_length_slice_is_rejected() {
        let bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();

        assert_eq!(
            OrderAccount::try_from(&bytes[..EncodedOrderAccount::SIZE - 1]),
            Err(ProgramError::InvalidAccountData),
        );

        let too_long = [bytes.as_slice(), [0].as_slice()].concat();
        assert_eq!(
            OrderAccount::try_from(&too_long[..]),
            Err(ProgramError::InvalidAccountData),
        );
    }

    #[test]
    fn try_from_slice_forwards_decoding_errors() {
        let mut bytes: [u8; EncodedOrderAccount::SIZE] =
            EncodedOrderAccount::from(sample_account(false)).into();
        bytes[CANCELLED_OFFSET] = 0xff;
        assert_eq!(
            OrderAccount::try_from(&bytes[..]),
            Err(ProgramError::InvalidAccountData),
        );
    }

    mod load_from_pda {
        use super::*;
        use crate::instruction::fixtures::fake_account_with_data;
        use crate::pda::order::find_order_pda;

        const PROGRAM_ID: Address = Address::new_from_array([0xc0; 32]);

        /// [`sample_account`] carrying its own canonical bump, plus the address
        /// of the PDA it belongs at.
        fn canonical_account(cancelled: bool) -> (OrderAccount, Address) {
            let mut account = sample_account(cancelled);
            let (pda_address, bump) = find_order_pda(&PROGRAM_ID, &account.intent.uid());
            account.bump = bump;
            (account, pda_address)
        }

        #[test]
        fn accepts_the_canonical_pda() {
            let (account, pda_address) = canonical_account(false);
            let order_pda = fake_account_with_data(
                pda_address,
                &EncodedOrderAccount::from(account.clone())[..],
            );

            let loaded = OrderAccount::load_from_pda(&order_pda, &PROGRAM_ID)
                .expect("canonical PDA must load");
            assert_eq!(loaded, account);
        }

        #[test]
        fn rejects_a_non_canonical_address() {
            let (account, _) = canonical_account(false);
            // An address unrelated to the intent's canonical seeds.
            let wrong_address = Pubkey::new_from_array([0x42; 32]);
            let order_pda =
                fake_account_with_data(wrong_address, &EncodedOrderAccount::from(account)[..]);

            let err = OrderAccount::load_from_pda(&order_pda, &PROGRAM_ID)
                .expect_err("a non-canonical address must be rejected");
            assert_eq!(err, SettlementError::AccountNotDerivable.into());
        }

        #[test]
        fn rejects_a_stored_bump_that_does_not_derive_the_address() {
            let (mut account, pda_address) = canonical_account(false);
            // Any bump other than the canonical one either derives a
            // different address or fails to derive one at all (falling on
            // curve); either way, the PDA can no longer be proven canonical.
            account.bump = account.bump.wrapping_sub(1);
            let order_pda =
                fake_account_with_data(pda_address, &EncodedOrderAccount::from(account)[..]);

            let err = OrderAccount::load_from_pda(&order_pda, &PROGRAM_ID)
                .expect_err("a non-canonical bump must be rejected");
            assert_eq!(err, SettlementError::AccountNotDerivable.into());
        }

        #[test]
        fn propagates_decode_errors() {
            let (account, pda_address) = canonical_account(false);
            let mut bytes: [u8; EncodedOrderAccount::SIZE] =
                EncodedOrderAccount::from(account).into();
            bytes[CANCELLED_OFFSET] = 0xff;
            let order_pda = fake_account_with_data(pda_address, &bytes);

            let err = OrderAccount::load_from_pda(&order_pda, &PROGRAM_ID)
                .expect_err("a corrupt account must fail to decode");
            assert_eq!(err, ProgramError::InvalidAccountData);
        }
    }

    #[test]
    fn direct_write_account_matches_order_account_decoding() {
        let bump = 254;
        let cancelled = true;
        let amount_withdrawn = 1337;
        let amount_received = 31337;
        let intent = sample_intent(Default::default());
        let created_by = Pubkey::new_from_array([0x42u8; 32]);

        let mut buffer = [0u8; EncodedOrderAccount::SIZE];
        write_account(
            &mut buffer,
            bump,
            cancelled,
            amount_withdrawn,
            amount_received,
            &created_by,
            &<[u8; EncodedOrderIntent::SIZE]>::from(&EncodedOrderIntent::from(&intent)),
        );
        let direct = EncodedOrderAccount(buffer);
        let via_order_account = EncodedOrderAccount::from(OrderAccount {
            bump,
            cancelled,
            amount_withdrawn,
            amount_received,
            created_by,
            intent,
        });

        assert_eq!(direct, via_order_account);
    }

    // Property-based tests, non-deterministic.
    mod proptest {
        use ::proptest::{prelude::*, test_runner::TestCaseError};

        use super::*;
        use crate::data::{intent::fixtures::arb_flags_byte, order::fixtures::arb_order_account};

        proptest! {
            // For any `OrderAccount`, encode then decode returns the same
            // account.
            #[test]
            fn account_roundtrip(account in arb_order_account()) {
                let encoded = EncodedOrderAccount::from(account.clone());
                let decoded = OrderAccount::try_from(encoded)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(decoded, account);
            }

            // For any bytes whose `cancelled` and embedded intent
            // discriminants are valid, decode + re-encode produces the
            // same bytes back.
            #[test]
            fn bytes_roundtrip(
                mut bytes in any::<[u8; EncodedOrderAccount::SIZE]>(),
                cancelled in any::<bool>(),
                flags in arb_flags_byte(),
            ) {
                bytes[DISCRIMINATOR_OFFSET] = EncodedOrderAccount::DISCRIMINATOR;
                bytes[CANCELLED_OFFSET] = cancelled as u8;
                bytes[INTENT_OFFSET + FLAGS_OFFSET] = flags;
                let account = OrderAccount::try_from(bytes)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(*EncodedOrderAccount::from(account), bytes);
            }

            #[test]
            fn consistent_decode_and_hash(account in arb_order_account()) {
                let encoded = EncodedOrderAccount::from(account.clone());
                let (decoded, hash) = EncodedOrderAccount::decode_and_hash(&encoded)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(hash, account.intent.uid());
                prop_assert_eq!(decoded, account);
            }
        }
    }
}