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
//! Order intents and their canonical byte representation.
//!
//! The intent has two representations:
//!
//! - [`OrderIntent`] is the idiomatic Rust representation.
//! - [`EncodedOrderIntent`] is its canonical byte representation: the only
//!   thing sent on the wire and also the data encoding used to generate the
//!   order UID. There, `kind` and the intent's booleans share a single flags
//!   byte.
//!
//! Conversion is asymmetric: [`EncodedOrderIntent`]`::from(OrderIntent)` is
//! infallible, but decoding raw bytes via [`OrderIntent`]`::try_from` returns
//! `Result` and rejects a flags byte carrying a bit the encoding doesn't
//! define.

use core::mem::size_of;

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

/// Direction of the trade. The discriminants are the values the `kind` bit of
/// the encoded flags byte takes.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
#[repr(u8)]
pub enum OrderKind {
    #[default]
    Sell = 0,
    Buy = 1,
}

/// Collection of [`OrderIntent`] fields that can be represented as a single bit.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
pub struct Flags {
    /// How the order is authenticated: `true` if the owner creates it
    /// themselves with a `CreateOrder` instruction they sign; `false` if it's
    /// authenticated off-chain by an Ed25519 signature, which lets anyone
    /// holding that signature create the order.
    pub created_on_chain: bool,

    /// Whether `sell_amount` or `buy_amount` is the exact figure; the
    /// other side is treated as the limit (minimum to receive for `Sell`,
    /// maximum to spend for `Buy`).
    pub kind: OrderKind,

    /// If `true`, the order may be filled across multiple settlements;
    /// proceeds and consumption scale proportionally with the amount of
    /// the sell side that's been used. If `false`, a single settlement
    /// must consume the full sell amount (fill-or-kill).
    pub partially_fillable: bool,
}

impl Flags {
    // The bit each field occupies
    const CREATED_ON_CHAIN: u8 = 1 << 0;
    const KIND: u8 = 1 << 1;
    const PARTIALLY_FILLABLE: u8 = 1 << 2;

    /// Every bit the encoding defines; the others are reserved.
    const DEFINED: u8 = Self::CREATED_ON_CHAIN | Self::KIND | Self::PARTIALLY_FILLABLE;
}

impl From<Flags> for [u8; 1] {
    /// The canonical flags byte. Reserved bits are left clear.
    fn from(flags: Flags) -> Self {
        let mut byte = 0;
        if flags.created_on_chain {
            byte |= Flags::CREATED_ON_CHAIN;
        }
        if flags.kind == OrderKind::Buy {
            byte |= Flags::KIND;
        }
        if flags.partially_fillable {
            byte |= Flags::PARTIALLY_FILLABLE;
        }
        [byte]
    }
}

impl TryFrom<[u8; 1]> for Flags {
    type Error = ProgramError;

    /// Decodes a flags byte, rejecting any reserved bit with
    /// [`ProgramError::InvalidInstructionData`]. A reserved bit carries no
    /// meaning to this version of the program, so accepting it would give the
    /// same flags several encodings, and with them several UIDs.
    fn try_from(bytes: [u8; 1]) -> Result<Self, Self::Error> {
        let [byte] = bytes;
        if byte & !Self::DEFINED != 0 {
            return Err(ProgramError::InvalidInstructionData);
        }
        Ok(Flags {
            created_on_chain: byte & Self::CREATED_ON_CHAIN != 0,
            kind: if byte & Self::KIND == 0 {
                OrderKind::Sell
            } else {
                OrderKind::Buy
            },
            partially_fillable: byte & Self::PARTIALLY_FILLABLE != 0,
        })
    }
}

/// Canonical order intent. Also the exact bytes hashed (SHA-256) to produce the order UID used in the order PDA's seeds,
/// and the exact wire format of create_order's `intent` argument. Field order and encoding here are load-bearing: they
/// must match this program's Rust definition exactly.
#[derive(Clone, Debug, Eq, PartialEq, Default)]
pub struct OrderIntent {
    /// Account authorized to create and invalidate this order and whose
    /// signature authenticates it. For off-chain orders this is the Ed25519
    /// signer; for on-chain creation it must be the transaction signer.
    pub owner: Pubkey,

