lightcone 0.7.1

Rust SDK for the Lightcone Protocol — unified native + WASM client
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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
//! Order types, serialization, hashing, and signing.
//!
//! This module provides the signed and compact order structures with
//! Keccak256 hashing and Ed25519 signing functionality.

use sha3::{Digest, Keccak256};
use solana_pubkey::Pubkey;
use solana_signature::Signature;

#[cfg(feature = "native-auth")]
use solana_keypair::Keypair;
#[cfg(feature = "native-auth")]
use solana_signer::Signer;

use crate::program::constants::{ORDER_SIZE, SIGNED_ORDER_SIZE};
use crate::program::error::{SdkError, SdkResult};
use crate::program::types::{AskOrderParams, BidOrderParams, OrderSide};
use crate::shared::SubmitOrderRequest;

// ============================================================================
// Signed Order (233 bytes)
// ============================================================================

/// Signed order structure with full context and signature.
///
/// Layout (233 bytes):
/// - [0..8]     nonce (8 bytes, u64)
/// - [8..16]    salt (8 bytes, u64)
/// - [16..48]   maker (32 bytes)
/// - [48..80]   market (32 bytes)
/// - [80..112]  base_mint (32 bytes)
/// - [112..144] quote_mint (32 bytes)
/// - [144]      side (1 byte)
/// - [145..153] amount_in (8 bytes)
/// - [153..161] amount_out (8 bytes)
/// - [161..169] expiration (8 bytes)
/// - [169..233] signature (64 bytes)
#[derive(Debug, Clone)]
pub struct OrderPayload {
    /// Unique order ID and replay protection
    pub nonce: u64,
    /// Random salt for order uniqueness
    pub salt: u64,
    /// Order maker's pubkey
    pub maker: Pubkey,
    /// Market pubkey
    pub market: Pubkey,
    /// Base mint (token being bought/sold)
    pub base_mint: Pubkey,
    /// Quote mint (token used for payment)
    pub quote_mint: Pubkey,
    /// Order side (0 = Bid, 1 = Ask)
    pub side: OrderSide,
    /// Amount maker gives
    pub amount_in: u64,
    /// Amount maker receives
    pub amount_out: u64,
    /// Expiration timestamp (0 = no expiration)
    pub expiration: i64,
    /// Ed25519 signature
    pub signature: [u8; 64],
}

impl OrderPayload {
    /// Order size in bytes
    pub const LEN: usize = SIGNED_ORDER_SIZE;

    /// Size of the signed portion of the order (for hashing)
    pub const HASH_SIZE: usize = 169;

    /// Create a new bid order (maker buys base, gives quote)
    pub fn new_bid(params: BidOrderParams) -> Self {
        Self {
            nonce: params.nonce,
            salt: params.salt,
            maker: params.maker,
            market: params.market,
            base_mint: params.base_mint,
            quote_mint: params.quote_mint,
            side: OrderSide::Bid,
            amount_in: params.amount_in,
            amount_out: params.amount_out,
            expiration: params.expiration,
            signature: [0u8; 64],
        }
    }

    /// Create a new ask order (maker sells base, receives quote)
    pub fn new_ask(params: AskOrderParams) -> Self {
        Self {
            nonce: params.nonce,
            salt: params.salt,
            maker: params.maker,
            market: params.market,
            base_mint: params.base_mint,
            quote_mint: params.quote_mint,
            side: OrderSide::Ask,
            amount_in: params.amount_in,
            amount_out: params.amount_out,
            expiration: params.expiration,
            signature: [0u8; 64],
        }
    }

