predict-fun-sdk 0.4.0

Rust SDK for the Predict.fun prediction market API — EIP-712 order signing, REST client, WebSocket feeds, and execution pipeline
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
//! Live integration tests for predict-fun-sdk.
//!
//! These tests hit real predict.fun endpoints (mainnet).
//! Run with: `cargo test --test integration`
//!
//! Environment:
//!   PREDICT_API_KEY — required (default: test key)
//!   PREDICT_TEST_PRIVATE_KEY — optional (default: hardhat account #0)

use std::time::{SystemTime, UNIX_EPOCH};

use alloy_primitives::{Signature, U256};
use predict_fun_sdk::api::*;
use predict_fun_sdk::execution::*;
use predict_fun_sdk::order::*;
use predict_fun_sdk::ws::*;

const DEFAULT_API_KEY: &str = "7fdc1c33-7bde-46c5-8308-2ce86507e27f";
const DEFAULT_PRIVATE_KEY: &str =
    "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

fn api_key() -> String {
    std::env::var("PREDICT_API_KEY").unwrap_or_else(|_| DEFAULT_API_KEY.into())
}

fn private_key() -> String {
    std::env::var("PREDICT_TEST_PRIVATE_KEY").unwrap_or_else(|_| DEFAULT_PRIVATE_KEY.into())
}

fn unix_now() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64
}

// ============================================================================
// REST API INTEGRATION TESTS
// ============================================================================

mod rest_tests {
    use super::*;

    #[tokio::test]
    async fn auth_flow_returns_jwt() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let signer =
            PredictOrderSigner::from_private_key(&private_key(), BNB_MAINNET_CHAIN_ID).unwrap();

        // Step 1: Get auth message
        let auth_msg = client.auth_message().await.unwrap();
        let message = auth_msg["data"]["message"].as_str().unwrap();
        assert!(!message.is_empty(), "Auth message should not be empty");

        // Step 2: Sign and authenticate
        let signature = signer.sign_auth_message(message).unwrap();
        let auth = client
            .auth(&signer.address().to_string(), message, &signature)
            .await
            .unwrap();

        let token = auth["data"]["token"].as_str().unwrap();
        assert!(!token.is_empty(), "JWT token should not be empty");
    }

    #[tokio::test]
    async fn search_returns_markets() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();

        let markets = search["data"]["markets"].as_array().unwrap();
        assert!(!markets.is_empty(), "Search should return BTC markets");

        // Each market should have an id and title/question
        let first = &markets[0];
        assert!(first["id"].as_i64().is_some(), "Market should have an id");
    }

    #[tokio::test]
    async fn list_markets_returns_data() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let markets = client
            .list_markets(&[("limit", "5".to_string())])
            .await
            .unwrap();

        let data = markets["data"].as_array().unwrap();
        assert!(!data.is_empty(), "Should return at least one market");
    }

    #[tokio::test]
    async fn get_market_by_id() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        // Find a market via search first
        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        // Fetch full market
        let market = client.get_market(market_id).await.unwrap();
        let data = &market["data"];

        assert_eq!(data["id"].as_i64().unwrap(), market_id);
        assert!(data.get("outcomes").is_some(), "Market should have outcomes");
    }

    #[tokio::test]
    async fn get_market_orderbook() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let ob = client.get_market_orderbook(market_id).await.unwrap();
        let data = &ob["data"];

        // Orderbook should have asks and bids arrays
        assert!(data.get("asks").is_some(), "Should have asks");
        assert!(data.get("bids").is_some(), "Should have bids");
    }

    #[tokio::test]
    async fn get_market_stats() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let stats = client.get_market_stats(market_id).await.unwrap();
        assert!(stats.get("data").is_some(), "Should have stats data");
    }

    #[tokio::test]
    async fn get_market_timeseries() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let from = unix_now() - 24 * 3600;
        let ts = client
            .get_market_timeseries(
                market_id,
                &[
                    ("metric", "chance".to_string()),
                    ("from", from.to_string()),
                    ("resolution", "1h".to_string()),
                ],
            )
            .await
            .unwrap();

        assert!(ts.get("data").is_some(), "Should have timeseries data");
    }

    #[tokio::test]
    async fn list_categories_and_tags() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();

        let cats = client.list_categories(&[]).await.unwrap();
        let cat_data = cats["data"].as_array().unwrap();
        assert!(!cat_data.is_empty(), "Should have categories");

        let tags = client.list_tags().await.unwrap();
        let tag_data = tags["data"].as_array().unwrap();
        assert!(!tag_data.is_empty(), "Should have tags");
    }

    #[tokio::test]
    async fn jwt_gated_endpoints_work_with_auth() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let signer =
            PredictOrderSigner::from_private_key(&private_key(), BNB_MAINNET_CHAIN_ID).unwrap();

        // Authenticate
        let auth_msg = client.auth_message().await.unwrap();
        let message = auth_msg["data"]["message"].as_str().unwrap();
        let sig = signer.sign_auth_message(message).unwrap();
        let auth = client
            .auth(&signer.address().to_string(), message, &sig)
            .await
            .unwrap();
        let jwt = auth["data"]["token"].as_str().unwrap();

        let authed = PredictApiClient::new_mainnet(&api_key())
            .unwrap()
            .with_jwt(jwt);

        // Account
        let account = authed.account().await.unwrap();
        assert!(
            account["data"].get("address").is_some(),
            "Account should have address"
        );

        // Orders
        let orders = authed
            .list_orders(&[("first", "5".to_string())])
            .await
            .unwrap();
        assert!(orders.get("data").is_some(), "Should have orders data");

        // Positions
        let positions = authed
            .list_positions(&[("first", "5".to_string())])
            .await
            .unwrap();
        assert!(
            positions.get("data").is_some(),
            "Should have positions data"
        );

        // Activity
        let activity = authed
            .account_activity(&[("first", "5".to_string())])
            .await
            .unwrap();
        assert!(activity.get("data").is_some(), "Should have activity data");
    }
}

