cow-settlement-interface 0.2.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
//! Order intents and their canonical byte representation.
//!
//! Two types live here:
//!
//! - [`OrderIntent`] is the idiomatic Rust representation. Every value is valid
//!   by construction: `kind` is an [`OrderKind`] enum, `partially_fillable` is
//!   a `bool`. Callers pattern-match on it directly.
//! - [`EncodedOrderIntent`] is its canonical byte representation: the only
//!   thing sent on the wire and also the data encoding used to generate the
//!   order UID.
//!
//! Conversion is asymmetric: [`EncodedOrderIntent`]`::from(OrderIntent)` is
//! infallible; decoding raw bytes via [`OrderIntent`]`::try_from` returns
//! `Result` and rejects out-of-range `kind` or `partially_fillable` bytes up
//! front. There is no path that produces an `OrderIntent` whose `kind` byte or
//! `partially_fillable` byte was not validated.

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.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Default)]
#[repr(u8)]
pub enum OrderKind {
    #[default]
    Sell = 0,
    Buy = 1,
}

#[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 that receives the buy-side proceeds. Implicitly
    /// encodes both the recipient and the buy token, since SPL token
    /// accounts are token-specific.
    pub buy_token_account: Pubkey,

    /// Token account the sell-side funds are pulled from. Implicitly
    /// encodes both the spender and the sell token. 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,

    /// 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,

    /// 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,

    /// 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 150-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