    /// Build the raw 169-byte order message from the signed fields.
    /// This is hashed (keccak256) and hex-encoded to produce the bytes that users sign.
    fn signing_message(&self) -> [u8; Self::HASH_SIZE] {
        let mut data = [0u8; Self::HASH_SIZE];

        data[0..8].copy_from_slice(&self.nonce.to_le_bytes());
        data[8..16].copy_from_slice(&self.salt.to_le_bytes());
        data[16..48].copy_from_slice(self.maker.as_ref());
        data[48..80].copy_from_slice(self.market.as_ref());
        data[80..112].copy_from_slice(self.base_mint.as_ref());
        data[112..144].copy_from_slice(self.quote_mint.as_ref());
        data[144] = self.side as u8;
        data[145..153].copy_from_slice(&self.amount_in.to_le_bytes());
        data[153..161].copy_from_slice(&self.amount_out.to_le_bytes());
        data[161..169].copy_from_slice(&self.expiration.to_le_bytes());

        data
    }

    /// Compute the 32-byte Keccak256 hash of the signed fields.
    pub fn hash(&self) -> [u8; 32] {
        Keccak256::digest(self.signing_message()).into()
    }

    /// Compute the order hash as a hex string.
    pub fn hash_hex(&self) -> String {
        hex::encode(self.hash())
    }

    /// Sign the order with the given keypair.
    #[cfg(feature = "native-auth")]
    pub fn sign(&mut self, keypair: &Keypair) {
        let hash = self.hash_hex();
        let sig = keypair.sign_message(hash.as_bytes());

        self.signature.copy_from_slice(sig.as_ref());
    }

    /// Create and sign an order in one step.
    #[cfg(feature = "native-auth")]
    pub fn new_bid_signed(params: BidOrderParams, keypair: &Keypair) -> Self {
        let mut order = Self::new_bid(params);
        order.sign(keypair);
        order
    }

    /// Create and sign an ask order in one step.
    #[cfg(feature = "native-auth")]
    pub fn new_ask_signed(params: AskOrderParams, keypair: &Keypair) -> Self {
        let mut order = Self::new_ask(params);
        order.sign(keypair);
        order
    }

    /// Verify the Ed25519 signature over hex(keccak256(order_message)).
    /// The signed payload is a 64-char ASCII hex string (UTF-8 safe for wallet compatibility).
    pub fn verify_signature(&self) -> SdkResult<()> {
        let hash_hex = self.hash_hex();
        let sig = Signature::try_from(self.signature.as_slice())
            .map_err(|_| SdkError::InvalidSignature)?;

        if !sig.verify(self.maker.as_ref(), hash_hex.as_bytes()) {
            return Err(SdkError::SignatureVerificationFailed);
        }
        Ok(())
    }

    /// Apply a signature to the order.
    pub fn apply_signature(&mut self, sig_bs58: String) -> SdkResult<()> {
        let signature = sig_bs58
            .parse::<Signature>()
            .map_err(|_| SdkError::InvalidSignature)?;

        self.signature = signature.into();
        Ok(())
    }

    /// Serialize to bytes (233 bytes).
    pub fn serialize(&self) -> [u8; SIGNED_ORDER_SIZE] {
        let mut data = [0u8; SIGNED_ORDER_SIZE];

        data[0..8].copy_from_slice(&self.nonce.to_le_bytes());
        data[8..16].copy_from_slice(&self.salt.to_le_bytes());
        data[16..48].copy_from_slice(self.maker.as_ref());
        data[48..80].copy_from_slice(self.market.as_ref());
        data[80..112].copy_from_slice(self.base_mint.as_ref());
        data[112..144].copy_from_slice(self.quote_mint.as_ref());
        data[144] = self.side as u8;
        data[145..153].copy_from_slice(&self.amount_in.to_le_bytes());
        data[153..161].copy_from_slice(&self.amount_out.to_le_bytes());
        data[161..169].copy_from_slice(&self.expiration.to_le_bytes());
        data[169..233].copy_from_slice(&self.signature);

        data
    }