// ============================================================================
// EIP-712 SIGNING INTEGRATION TESTS
// ============================================================================

mod signing_tests {
    use super::*;

    #[tokio::test]
    async fn sign_order_for_live_market() {
        let client = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let signer =
            PredictOrderSigner::from_private_key(&private_key(), BNB_MAINNET_CHAIN_ID).unwrap();
        let addr = signer.address();

        // Find a market with outcomes
        let search = client
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let market = client.get_market(market_id).await.unwrap();
        let data = &market["data"];

        let is_neg_risk = data["isNegRisk"].as_bool().unwrap_or(false);
        let is_yield_bearing = data["isYieldBearing"].as_bool().unwrap_or(true);
        let fee_rate_bps = data["feeRateBps"].as_u64().unwrap_or(0) as u32;

        // Get YES token ID
        let outcomes = data["outcomes"].as_array().unwrap();
        let yes_token = outcomes
            .iter()
            .find(|o| o["indexSet"].as_u64() == Some(1))
            .and_then(|o| o["onChainId"].as_str())
            .unwrap();

        // Build and sign order
        let price_wei = U256::from(400_000_000_000_000_000u128); // 0.4
        let qty_wei = U256::from(10_000_000_000_000_000_000u128); // 10

        let (maker_amount, taker_amount) =
            predict_limit_order_amounts(PredictSide::Buy, price_wei, qty_wei);

        let order = PredictOrder::new_limit(
            addr,
            addr,
            yes_token,
            PredictSide::Buy,
            maker_amount,
            taker_amount,
            fee_rate_bps,
        );

        let signed = signer
            .sign_order(&order, is_neg_risk, is_yield_bearing)
            .unwrap();

        // Verify hash
        assert!(signed.hash.starts_with("0x"));
        assert!(signed.hash.len() > 10);

        // Verify signature recovery
        let hash = signer
            .order_hash(&order, is_neg_risk, is_yield_bearing)
            .unwrap();
        let sig: Signature = signed.signature.parse().unwrap();
        let recovered = sig.recover_address_from_prehash(&hash).unwrap();
        assert_eq!(recovered, addr, "Signature recovery should match signer");

        // Verify payload structure
        let req = signed.to_create_order_request(
            price_wei,
            PredictStrategy::Limit,
            None,
            Some(true),
        );
        let json = serde_json::to_value(&req).unwrap();
        let data = &json["data"];

        assert_eq!(data["strategy"].as_str().unwrap(), "LIMIT");
        assert!(data.get("order").is_some());
        assert!(data["order"].get("hash").is_some());
        assert!(data["order"].get("signature").is_some());
    }