    /// Token account the sell-side funds are pulled from. Implicitly
    /// encodes the spender. The settlement state PDA must hold the SPL
    /// `delegate` on this account for the order to be settleable.
    /// This token account must be owned by the intent owner. An intent
    /// that doesn't satisfy this property will be rejected.
    pub sell_token_account: Pubkey,

    /// Mint of the sell token.
    pub sell_mint: Pubkey,

    /// Token account that receives the buy-side proceeds. Implicitly
    /// encodes the recipient.
    pub buy_token_account: Pubkey,

    /// Mint of the buy token.
    pub buy_mint: Pubkey,

    /// Amount of the sell token. For `Sell` orders this is the exact
    /// amount to be sold (subject to `partially_fillable`); for `Buy`
    /// orders it is the maximum the user is willing to spend.
    pub sell_amount: u64,

    /// Amount of the buy token. For `Buy` orders this is the exact amount
    /// to be received (subject to `partially_fillable`); for `Sell`
    /// orders it is the minimum the user is willing to receive.
    pub buy_amount: u64,

    /// Unix timestamp after which the order expires.
    /// The order cannot be executed after expiration.
    pub valid_to: u32,

    /// The settings the encoding packs bit by bit into a single byte; see
    /// [`Flags`].
    pub flags: Flags,

    /// Opaque 32 bytes set by the order creator. Not interpreted by the
    /// settlement program; used off-chain for metadata such as the
    /// frontend version, slippage hints, or attribution.
    pub app_data: [u8; 32],
}

/// Canonical 213-byte representation of an [`OrderIntent`]. The wire format and
/// the order UID preimage.
///
/// Layout: one character per byte, cell widths proportional to field size,
/// each divider belongs to the cell on its right. The byte range is
/// annotated below. Amounts and `valid_to` are little-endian encoded.
///
/// ```text
///                                                                                                                                                                           flags ────┐
/// ┌───────────────────────────────┬───────────────────────────────┬───────────────────────────────┬───────────────────────────────┬───────────────────────────────┬───────┬───────┬───┬┬───────────────────────────────┐
/// │                               │                               │                               │                               │                               │sell_  │buy_   │val││                               │
/// │             owner             │      sell_token_account       │           sell_mint           │       buy_token_account       │           buy_mint            │       │       │id_││           app_data            │
/// │                               │                               │                               │                               │                               │amount │amount │to ││                               │
/// └───────────────────────────────┴───────────────────────────────┴───────────────────────────────┴───────────────────────────────┴───────────────────────────────┴───────┴───────┴───┴┴───────────────────────────────┘
/// 0                               32                              64                              96                              128                             160     168     176 180                           213
///                                                                                                                                                                                      181
/// ```
///
#[derive(Clone, Debug, Deref, Eq, PartialEq)]
pub struct EncodedOrderIntent([u8; Self::SIZE]);

impl EncodedOrderIntent {
    // Per-field widths, derived from the `OrderIntent` field types.
    const WIDTH_OWNER: usize = size_of::<Pubkey>();
    const WIDTH_SELL_TOKEN: usize = size_of::<Pubkey>();
    const WIDTH_SELL_MINT: usize = size_of::<Pubkey>();
    const WIDTH_BUY_TOKEN: usize = size_of::<Pubkey>();
    const WIDTH_BUY_MINT: usize = size_of::<Pubkey>();
    const WIDTH_SELL_AMOUNT: usize = size_of::<u64>();
    const WIDTH_BUY_AMOUNT: usize = size_of::<u64>();
    const WIDTH_VALID_TO: usize = size_of::<u32>();
    const WIDTH_FLAGS: usize = size_of::<u8>();
    const WIDTH_APP_DATA: usize = size_of::<[u8; 32]>();

    pub const SIZE: usize = 213;

    /// Canonical hash of the bytes.
    pub fn hash(&self) -> Hash {
        hash_bytes(&self.0)
    }