    /// Deserialize from bytes.
    pub fn deserialize(data: &[u8]) -> SdkResult<Self> {
        if data.len() < SIGNED_ORDER_SIZE {
            return Err(SdkError::InvalidDataLength {
                expected: SIGNED_ORDER_SIZE,
                actual: data.len(),
            });
        }

        let mut nonce_bytes = [0u8; 8];
        nonce_bytes.copy_from_slice(&data[0..8]);

        let mut salt_bytes = [0u8; 8];
        salt_bytes.copy_from_slice(&data[8..16]);

        let mut maker_bytes = [0u8; 32];
        maker_bytes.copy_from_slice(&data[16..48]);

        let mut market_bytes = [0u8; 32];
        market_bytes.copy_from_slice(&data[48..80]);

        let mut base_mint_bytes = [0u8; 32];
        base_mint_bytes.copy_from_slice(&data[80..112]);

        let mut quote_mint_bytes = [0u8; 32];
        quote_mint_bytes.copy_from_slice(&data[112..144]);

        let mut amount_in_bytes = [0u8; 8];
        amount_in_bytes.copy_from_slice(&data[145..153]);

        let mut amount_out_bytes = [0u8; 8];
        amount_out_bytes.copy_from_slice(&data[153..161]);

        let mut expiration_bytes = [0u8; 8];
        expiration_bytes.copy_from_slice(&data[161..169]);

        let mut signature = [0u8; 64];
        signature.copy_from_slice(&data[169..233]);

        Ok(Self {
            nonce: u64::from_le_bytes(nonce_bytes),
            salt: u64::from_le_bytes(salt_bytes),
            maker: Pubkey::new_from_array(maker_bytes),
            market: Pubkey::new_from_array(market_bytes),
            base_mint: Pubkey::new_from_array(base_mint_bytes),
            quote_mint: Pubkey::new_from_array(quote_mint_bytes),
            side: OrderSide::try_from(data[144])?,
            amount_in: u64::from_le_bytes(amount_in_bytes),
            amount_out: u64::from_le_bytes(amount_out_bytes),
            expiration: i64::from_le_bytes(expiration_bytes),
            signature,
        })
    }

    /// Convert to compact order format (37 bytes, no maker field).
    pub fn to_order(&self) -> Order {
        Order {
            nonce: self.nonce as u32,
            salt: self.salt,
            side: self.side,
            amount_in: self.amount_in,
            amount_out: self.amount_out,
            expiration: self.expiration,
        }
    }

    /// Get the signature as a hex string (128 chars).
    pub fn signature_hex(&self) -> String {
        hex::encode(self.signature)
    }

    /// Check if the order has been signed.
    pub fn is_signed(&self) -> bool {
        self.signature != [0u8; 64]
    }

    /// Convert a signed payload to a `SubmitOrderRequest` (limit order, no trigger fields).
    ///
    /// Intended for internal use by envelope types. Prefer using
    /// `LimitOrderEnvelope::sign()` or `TriggerOrderEnvelope::sign()`.
    pub(crate) fn to_submit_request(
        &self,
        orderbook_id: impl Into<String>,
        time_in_force: Option<crate::shared::TimeInForce>,
        trigger_price: Option<f64>,
        trigger_type: Option<crate::shared::TriggerType>,
        deposit_source: Option<crate::shared::DepositSource>,
    ) -> Result<SubmitOrderRequest, SdkError> {
        if self.signature == [0u8; 64] {
            return Err(SdkError::UnsignedOrder);
        }

        Ok(SubmitOrderRequest {
            maker: self.maker.to_string(),
            nonce: self.nonce,
            salt: self.salt,
            market_pubkey: self.market.to_string(),
            base_token: self.base_mint.to_string(),
            quote_token: self.quote_mint.to_string(),
            side: self.side as u32,
            amount_in: self.amount_in,
            amount_out: self.amount_out,
            expiration: self.expiration,
            signature: hex::encode(self.signature),
            orderbook_id: orderbook_id.into(),
            time_in_force,
            trigger_price,
            trigger_type,
            deposit_source,
        })
    }

    /// Derive the orderbook ID for this order.
    ///
    /// Format: `{base_token[0:8]}_{quote_token[0:8]}`
    pub fn derive_orderbook_id(&self) -> String {
        crate::shared::derive_orderbook_id(
            &self.base_mint.to_string(),
            &self.quote_mint.to_string(),
        )
        .to_string()
    }
}

// ============================================================================
// Order (37 bytes)
// ============================================================================