    #[test]
    fn buy_sell_amounts_symmetric_across_prices() {
        for pct in [5, 10, 25, 33, 50, 67, 75, 90, 95] {
            let price = U256::from(pct as u128) * U256::from(10_000_000_000_000_000u128);
            let qty = U256::from(10_000_000_000_000_000_000u128);

            let (buy_m, buy_t) = predict_limit_order_amounts(PredictSide::Buy, price, qty);
            let (sell_m, sell_t) = predict_limit_order_amounts(PredictSide::Sell, price, qty);

            assert_eq!(buy_m, sell_t, "BUY maker == SELL taker at {}%", pct);
            assert_eq!(buy_t, sell_m, "BUY taker == SELL maker at {}%", pct);
        }
    }

    #[test]
    fn all_eight_exchange_addresses_unique() {
        let mut addrs = std::collections::HashSet::new();
        for chain in [BNB_MAINNET_CHAIN_ID, BNB_TESTNET_CHAIN_ID] {
            for neg in [false, true] {
                for yld in [false, true] {
                    let addr = predict_exchange_address(chain, neg, yld).unwrap();
                    assert!(addrs.insert(addr), "Duplicate at chain={} neg={} yld={}", chain, neg, yld);
                }
            }
        }
        assert_eq!(addrs.len(), 8);
    }
}

// ============================================================================
// EXECUTION CLIENT INTEGRATION TESTS
// ============================================================================

mod execution_tests {
    use super::*;

    #[tokio::test]
    async fn execution_client_authenticates_and_prepares_order() {
        let config = PredictExecConfig {
            api_key: api_key(),
            private_key: private_key(),
            chain_id: BNB_MAINNET_CHAIN_ID,
            live_execution: false,
            fill_or_kill: true,
        };

        let exec = PredictExecutionClient::new(config).await.unwrap();

        // Find active market
        let search = exec
            .api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        // Place limit order (dry-run)
        let result = exec
            .place_limit_order(&PredictLimitOrderRequest {
                market_id,
                outcome: PredictOutcome::Yes,
                side: PredictSide::Buy,
                price_per_share: 0.10, // deep out of money — safe even if submitted
                quantity: 1.0,
                strategy: PredictStrategy::Limit,
                slippage_bps: None,
            })
            .await
            .unwrap();

        assert!(!result.submitted, "Should be dry-run (not submitted)");
        assert!(result.response.is_none(), "Dry-run should have no response");
        assert!(
            !result.prepared.signed_order.hash.is_empty(),
            "Should have order hash"
        );
    }

    #[tokio::test]
    async fn execution_client_sell_order() {
        let config = PredictExecConfig {
            api_key: api_key(),
            private_key: private_key(),
            chain_id: BNB_MAINNET_CHAIN_ID,
            live_execution: false,
            fill_or_kill: true,
        };

        let exec = PredictExecutionClient::new(config).await.unwrap();

        let search = exec
            .api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let result = exec
            .place_limit_order(&PredictLimitOrderRequest {
                market_id,
                outcome: PredictOutcome::No,
                side: PredictSide::Sell,
                price_per_share: 0.90,
                quantity: 1.0,
                strategy: PredictStrategy::Limit,
                slippage_bps: None,
            })
            .await
            .unwrap();

        assert!(!result.submitted);
        assert!(!result.prepared.signed_order.hash.is_empty());
    }

    #[tokio::test]
    async fn execution_client_market_order_with_slippage() {
        let config = PredictExecConfig {
            api_key: api_key(),
            private_key: private_key(),
            chain_id: BNB_MAINNET_CHAIN_ID,
            live_execution: false,
            fill_or_kill: false,
        };

        let exec = PredictExecutionClient::new(config).await.unwrap();

        let search = exec
            .api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        let result = exec
            .place_limit_order(&PredictLimitOrderRequest {
                market_id,
                outcome: PredictOutcome::Yes,
                side: PredictSide::Buy,
                price_per_share: 0.50,
                quantity: 5.0,
                strategy: PredictStrategy::Market,
                slippage_bps: Some(200), // 2%
            })
            .await
            .unwrap();

        assert!(!result.submitted);

        // Verify MARKET strategy in payload
        let json = serde_json::to_value(&result.prepared.request).unwrap();
        assert_eq!(json["data"]["strategy"].as_str().unwrap(), "MARKET");
        assert_eq!(json["data"]["slippageBps"].as_str().unwrap(), "200");
    }