    /// Decode raw bytes to an [`OrderIntent`] and compute the UID in one shot.
    /// Returns [`ProgramError::InvalidInstructionData`] for a flags byte that
    /// doesn't encode correctly; every other byte combination decodes.
    pub fn decode_and_hash(bytes: &[u8; Self::SIZE]) -> Result<(OrderIntent, Hash), ProgramError> {
        let intent = OrderIntent::try_from(bytes)?;
        // The UID is the SHA-256 of the input bytes. Hashing the input
        // (no re-encode) is correct because encode/decode is a bijection on
        // inputs that pass validation. Any normalization added to the `From`
        // or `TryFrom` impls later would break this and the UID would silently
        // diverge from `OrderIntent::uid()`.
        let uid = hash_bytes(bytes);
        Ok((intent, uid))
    }
}

pub fn hash_bytes(bytes: &[u8; EncodedOrderIntent::SIZE]) -> Hash {
    solana_sha256_hasher::hashv(&[bytes.as_slice()])
}

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

impl From<&OrderIntent> for EncodedOrderIntent {
    fn from(intent: &OrderIntent) -> Self {
        // `mut_array_refs` checks that `SIZE` is consistent with the sum of
        // the widths.
        let mut out = [0u8; Self::SIZE];
        let (
            owner,
            sell_token,
            sell_mint,
            buy_token,
            buy_mint,
            sell_amount,
            buy_amount,
            valid_to,
            flags,
            app_data,
        ) = mut_array_refs![
            &mut out,
            EncodedOrderIntent::WIDTH_OWNER,
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_MINT,
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            EncodedOrderIntent::WIDTH_BUY_MINT,
            EncodedOrderIntent::WIDTH_SELL_AMOUNT,
            EncodedOrderIntent::WIDTH_BUY_AMOUNT,
            EncodedOrderIntent::WIDTH_VALID_TO,
            EncodedOrderIntent::WIDTH_FLAGS,
            EncodedOrderIntent::WIDTH_APP_DATA
        ];
        *owner = intent.owner.to_bytes();
        *sell_token = intent.sell_token_account.to_bytes();
        *sell_mint = intent.sell_mint.to_bytes();
        *buy_token = intent.buy_token_account.to_bytes();
        *buy_mint = intent.buy_mint.to_bytes();
        *sell_amount = intent.sell_amount.to_le_bytes();
        *buy_amount = intent.buy_amount.to_le_bytes();
        *valid_to = intent.valid_to.to_le_bytes();
        *flags = intent.flags.into();
        *app_data = intent.app_data;
        Self(out)
    }
}

impl TryFrom<&[u8; EncodedOrderIntent::SIZE]> for OrderIntent {
    type Error = ProgramError;

    fn try_from(bytes: &[u8; EncodedOrderIntent::SIZE]) -> Result<Self, Self::Error> {
        // It's important that the byte representation of an intent is unique.
        // This function should be injective: there shouldn't be two byte
        // sequences that decode to the same order intent.
        // If this were to happen, then the user intent may not be recognized
        // as valid or it might be possible to replay the same order more
        // than once.

        let (
            owner,
            sell_token,
            sell_mint,
            buy_token,
            buy_mint,
            sell_amount,
            buy_amount,
            valid_to,
            flags,
            app_data,
        ) = array_refs![
            bytes,
            EncodedOrderIntent::WIDTH_OWNER,
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_MINT,
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            EncodedOrderIntent::WIDTH_BUY_MINT,
            EncodedOrderIntent::WIDTH_SELL_AMOUNT,
            EncodedOrderIntent::WIDTH_BUY_AMOUNT,
            EncodedOrderIntent::WIDTH_VALID_TO,
            EncodedOrderIntent::WIDTH_FLAGS,
            EncodedOrderIntent::WIDTH_APP_DATA
        ];

        Ok(OrderIntent {
            owner: Pubkey::new_from_array(*owner),
            sell_token_account: Pubkey::new_from_array(*sell_token),
            sell_mint: Pubkey::new_from_array(*sell_mint),
            buy_token_account: Pubkey::new_from_array(*buy_token),
            buy_mint: Pubkey::new_from_array(*buy_mint),
            sell_amount: u64::from_le_bytes(*sell_amount),
            buy_amount: u64::from_le_bytes(*buy_amount),
            valid_to: u32::from_le_bytes(*valid_to),
            flags: Flags::try_from(*flags)?,
            app_data: *app_data,
        })
    }
}