/// Compact order format for on-chain transaction data.
///
/// No `maker` field (derived from Position PDA on-chain).
///
/// Layout (37 bytes):
/// - [0..4]   nonce (4 bytes, u32)
/// - [4..12]  salt (8 bytes, u64)
/// - [12]     side (1 byte)
/// - [13..21] amount_in (8 bytes)
/// - [21..29] amount_out (8 bytes)
/// - [29..37] expiration (8 bytes)
#[derive(Debug, Clone)]
pub struct Order {
    /// Unique order ID and replay protection
    pub nonce: u32,
    /// Random salt for order uniqueness
    pub salt: u64,
    /// Order side (0 = Bid, 1 = Ask)
    pub side: OrderSide,
    /// Amount maker gives
    pub amount_in: u64,
    /// Amount maker receives
    pub amount_out: u64,
    /// Expiration timestamp (0 = no expiration)
    pub expiration: i64,
}

impl Order {
    /// Order size in bytes
    pub const LEN: usize = ORDER_SIZE;

    /// Serialize to bytes (37 bytes).
    pub fn serialize(&self) -> [u8; ORDER_SIZE] {
        let mut data = [0u8; ORDER_SIZE];

        data[0..4].copy_from_slice(&self.nonce.to_le_bytes());
        data[4..12].copy_from_slice(&self.salt.to_le_bytes());
        data[12] = self.side as u8;
        data[13..21].copy_from_slice(&self.amount_in.to_le_bytes());
        data[21..29].copy_from_slice(&self.amount_out.to_le_bytes());
        data[29..37].copy_from_slice(&self.expiration.to_le_bytes());

        data
    }

    /// Deserialize from bytes.
    pub fn deserialize(data: &[u8]) -> SdkResult<Self> {
        if data.len() < ORDER_SIZE {
            return Err(SdkError::InvalidDataLength {
                expected: ORDER_SIZE,
                actual: data.len(),
            });
        }

        let mut nonce_bytes = [0u8; 4];
        nonce_bytes.copy_from_slice(&data[0..4]);

        let mut salt_bytes = [0u8; 8];
        salt_bytes.copy_from_slice(&data[4..12]);

        let mut amount_in_bytes = [0u8; 8];
        amount_in_bytes.copy_from_slice(&data[13..21]);

        let mut amount_out_bytes = [0u8; 8];
        amount_out_bytes.copy_from_slice(&data[21..29]);

        let mut expiration_bytes = [0u8; 8];
        expiration_bytes.copy_from_slice(&data[29..37]);

        Ok(Self {
            nonce: u32::from_le_bytes(nonce_bytes),
            salt: u64::from_le_bytes(salt_bytes),
            side: OrderSide::try_from(data[12])?,
            amount_in: u64::from_le_bytes(amount_in_bytes),
            amount_out: u64::from_le_bytes(amount_out_bytes),
            expiration: i64::from_le_bytes(expiration_bytes),
        })
    }

    /// Expand to signed order using pubkeys from accounts.
    pub fn to_signed(
        &self,
        maker: Pubkey,
        market: Pubkey,
        base_mint: Pubkey,
        quote_mint: Pubkey,
        signature: [u8; 64],
    ) -> OrderPayload {
        OrderPayload {
            nonce: self.nonce as u64,
            salt: self.salt,
            maker,
            market,
            base_mint,
            quote_mint,
            side: self.side,
            amount_in: self.amount_in,
            amount_out: self.amount_out,
            expiration: self.expiration,
            signature,
        }
    }
}

// ============================================================================
// Order Validation Helpers
// ============================================================================

/// Check if an order is expired.
pub fn is_order_expired(order: &OrderPayload, current_time: i64) -> bool {
    order.expiration != 0 && current_time >= order.expiration
}