///                                                                                              partially_fillable ─────┐
///                                                                                                            kind ────┐│
/// ┌───────────────────────────────┬───────────────────────────────┬───────────────────────────────┬───────┬───────┬───┬┬┬───────────────────────────────┐
/// │                               │                               │                               │sell_  │buy_   │val│││                               │
/// │             owner             │       buy_token_account       │       sell_token_account      │       │       │id_│││            app_data           │
/// │                               │                               │                               │amount │amount │to │││                               │
/// └───────────────────────────────┴───────────────────────────────┴───────────────────────────────┴───────┴───────┴───┴┴┴───────────────────────────────┘
/// 0                               32                              64                              96      104    112 116 118                            150
///                                                                                                                     117
/// ```
#[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_BUY_TOKEN: usize = size_of::<Pubkey>();
    const WIDTH_SELL_TOKEN: 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_KIND: usize = size_of::<OrderKind>();
    const WIDTH_PARTIALLY_FILLABLE: usize = size_of::<bool>();
    const WIDTH_APP_DATA: usize = size_of::<[u8; 32]>();

    pub const SIZE: usize = 150;

    /// 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 an out-of-range
    /// `kind` or `partially_fillable` byte; 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,
            buy_token,
            sell_token,
            sell_amount,
            buy_amount,
            valid_to,
            kind,
            partially_fillable,
            app_data,
        ) = mut_array_refs![
            &mut out,
            EncodedOrderIntent::WIDTH_OWNER,
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_AMOUNT,
            EncodedOrderIntent::WIDTH_BUY_AMOUNT,
            EncodedOrderIntent::WIDTH_VALID_TO,
            EncodedOrderIntent::WIDTH_KIND,
            EncodedOrderIntent::WIDTH_PARTIALLY_FILLABLE,
            EncodedOrderIntent::WIDTH_APP_DATA
        ];
        *owner = intent.owner.to_bytes();
        *buy_token = intent.buy_token_account.to_bytes();
        *sell_token = intent.sell_token_account.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();
        *kind = [intent.kind as u8];
        *partially_fillable = [intent.partially_fillable as u8];
        *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,
            buy_token,
            sell_token,
            sell_amount,
            buy_amount,
            valid_to,
            kind,
            partially_fillable,
            app_data,
        ) = array_refs![
            bytes,
            EncodedOrderIntent::WIDTH_OWNER,
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            EncodedOrderIntent::WIDTH_SELL_AMOUNT,
            EncodedOrderIntent::WIDTH_BUY_AMOUNT,
            EncodedOrderIntent::WIDTH_VALID_TO,
            EncodedOrderIntent::WIDTH_KIND,
            EncodedOrderIntent::WIDTH_PARTIALLY_FILLABLE,
            EncodedOrderIntent::WIDTH_APP_DATA
        ];

        Ok(OrderIntent {
            owner: Pubkey::new_from_array(*owner),
            buy_token_account: Pubkey::new_from_array(*buy_token),
            sell_token_account: Pubkey::new_from_array(*sell_token),
            sell_amount: u64::from_le_bytes(*sell_amount),
            buy_amount: u64::from_le_bytes(*buy_amount),
            valid_to: u32::from_le_bytes(*valid_to),
            kind: match kind {
                [0] => OrderKind::Sell,
                [1] => OrderKind::Buy,
                _ => return Err(ProgramError::InvalidInstructionData),
            },
            partially_fillable: match partially_fillable {
                [0] => false,
                [1] => true,
                _ => return Err(ProgramError::InvalidInstructionData),
            },
            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::{EncodedOrderIntent, 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 KIND_OFFSET: usize = 116;
    pub const PARTIALLY_FILLABLE_OFFSET: usize = KIND_OFFSET + EncodedOrderIntent::WIDTH_KIND;

    pub fn sample_intent(kind: OrderKind, partially_fillable: bool) -> OrderIntent {
        OrderIntent {
            owner: Pubkey::new_from_array([0x11; 32]),
            buy_token_account: Pubkey::new_from_array([0x22; 32]),
            sell_token_account: Pubkey::new_from_array([0x33; 32]),
            sell_amount: 0x0123_4567_89ab_cdef,
            buy_amount: 0xfedc_ba98_7654_3210,
            valid_to: 0xdead_beef,
            kind,
            partially_fillable,
            app_data: [0x44; 32],
        }
    }

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

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

#[cfg(test)]
mod tests {
    use hex_literal::hex;

    use super::fixtures::{sample_intent, KIND_OFFSET, PARTIALLY_FILLABLE_OFFSET};
    use super::*;

    // Full Cartesian product of `OrderKind × bool` for tests that need to
    // exercise every shape an `OrderIntent` can take on these axes.
    fn all_kind_and_fillable() -> impl Iterator<Item = (OrderKind, bool)> {
        fixtures::ALL_ORDER_KINDS
            .into_iter()
            .flat_map(|kind| core::iter::repeat(kind).zip([false, true]))
    }

    // 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(OrderKind::Sell, false);

        assert_eq!(EncodedOrderIntent::WIDTH_OWNER, size_of_val(&intent.owner));
        assert_eq!(
            EncodedOrderIntent::WIDTH_BUY_TOKEN,
            size_of_val(&intent.buy_token_account)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_SELL_TOKEN,
            size_of_val(&intent.sell_token_account)
        );
        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_KIND, size_of_val(&intent.kind));
        assert_eq!(
            EncodedOrderIntent::WIDTH_PARTIALLY_FILLABLE,
            size_of_val(&intent.partially_fillable)
        );
        assert_eq!(
            EncodedOrderIntent::WIDTH_APP_DATA,
            size_of_val(&intent.app_data)
        );

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

    #[test]
    fn roundtrip_all_kind_and_bool_combinations() {
        for (kind, partially_fillable) in all_kind_and_fillable() {
            let intent = sample_intent(kind, partially_fillable);
            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 (kind, partially_fillable) in all_kind_and_fillable() {
            let encoded = EncodedOrderIntent::from(&sample_intent(kind, partially_fillable));
            let (_intent, uid) =
                EncodedOrderIntent::decode_and_hash(&encoded).expect("example must decode");
            assert_eq!(uid, encoded.hash());
        }
    }

    #[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 sell_false: EncodedOrderIntent = (&sample_intent(OrderKind::Sell, false)).into();
        let sell_true: EncodedOrderIntent = (&sample_intent(OrderKind::Sell, true)).into();
        let buy_true: EncodedOrderIntent = (&sample_intent(OrderKind::Buy, true)).into();

        assert_eq!(
            first_differing_byte(sell_false.as_slice(), sell_true.as_slice())
                .expect("should have different partially fillable byte"),
            PARTIALLY_FILLABLE_OFFSET
        );
        assert_eq!(
            first_differing_byte(buy_true.as_slice(), sell_true.as_slice())
                .expect("should have different kind byte"),
            KIND_OFFSET
        );
    }

    #[test]
    fn decode_rejects_out_of_range_kind() {
        let encoded = EncodedOrderIntent::from(&sample_intent(OrderKind::Sell, false));
        let mut bytes: [u8; EncodedOrderIntent::SIZE] = *encoded;
        for bad in 0x02u8..=0xff {
            bytes[KIND_OFFSET] = bad;
            let err = EncodedOrderIntent::decode_and_hash(&bytes)
                .expect_err("should reject out of range kind");
            assert_eq!(err, ProgramError::InvalidInstructionData);
        }
    }

    #[test]
    fn decode_rejects_non_boolean_partially_fillable() {
        let encoded = EncodedOrderIntent::from(&sample_intent(OrderKind::Sell, false));
        let mut bytes: [u8; EncodedOrderIntent::SIZE] = *encoded;
        for bad in 0x02u8..=0xff {
            bytes[PARTIALLY_FILLABLE_OFFSET] = bad;
            let err = EncodedOrderIntent::decode_and_hash(&bytes)
                .expect_err("should reject out of range partially fillable");
            assert_eq!(err, ProgramError::InvalidInstructionData);
        }
    }

    #[test]
    fn uid_digest_regression() {
        let intent = sample_intent(OrderKind::Buy, true);
        let expected = hex!("7ce7c6a74671090771fa33851387444064aca759ce55b80708723076722f5e00");
        assert_eq!(intent.uid(), Hash::from(expected));
    }

    #[test]
    fn encoding_regression() {
        let encoded = EncodedOrderIntent::from(&sample_intent(OrderKind::Buy, 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,
            // buy_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_token_account ([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,
            // 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,
            // kind (Buy = 1)
            0x01,
            // partially_fillable (true = 1)
            0x01,
            // app_data ([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,
        ];
        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_order_intent, arb_order_kind, KIND_OFFSET, PARTIALLY_FILLABLE_OFFSET,
        };

        // Any byte not decoding to a valid order type.
        fn arb_bad_order_kind_byte() -> impl Strategy<Value = u8> {
            2u8..=255
        }

        // Any byte not decoding to a valid bool.
        fn arb_bad_bool_byte() -> impl Strategy<Value = u8> {
            2u8..=255
        }

        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 `kind` and `partially_fillable` slots
            // are valid, `decode_and_hash` and then re-encoding produces
            // back the original bytes.
            #[test]
            fn bytes_roundtrip(
                mut bytes in any::<[u8; EncodedOrderIntent::SIZE]>(),
                kind in arb_order_kind(),
                partially_fillable in any::<bool>(),
            ) {
                bytes[KIND_OFFSET] = kind as u8;
                bytes[PARTIALLY_FILLABLE_OFFSET] = partially_fillable as u8;
                let (intent, _uid) = EncodedOrderIntent::decode_and_hash(&bytes)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(*EncodedOrderIntent::from(&intent), bytes);
            }

            // For any bytes with an invalid `kind` byte (and a valid
            // `partially_fillable`), `decode_and_hash` returns
            // `InvalidInstructionData`.
            #[test]
            fn rejects_invalid_kind_byte(
                mut bytes in any::<[u8; EncodedOrderIntent::SIZE]>(),
                bad_kind in arb_bad_order_kind_byte(),
                partially_fillable in any::<bool>(),
            ) {
                bytes[KIND_OFFSET] = bad_kind;
                bytes[PARTIALLY_FILLABLE_OFFSET] = partially_fillable as u8;
                prop_assert_eq!(
                    EncodedOrderIntent::decode_and_hash(&bytes),
                    Err(ProgramError::InvalidInstructionData),
                );
            }

            // Symmetric: any bytes with an out-of-range
            // `partially_fillable` byte (and a valid `kind`) return
            // `InvalidInstructionData`.
            #[test]
            fn rejects_invalid_partially_fillable_byte(
                mut bytes in any::<[u8; EncodedOrderIntent::SIZE]>(),
                kind in arb_order_kind(),
                bad_pf in arb_bad_bool_byte(),
            ) {
                bytes[KIND_OFFSET] = kind as u8;
                bytes[PARTIALLY_FILLABLE_OFFSET] = bad_pf;
                prop_assert_eq!(
                    EncodedOrderIntent::decode_and_hash(&bytes),
                    Err(ProgramError::InvalidInstructionData),
                );
            }
        }
    }
}