cow-settlement-interface 0.5.1

Account layouts, PDA derivations, and instruction builders for the CoW Protocol Solana settlement program.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
//! Order intents and their canonical byte representation.
//!
//! The intent has two representations:
//!
//! - [`OrderIntent`] is the idiomatic Rust representation. Everything outside
//!   the settlement program uses it.
//! - [`EncodedOrderIntent`] is the canonical byte representation: the only
//!   thing sent on the wire and also the data encoding used to generate the
//!   order UID. There, `kind` and `partially_fillable` share a single flags
//!   byte.
//!
//! Conversion is asymmetric: encoding an [`OrderIntent`] is infallible, but
//! decoding raw bytes returns `Result` and rejects a flags byte carrying a bit
//! the encoding doesn't define.

use core::mem::size_of;
use core::num::NonZeroU64;

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

use crate::SettlementError;

/// The address an encoded intent carries as a mint to trade native SOL rather
/// than a token; see [`Asset::Native`].
pub const ENCODED_NATIVE_SOL_TRANSFER: Pubkey = solana_system_interface::program::ID;

/// 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 {
    /// 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. Bit 0 is reserved for off-chain orders.
    const KIND: u8 = 1 << 1;
    const PARTIALLY_FILLABLE: u8 = 1 << 2;

    /// Every bit the encoding defines; the others are reserved.
    const DEFINED: u8 = 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.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 {
            kind: if byte & Self::KIND == 0 {
                OrderKind::Sell
            } else {
                OrderKind::Buy
            },
            partially_fillable: byte & Self::PARTIALLY_FILLABLE != 0,
        })
    }
}

/// The representation of the side of a trade involving an actual token.
/// Tokens from the mint `mint` stored at `token_account`.
#[cfg_attr(any(test, feature = "test-fixtures"), derive(Default))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TokenAsset {
    pub mint: Pubkey,
    pub token_account: Pubkey,
}

/// One side of a trade: what moves, and the account it moves through.
///
/// The wire spells a side as a `(mint, account)` pair; this is the same pair
/// with the one combination that isn't a token account named for what it is.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Asset {
    /// Native SOL, moving as lamports on this plain account rather than
    /// through a token account.
    Native(Pubkey),

    /// Tokens moved by a token program.
    TokenProgram(TokenAsset),
}

/// Native SOL has no mint: it moves as lamports, not through a token program.
/// The error returned when a [`TokenAsset`] naming native SOL is converted to
/// an [`Asset`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct NativeSolHasNoMint;

impl TryFrom<TokenAsset> for Asset {
    type Error = NativeSolHasNoMint;

    /// Rejects a `token` naming [`ENCODED_NATIVE_SOL_TRANSFER`]: that's native SOL, and
    /// wrapping it as a token side would encode an asset that decodes back as
    /// [`Asset::Native`].
    fn try_from(token: TokenAsset) -> Result<Self, Self::Error> {
        if token.mint == ENCODED_NATIVE_SOL_TRANSFER {
            return Err(NativeSolHasNoMint);
        }
        Ok(Asset::TokenProgram(token))
    }
}

impl Asset {
    /// The `(mint, account)` pair as used on the wire: a token becomes a mint
    /// and token account; native SOL becomes [`ENCODED_NATIVE_SOL_TRANSFER`]
    /// and the address its lamports move on.
    pub fn encode(&self) -> (Pubkey, Pubkey) {
        match self {
            Asset::Native(account) => (ENCODED_NATIVE_SOL_TRANSFER, *account),
            Asset::TokenProgram(token) => (token.mint, token.token_account),
        }
    }

    /// Decode the `(mint, account)` pair the wire carries into the [`Asset`] it
    /// denotes, for callers that have a side in that shape rather than a chosen
    /// variant.
    pub fn decode(mint: Pubkey, account: Pubkey) -> Self {
        if mint == ENCODED_NATIVE_SOL_TRANSFER {
            Asset::Native(account)
        } else {
            Asset::TokenProgram(TokenAsset {
                mint,
                token_account: account,
            })
        }
    }
}