impl TryFrom<&EncodedOrderIntent> for OrderIntent {
    type Error = ProgramError;

    fn try_from(encoded: &EncodedOrderIntent) -> Result<Self, Self::Error> {
        OrderIntent::try_from(&encoded.0)
    }
}

impl OrderIntent {
    /// SHA-256 of the canonical bytes. Doubles as the order UID and the
    /// middle seed of the order PDA. On SBF this compiles to a single
    /// `sol_sha256` syscall; off-target it goes through the `sha2` crate.
    pub fn uid(&self) -> Hash {
        EncodedOrderIntent::from(self).hash()
    }
}

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

    use super::{Flags, OrderIntent, OrderKind, Pubkey};

    /// Every valid [`OrderKind`].
    pub const ALL_ORDER_KINDS: [OrderKind; 2] = [OrderKind::Sell, OrderKind::Buy];

    // Hardcoded but verified in a sanity-check test.
    pub const FLAGS_OFFSET: usize = 180;

    pub fn sample_intent(flags: Flags) -> OrderIntent {
        OrderIntent {
            owner: Pubkey::new_from_array([0x11; 32]),
            sell_token_account: Pubkey::new_from_array([0x22; 32]),
            sell_mint: Pubkey::new_from_array([0x33; 32]),
            buy_token_account: Pubkey::new_from_array([0x44; 32]),
            buy_mint: Pubkey::new_from_array([0x55; 32]),
            sell_amount: 0x0123_4567_89ab_cdef,
            buy_amount: 0xfedc_ba98_7654_3210,
            valid_to: 0xdead_beef,
            flags,
            app_data: [0x66; 32],
        }
    }

    /// Any valid [`OrderKind`].
    pub fn arb_order_kind() -> impl Strategy<Value = OrderKind> {
        Union::new(ALL_ORDER_KINDS.map(Just))
    }

    /// Any valid [`Flags`].
    pub fn arb_flags() -> impl Strategy<Value = Flags> {
        (any::<bool>(), arb_order_kind(), any::<bool>()).prop_map(
            |(created_on_chain, kind, partially_fillable)| Flags {
                created_on_chain,
                kind,
                partially_fillable,
            },
        )
    }

    /// Any flags byte the decoder accepts.
    pub fn arb_flags_byte() -> impl Strategy<Value = u8> {
        any::<u8>().prop_map(|byte| byte & Flags::DEFINED)
    }

    /// Any flags byte the decoder rejects.
    pub fn arb_invalid_flags_byte() -> impl Strategy<Value = u8> {
        any::<u8>().prop_filter("must have at least one bit that is undefined", |byte| {
            byte & !Flags::DEFINED > 0
        })
    }

    /// Any valid [`OrderIntent`].
    pub fn arb_order_intent() -> impl Strategy<Value = OrderIntent> {
        (
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<u64>(),
            any::<u64>(),
            any::<u32>(),
            arb_flags(),
            any::<[u8; 32]>(),
        )
            .prop_map(
                |(
                    owner,
                    sell_tok,
                    sell_mint,
                    buy_tok,
                    buy_mint,
                    sell_amount,
                    buy_amount,
                    valid_to,
                    flags,
                    app,
                )| {
                    OrderIntent {
                        owner: Pubkey::new_from_array(owner),
                        sell_token_account: Pubkey::new_from_array(sell_tok),
                        sell_mint: Pubkey::new_from_array(sell_mint),
                        buy_token_account: Pubkey::new_from_array(buy_tok),
                        buy_mint: Pubkey::new_from_array(buy_mint),
                        sell_amount,
                        buy_amount,
                        valid_to,
                        flags,
                        app_data: app,
                    }
                },
            )
    }
}

#[cfg(test)]
mod tests {
    use crate::data::intent::fixtures::FLAGS_OFFSET;

    use super::fixtures::sample_intent;
    use super::*;