/// Check if two orders can cross (prices are compatible).
///
/// Returns true if the buyer's price >= seller's price.
pub fn orders_can_cross(buy_order: &OrderPayload, sell_order: &OrderPayload) -> bool {
    if buy_order.side != OrderSide::Bid || sell_order.side != OrderSide::Ask {
        return false;
    }

    if buy_order.amount_in == 0
        || buy_order.amount_out == 0
        || sell_order.amount_in == 0
        || sell_order.amount_out == 0
    {
        return false;
    }

    // Buyer gives quote, receives base
    // Seller gives base, receives quote
    // Cross condition: buyer's price >= seller's price
    // buyer_price = buyer.amount_in / buyer.amount_out (quote per base)
    // seller_price = seller.amount_out / seller.amount_in (quote per base)
    // Cross: buyer.amount_in / buyer.amount_out >= seller.amount_out / seller.amount_in
    // Rearrange: buyer.amount_in * seller.amount_in >= buyer.amount_out * seller.amount_out

    let buyer_cross = (buy_order.amount_in as u128) * (sell_order.amount_in as u128);
    let seller_cross = (buy_order.amount_out as u128) * (sell_order.amount_out as u128);

    buyer_cross >= seller_cross
}

/// Calculate the taker fill amount given a maker fill amount.
pub fn calculate_taker_fill(maker_order: &OrderPayload, maker_fill_amount: u64) -> SdkResult<u64> {
    if maker_order.amount_in == 0 {
        return Err(SdkError::Overflow);
    }

    let result = (maker_fill_amount as u128)
        .checked_mul(maker_order.amount_out as u128)
        .ok_or(SdkError::Overflow)?
        .checked_div(maker_order.amount_in as u128)
        .ok_or(SdkError::Overflow)?;

    if result > u64::MAX as u128 {
        return Err(SdkError::Overflow);
    }

    Ok(result as u64)
}

/// Derive condition ID from oracle, question_id, and num_outcomes.
pub fn derive_condition_id(oracle: &Pubkey, question_id: &[u8; 32], num_outcomes: u8) -> [u8; 32] {
    let mut hasher = Keccak256::new();
    hasher.update(oracle.as_ref());
    hasher.update(question_id);
    hasher.update([num_outcomes]);
    hasher.finalize().into()
}

// ============================================================================
// Cancel Order Signing Helpers
// ============================================================================

/// Build the message bytes for cancelling an order.
///
/// The message is the order hash hex string as UTF-8 bytes (same protocol as order signing).
pub fn cancel_order_message(order_hash: &str) -> Vec<u8> {
    order_hash.as_bytes().to_vec()
}

/// Build the message bytes for cancelling a trigger order.
///
/// The message is the trigger_order_id as UTF-8 bytes.
#[cfg(feature = "trigger_orders")]
pub fn cancel_trigger_order_message(trigger_order_id: &str) -> Vec<u8> {
    trigger_order_id.as_bytes().to_vec()
}

/// Build the message string for cancelling all orders.
///
/// Format: `"cancel_all:{pubkey}:{orderbook_id}:{timestamp}:{salt}"`
pub fn cancel_all_message(
    user_pubkey: &str,
    orderbook_id: &str,
    timestamp: i64,
    salt: &str,
) -> String {
    format!(
        "cancel_all:{}:{}:{}:{}",
        user_pubkey, orderbook_id, timestamp, salt
    )
}

/// Generate a random salt for order uniqueness.
pub fn generate_salt() -> u64 {
    rand::random::<u64>()
}