/// Order intent. Its canonical encoding, [`EncodedOrderIntent`], is the exact wire format of create_order's `intent`
/// argument and the exact bytes hashed (SHA-256) to produce the order UID used in the order PDA's seeds.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrderIntent {
    /// Account authorized to create and invalidate this order and whose
    /// signature authenticates it.
    pub owner: Pubkey,

    /// What the order sells, and the token account the funds are pulled from.
    /// That account implicitly encodes the spender: the settlement state PDA
    /// must hold the SPL `delegate` on it for the order to be settleable, and
    /// it must be owned by the intent owner. An intent that doesn't satisfy
    /// this property will be rejected.
    pub sell: TokenAsset,

    /// What the order buys, and the account that receives the proceeds. That
    /// account implicitly encodes the recipient
    pub buy: Asset,

    /// 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. Must be non-zero.
    pub sell_amount: NonZeroU64,

    /// 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. Must be non-zero.
    pub buy_amount: NonZeroU64,

    /// 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)
    }
}

/// Given a slice of intent bytes, verify that it can encode a valid intent.
#[must_use = "ignoring the result skips the validation"]
#[inline]
pub fn check_bytes(bytes: &[u8; EncodedOrderIntent::SIZE]) -> Result<(), ProgramError> {
    let slots = intent_slots(bytes);
    Flags::try_from(*slots.flags)?;
    if u64::from_le_bytes(*slots.sell_amount) == 0 || u64::from_le_bytes(*slots.buy_amount) == 0 {
        return Err(SettlementError::ZeroOrderAmount.into());
    }
    Ok(())
}

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
    }
}

/// A borrowed view over an intent's bytes, split into named slots so each
/// field can be named. The slots hold raw encoded bytes, not decoded values.
#[doc(hidden)]
pub struct IntentSlots<'a> {
    pub owner: &'a [u8; EncodedOrderIntent::WIDTH_OWNER],
    pub sell_token: &'a [u8; EncodedOrderIntent::WIDTH_SELL_TOKEN],
    pub sell_mint: &'a [u8; EncodedOrderIntent::WIDTH_SELL_MINT],
    pub buy_token: &'a [u8; EncodedOrderIntent::WIDTH_BUY_TOKEN],
    pub buy_mint: &'a [u8; EncodedOrderIntent::WIDTH_BUY_MINT],
    pub sell_amount: &'a [u8; EncodedOrderIntent::WIDTH_SELL_AMOUNT],
    pub buy_amount: &'a [u8; EncodedOrderIntent::WIDTH_BUY_AMOUNT],
    pub valid_to: &'a [u8; EncodedOrderIntent::WIDTH_VALID_TO],
    pub flags: &'a [u8; EncodedOrderIntent::WIDTH_FLAGS],
    pub app_data: &'a [u8; EncodedOrderIntent::WIDTH_APP_DATA],
}

/// Split an intent's bytes into its named slots.
#[inline]
#[doc(hidden)]
pub fn intent_slots(bytes: &[u8; EncodedOrderIntent::SIZE]) -> IntentSlots<'_> {
    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
    ];
    IntentSlots {
        owner,
        sell_token,
        sell_mint,
        buy_token,
        buy_mint,
        sell_amount,
        buy_amount,
        valid_to,
        flags,
        app_data,
    }
}

impl From<&OrderIntent> for EncodedOrderIntent {
    /// Lays each side out the way the wire spells it.
    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();
        let (buy_mint_address, buy_account) = intent.buy.encode();
        *buy_token = buy_account.to_bytes();
        *buy_mint = buy_mint_address.to_bytes();
        *sell_amount = intent.sell_amount.get().to_le_bytes();
        *buy_amount = intent.buy_amount.get().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;

    /// Decode an intent's canonical bytes. Fails with
    /// [`ProgramError::InvalidInstructionData`] if the flags byte sets a
    /// reserved bit; every other byte combination decodes.
    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 slots = intent_slots(bytes);
        Ok(OrderIntent {
            owner: Pubkey::new_from_array(*slots.owner),
            sell: TokenAsset {
                mint: Pubkey::new_from_array(*slots.sell_mint),
                token_account: Pubkey::new_from_array(*slots.sell_token),
            },
            buy: Asset::decode(
                Pubkey::new_from_array(*slots.buy_mint),
                Pubkey::new_from_array(*slots.buy_token),
            ),
            sell_amount: NonZeroU64::new(u64::from_le_bytes(*slots.sell_amount))
                .ok_or(SettlementError::ZeroOrderAmount)?,
            buy_amount: NonZeroU64::new(u64::from_le_bytes(*slots.buy_amount))
                .ok_or(SettlementError::ZeroOrderAmount)?,
            valid_to: u32::from_le_bytes(*slots.valid_to),
            flags: Flags::try_from(*slots.flags)?,
            app_data: *slots.app_data,
        })
    }
}