    #[tokio::test]
    async fn remove_orders_dry_run() {
        let config = PredictExecConfig {
            api_key: api_key(),
            private_key: private_key(),
            chain_id: BNB_MAINNET_CHAIN_ID,
            live_execution: false,
            fill_or_kill: true,
        };

        let exec = PredictExecutionClient::new(config).await.unwrap();

        let resp = exec
            .remove_order_ids(&["fake-order-id".to_string()])
            .await
            .unwrap();

        // Dry-run should return our mock response
        let is_dry = resp
            .json
            .as_ref()
            .and_then(|j| j.get("dryRun"))
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        assert!(is_dry, "Should be a dry-run response");
    }
}

// ============================================================================
// WEBSOCKET INTEGRATION TESTS
// ============================================================================

mod ws_tests {
    use super::*;
    use tokio::time::{timeout, Duration};

    #[tokio::test]
    async fn connect_and_subscribe_orderbook() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        // Find a market with orderbook
        let api = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let search = api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();

        client
            .subscribe(Topic::Orderbook { market_id })
            .await
            .unwrap();

        // Should receive an orderbook snapshot
        let msg = timeout(Duration::from_secs(10), rx.recv())
            .await
            .expect("Timeout waiting for orderbook")
            .expect("Channel closed");

        match msg {
            PredictWsMessage::Orderbook(ob) => {
                assert_eq!(ob.market_id, market_id);
                // OB should have at least one of bids or asks
                assert!(
                    !ob.bids.is_empty() || !ob.asks.is_empty(),
                    "Orderbook should have at least some levels"
                );
                assert!(ob.version > 0, "Version should be positive");
            }
            other => panic!("Expected Orderbook message, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn subscribe_asset_price_btc() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::BTC,
            })
            .await
            .unwrap();

        // Should receive a price update within a few seconds
        let msg = timeout(Duration::from_secs(10), rx.recv())
            .await
            .expect("Timeout waiting for BTC price")
            .expect("Channel closed");

        match msg {
            PredictWsMessage::AssetPrice(p) => {
                assert_eq!(p.feed_id, feeds::BTC);
                assert!(p.price > 1000.0, "BTC price should be > $1,000");
                assert!(p.price < 1_000_000.0, "BTC price should be < $1M");
                assert!(p.timestamp > 0, "Timestamp should be positive");
            }
            other => panic!("Expected AssetPrice message, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn subscribe_asset_price_eth() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::ETH,
            })
            .await
            .unwrap();

        let msg = timeout(Duration::from_secs(10), rx.recv())
            .await
            .expect("Timeout waiting for ETH price")
            .expect("Channel closed");

        match msg {
            PredictWsMessage::AssetPrice(p) => {
                assert_eq!(p.feed_id, feeds::ETH);
                assert!(p.price > 10.0, "ETH price should be > $10");
                assert!(p.price < 100_000.0, "ETH price should be < $100K");
            }
            other => panic!("Expected AssetPrice message, got {:?}", other),
        }
    }

    #[tokio::test]
    async fn subscribe_multiple_topics() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::BTC,
            })
            .await
            .unwrap();
        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::ETH,
            })
            .await
            .unwrap();

        let topics = client.active_topics().await;
        assert_eq!(topics.len(), 2, "Should have 2 active topics");

        // Receive at least 3 messages (mix of BTC and ETH)
        let mut count = 0;
        let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
        while count < 3 && tokio::time::Instant::now() < deadline {
            if let Ok(Some(msg)) = timeout(Duration::from_secs(5), rx.recv()).await {
                if matches!(msg, PredictWsMessage::AssetPrice(_)) {
                    count += 1;
                }
            }
        }
        assert!(count >= 3, "Should receive at least 3 price updates");
    }

    #[tokio::test]
    async fn subscribe_polymarket_chance() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        // polymarketChance subscription should succeed
        let result = client
            .subscribe(Topic::PolymarketChance { market_id: 7731 })
            .await;
        assert!(result.is_ok(), "polymarketChance subscription should succeed");
    }

    #[tokio::test]
    async fn subscribe_kalshi_chance() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        let result = client
            .subscribe(Topic::KalshiChance { market_id: 7731 })
            .await;
        assert!(result.is_ok(), "kalshiChance subscription should succeed");
    }

    #[tokio::test]
    async fn wallet_events_requires_auth() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        // predictWalletEvents with invalid JWT should fail
        let result = client
            .subscribe(Topic::WalletEvents {
                jwt: "invalid-token".to_string(),
            })
            .await;

        assert!(result.is_err(), "WalletEvents with bad JWT should fail");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("authorization") || err.contains("auth") || err.contains("failed"),
            "Error should mention auth: {}",
            err
        );
    }

    #[tokio::test]
    async fn orderbook_snapshot_has_helper_methods() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        let api = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let search = api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();

        // Find market with orderbook depth
        let markets = search["data"]["markets"].as_array().unwrap();
        let mut found_ob = false;

        for m in markets.iter().take(5) {
            let market_id = m["id"].as_i64().unwrap();
            client
                .subscribe(Topic::Orderbook { market_id })
                .await
                .unwrap();

            if let Ok(Some(PredictWsMessage::Orderbook(ob))) =
                timeout(Duration::from_secs(5), rx.recv()).await
            {
                if ob.best_bid().is_some() && ob.best_ask().is_some() {
                    let mid = ob.mid().unwrap();
                    let spread = ob.spread().unwrap();
                    assert!(mid > 0.0 && mid < 1.0, "Mid should be in (0, 1)");
                    assert!(spread >= 0.0, "Spread should be non-negative");
                    assert!(spread < 1.0, "Spread should be < 1.0");
                    found_ob = true;
                    break;
                }
            }
        }

        assert!(found_ob, "Should find at least one market with bid+ask");
    }
}