/// Generate a random UUID v4 salt for cancel-all replay protection.
pub fn generate_cancel_all_salt() -> String {
    let mut bytes = rand::random::<[u8; 16]>();
    bytes[6] = (bytes[6] & 0x0f) | 0x40;
    bytes[8] = (bytes[8] & 0x3f) | 0x80;

    format!(
        "{}-{}-{}-{}-{}",
        hex::encode(&bytes[0..4]),
        hex::encode(&bytes[4..6]),
        hex::encode(&bytes[6..8]),
        hex::encode(&bytes[8..10]),
        hex::encode(&bytes[10..16]),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_order_payload_serialization_roundtrip() {
        let order = OrderPayload {
            nonce: 12345,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 1000000,
            amount_out: 500000,
            expiration: 1234567890,
            signature: [0u8; 64],
        };

        let serialized = order.serialize();
        let deserialized = OrderPayload::deserialize(&serialized).unwrap();

        assert_eq!(order.nonce, deserialized.nonce);
        assert_eq!(order.salt, deserialized.salt);
        assert_eq!(order.maker, deserialized.maker);
        assert_eq!(order.market, deserialized.market);
        assert_eq!(order.base_mint, deserialized.base_mint);
        assert_eq!(order.quote_mint, deserialized.quote_mint);
        assert_eq!(order.side, deserialized.side);
        assert_eq!(order.amount_in, deserialized.amount_in);
        assert_eq!(order.amount_out, deserialized.amount_out);
        assert_eq!(order.expiration, deserialized.expiration);
    }

    #[test]
    fn test_order_serialization_roundtrip() {
        let order = Order {
            nonce: 12345,
            salt: 0,
            side: OrderSide::Ask,
            amount_in: 1000000,
            amount_out: 500000,
            expiration: 1234567890,
        };

        let serialized = order.serialize();
        let deserialized = Order::deserialize(&serialized).unwrap();

        assert_eq!(order.nonce, deserialized.nonce);
        assert_eq!(order.salt, deserialized.salt);
        assert_eq!(order.side, deserialized.side);
        assert_eq!(order.amount_in, deserialized.amount_in);
        assert_eq!(order.amount_out, deserialized.amount_out);
        assert_eq!(order.expiration, deserialized.expiration);
    }

    #[test]
    fn test_order_size() {
        assert_eq!(ORDER_SIZE, 37);
        let order = Order {
            nonce: 1,
            salt: 0,
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
        };
        assert_eq!(order.serialize().len(), 37);
    }

    #[test]
    fn test_order_hash_consistency() {
        let order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_from_array([1u8; 32]),
            market: Pubkey::new_from_array([2u8; 32]),
            base_mint: Pubkey::new_from_array([3u8; 32]),
            quote_mint: Pubkey::new_from_array([4u8; 32]),
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
            signature: [0u8; 64],
        };

        let hash1 = order.hash();
        let hash2 = order.hash();
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_signed_order_to_order_roundtrip() {
        let signed = OrderPayload {
            nonce: 42,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 1000,
            amount_out: 500,
            expiration: 12345,
            signature: [7u8; 64],
        };

        let order = signed.to_order();
        assert_eq!(order.nonce, 42);
        assert_eq!(order.side, OrderSide::Bid);
        assert_eq!(order.amount_in, 1000);
        assert_eq!(order.amount_out, 500);
        assert_eq!(order.expiration, 12345);

        let back = order.to_signed(
            signed.maker,
            signed.market,
            signed.base_mint,
            signed.quote_mint,
            signed.signature,
        );
        assert_eq!(back.nonce, 42);
        assert_eq!(back.maker, signed.maker);
        assert_eq!(back.amount_in, 1000);
    }

    #[test]
    fn test_orders_can_cross() {
        let buy_order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 100, // 100 quote
            amount_out: 50, // for 50 base (price = 2 quote/base)
            expiration: 0,
            signature: [0u8; 64],
        };

        let sell_order = OrderPayload {
            nonce: 2,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: buy_order.market,
            base_mint: buy_order.base_mint,
            quote_mint: buy_order.quote_mint,
            side: OrderSide::Ask,
            amount_in: 50,  // 50 base
            amount_out: 90, // for 90 quote (price = 1.8 quote/base)
            expiration: 0,
            signature: [0u8; 64],
        };

        // Buyer pays 2 quote/base, seller wants 1.8 quote/base - should cross
        assert!(orders_can_cross(&buy_order, &sell_order));
    }

    #[test]
    fn test_orders_cannot_cross() {
        let buy_order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 50,  // 50 quote
            amount_out: 50, // for 50 base (price = 1 quote/base)
            expiration: 0,
            signature: [0u8; 64],
        };

        let sell_order = OrderPayload {
            nonce: 2,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: buy_order.market,
            base_mint: buy_order.base_mint,
            quote_mint: buy_order.quote_mint,
            side: OrderSide::Ask,
            amount_in: 50,   // 50 base
            amount_out: 100, // for 100 quote (price = 2 quote/base)
            expiration: 0,
            signature: [0u8; 64],
        };

        // Buyer pays 1 quote/base, seller wants 2 quote/base - should not cross
        assert!(!orders_can_cross(&buy_order, &sell_order));
    }

    #[test]
    fn test_calculate_taker_fill() {
        let maker_order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Ask,
            amount_in: 100,  // gives 100 base
            amount_out: 200, // wants 200 quote
            expiration: 0,
            signature: [0u8; 64],
        };

        // If filling 50 amount_in, taker should get 50 * 200 / 100 = 100
        let taker_fill = calculate_taker_fill(&maker_order, 50).unwrap();
        assert_eq!(taker_fill, 100);
    }

    #[test]
    #[cfg(feature = "native-auth")]
    fn test_to_submit_request() {
        use solana_keypair::Keypair;
        use solana_signer::Signer;

        let keypair = Keypair::new();
        let maker = keypair.pubkey();
        let market = Pubkey::new_unique();
        let base_mint = Pubkey::new_unique();
        let quote_mint = Pubkey::new_unique();

        let mut order = OrderPayload {
            nonce: 42,
            salt: 0,
            maker,
            market,
            base_mint,
            quote_mint,
            side: OrderSide::Bid,
            amount_in: 1_000_000,
            amount_out: 500_000,
            expiration: 1234567890,
            signature: [0u8; 64],
        };

        order.sign(&keypair);

        let request = order
            .to_submit_request("test_orderbook", None, None, None, None)
            .unwrap();

        assert_eq!(request.maker, maker.to_string());
        assert_eq!(request.nonce, 42);
        assert_eq!(request.market_pubkey, market.to_string());
        assert_eq!(request.base_token, base_mint.to_string());
        assert_eq!(request.quote_token, quote_mint.to_string());
        assert_eq!(request.side, 0); // Bid
        assert_eq!(request.amount_in, 1_000_000);
        assert_eq!(request.amount_out, 500_000);
        assert_eq!(request.expiration, 1234567890);
        assert_eq!(request.orderbook_id, "test_orderbook");
        assert_eq!(request.signature.len(), 128); // 64 bytes = 128 hex chars
    }

    #[test]
    fn test_derive_orderbook_id() {
        let order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_from_array([1u8; 32]),
            market: Pubkey::new_from_array([2u8; 32]),
            base_mint: Pubkey::new_from_array([3u8; 32]),
            quote_mint: Pubkey::new_from_array([4u8; 32]),
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
            signature: [0u8; 64],
        };

        let orderbook_id = order.derive_orderbook_id();
        // The orderbook ID should be first 8 chars of each pubkey string
        let base_str = order.base_mint.to_string();
        let quote_str = order.quote_mint.to_string();
        let expected = format!("{}_{}", &base_str[..8], &quote_str[..8]);
        assert_eq!(orderbook_id, expected);
    }

    #[test]
    #[cfg(feature = "native-auth")]
    fn test_is_signed() {
        use solana_keypair::Keypair;
        use solana_signer::Signer;

        let keypair = Keypair::new();
        let mut order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: keypair.pubkey(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
            signature: [0u8; 64],
        };

        assert!(!order.is_signed());

        order.sign(&keypair);

        assert!(order.is_signed());
    }

    #[test]
    #[cfg(feature = "native-auth")]
    fn test_signature_and_hash_hex() {
        use solana_keypair::Keypair;
        use solana_signer::Signer;

        let keypair = Keypair::new();
        let mut order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: keypair.pubkey(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
            signature: [0u8; 64],
        };

        order.sign(&keypair);

        let sig_hex = order.signature_hex();
        let hash_hex = order.hash_hex();

        // Signature should be 128 hex chars (64 bytes)
        assert_eq!(sig_hex.len(), 128);
        // Hash should be 64 hex chars (32 bytes)
        assert_eq!(hash_hex.len(), 64);

        // Verify they are valid hex
        assert!(hex::decode(&sig_hex).is_ok());
        assert!(hex::decode(&hash_hex).is_ok());
    }

    #[test]
    fn test_to_submit_request_errors_unsigned() {
        let order = OrderPayload {
            nonce: 1,
            salt: 0,
            maker: Pubkey::new_unique(),
            market: Pubkey::new_unique(),
            base_mint: Pubkey::new_unique(),
            quote_mint: Pubkey::new_unique(),
            side: OrderSide::Bid,
            amount_in: 100,
            amount_out: 50,
            expiration: 0,
            signature: [0u8; 64],
        };

        let result = order.to_submit_request("test_orderbook", None, None, None, None);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("must be signed"),);
    }

    #[test]
    #[cfg(feature = "trigger_orders")]
    fn test_cancel_trigger_order_message() {
        let id = "trigger-order-uuid-123";
        let message = cancel_trigger_order_message(id);
        assert_eq!(message, id.as_bytes());
    }

    #[test]
    fn test_cancel_order_message() {
        let hash = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
        let message = cancel_order_message(hash);
        assert_eq!(message, hash.as_bytes());
    }

    #[test]
    fn test_cancel_all_message() {
        let pubkey = "SomePubkey123";
        let orderbook_id = "test_orderbook";
        let timestamp = 1700000000i64;
        let salt = "550e8400-e29b-41d4-a716-446655440000";
        let message = cancel_all_message(pubkey, orderbook_id, timestamp, salt);
        assert_eq!(
            message,
            "cancel_all:SomePubkey123:test_orderbook:1700000000:550e8400-e29b-41d4-a716-446655440000"
        );
    }

    #[test]
    fn test_generate_cancel_all_salt() {
        let salt = generate_cancel_all_salt();
        assert_eq!(salt.len(), 36);
        assert_eq!(salt.chars().filter(|c| *c == '-').count(), 4);
        assert_eq!(salt.chars().nth(14), Some('4'));
    }

    #[test]
    #[cfg(feature = "native-auth")]
    fn test_cancel_body_signed() {
        use crate::domain::order::CancelBody;
        use solana_keypair::Keypair;
        use solana_signer::Signer;

        let keypair = Keypair::new();
        let order_hash = "abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890";
        let maker = crate::shared::PubkeyStr::from_pubkey(keypair.pubkey());

        let body = CancelBody::signed(order_hash.to_string(), maker, &keypair);
        assert_eq!(body.signature.len(), 128);
        assert_eq!(body.order_hash, order_hash);

        let sig_bytes = hex::decode(&body.signature).unwrap();
        let sig = Signature::try_from(sig_bytes.as_slice()).unwrap();
        assert!(sig.verify(keypair.pubkey().as_ref(), order_hash.as_bytes()));
    }

    #[test]
    #[cfg(feature = "native-auth")]
    fn test_cancel_all_body_signed() {
        use crate::domain::order::CancelAllBody;
        use solana_keypair::Keypair;
        use solana_signer::Signer;

        let keypair = Keypair::new();
        let pubkey_str = crate::shared::PubkeyStr::from_pubkey(keypair.pubkey());
        let orderbook_id = crate::shared::OrderBookId::from("");
        let timestamp = 1700000000i64;
        let salt = "550e8400-e29b-41d4-a716-446655440000".to_string();

        let body = CancelAllBody::signed(
            pubkey_str.clone(),
            orderbook_id.clone(),
            timestamp,
            salt.clone(),
            &keypair,
        );
        assert_eq!(body.signature.len(), 128);
        assert_eq!(body.salt, salt);

        let message =
            cancel_all_message(pubkey_str.as_str(), orderbook_id.as_str(), timestamp, &salt);
        let sig_bytes = hex::decode(&body.signature).unwrap();
        let sig = Signature::try_from(sig_bytes.as_slice()).unwrap();
        assert!(sig.verify(keypair.pubkey().as_ref(), message.as_bytes()));
    }
}