impl OrderIntent {
    /// SHA-256 of the canonical bytes. Doubles as the order UID and the
    /// middle seed of the order PDA.
    pub fn uid(&self) -> Hash {
        EncodedOrderIntent::from(self).hash()
    }
}

#[cfg(any(test, feature = "test-fixtures"))]
pub mod fixtures {
    use core::mem::size_of;

    use proptest::{prelude::*, strategy::Union};

    use super::{Asset, EncodedOrderIntent, Flags, OrderIntent, OrderKind, Pubkey, TokenAsset};
    use crate::fixtures::IntoNonZero;

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

    // Byte offsets of the fields within an encoded intent. Hardcoded but
    // verified in a sanity-check test.
    pub const SELL_AMOUNT_OFFSET: usize = 160;
    pub const BUY_AMOUNT_OFFSET: usize = 168;
    pub const FLAGS_OFFSET: usize = 180;

    impl Default for Asset {
        /// Native SOL on the all-zero address, the side an all-zero encoding
        fn default() -> Self {
            Asset::Native(Pubkey::default())
        }
    }

    impl Default for OrderIntent {
        /// Every field takes its zero value except the amounts, which are
        /// `NonZeroU64` and so default to arbitrary small non-zero constants.
        fn default() -> Self {
            OrderIntent {
                owner: Pubkey::default(),
                sell: TokenAsset::default(),
                buy: Asset::default(),
                sell_amount: 42.nz(),
                buy_amount: 1337.nz(),
                valid_to: 0,
                flags: Flags::default(),
                app_data: [0; 32],
            }
        }
    }