// ============================================================================
// FULL PIPELINE INTEGRATION TEST
// ============================================================================

#[tokio::test]
async fn full_pipeline_rest_ws_signing() {
    // 1. REST: search for a market
    let api = PredictApiClient::new_mainnet(&api_key()).unwrap();
    let search = api
        .search(&[("query", "btc".to_string())])
        .await
        .unwrap();
    let market_id = search["data"]["markets"][0]["id"].as_i64().unwrap();
    assert!(market_id > 0, "Should find a BTC market");

    // 2. REST: fetch market details
    let market = api.get_market(market_id).await.unwrap();
    let outcomes = market["data"]["outcomes"].as_array().unwrap();
    assert!(!outcomes.is_empty(), "Market should have outcomes");

    // 3. REST: fetch orderbook
    let ob = api.get_market_orderbook(market_id).await.unwrap();
    assert!(ob["data"].get("asks").is_some());

    // 4. WebSocket: subscribe and receive live data
    let (ws, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();
    ws.subscribe(Topic::Orderbook { market_id }).await.unwrap();
    ws.subscribe(Topic::AssetPrice {
        feed_id: feeds::BTC,
    })
    .await
    .unwrap();

    let msg = tokio::time::timeout(std::time::Duration::from_secs(10), rx.recv())
        .await
        .expect("Timeout")
        .expect("Channel closed");
    assert!(
        matches!(
            msg,
            PredictWsMessage::Orderbook(_) | PredictWsMessage::AssetPrice(_)
        ),
        "Should receive OB or price update"
    );

    // 5. Signing: build and sign an order for this market
    let signer =
        PredictOrderSigner::from_private_key(&private_key(), BNB_MAINNET_CHAIN_ID).unwrap();
    let addr = signer.address();

    let is_neg_risk = market["data"]["isNegRisk"].as_bool().unwrap_or(false);
    let is_yield_bearing = market["data"]["isYieldBearing"].as_bool().unwrap_or(true);
    let fee_bps = market["data"]["feeRateBps"].as_u64().unwrap_or(0) as u32;

    let yes_token = outcomes
        .iter()
        .find(|o| o["indexSet"].as_u64() == Some(1))
        .and_then(|o| o["onChainId"].as_str())
        .unwrap();

    let price = U256::from(100_000_000_000_000_000u128); // 0.10
    let qty = U256::from(1_000_000_000_000_000_000u128); // 1
    let (maker_amount, taker_amount) =
        predict_limit_order_amounts(PredictSide::Buy, price, qty);

    let order = PredictOrder::new_limit(
        addr, addr, yes_token, PredictSide::Buy, maker_amount, taker_amount, fee_bps,
    );

    let signed = signer.sign_order(&order, is_neg_risk, is_yield_bearing).unwrap();
    let sig: Signature = signed.signature.parse().unwrap();
    let hash = signer.order_hash(&order, is_neg_risk, is_yield_bearing).unwrap();
    let recovered = sig.recover_address_from_prehash(&hash).unwrap();
    assert_eq!(recovered, addr, "Full pipeline: signature recovery must match");

    // 6. Execution: dry-run via PredictExecutionClient
    let exec = PredictExecutionClient::new(PredictExecConfig {
        api_key: api_key(),
        private_key: private_key(),
        chain_id: BNB_MAINNET_CHAIN_ID,
        live_execution: false,
        fill_or_kill: true,
    })
    .await
    .unwrap();

    let result = exec
        .place_limit_order(&PredictLimitOrderRequest {
            market_id,
            outcome: PredictOutcome::Yes,
            side: PredictSide::Buy,
            price_per_share: 0.10,
            quantity: 1.0,
            strategy: PredictStrategy::Limit,
            slippage_bps: None,
        })
        .await
        .unwrap();

    assert!(!result.submitted, "Should be dry-run");
    assert!(
        !result.prepared.signed_order.hash.is_empty(),
        "Should have signed hash"
    );
}

// ============================================================================
// MARKET CACHE TESTS
// ============================================================================

mod cache_tests {
    use super::*;

    #[tokio::test]
    async fn market_meta_caches_on_second_call() {
        let exec = make_exec_client().await;
        let market_id = find_btc_market_id(&exec.api).await;

        // First call — fetches from API
        let meta1 = exec.market_meta(market_id).await.unwrap();
        assert_eq!(meta1.market_id, market_id);
        assert!(!meta1.yes_token_id.is_empty());
        assert!(!meta1.no_token_id.is_empty());
        assert_ne!(meta1.yes_token_id, meta1.no_token_id);

        // Second call — should return cached (same values)
        let meta2 = exec.market_meta(market_id).await.unwrap();
        assert_eq!(meta1.yes_token_id, meta2.yes_token_id);
        assert_eq!(meta1.no_token_id, meta2.no_token_id);
        assert_eq!(meta1.fee_rate_bps, meta2.fee_rate_bps);
    }

    #[tokio::test]
    async fn preload_markets_parallel() {
        let exec = make_exec_client().await;

        let search = exec
            .api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let markets = search["data"]["markets"].as_array().unwrap();
        let ids: Vec<i64> = markets.iter().take(3).filter_map(|m| m["id"].as_i64()).collect();

        assert!(ids.len() >= 2, "Need at least 2 markets to test preload");

        // Preload all at once
        exec.preload_markets(&ids).await.unwrap();

        // All should be cached now
        for &id in &ids {
            let meta = exec.market_meta(id).await.unwrap();
            assert_eq!(meta.market_id, id);
        }
    }

    #[tokio::test]
    async fn prepare_with_meta_zero_network() {
        let exec = make_exec_client().await;
        let market_id = find_btc_market_id(&exec.api).await;

        let meta = exec.market_meta(market_id).await.unwrap();

        // This should make ZERO network calls
        let req = PredictLimitOrderRequest {
            market_id,
            outcome: PredictOutcome::Yes,
            side: PredictSide::Buy,
            price_per_share: 0.10,
            quantity: 1.0,
            strategy: PredictStrategy::Limit,
            slippage_bps: None,
        };

        let prepared = exec.prepare_limit_order_with_meta(&req, &meta).unwrap();
        assert!(!prepared.signed_order.hash.is_empty());
        assert_eq!(prepared.is_neg_risk, meta.is_neg_risk);
    }

    #[tokio::test]
    async fn refresh_market_meta_overwrites_cache() {
        let exec = make_exec_client().await;
        let market_id = find_btc_market_id(&exec.api).await;

        let meta1 = exec.market_meta(market_id).await.unwrap();
        let meta2 = exec.refresh_market_meta(market_id).await.unwrap();

        // Same market, same data
        assert_eq!(meta1.yes_token_id, meta2.yes_token_id);
        assert_eq!(meta1.fee_rate_bps, meta2.fee_rate_bps);
    }

    #[tokio::test]
    async fn clear_cache_forces_refetch() {
        let exec = make_exec_client().await;
        let market_id = find_btc_market_id(&exec.api).await;

        exec.market_meta(market_id).await.unwrap();
        exec.clear_cache().await;

        // Should refetch
        let meta = exec.market_meta(market_id).await.unwrap();
        assert_eq!(meta.market_id, market_id);
    }
}

// ============================================================================
// EDGE CASE / ERROR HANDLING TESTS
// ============================================================================

mod edge_case_tests {
    use super::*;

    #[tokio::test]
    async fn invalid_market_id_returns_error() {
        let exec = make_exec_client().await;

        let result = exec.market_meta(999999999).await;
        assert!(result.is_err(), "Nonexistent market should error");
    }

    #[test]
    fn wei_from_zero_errors() {
        let req = PredictLimitOrderRequest {
            market_id: 1,
            outcome: PredictOutcome::Yes,
            side: PredictSide::Buy,
            price_per_share: 0.0,
            quantity: 1.0,
            strategy: PredictStrategy::Limit,
            slippage_bps: None,
        };

        let exec_config = PredictExecConfig {
            api_key: "test".into(),
            private_key: private_key(),
            chain_id: BNB_MAINNET_CHAIN_ID,
            live_execution: false,
            fill_or_kill: true,
        };
        let signer =
            PredictOrderSigner::from_private_key(&exec_config.private_key, BNB_MAINNET_CHAIN_ID)
                .unwrap();

        let meta = MarketMeta {
            market_id: 1,
            yes_token_id: "123".into(),
            no_token_id: "456".into(),
            fee_rate_bps: 200,
            is_neg_risk: false,
            is_yield_bearing: true,
        };

        // Build a temporary client just for the signing test
        // prepare_limit_order_with_meta should fail on price=0.0
        let api = PredictApiClient::new_mainnet("test").unwrap();
        let exec = PredictExecutionClient {
            api,
            signer,
            config: exec_config,
            market_cache: std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        };
        let result = exec.prepare_limit_order_with_meta(&req, &meta);
        assert!(result.is_err(), "price=0 should error");
    }

    #[test]
    fn negative_price_errors() {
        let signer =
            PredictOrderSigner::from_private_key(&private_key(), BNB_MAINNET_CHAIN_ID).unwrap();
        let api = PredictApiClient::new_mainnet("test").unwrap();
        let exec = PredictExecutionClient {
            api,
            signer,
            config: PredictExecConfig {
                api_key: "test".into(),
                private_key: private_key(),
                chain_id: BNB_MAINNET_CHAIN_ID,
                live_execution: false,
                fill_or_kill: true,
            },
            market_cache: std::sync::Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::new())),
        };
        let meta = MarketMeta {
            market_id: 1,
            yes_token_id: "123".into(),
            no_token_id: "456".into(),
            fee_rate_bps: 0,
            is_neg_risk: false,
            is_yield_bearing: false,
        };

        let result = exec.prepare_limit_order_with_meta(
            &PredictLimitOrderRequest {
                market_id: 1,
                outcome: PredictOutcome::No,
                side: PredictSide::Sell,
                price_per_share: -0.5,
                quantity: 1.0,
                strategy: PredictStrategy::Limit,
                slippage_bps: None,
            },
            &meta,
        );
        assert!(result.is_err(), "negative price should error");
    }

    #[test]
    fn invalid_private_key_errors() {
        let result = PredictOrderSigner::from_private_key("not-a-key", BNB_MAINNET_CHAIN_ID);
        assert!(result.is_err());
    }

    #[test]
    fn unsupported_chain_id_errors() {
        let result = predict_exchange_address(999, false, false);
        assert!(result.is_err());
    }

    #[test]
    fn order_amounts_zero_quantity() {
        let price = U256::from(500_000_000_000_000_000u128); // 0.5
        let qty = U256::ZERO;
        let (m, t) = predict_limit_order_amounts(PredictSide::Buy, price, qty);
        assert_eq!(m, U256::ZERO);
        assert_eq!(t, U256::ZERO);
    }

    #[test]
    fn order_amounts_extreme_prices() {
        let qty = U256::from(1_000_000_000_000_000_000u128);

        // price = 0.01 (1%)
        let (m, _t) = predict_limit_order_amounts(
            PredictSide::Buy,
            U256::from(10_000_000_000_000_000u128),
            qty,
        );
        assert_eq!(m, U256::from(10_000_000_000_000_000u128));

        // price = 0.99 (99%)
        let (m, _t) = predict_limit_order_amounts(
            PredictSide::Buy,
            U256::from(990_000_000_000_000_000u128),
            qty,
        );
        assert_eq!(m, U256::from(990_000_000_000_000_000u128));
    }

    #[test]
    fn topic_parse_invalid_ids() {
        // Non-numeric IDs fall back to Raw
        let t = Topic::from_topic_string("predictOrderbook/abc");
        assert!(matches!(t, Topic::Raw(_)));

        let t = Topic::from_topic_string("assetPriceUpdate/");
        assert!(matches!(t, Topic::Raw(_)));

        let t = Topic::from_topic_string("");
        assert!(matches!(t, Topic::Raw(_)));
    }

    #[test]
    fn orderbook_snapshot_single_side() {
        let ob = OrderbookSnapshot {
            market_id: 1,
            bids: vec![(0.45, 100.0)],
            asks: vec![],
            version: 1,
            update_timestamp_ms: 0,
            order_count: 1,
            last_order_settled: None,
        };
        assert_eq!(ob.best_bid(), Some(0.45));
        assert_eq!(ob.best_ask(), None);
        assert_eq!(ob.mid(), None); // can't compute without both sides
        assert_eq!(ob.spread(), None);
    }

    #[test]
    fn market_meta_outcome_lookup() {
        let meta = MarketMeta {
            market_id: 42,
            yes_token_id: "token_yes".into(),
            no_token_id: "token_no".into(),
            fee_rate_bps: 150,
            is_neg_risk: true,
            is_yield_bearing: false,
        };
        assert_eq!(meta.token_id(PredictOutcome::Yes), "token_yes");
        assert_eq!(meta.token_id(PredictOutcome::No), "token_no");
    }
}