    // Every shape an `OrderIntent` can take on its validated axes: the
    // `created_on_chain` flag bit, the `kind` enum, and the
    // `partially_fillable` flag bit.
    fn all_flag_shapes() -> impl Iterator<Item = OrderIntent> {
        [false, true].into_iter().flat_map(|created_on_chain| {
            fixtures::ALL_ORDER_KINDS.into_iter().flat_map(move |kind| {
                [false, true].into_iter().map(move |partially_fillable| {
                    sample_intent(Flags {
                        created_on_chain,
                        kind,
                        partially_fillable,
                    })
                })
            })
        })
    }

    // Pin each width to the size of the `OrderIntent` 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, size_of_val};

        // Any `OrderIntent` works: `size_of_val` only consults the field
        // type, never the data.
        let intent = sample_intent(Default::default());

        assert_eq!(EncodedOrderIntent::WIDTH_OWNER, size_of_val(&intent.owner));
        assert_eq!(
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            size_of_val(&intent.sell_token_account)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_SELL_MINT,
            size_of_val(&intent.sell_mint)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            size_of_val(&intent.buy_token_account)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_BUY_MINT,
            size_of_val(&intent.buy_mint)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_SELL_AMOUNT,
            size_of_val(&intent.sell_amount)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_BUY_AMOUNT,
            size_of_val(&intent.buy_amount)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_VALID_TO,
            size_of_val(&intent.valid_to)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_FLAGS,
            // in truth if there was a problem here it would actually cause a compilation error
            size_of_val::<[u8; 1]>(&Flags::default().into())
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_APP_DATA,
            size_of_val(&intent.app_data)
        );

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

    #[test]
    fn every_flag_owns_a_distinct_bit() {
        let byte = |flags: Flags| <[u8; 1]>::from(flags)[0];
        let cleared = Flags {
            created_on_chain: false,
            kind: OrderKind::Sell,
            partially_fillable: false,
        };
        assert_eq!(byte(cleared), 0);

        let set_one_by_one = [
            (
                Flags::CREATED_ON_CHAIN,
                Flags {
                    created_on_chain: true,
                    ..cleared
                },
            ),
            (
                Flags::KIND,
                Flags {
                    kind: OrderKind::Buy,
                    ..cleared
                },
            ),
            (
                Flags::PARTIALLY_FILLABLE,
                Flags {
                    partially_fillable: true,
                    ..cleared
                },
            ),
        ];
        let mut seen = 0u8;
        for (bit, flags) in set_one_by_one {
            assert_eq!(bit.count_ones(), 1, "a flag must occupy a single bit");
            assert_eq!(seen & bit, 0, "two flags must not share a bit");
            assert!(
                bit > seen,
                "each flag must be more significant than the ones before it"
            );
            seen |= bit;
            assert_eq!(byte(flags), bit);
        }
        assert_eq!(seen, Flags::DEFINED);
    }

    #[test]
    fn roundtrip_all_kind_and_flag_combinations() {
        for intent in all_flag_shapes() {
            let encoded = EncodedOrderIntent::from(&intent);
            let (decoded, _uid) =
                EncodedOrderIntent::decode_and_hash(&encoded).expect("example must decode");
            assert_eq!(decoded, intent);
        }
    }

    // Locks the bijection invariant called out in `decode_and_hash`: the
    // UID computed over the raw input bytes must equal the hash of the
    // canonical re-encoding. If anything ever normalizes during
    // encode/decode, this test fails.
    #[test]
    fn decode_and_hash_uid_matches_encoded_hash() {
        for intent in all_flag_shapes() {
            let encoded = EncodedOrderIntent::from(&intent);
            let (_intent, uid) =
                EncodedOrderIntent::decode_and_hash(&encoded).expect("example must decode");
            assert_eq!(uid, encoded.hash());
        }
    }

    #[test]
    fn decode_accepts_defined_flag_bits_only() {
        let encoded = EncodedOrderIntent::from(&sample_intent(Default::default()));
        let mut bytes: [u8; EncodedOrderIntent::SIZE] = *encoded;
        for flags in u8::MIN..=u8::MAX {
            bytes[FLAGS_OFFSET] = flags;
            let decoded = EncodedOrderIntent::decode_and_hash(&bytes);
            if flags & !Flags::DEFINED != 0 {
                assert_eq!(
                    decoded.err(),
                    Some(ProgramError::InvalidInstructionData),
                    "flags {flags:#04x} sets a reserved bit and must be rejected",
                );
            }
        }
    }