    pub fn sample_intent(flags: Flags) -> OrderIntent {
        OrderIntent {
            owner: Pubkey::new_from_array([0x11; 32]),
            sell: TokenAsset {
                token_account: Pubkey::new_from_array([0x22; 32]),
                mint: Pubkey::new_from_array([0x33; 32]),
            },
            buy: Asset::TokenProgram(TokenAsset {
                token_account: Pubkey::new_from_array([0x44; 32]),
                mint: Pubkey::new_from_array([0x55; 32]),
            }),
            sell_amount: 0x0123_4567_89ab_cdef.nz(),
            buy_amount: 0xfedc_ba98_7654_3210.nz(),
            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> {
        (arb_order_kind(), any::<bool>()).prop_map(|(kind, partially_fillable)| Flags {
            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 encoded-intent bytes that decode: random bytes with a valid flags
    /// byte and non-zero amounts (the amounts are `NonZeroU64`).
    pub fn arb_intent_bytes() -> impl Strategy<Value = [u8; EncodedOrderIntent::SIZE]> {
        (
            any::<[u8; EncodedOrderIntent::SIZE]>(),
            arb_flags_byte(),
            1..=u64::MAX,
            1..=u64::MAX,
        )
            .prop_map(|(mut bytes, flags, sell_amount, buy_amount)| {
                bytes[FLAGS_OFFSET] = flags;
                bytes[SELL_AMOUNT_OFFSET..SELL_AMOUNT_OFFSET.strict_add(size_of::<u64>())]
                    .copy_from_slice(&sell_amount.to_le_bytes());
                bytes[BUY_AMOUNT_OFFSET..BUY_AMOUNT_OFFSET.strict_add(size_of::<u64>())]
                    .copy_from_slice(&buy_amount.to_le_bytes());
                bytes
            })
    }

    /// 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 [`Asset`], either variant equally likely.
    pub fn arb_asset() -> impl Strategy<Value = Asset> {
        prop_oneof![
            any::<[u8; 32]>().prop_map(|account| Asset::Native(Pubkey::new_from_array(account))),
            (any::<[u8; 32]>(), any::<[u8; 32]>()).prop_filter_map(
                "mint must not be the native SOL marker",
                |(mint, token_account)| Asset::try_from(TokenAsset {
                    mint: Pubkey::new_from_array(mint),
                    token_account: Pubkey::new_from_array(token_account),
                })
                .ok(),
            ),
        ]
    }

    /// Any valid [`OrderIntent`].
    pub fn arb_order_intent() -> impl Strategy<Value = OrderIntent> {
        (
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            arb_asset(),
            1..=u64::MAX,
            1..=u64::MAX,
            any::<u32>(),
            arb_flags(),
            any::<[u8; 32]>(),
        )
            .prop_map(
                |(
                    owner,
                    sell_tok,
                    sell_mint,
                    buy,
                    sell_amount,
                    buy_amount,
                    valid_to,
                    flags,
                    app,
                )| {
                    OrderIntent {
                        owner: Pubkey::new_from_array(owner),
                        sell: TokenAsset {
                            mint: Pubkey::new_from_array(sell_mint),
                            token_account: Pubkey::new_from_array(sell_tok),
                        },
                        buy,
                        sell_amount: sell_amount.nz(),
                        buy_amount: buy_amount.nz(),
                        valid_to,
                        flags,
                        app_data: app,
                    }
                },
            )
    }
}

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

    use super::fixtures::sample_intent;
    use super::*;
    use crate::fixtures::pubkey_from_seed;
    use crate::SettlementError;

    // Every shape an `OrderIntent` can take on its validated axes: the `kind`
    // enum and the `partially_fillable` flag bit.
    fn all_flag_shapes() -> impl Iterator<Item = OrderIntent> {
        fixtures::ALL_ORDER_KINDS.into_iter().flat_map(|kind| {
            [false, true].into_iter().map(move |partially_fillable| {
                sample_intent(Flags {
                    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());
        let (token_account, mint) = &intent.buy.encode();

        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(token_account)
        );
        assert_eq!(EncodedOrderIntent::WIDTH_BUY_MINT, size_of_val(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 {
            kind: OrderKind::Sell,
            partially_fillable: false,
        };
        assert_eq!(byte(cleared), 0);

        let set_one_by_one = [
            (
                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 = OrderIntent::try_from(&*encoded).expect("example must decode");
            assert_eq!(decoded, intent);
        }
    }

    #[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 = OrderIntent::try_from(&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 {
            kind: OrderKind::Buy,
            partially_fillable: true,
        });
        assert_eq!(
            hex(intent.uid().as_ref()),
            "fa1b214e3167f3fdae13ba61f6d2f97975d5b8185912a46a7182a59aba07a3c2",
        );
    }

    #[test]
    fn encoding_regression() {
        let encoded = EncodedOrderIntent::from(&sample_intent(Flags {
            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 (bit 0 reserved | kind (Buy = 1) | partially_fillable)
            0b00000110,
            // 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);
    }

    #[test]
    fn an_asset_lowers_to_the_pair_the_wire_carries() {
        let mint = pubkey_from_seed("mint");
        let account = pubkey_from_seed("account");

        for (buy, expected_mint) in [
            (
                Asset::try_from(TokenAsset {
                    mint,
                    token_account: account,
                })
                .expect("not native SOL"),
                mint,
            ),
            (Asset::Native(account), ENCODED_NATIVE_SOL_TRANSFER),
        ] {
            let encoded = EncodedOrderIntent::from(&OrderIntent {
                buy,
                ..sample_intent(Default::default())
            });
            assert_eq!(intent_slots(&encoded).buy_mint, expected_mint.as_array());
            assert_eq!(intent_slots(&encoded).buy_token, account.as_array());
        }
    }

    #[test]
    fn a_token_side_naming_the_native_marker_is_native_sol() {
        let account = pubkey_from_seed("some account");
        assert_eq!(
            Asset::decode(ENCODED_NATIVE_SOL_TRANSFER, account),
            Asset::Native(account),
        );
    }

    #[test]
    fn a_token_side_naming_the_native_marker_is_not_a_token_asset() {
        let token = TokenAsset {
            mint: ENCODED_NATIVE_SOL_TRANSFER,
            token_account: Pubkey::new_from_array([0x44; 32]),
        };
        assert_eq!(Asset::try_from(token), Err(NativeSolHasNoMint));
    }

    #[test]
    fn all_zero_bytes_do_not_decode() {
        let bytes = [0u8; EncodedOrderIntent::SIZE];
        assert_eq!(
            OrderIntent::try_from(&bytes).err(),
            Some(SettlementError::ZeroOrderAmount.into()),
        );
    }

    #[test]
    fn sanity_check_amounts_decode_from_their_slots() {
        // Two distinct non-zero markers, one per slot, must read back from the
        // matching field. This pins SELL_AMOUNT_OFFSET and BUY_AMOUNT_OFFSET to
        // the decoder without leaning on the sample's other bytes.
        let valid: [u8; EncodedOrderIntent::SIZE] =
            *EncodedOrderIntent::from(&sample_intent(Default::default()));
        let sell_marker: u64 = 0x1111_2222_3333_4444;
        let buy_marker: u64 = 0x5555_6666_7777_8888;
        let mut marked = valid;
        marked[SELL_AMOUNT_OFFSET..SELL_AMOUNT_OFFSET + size_of::<u64>()]
            .copy_from_slice(&sell_marker.to_le_bytes());
        marked[BUY_AMOUNT_OFFSET..BUY_AMOUNT_OFFSET + size_of::<u64>()]
            .copy_from_slice(&buy_marker.to_le_bytes());
        let decoded = OrderIntent::try_from(&marked).expect("non-zero amounts decode");
        assert_eq!(decoded.sell_amount.get(), sell_marker);
        assert_eq!(decoded.buy_amount.get(), buy_marker);
    }

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

        use super::*;
        use crate::data::intent::fixtures::{
            arb_asset, arb_intent_bytes, arb_invalid_flags_byte, arb_order_intent,
            BUY_AMOUNT_OFFSET, FLAGS_OFFSET, SELL_AMOUNT_OFFSET,
        };

        proptest! {

            #[test]
            fn unique_intents_do_not_share_uid(intent_a in arb_order_intent(), intent_b in arb_order_intent()) {
                prop_assume!(intent_a != intent_b);
                prop_assert_ne!(intent_a.uid(), intent_b.uid());
            }

            // For any `OrderIntent`, encoding an intent into an encoded
            // intent and then decoding it returns the same intent.
            #[test]
            fn intent_roundtrip(intent in arb_order_intent()) {
                let encoded = EncodedOrderIntent::from(&intent);
                let decoded = OrderIntent::try_from(&*encoded)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(decoded, intent);
            }

            // For any decodable intent bytes, decoding and then re-encoding
            // produces back the original bytes.
            #[test]
            fn bytes_roundtrip(bytes in arb_intent_bytes()) {
                let intent = OrderIntent::try_from(&bytes)
                    .map_err(|e| TestCaseError::fail(format!("decode failed: {e:?}")))?;
                prop_assert_eq!(*EncodedOrderIntent::from(&intent), bytes);
            }

            // Symmetric: intent bytes whose flags byte carries a reserved bit
            // return `InvalidInstructionData`.
            #[test]
            fn rejects_reserved_flag_bits(
                mut bytes in arb_intent_bytes(),
                bad_flags in arb_invalid_flags_byte(),
            ) {
                bytes[FLAGS_OFFSET] = bad_flags;
                prop_assert_eq!(
                    OrderIntent::try_from(&bytes),
                    Err(ProgramError::InvalidInstructionData),
                );
            }

            // The same, for the amounts: otherwise-valid intent bytes with
            // either amount slot zeroed fail to decode with `ZeroOrderAmount`.
            #[test]
            fn rejects_zero_amount(
                mut bytes in arb_intent_bytes(),
                offset in prop_oneof![Just(SELL_AMOUNT_OFFSET), Just(BUY_AMOUNT_OFFSET)],
            ) {
                bytes[offset..offset.strict_add(size_of::<u64>())].fill(0);
                prop_assert_eq!(
                    OrderIntent::try_from(&bytes),
                    Err(SettlementError::ZeroOrderAmount.into()),
                );
            }

            #[test]
            fn round_trip_encode(asset in arb_asset()) {
                let (mint, account) = asset.encode();
                let decoded_asset = Asset::decode(mint, account);
                prop_assert_eq!(decoded_asset, asset);
            }

            #[test]
            fn round_trip_decode(
                mint in prop_oneof![
                    any::<[u8; 32]>(),
                    Just(ENCODED_NATIVE_SOL_TRANSFER.to_bytes()),
                ],
                account in any::<[u8; 32]>(),
            ) {
                let mint = Pubkey::new_from_array(mint);
                let account = Pubkey::new_from_array(account);
                let asset = Asset::decode(mint, account);
                let (encoded_mint, encoded_account) = asset.encode();
                prop_assert_eq!(encoded_mint, mint);
                prop_assert_eq!(encoded_account, account);
            }
        }
    }
}