// ============================================================================
// WEBSOCKET EDGE CASES
// ============================================================================

mod ws_edge_tests {
    use super::*;
    use tokio::time::{timeout, Duration};

    #[tokio::test]
    async fn unsubscribe_removes_topic() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::BTC,
            })
            .await
            .unwrap();

        let topics = client.active_topics().await;
        assert_eq!(topics.len(), 1);

        client
            .unsubscribe(Topic::AssetPrice {
                feed_id: feeds::BTC,
            })
            .await
            .unwrap();

        let topics = client.active_topics().await;
        assert_eq!(topics.len(), 0, "Unsubscribe should remove topic");
    }

    #[tokio::test]
    async fn subscribe_same_topic_twice_idempotent() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::ETH,
            })
            .await
            .unwrap();
        client
            .subscribe(Topic::AssetPrice {
                feed_id: feeds::ETH,
            })
            .await
            .unwrap();

        let topics = client.active_topics().await;
        assert_eq!(topics.len(), 1, "Duplicate subscribe should not add twice");
    }

    #[tokio::test]
    async fn raw_topic_subscribe() {
        let (client, _rx) = PredictWsClient::connect_mainnet().await.unwrap();

        // Subscribe with raw topic string — server may reject but should not crash
        let result = client.subscribe(Topic::Raw("nonexistent/123".to_string())).await;
        // Either succeeds or returns an error — both are acceptable
        let _ = result;
    }

    #[tokio::test]
    async fn multiple_orderbook_markets() {
        let (client, mut rx) = PredictWsClient::connect_mainnet().await.unwrap();

        let api = PredictApiClient::new_mainnet(&api_key()).unwrap();
        let search = api
            .search(&[("query", "btc".to_string())])
            .await
            .unwrap();
        let markets = search["data"]["markets"].as_array().unwrap();
        let ids: Vec<i64> = markets.iter().take(2).filter_map(|m| m["id"].as_i64()).collect();

        for &id in &ids {
            client.subscribe(Topic::Orderbook { market_id: id }).await.unwrap();
        }

        let topics = client.active_topics().await;
        assert_eq!(topics.len(), ids.len());

        // Should receive messages from at least one market
        let msg = timeout(Duration::from_secs(10), rx.recv())
            .await
            .expect("Timeout")
            .expect("Channel closed");
        assert!(matches!(msg, PredictWsMessage::Orderbook(_)));
    }
}

// ============================================================================
// HTTP/2 VERIFICATION TEST
// ============================================================================

#[tokio::test]
async fn api_uses_http2() {
    // Verify we're actually negotiating HTTP/2 with predict.fun
    // reqwest with rustls-tls does ALPN h2 negotiation automatically
    let client = PredictApiClient::new_mainnet(&api_key()).unwrap();
    let result = client.list_tags().await;
    assert!(result.is_ok(), "HTTP/2 request should succeed");
}

// ============================================================================
// HELPERS
// ============================================================================

async fn make_exec_client() -> PredictExecutionClient {
    PredictExecutionClient::new(PredictExecConfig {
        api_key: api_key(),
        private_key: private_key(),
        chain_id: BNB_MAINNET_CHAIN_ID,
        live_execution: false,
        fill_or_kill: true,
    })
    .await
    .unwrap()
}

async fn find_btc_market_id(api: &PredictApiClient) -> i64 {
    let search = api
        .search(&[("query", "btc".to_string())])
        .await
        .unwrap();
    search["data"]["markets"][0]["id"].as_i64().unwrap()
}