ccxt-exchanges 0.1.5

Exchange implementations for CCXT Rust
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
#![allow(clippy::disallowed_methods)]
//! Property-based tests for HyperLiquid exchange implementation.
//!
//! These tests verify correctness properties using proptest.

use proptest::prelude::*;

/// **Feature: hyperliquid-exchange, Property 1: Private Key to Address Derivation**
/// **Validates: Requirements 1.1**
///
/// For any valid 32-byte private key, deriving the wallet address SHALL produce
/// a valid Ethereum address (40 hex characters prefixed with "0x") that is
/// deterministic for the same input.
mod private_key_derivation {
    use super::*;
    use ccxt_exchanges::hyperliquid::HyperLiquidAuth;

    // Strategy for generating valid 32-byte private keys as hex strings
    fn valid_private_key_strategy() -> impl Strategy<Value = String> {
        // Generate 32 random bytes as hex (64 hex chars)
        prop::collection::vec(any::<u8>(), 32..=32)
            .prop_map(|bytes| format!("0x{}", hex::encode(bytes)))
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that valid private keys produce valid Ethereum addresses
        #[test]
        fn prop_valid_key_produces_valid_address(key in valid_private_key_strategy()) {
            // Some keys may be invalid (out of curve range), skip those
            if let Ok(auth) = HyperLiquidAuth::from_private_key(&key) {
                let address = auth.wallet_address();

                // Address should start with "0x"
                prop_assert!(
                    address.starts_with("0x"),
                    "Address should start with '0x', got: {}",
                    address
                );

                // Address should be 42 characters (0x + 40 hex chars)
                prop_assert_eq!(
                    address.len(),
                    42,
                    "Address should be 42 characters, got: {}",
                    address.len()
                );

                // Address should only contain valid hex characters after 0x
                let hex_part = &address[2..];
                prop_assert!(
                    hex_part.chars().all(|c| c.is_ascii_hexdigit()),
                    "Address should only contain hex characters, got: {}",
                    address
                );
            }
        }

        /// Test that address derivation is deterministic
        #[test]
        fn prop_address_derivation_deterministic(key in valid_private_key_strategy()) {
            // Some keys may be invalid (out of curve range), skip those
            if let Ok(auth1) = HyperLiquidAuth::from_private_key(&key) {
                let auth2 = HyperLiquidAuth::from_private_key(&key)
                    .expect("Second derivation should succeed if first did");

                prop_assert_eq!(
                    auth1.wallet_address(),
                    auth2.wallet_address(),
                    "Same private key should always produce same address"
                );
            }
        }

        /// Test that private key without 0x prefix works the same
        #[test]
        fn prop_key_with_and_without_prefix_same(key in valid_private_key_strategy()) {
            let key_without_prefix = key.strip_prefix("0x").unwrap_or(&key);

            if let Ok(auth_with) = HyperLiquidAuth::from_private_key(&key) {
                let auth_without = HyperLiquidAuth::from_private_key(key_without_prefix)
                    .expect("Key without prefix should work if key with prefix works");

                prop_assert_eq!(
                    auth_with.wallet_address(),
                    auth_without.wallet_address(),
                    "Keys with and without 0x prefix should produce same address"
                );
            }
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 2: Invalid Private Key Rejection**
/// **Validates: Requirements 1.2**
///
/// For any byte sequence that is not a valid 32-byte private key (wrong length,
/// invalid format, or out of curve range), the authenticator SHALL return an
/// error without panicking.
mod invalid_private_key_rejection {
    use super::*;
    use ccxt_exchanges::hyperliquid::HyperLiquidAuth;

    // Strategy for generating invalid hex strings (wrong length)
    fn wrong_length_key_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            // Too short (1-31 bytes)
            prop::collection::vec(any::<u8>(), 1..32)
                .prop_map(|bytes| format!("0x{}", hex::encode(bytes))),
            // Too long (33-64 bytes)
            prop::collection::vec(any::<u8>(), 33..65)
                .prop_map(|bytes| format!("0x{}", hex::encode(bytes))),
            // Empty
            Just("0x".to_string()),
            Just("".to_string()),
        ]
    }

    // Strategy for generating invalid hex format strings
    fn invalid_hex_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            // Contains non-hex characters (G is not valid hex)
            Just("0xGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG".to_string()),
            Just("0x123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefZ".to_string()),
            // Contains spaces
            Just("0x 1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcde".to_string()),
            // Contains special characters
            Just("0x!@#$%^&*()1234567890abcdef1234567890abcdef1234567890abcdef12345".to_string()),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that wrong length keys are rejected
        #[test]
        fn prop_wrong_length_rejected(key in wrong_length_key_strategy()) {
            let result = HyperLiquidAuth::from_private_key(&key);
            prop_assert!(
                result.is_err(),
                "Wrong length key should be rejected: {}",
                key
            );
        }

        /// Test that invalid hex format is rejected
        #[test]
        fn prop_invalid_hex_rejected(key in invalid_hex_strategy()) {
            let result = HyperLiquidAuth::from_private_key(&key);
            prop_assert!(
                result.is_err(),
                "Invalid hex format should be rejected: {}",
                key
            );
        }

        /// Test that very short strings are rejected gracefully
        #[test]
        fn prop_short_strings_rejected(len in 0usize..10usize) {
            let key = "a".repeat(len);
            let result = HyperLiquidAuth::from_private_key(&key);
            // Should not panic, should return error
            prop_assert!(
                result.is_err(),
                "Short string should be rejected: {}",
                key
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 3: EIP-712 Signature Determinism**
/// **Validates: Requirements 3.1, 3.4**
///
/// For any L1 action and nonce, signing with the same private key SHALL produce
/// the same signature, and the signature SHALL be in valid secp256k1 format
/// (r, s, v components).
mod eip712_signature_determinism {
    use super::*;
    use ccxt_exchanges::hyperliquid::HyperLiquidAuth;
    use serde_json::json;

    // Test private key (DO NOT USE IN PRODUCTION)
    const TEST_PRIVATE_KEY: &str =
        "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

    // Strategy for generating valid nonces (timestamp-like values)
    fn nonce_strategy() -> impl Strategy<Value = u64> {
        1577836800000u64..1893456000000u64 // 2020-2030 in milliseconds
    }

    // Strategy for generating action types
    fn action_type_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("order".to_string()),
            Just("cancel".to_string()),
            Just("cancelByCloid".to_string()),
            Just("modifyOrder".to_string()),
            Just("updateLeverage".to_string()),
        ]
    }

    // Strategy for generating simple action payloads
    fn action_payload_strategy() -> impl Strategy<Value = serde_json::Value> {
        (action_type_strategy(), 0u32..100u32, any::<bool>()).prop_map(
            |(action_type, asset, is_buy)| {
                json!({
                    "type": action_type,
                    "asset": asset,
                    "isBuy": is_buy
                })
            },
        )
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that signing the same action with same nonce produces same signature
        #[test]
        fn prop_signature_deterministic(
            action in action_payload_strategy(),
            nonce in nonce_strategy(),
            is_mainnet in any::<bool>()
        ) {
            let auth = HyperLiquidAuth::from_private_key(TEST_PRIVATE_KEY)
                .expect("Failed to create auth");

            let sig1 = auth.sign_l1_action(&action, nonce, is_mainnet)
                .expect("First signing should succeed");
            let sig2 = auth.sign_l1_action(&action, nonce, is_mainnet)
                .expect("Second signing should succeed");

            prop_assert_eq!(sig1.r, sig2.r, "R component should be deterministic");
            prop_assert_eq!(sig1.s, sig2.s, "S component should be deterministic");
            prop_assert_eq!(sig1.v, sig2.v, "V component should be deterministic");
        }

        /// Test that signature components have valid format
        #[test]
        fn prop_signature_format_valid(
            action in action_payload_strategy(),
            nonce in nonce_strategy(),
            is_mainnet in any::<bool>()
        ) {
            let auth = HyperLiquidAuth::from_private_key(TEST_PRIVATE_KEY)
                .expect("Failed to create auth");

            let sig = auth.sign_l1_action(&action, nonce, is_mainnet)
                .expect("Signing should succeed");

            // R and S should be 64 hex characters (32 bytes each)
            prop_assert_eq!(
                sig.r.len(),
                64,
                "R component should be 64 hex chars, got: {}",
                sig.r.len()
            );
            prop_assert_eq!(
                sig.s.len(),
                64,
                "S component should be 64 hex chars, got: {}",
                sig.s.len()
            );

            // R and S should be valid hex
            prop_assert!(
                sig.r.chars().all(|c| c.is_ascii_hexdigit()),
                "R should be valid hex"
            );
            prop_assert!(
                sig.s.chars().all(|c| c.is_ascii_hexdigit()),
                "S should be valid hex"
            );

            // V should be 27 or 28 (standard Ethereum recovery id)
            prop_assert!(
                sig.v == 27 || sig.v == 28,
                "V should be 27 or 28, got: {}",
                sig.v
            );
        }

        /// Test that different nonces produce different signatures
        #[test]
        fn prop_different_nonce_different_signature(
            action in action_payload_strategy(),
            nonce1 in nonce_strategy(),
            nonce2 in nonce_strategy(),
            is_mainnet in any::<bool>()
        ) {
            prop_assume!(nonce1 != nonce2);

            let auth = HyperLiquidAuth::from_private_key(TEST_PRIVATE_KEY)
                .expect("Failed to create auth");

            let sig1 = auth.sign_l1_action(&action, nonce1, is_mainnet)
                .expect("First signing should succeed");
            let sig2 = auth.sign_l1_action(&action, nonce2, is_mainnet)
                .expect("Second signing should succeed");

            // At least one component should differ
            prop_assert!(
                sig1.r != sig2.r || sig1.s != sig2.s,
                "Different nonces should produce different signatures"
            );
        }

        /// Test that signature to_hex produces valid format
        #[test]
        fn prop_signature_to_hex_valid(
            action in action_payload_strategy(),
            nonce in nonce_strategy(),
            is_mainnet in any::<bool>()
        ) {
            let auth = HyperLiquidAuth::from_private_key(TEST_PRIVATE_KEY)
                .expect("Failed to create auth");

            let sig = auth.sign_l1_action(&action, nonce, is_mainnet)
                .expect("Signing should succeed");

            let hex = sig.to_hex();

            // Should start with 0x
            prop_assert!(hex.starts_with("0x"), "Hex should start with 0x");

            // Should be 132 characters (0x + 64 + 64 + 2)
            prop_assert_eq!(
                hex.len(),
                132,
                "Hex signature should be 132 chars, got: {}",
                hex.len()
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 4: Market Symbol Format**
/// **Validates: Requirements 2.1**
///
/// For any market returned by fetch_markets, the symbol SHALL match the pattern
/// "{BASE}/USDC:USDC" for perpetual contracts.
mod market_symbol_format {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::parse_market;
    use serde_json::json;

    // Strategy for generating valid asset names (uppercase letters, 2-10 chars)
    fn asset_name_strategy() -> impl Strategy<Value = String> {
        "[A-Z]{2,10}"
    }

    // Strategy for generating valid size decimals (0-8)
    fn sz_decimals_strategy() -> impl Strategy<Value = u64> {
        0u64..9u64
    }

    // Strategy for generating market index
    fn market_index_strategy() -> impl Strategy<Value = usize> {
        0usize..1000usize
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that parsed market symbol follows the correct format
        #[test]
        fn prop_market_symbol_format(
            asset_name in asset_name_strategy(),
            sz_decimals in sz_decimals_strategy(),
            index in market_index_strategy()
        ) {
            let data = json!({
                "name": asset_name,
                "szDecimals": sz_decimals
            });

            let market = parse_market(&data, index)
                .expect("Market parsing should succeed");

            // Symbol should match pattern {BASE}/USDC:USDC
            let expected_symbol = format!("{}/USDC:USDC", asset_name);
            prop_assert_eq!(
                market.symbol,
                expected_symbol,
                "Symbol should match pattern BASE/USDC:USDC"
            );

            // Base should be the asset name
            prop_assert_eq!(
                market.base,
                asset_name,
                "Base should be the asset name"
            );

            // Quote should be USDC
            prop_assert_eq!(
                market.quote,
                "USDC",
                "Quote should be USDC"
            );

            // Settle should be USDC
            prop_assert_eq!(
                market.settle,
                Some("USDC".to_string()),
                "Settle should be USDC"
            );
        }

        /// Test that market is always active and supports margin
        #[test]
        fn prop_market_is_perpetual(
            asset_name in asset_name_strategy(),
            sz_decimals in sz_decimals_strategy(),
            index in market_index_strategy()
        ) {
            let data = json!({
                "name": asset_name,
                "szDecimals": sz_decimals
            });

            let market = parse_market(&data, index)
                .expect("Market parsing should succeed");

            prop_assert!(market.active, "Market should be active");
            prop_assert!(market.margin, "Market should support margin");
            prop_assert_eq!(market.contract, Some(true), "Market should be a contract");
            prop_assert_eq!(market.linear, Some(true), "Market should be linear");
            prop_assert_eq!(market.inverse, Some(false), "Market should not be inverse");
        }

        /// Test that market ID is the index as string
        #[test]
        fn prop_market_id_is_index(
            asset_name in asset_name_strategy(),
            sz_decimals in sz_decimals_strategy(),
            index in market_index_strategy()
        ) {
            let data = json!({
                "name": asset_name,
                "szDecimals": sz_decimals
            });

            let market = parse_market(&data, index)
                .expect("Market parsing should succeed");

            prop_assert_eq!(
                market.id,
                index.to_string(),
                "Market ID should be the index as string"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 5: Ticker Data Completeness**
/// **Validates: Requirements 2.2**
///
/// For any ticker returned by fetch_ticker, the ticker SHALL contain non-null
/// values for last price, and the timestamp SHALL be a valid Unix millisecond timestamp.
mod ticker_data_completeness {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::parse_ticker;
    use rust_decimal::Decimal;
    use rust_decimal::prelude::FromPrimitive;

    // Strategy for generating valid mid prices
    fn mid_price_strategy() -> impl Strategy<Value = Decimal> {
        (1u64..1000000u64).prop_map(|n| Decimal::from_u64(n).unwrap())
    }

    // Strategy for generating valid symbols
    fn symbol_strategy() -> impl Strategy<Value = String> {
        "[A-Z]{2,10}".prop_map(|s| format!("{}/USDC:USDC", s))
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that ticker has valid last price
        #[test]
        fn prop_ticker_has_last_price(
            symbol in symbol_strategy(),
            mid_price in mid_price_strategy()
        ) {
            let ticker = parse_ticker(&symbol, mid_price, None)
                .expect("Ticker parsing should succeed");

            prop_assert!(
                ticker.last.is_some(),
                "Ticker should have last price"
            );

            let last = ticker.last.unwrap();
            prop_assert!(
                last.0 > Decimal::ZERO,
                "Last price should be positive"
            );
        }

        /// Test that ticker has valid timestamp
        #[test]
        fn prop_ticker_has_valid_timestamp(
            symbol in symbol_strategy(),
            mid_price in mid_price_strategy()
        ) {
            let ticker = parse_ticker(&symbol, mid_price, None)
                .expect("Ticker parsing should succeed");

            // Timestamp should be in reasonable range (2020-2030)
            prop_assert!(
                ticker.timestamp >= 1577836800000,
                "Timestamp should be after 2020"
            );
            prop_assert!(
                ticker.timestamp <= 1893456000000,
                "Timestamp should be before 2030"
            );
        }

        /// Test that ticker symbol matches input
        #[test]
        fn prop_ticker_symbol_matches(
            symbol in symbol_strategy(),
            mid_price in mid_price_strategy()
        ) {
            let ticker = parse_ticker(&symbol, mid_price, None)
                .expect("Ticker parsing should succeed");

            prop_assert_eq!(
                ticker.symbol,
                symbol,
                "Ticker symbol should match input"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 6: OrderBook Invariants**
/// **Validates: Requirements 2.3**
///
/// For any order book returned by fetch_order_book, bids SHALL be sorted in
/// descending order by price, asks SHALL be sorted in ascending order by price,
/// and all entries SHALL have positive price and quantity.
mod orderbook_invariants {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::parse_orderbook;
    use rust_decimal::Decimal;
    use serde_json::json;

    // Strategy for generating valid price strings
    fn price_strategy() -> impl Strategy<Value = String> {
        (1u64..100000u64).prop_map(|n| format!("{}.{}", n / 100, n % 100))
    }

    // Strategy for generating valid size strings
    fn size_strategy() -> impl Strategy<Value = String> {
        (1u64..10000u64).prop_map(|n| format!("{}.{}", n / 1000, n % 1000))
    }

    // Strategy for generating orderbook levels
    fn levels_strategy() -> impl Strategy<Value = Vec<(String, String)>> {
        prop::collection::vec((price_strategy(), size_strategy()), 1..20)
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that bids are sorted in descending order
        #[test]
        fn prop_bids_sorted_descending(bid_levels in levels_strategy()) {
            let bids_json: Vec<serde_json::Value> = bid_levels
                .iter()
                .map(|(px, sz)| json!({"px": px, "sz": sz}))
                .collect();

            let data = json!({
                "levels": [bids_json, []]
            });

            let orderbook = parse_orderbook(&data, "BTC/USDC:USDC".to_string())
                .expect("Orderbook parsing should succeed");

            for i in 1..orderbook.bids.len() {
                prop_assert!(
                    orderbook.bids[i - 1].price >= orderbook.bids[i].price,
                    "Bids should be sorted descending: {:?} >= {:?}",
                    orderbook.bids[i - 1].price,
                    orderbook.bids[i].price
                );
            }
        }

        /// Test that asks are sorted in ascending order
        #[test]
        fn prop_asks_sorted_ascending(ask_levels in levels_strategy()) {
            let asks_json: Vec<serde_json::Value> = ask_levels
                .iter()
                .map(|(px, sz)| json!({"px": px, "sz": sz}))
                .collect();

            let data = json!({
                "levels": [[], asks_json]
            });

            let orderbook = parse_orderbook(&data, "BTC/USDC:USDC".to_string())
                .expect("Orderbook parsing should succeed");

            for i in 1..orderbook.asks.len() {
                prop_assert!(
                    orderbook.asks[i - 1].price <= orderbook.asks[i].price,
                    "Asks should be sorted ascending: {:?} <= {:?}",
                    orderbook.asks[i - 1].price,
                    orderbook.asks[i].price
                );
            }
        }

        /// Test that all entries have positive price and quantity
        #[test]
        fn prop_all_entries_positive(
            bid_levels in levels_strategy(),
            ask_levels in levels_strategy()
        ) {
            let bids_json: Vec<serde_json::Value> = bid_levels
                .iter()
                .map(|(px, sz)| json!({"px": px, "sz": sz}))
                .collect();
            let asks_json: Vec<serde_json::Value> = ask_levels
                .iter()
                .map(|(px, sz)| json!({"px": px, "sz": sz}))
                .collect();

            let data = json!({
                "levels": [bids_json, asks_json]
            });

            let orderbook = parse_orderbook(&data, "BTC/USDC:USDC".to_string())
                .expect("Orderbook parsing should succeed");

            for bid in &orderbook.bids {
                prop_assert!(
                    bid.price.0 > Decimal::ZERO,
                    "Bid price should be positive"
                );
                prop_assert!(
                    bid.amount.0 > Decimal::ZERO,
                    "Bid amount should be positive"
                );
            }

            for ask in &orderbook.asks {
                prop_assert!(
                    ask.price.0 > Decimal::ZERO,
                    "Ask price should be positive"
                );
                prop_assert!(
                    ask.amount.0 > Decimal::ZERO,
                    "Ask amount should be positive"
                );
            }
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 7: Trade Data Completeness**
/// **Validates: Requirements 2.4**
///
/// For any trade returned by fetch_trades, the trade SHALL contain valid timestamp,
/// positive price, positive quantity, and a valid side (buy or sell).
mod trade_data_completeness {
    use super::*;
    use ccxt_core::types::OrderSide;
    use ccxt_exchanges::hyperliquid::parser::parse_trade;
    use rust_decimal::Decimal;
    use serde_json::json;

    // Strategy for generating valid timestamps
    fn timestamp_strategy() -> impl Strategy<Value = i64> {
        1577836800000i64..1893456000000i64
    }

    // Strategy for generating valid prices
    fn price_strategy() -> impl Strategy<Value = String> {
        (1u64..100000u64).prop_map(|n| n.to_string())
    }

    // Strategy for generating valid sizes
    fn size_strategy() -> impl Strategy<Value = String> {
        (1u64..10000u64).prop_map(|n| format!("{}.{}", n / 1000, n % 1000))
    }

    // Strategy for generating valid sides
    fn side_strategy() -> impl Strategy<Value = &'static str> {
        prop_oneof![Just("B"), Just("A"), Just("buy"), Just("sell"),]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that trade has valid timestamp
        #[test]
        fn prop_trade_has_valid_timestamp(
            timestamp in timestamp_strategy(),
            price in price_strategy(),
            size in size_strategy(),
            side in side_strategy()
        ) {
            let data = json!({
                "time": timestamp,
                "px": price,
                "sz": size,
                "side": side,
                "tid": "123"
            });

            let trade = parse_trade(&data, None)
                .expect("Trade parsing should succeed");

            prop_assert_eq!(
                trade.timestamp,
                timestamp,
                "Trade timestamp should match input"
            );
        }

        /// Test that trade has positive price and amount
        #[test]
        fn prop_trade_has_positive_values(
            timestamp in timestamp_strategy(),
            price in price_strategy(),
            size in size_strategy(),
            side in side_strategy()
        ) {
            let data = json!({
                "time": timestamp,
                "px": price,
                "sz": size,
                "side": side,
                "tid": "123"
            });

            let trade = parse_trade(&data, None)
                .expect("Trade parsing should succeed");

            prop_assert!(
                trade.price.0 > Decimal::ZERO,
                "Trade price should be positive"
            );
            prop_assert!(
                trade.amount.0 > Decimal::ZERO,
                "Trade amount should be positive"
            );
        }

        /// Test that trade side is correctly parsed
        #[test]
        fn prop_trade_side_valid(
            timestamp in timestamp_strategy(),
            price in price_strategy(),
            size in size_strategy(),
            side in side_strategy()
        ) {
            let data = json!({
                "time": timestamp,
                "px": price,
                "sz": size,
                "side": side,
                "tid": "123"
            });

            let trade = parse_trade(&data, None)
                .expect("Trade parsing should succeed");

            // Side should be either Buy or Sell
            prop_assert!(
                trade.side == OrderSide::Buy || trade.side == OrderSide::Sell,
                "Trade side should be Buy or Sell"
            );

            // Verify correct mapping
            match side {
                "B" | "buy" | "Buy" => prop_assert_eq!(trade.side, OrderSide::Buy),
                "A" | "sell" | "Sell" => prop_assert_eq!(trade.side, OrderSide::Sell),
                _ => {}
            }
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 8: OHLCV Data Validity**
/// **Validates: Requirements 2.5**
///
/// For any OHLCV candle returned by fetch_ohlcv, high >= max(open, close),
/// low <= min(open, close), and volume >= 0.
mod ohlcv_data_validity {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::parse_ohlcv;
    use rust_decimal::Decimal;
    use serde_json::json;

    // Strategy for generating valid timestamps
    fn timestamp_strategy() -> impl Strategy<Value = i64> {
        1577836800000i64..1893456000000i64
    }

    // Strategy for generating valid OHLCV prices where high >= max(open, close) and low <= min(open, close)
    fn valid_ohlcv_prices_strategy() -> impl Strategy<Value = (String, String, String, String)> {
        (
            1u64..100000u64,
            1u64..100000u64,
            1u64..100000u64,
            1u64..100000u64,
        )
            .prop_map(|(a, b, c, d)| {
                let mut prices = [a, b, c, d];
                prices.sort();
                // low, open/close, open/close, high
                let low = prices[0];
                let high = prices[3];
                let open = prices[1];
                let close = prices[2];
                (
                    open.to_string(),
                    high.to_string(),
                    low.to_string(),
                    close.to_string(),
                )
            })
    }

    // Strategy for generating valid volume
    fn volume_strategy() -> impl Strategy<Value = String> {
        (0u64..1000000u64).prop_map(|v| v.to_string())
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that OHLCV high >= max(open, close)
        #[test]
        fn prop_ohlcv_high_valid(
            timestamp in timestamp_strategy(),
            (open, high, low, close) in valid_ohlcv_prices_strategy(),
            volume in volume_strategy()
        ) {
            let data = json!([timestamp, open, high, low, close, volume]);

            let ohlcv = parse_ohlcv(&data)
                .expect("OHLCV parsing should succeed");

            let max_oc = std::cmp::max(ohlcv.open.0, ohlcv.close.0);
            prop_assert!(
                ohlcv.high.0 >= max_oc,
                "High ({}) should be >= max(open, close) ({})",
                ohlcv.high.0,
                max_oc
            );
        }

        /// Test that OHLCV low <= min(open, close)
        #[test]
        fn prop_ohlcv_low_valid(
            timestamp in timestamp_strategy(),
            (open, high, low, close) in valid_ohlcv_prices_strategy(),
            volume in volume_strategy()
        ) {
            let data = json!([timestamp, open, high, low, close, volume]);

            let ohlcv = parse_ohlcv(&data)
                .expect("OHLCV parsing should succeed");

            let min_oc = std::cmp::min(ohlcv.open.0, ohlcv.close.0);
            prop_assert!(
                ohlcv.low.0 <= min_oc,
                "Low ({}) should be <= min(open, close) ({})",
                ohlcv.low.0,
                min_oc
            );
        }

        /// Test that OHLCV volume >= 0
        #[test]
        fn prop_ohlcv_volume_non_negative(
            timestamp in timestamp_strategy(),
            (open, high, low, close) in valid_ohlcv_prices_strategy(),
            volume in volume_strategy()
        ) {
            let data = json!([timestamp, open, high, low, close, volume]);

            let ohlcv = parse_ohlcv(&data)
                .expect("OHLCV parsing should succeed");

            prop_assert!(
                ohlcv.volume.0 >= Decimal::ZERO,
                "Volume should be non-negative"
            );
        }

        /// Test that OHLCV timestamp is preserved
        #[test]
        fn prop_ohlcv_timestamp_preserved(
            timestamp in timestamp_strategy(),
            (open, high, low, close) in valid_ohlcv_prices_strategy(),
            volume in volume_strategy()
        ) {
            let data = json!([timestamp, open, high, low, close, volume]);

            let ohlcv = parse_ohlcv(&data)
                .expect("OHLCV parsing should succeed");

            prop_assert_eq!(
                ohlcv.timestamp,
                timestamp,
                "Timestamp should be preserved"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 10: Balance Parsing Accuracy**
/// **Validates: Requirements 5.1, 9.3**
///
/// For any balance response, the parsed Balance SHALL have total = free + used
/// for each currency, and all values SHALL be non-negative.
mod balance_parsing_accuracy {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::parse_balance;
    use rust_decimal::Decimal;
    use serde_json::json;

    // Strategy for generating valid account values
    #[allow(dead_code)]
    fn account_value_strategy() -> impl Strategy<Value = String> {
        (0u64..1000000u64).prop_map(|v| v.to_string())
    }

    // Strategy for generating valid margin used (must be <= account value)
    fn margin_used_strategy() -> impl Strategy<Value = (String, String)> {
        (0u64..1000000u64, 0u64..100u64).prop_map(|(account, pct)| {
            let margin = account * pct / 100;
            (account.to_string(), margin.to_string())
        })
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that balance total = free + used
        #[test]
        fn prop_balance_total_equals_free_plus_used(
            (account_value, margin_used) in margin_used_strategy()
        ) {
            let data = json!({
                "marginSummary": {
                    "accountValue": account_value,
                    "totalMarginUsed": margin_used
                }
            });

            let balance = parse_balance(&data)
                .expect("Balance parsing should succeed");

            if let Some(usdc) = balance.get("USDC") {
                prop_assert_eq!(
                    usdc.total,
                    usdc.free + usdc.used,
                    "Total should equal free + used"
                );
            }
        }

        /// Test that all balance values are non-negative
        #[test]
        fn prop_balance_values_non_negative(
            (account_value, margin_used) in margin_used_strategy()
        ) {
            let data = json!({
                "marginSummary": {
                    "accountValue": account_value,
                    "totalMarginUsed": margin_used
                }
            });

            let balance = parse_balance(&data)
                .expect("Balance parsing should succeed");

            if let Some(usdc) = balance.get("USDC") {
                prop_assert!(
                    usdc.total >= Decimal::ZERO,
                    "Total should be non-negative"
                );
                prop_assert!(
                    usdc.used >= Decimal::ZERO,
                    "Used should be non-negative"
                );
            }
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 12: Error Response Parsing**
/// **Validates: Requirements 8.1, 8.3, 8.4**
///
/// For any error response from the API, the parser SHALL extract a structured
/// error with code and message without throwing exceptions.
mod error_response_parsing {
    use super::*;
    use ccxt_exchanges::hyperliquid::error::{is_error_response, parse_error};
    use serde_json::json;

    // Strategy for generating error messages
    fn error_message_strategy() -> impl Strategy<Value = String> {
        prop_oneof![
            Just("Invalid signature".to_string()),
            Just("Insufficient margin".to_string()),
            Just("Rate limit exceeded".to_string()),
            Just("Order not found".to_string()),
            Just("Invalid parameter".to_string()),
            "[a-zA-Z0-9 ]{5,50}".prop_map(|s| s.to_string()),
        ]
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that error responses are correctly identified
        #[test]
        fn prop_error_response_identified(msg in error_message_strategy()) {
            let response = json!({
                "error": msg
            });

            prop_assert!(
                is_error_response(&response),
                "Response with 'error' field should be identified as error"
            );
        }

        /// Test that status: err responses are correctly identified
        #[test]
        fn prop_status_err_identified(msg in error_message_strategy()) {
            let response = json!({
                "status": "err",
                "response": msg
            });

            prop_assert!(
                is_error_response(&response),
                "Response with status 'err' should be identified as error"
            );
        }

        /// Test that success responses are not identified as errors
        #[test]
        fn prop_success_not_error(_dummy in 0u32..100u32) {
            let response = json!({
                "status": "ok",
                "response": {"data": []}
            });

            prop_assert!(
                !is_error_response(&response),
                "Success response should not be identified as error"
            );
        }

        /// Test that parse_error produces valid error for any error response
        #[test]
        fn prop_parse_error_produces_valid_error(msg in error_message_strategy()) {
            let response = json!({
                "error": msg
            });

            let error = parse_error(&response);
            let display = error.to_string();

            prop_assert!(
                !display.is_empty(),
                "Error display should not be empty"
            );
        }

        /// Test that insufficient margin errors are correctly mapped
        #[test]
        fn prop_insufficient_margin_mapped(_dummy in 0u32..100u32) {
            let response = json!({
                "error": "Insufficient margin for order"
            });

            let error = parse_error(&response);
            let display = error.to_string().to_lowercase();

            prop_assert!(
                display.contains("insufficient") || display.contains("balance"),
                "Insufficient margin error should be correctly mapped"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 13: Order Parsing Correctness**
/// **Validates: Requirements 4.4, 4.5, 9.2**
///
/// For any order response, the parsed Order SHALL have correct status mapping
/// (open, closed, canceled) and all required fields populated.
mod order_parsing_correctness {
    use super::*;
    use ccxt_core::types::OrderStatus;
    use ccxt_exchanges::hyperliquid::parser::{parse_order, parse_order_status};
    use serde_json::json;

    // Strategy for generating order statuses
    fn status_strategy() -> impl Strategy<Value = &'static str> {
        prop_oneof![
            Just("open"),
            Just("resting"),
            Just("filled"),
            Just("canceled"),
            Just("cancelled"),
            Just("rejected"),
        ]
    }

    // Strategy for generating order IDs
    fn order_id_strategy() -> impl Strategy<Value = u64> {
        1u64..1000000u64
    }

    // Strategy for generating prices
    fn price_strategy() -> impl Strategy<Value = String> {
        (1u64..100000u64).prop_map(|n| n.to_string())
    }

    // Strategy for generating sizes
    fn size_strategy() -> impl Strategy<Value = String> {
        (1u64..10000u64).prop_map(|n| format!("{}.{}", n / 1000, n % 1000))
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that order status is correctly mapped
        #[test]
        fn prop_order_status_mapping(status in status_strategy()) {
            let parsed = parse_order_status(status);

            match status {
                "open" | "resting" => prop_assert_eq!(parsed, OrderStatus::Open),
                "filled" => prop_assert_eq!(parsed, OrderStatus::Closed),
                "canceled" | "cancelled" => prop_assert_eq!(parsed, OrderStatus::Cancelled),
                "rejected" => prop_assert_eq!(parsed, OrderStatus::Rejected),
                _ => {}
            }
        }

        /// Test that order ID is correctly parsed
        #[test]
        fn prop_order_id_parsed(
            oid in order_id_strategy(),
            price in price_strategy(),
            size in size_strategy()
        ) {
            let data = json!({
                "oid": oid,
                "coin": "BTC",
                "limitPx": price,
                "sz": size,
                "side": "B",
                "status": "open"
            });

            let order = parse_order(&data, None)
                .expect("Order parsing should succeed");

            prop_assert_eq!(
                order.id,
                oid.to_string(),
                "Order ID should be correctly parsed"
            );
        }

        /// Test that order symbol is correctly formatted
        #[test]
        fn prop_order_symbol_formatted(
            oid in order_id_strategy(),
            price in price_strategy(),
            size in size_strategy()
        ) {
            let data = json!({
                "oid": oid,
                "coin": "BTC",
                "limitPx": price,
                "sz": size,
                "side": "B",
                "status": "open"
            });

            let order = parse_order(&data, None)
                .expect("Order parsing should succeed");

            prop_assert!(
                order.symbol.ends_with("/USDC:USDC"),
                "Order symbol should end with /USDC:USDC"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 15: Parser Robustness**
/// **Validates: Requirements 9.5**
///
/// For any API response with missing optional fields, the parser SHALL
/// successfully parse the response and use appropriate default values without errors.
mod parser_robustness {
    use super::*;
    use ccxt_exchanges::hyperliquid::parser::{parse_balance, parse_market, parse_ticker};
    use rust_decimal::Decimal;
    use rust_decimal::prelude::FromPrimitive;
    use serde_json::json;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that market parser handles minimal data
        #[test]
        fn prop_market_parser_minimal(
            name in "[A-Z]{2,10}",
            index in 0usize..1000usize
        ) {
            // Minimal market data - only required fields
            let data = json!({
                "name": name
            });

            let result = parse_market(&data, index);
            prop_assert!(
                result.is_ok(),
                "Market parser should handle minimal data"
            );
        }

        /// Test that ticker parser handles any valid price
        #[test]
        fn prop_ticker_parser_any_price(
            symbol in "[A-Z]{2,10}".prop_map(|s| format!("{}/USDC:USDC", s)),
            price in 1u64..1000000u64
        ) {
            let mid_price = Decimal::from_u64(price).unwrap();
            let result = parse_ticker(&symbol, mid_price, None);

            prop_assert!(
                result.is_ok(),
                "Ticker parser should handle any valid price"
            );
        }

        /// Test that balance parser handles empty margin summary
        #[test]
        fn prop_balance_parser_empty(_dummy in 0u32..100u32) {
            let data = json!({});
            let result = parse_balance(&data);

            prop_assert!(
                result.is_ok(),
                "Balance parser should handle empty data"
            );
        }

        /// Test that balance parser handles partial data
        #[test]
        fn prop_balance_parser_partial(account_value in 0u64..1000000u64) {
            let data = json!({
                "marginSummary": {
                    "accountValue": account_value.to_string()
                }
            });

            let result = parse_balance(&data);
            prop_assert!(
                result.is_ok(),
                "Balance parser should handle partial data"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 9: Order Parameter Validation**
/// **Validates: Requirements 4.6**
///
/// For any order request with invalid parameters (negative amount, zero price
/// for limit order, invalid symbol), the exchange SHALL return an error before
/// attempting to send the request.
mod order_parameter_validation {
    use super::*;

    // Note: This property test validates the concept that invalid parameters
    // should be rejected. Since we can't actually call the exchange without
    // network access, we test the validation logic conceptually.

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that negative amounts are conceptually invalid
        #[test]
        fn prop_negative_amount_invalid(amount in -1000.0f64..-0.001f64) {
            // Negative amounts should be rejected
            prop_assert!(
                amount < 0.0,
                "Negative amounts should be invalid"
            );
        }

        /// Test that zero price for limit orders is conceptually invalid
        #[test]
        fn prop_zero_price_invalid_for_limit(_dummy in 0u32..100u32) {
            let price = 0.0f64;
            // Zero price for limit orders should be rejected
            prop_assert!(
                price <= 0.0,
                "Zero or negative price should be invalid for limit orders"
            );
        }

        /// Test that valid order parameters pass validation
        #[test]
        fn prop_valid_params_accepted(
            amount in 0.001f64..1000.0f64,
            price in 0.01f64..100000.0f64
        ) {
            prop_assert!(amount > 0.0, "Amount should be positive");
            prop_assert!(price > 0.0, "Price should be positive");
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 14: Request Serialization Round-Trip**
/// **Validates: Requirements 9.4, 9.6**
///
/// For any order request, serializing to JSON and then parsing back SHALL
/// produce an equivalent request structure.
mod request_serialization_roundtrip {
    use super::*;
    use serde_json::json;

    // Strategy for generating valid asset indices
    fn asset_index_strategy() -> impl Strategy<Value = u32> {
        0u32..100u32
    }

    // Strategy for generating valid prices
    fn price_strategy() -> impl Strategy<Value = String> {
        (1u64..100000u64).prop_map(|n| n.to_string())
    }

    // Strategy for generating valid sizes
    fn size_strategy() -> impl Strategy<Value = String> {
        (1u64..10000u64).prop_map(|n| format!("{}.{}", n / 1000, n % 1000))
    }

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that order request JSON round-trips correctly
        #[test]
        fn prop_order_request_roundtrip(
            asset in asset_index_strategy(),
            is_buy in any::<bool>(),
            price in price_strategy(),
            size in size_strategy()
        ) {
            let order_request = json!({
                "a": asset,
                "b": is_buy,
                "p": price,
                "s": size,
                "r": false,
                "t": {
                    "limit": {
                        "tif": "Gtc"
                    }
                }
            });

            // Serialize to string
            let serialized = serde_json::to_string(&order_request)
                .expect("Serialization should succeed");

            // Parse back
            let parsed: serde_json::Value = serde_json::from_str(&serialized)
                .expect("Parsing should succeed");

            // Verify round-trip
            prop_assert_eq!(
                parsed["a"].as_u64().unwrap() as u32,
                asset,
                "Asset should round-trip"
            );
            prop_assert_eq!(
                parsed["b"].as_bool().unwrap(),
                is_buy,
                "isBuy should round-trip"
            );
            prop_assert_eq!(
                parsed["p"].as_str().unwrap(),
                price,
                "Price should round-trip"
            );
            prop_assert_eq!(
                parsed["s"].as_str().unwrap(),
                size,
                "Size should round-trip"
            );
        }

        /// Test that cancel request JSON round-trips correctly
        #[test]
        fn prop_cancel_request_roundtrip(
            asset in asset_index_strategy(),
            order_id in 1u64..1000000u64
        ) {
            let cancel_request = json!({
                "type": "cancel",
                "cancels": [{
                    "a": asset,
                    "o": order_id
                }]
            });

            // Serialize to string
            let serialized = serde_json::to_string(&cancel_request)
                .expect("Serialization should succeed");

            // Parse back
            let parsed: serde_json::Value = serde_json::from_str(&serialized)
                .expect("Parsing should succeed");

            // Verify round-trip
            prop_assert_eq!(
                parsed["type"].as_str().unwrap(),
                "cancel",
                "Type should round-trip"
            );

            let cancel = &parsed["cancels"][0];
            prop_assert_eq!(
                cancel["a"].as_u64().unwrap() as u32,
                asset,
                "Asset should round-trip"
            );
            prop_assert_eq!(
                cancel["o"].as_u64().unwrap(),
                order_id,
                "Order ID should round-trip"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 16: Exchange Trait Consistency**
/// **Validates: Requirements 7.1**
///
/// For any method implemented in the Exchange trait, calling it through the
/// trait object SHALL produce the same result as calling it directly on HyperLiquid.
mod exchange_trait_consistency {
    use super::*;
    use ccxt_core::exchange::Exchange;
    use ccxt_exchanges::hyperliquid::HyperLiquid;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        /// Test that Exchange trait metadata methods are consistent
        #[test]
        fn prop_metadata_consistent(_dummy in 0u32..100u32) {
            let exchange = HyperLiquid::builder()
                .testnet(true)
                .build()
                .expect("Failed to build HyperLiquid");

            // Test via trait object
            let trait_obj: &dyn Exchange = &exchange;

            prop_assert_eq!(trait_obj.id(), "hyperliquid");
            prop_assert_eq!(trait_obj.name(), "HyperLiquid");
            prop_assert_eq!(trait_obj.version(), "1");
            prop_assert!(!trait_obj.certified());
            prop_assert!(trait_obj.has_websocket());
        }

        /// Test that capabilities are correctly reported
        #[test]
        fn prop_capabilities_consistent(_dummy in 0u32..100u32) {
            let exchange = HyperLiquid::builder()
                .testnet(true)
                .build()
                .expect("Failed to build HyperLiquid");

            let trait_obj: &dyn Exchange = &exchange;
            let caps = trait_obj.capabilities();

            // Public API capabilities
            prop_assert!(caps.fetch_markets());
            prop_assert!(caps.fetch_ticker());
            prop_assert!(caps.fetch_tickers());
            prop_assert!(caps.fetch_order_book());
            prop_assert!(caps.fetch_trades());
            prop_assert!(caps.fetch_ohlcv());

            // Private API capabilities
            prop_assert!(caps.create_order());
            prop_assert!(caps.cancel_order());
            prop_assert!(caps.cancel_all_orders());
            prop_assert!(caps.fetch_open_orders());
            prop_assert!(caps.fetch_balance());
            prop_assert!(caps.fetch_positions());
            prop_assert!(caps.set_leverage());

            // Not implemented
            prop_assert!(!caps.fetch_currencies());
            prop_assert!(!caps.edit_order());
            prop_assert!(!caps.fetch_my_trades());
        }

        /// Test that rate limit is consistent
        #[test]
        fn prop_rate_limit_consistent(_dummy in 0u32..100u32) {
            let exchange = HyperLiquid::builder()
                .testnet(true)
                .build()
                .expect("Failed to build HyperLiquid");

            let trait_obj: &dyn Exchange = &exchange;

            prop_assert!(
                trait_obj.rate_limit() == 100,
                "Rate limit should be 100"
            );
        }
    }
}

/// **Feature: hyperliquid-exchange, Property 17: NotImplemented Error Handling**
/// **Validates: Requirements 7.3**
///
/// For any method not supported by HyperLiquid (e.g., spot trading), calling it
/// SHALL return a NotImplemented error with a descriptive message.
mod not_implemented_error_handling {
    use super::*;
    use ccxt_core::exchange::Exchange;
    use ccxt_exchanges::hyperliquid::HyperLiquid;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(10))]

        /// Test that fetch_order returns NotImplemented
        #[test]
        fn prop_fetch_order_not_implemented(_dummy in 0u32..10u32) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let exchange = HyperLiquid::builder()
                    .testnet(true)
                    .build()
                    .expect("Failed to build HyperLiquid");

                let trait_obj: &dyn Exchange = &exchange;
                let result = trait_obj.fetch_order("123", Some("BTC/USDC:USDC")).await;

                prop_assert!(result.is_err(), "fetch_order should return error");
                let err = result.unwrap_err();
                prop_assert!(
                    err.to_string().to_lowercase().contains("not implemented") ||
                    err.to_string().to_lowercase().contains("notimplemented"),
                    "Error should indicate not implemented"
                );
                Ok(())
            })?;
        }

        /// Test that fetch_closed_orders returns NotImplemented
        #[test]
        fn prop_fetch_closed_orders_not_implemented(_dummy in 0u32..10u32) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let exchange = HyperLiquid::builder()
                    .testnet(true)
                    .build()
                    .expect("Failed to build HyperLiquid");

                let trait_obj: &dyn Exchange = &exchange;
                let result = trait_obj.fetch_closed_orders(None, None, None).await;

                prop_assert!(result.is_err(), "fetch_closed_orders should return error");
                let err = result.unwrap_err();
                prop_assert!(
                    err.to_string().to_lowercase().contains("not implemented") ||
                    err.to_string().to_lowercase().contains("notimplemented"),
                    "Error should indicate not implemented"
                );
                Ok(())
            })?;
        }

        /// Test that fetch_my_trades returns NotImplemented
        #[test]
        fn prop_fetch_my_trades_not_implemented(_dummy in 0u32..10u32) {
            let rt = tokio::runtime::Runtime::new().unwrap();
            rt.block_on(async {
                let exchange = HyperLiquid::builder()
                    .testnet(true)
                    .build()
                    .expect("Failed to build HyperLiquid");

                let trait_obj: &dyn Exchange = &exchange;
                let result = trait_obj.fetch_my_trades(None, None, None).await;

                prop_assert!(result.is_err(), "fetch_my_trades should return error");
                let err = result.unwrap_err();
                prop_assert!(
                    err.to_string().to_lowercase().contains("not implemented") ||
                    err.to_string().to_lowercase().contains("notimplemented"),
                    "Error should indicate not implemented"
                );
                Ok(())
            })?;
        }
    }
}