    #[test]
    fn uid_digest_regression() {
        // Compared as hex: `Hash`'s `Display` and `Debug` are both base58,
        // which is not how we represent order UIDs elsewhere.
        fn hex(bytes: &[u8]) -> String {
            bytes.iter().map(|b| format!("{b:02x}")).collect()
        }
        let intent = sample_intent(Flags {
            created_on_chain: true,
            kind: OrderKind::Buy,
            partially_fillable: true,
        });
        assert_eq!(
            hex(intent.uid().as_ref()),
            "de4096c6c100056f1e4636ea4fafefad40fc1d0b37692fe3ca1e0db3644b86bd",
        );
    }

    #[test]
    fn encoding_regression() {
        let encoded = EncodedOrderIntent::from(&sample_intent(Flags {
            created_on_chain: true,
            kind: OrderKind::Buy,
            partially_fillable: true,
        }));
        let encoding: [u8; EncodedOrderIntent::SIZE] = *encoded;
        #[rustfmt::skip]
        let expected: [u8; EncodedOrderIntent::SIZE] = [
            // owner ([0x11; 32])
            0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
            0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
            0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
            0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,
            // sell_token_account ([0x22; 32])
            0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
            0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
            0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
            0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,
            // sell_mint ([0x33; 32])
            0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
            0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
            0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
            0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
            // buy_token_account ([0x44; 32])
            0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
            0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
            0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
            0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44,
            // buy_mint ([0x55; 32])
            0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
            0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
            0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
            0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
            // sell_amount (0x0123_4567_89ab_cdef, LE u64)
            0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01,
            // buy_amount (0xfedc_ba98_7654_3210, LE u64)
            0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe,
            // valid_to (0xdead_beef, LE u32)
            0xef, 0xbe, 0xad, 0xde,
            // flags (created_on_chain | kind (Buy = 1) | partially_fillable)
            0b00000111,
            // app_data ([0x66; 32])
            0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
            0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
            0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
            0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66,
        ];
        assert_eq!(encoding, expected);
    }

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

        use super::*;
        use crate::data::intent::fixtures::{
            arb_flags_byte, arb_invalid_flags_byte, arb_order_intent, FLAGS_OFFSET,
        };

        proptest! {
            // For any `OrderIntent`, encoding an intent into an encoded
            // intent and then decoding it with `decode_and_hash()` returns
            // the same intent plus a UID that matches the encoded bytes'
            // hash.
            #[test]
            fn intent_roundtrip(intent in arb_order_intent()) {
                let encoded = EncodedOrderIntent::from(&intent);
                let (decoded, uid) = EncodedOrderIntent::decode_and_hash(&encoded)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(decoded, intent);
                prop_assert_eq!(uid, encoded.hash());
            }

            // For any bytes whose flags slot is valid, `decode_and_hash` and
            // then re-encoding produces back the original bytes.
            #[test]
            fn bytes_roundtrip(
                mut bytes in any::<[u8; EncodedOrderIntent::SIZE]>(),
                flags in arb_flags_byte(),
            ) {
                bytes[FLAGS_OFFSET] = flags;
                let (intent, _uid) = EncodedOrderIntent::decode_and_hash(&bytes)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(*EncodedOrderIntent::from(&intent), bytes);
            }

            // Symmetric: any bytes whose flags byte carries a reserved bit
            // return `InvalidInstructionData`.
            #[test]
            fn rejects_reserved_flag_bits(
                mut bytes in any::<[u8; EncodedOrderIntent::SIZE]>(),
                bad_flags in arb_invalid_flags_byte(),
            ) {
                bytes[FLAGS_OFFSET] = bad_flags;
                prop_assert_eq!(
                    EncodedOrderIntent::decode_and_hash(&bytes),
                    Err(ProgramError::InvalidInstructionData),
                );
            }
        }
    }
}