ostium-rust-sdk 0.1.0

Rust SDK for interacting with the Ostium trading platform on Arbitrum
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
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
//! Main client for interacting with the Ostium platform
//!
//! The `OstiumClient` provides a unified interface for all SDK functionality
//! including trading operations, market data queries, and account management.

use alloy::providers::ProviderBuilder;
use alloy::signers::local::PrivateKeySigner;
use alloy_primitives::{aliases::U192, Address, U256};
use reqwest::Client as HttpClient;
use rust_decimal::prelude::ToPrimitive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde_json::{json, Value};
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, info, warn};

use crate::config::{Network, NetworkConfig};
use crate::contracts::{TradingContract, TradingStorageContract, UsdcContract};
use crate::error::{OstiumError, Result};
use crate::rate_limit::RateLimiterManager;
use crate::retry::{RetryConfig, RetryExecutor};
use crate::types::*;

// Type alias for the provider returned by ProviderBuilder
type Provider = alloy::providers::fillers::FillProvider<
    alloy::providers::fillers::JoinFill<
        alloy_provider::Identity,
        alloy::providers::fillers::JoinFill<
            alloy::providers::fillers::GasFiller,
            alloy::providers::fillers::JoinFill<
                alloy::providers::fillers::BlobGasFiller,
                alloy::providers::fillers::JoinFill<
                    alloy::providers::fillers::NonceFiller,
                    alloy::providers::fillers::ChainIdFiller,
                >,
            >,
        >,
    >,
    alloy::providers::RootProvider<alloy::network::Ethereum>,
    alloy::network::Ethereum,
>;

/// Builder for creating an `OstiumClient` instance
pub struct OstiumClientBuilder {
    config: NetworkConfig,
    signer: Option<PrivateKeySigner>,
    http_client: Option<HttpClient>,
    retry_config: RetryConfig,
    enable_circuit_breaker: bool,
    rate_limiter: Option<RateLimiterManager>,
}

impl OstiumClientBuilder {
    /// Create a new builder with the specified network
    pub fn new(network: Network) -> Self {
        Self {
            config: network.config(),
            signer: None,
            http_client: None,
            retry_config: RetryConfig::default(),
            enable_circuit_breaker: true,
            rate_limiter: None,
        }
    }

    /// Create a new builder with custom configuration
    pub fn with_config(config: NetworkConfig) -> Self {
        Self {
            config,
            signer: None,
            http_client: None,
            retry_config: RetryConfig::default(),
            enable_circuit_breaker: true,
            rate_limiter: None,
        }
    }

    /// Set the private key for signing transactions
    pub fn with_private_key(mut self, private_key: &str) -> Result<Self> {
        let signer = private_key
            .parse::<PrivateKeySigner>()
            .map_err(|e| OstiumError::wallet(format!("Invalid private key: {}", e)))?;
        self.signer = Some(signer);
        Ok(self)
    }

    /// Set a custom RPC URL
    pub fn with_rpc_url(mut self, url: &str) -> Result<Self> {
        self.config.rpc_url = url
            .parse()
            .map_err(|e| OstiumError::config(format!("Invalid RPC URL: {}", e)))?;
        Ok(self)
    }

    /// Set a custom HTTP client for GraphQL requests
    pub fn with_http_client(mut self, client: HttpClient) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Configure retry behavior for network operations
    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
        self.retry_config = retry_config;
        self
    }

    /// Enable/disable circuit breaker (enabled by default)
    pub fn with_circuit_breaker(mut self, enabled: bool) -> Self {
        self.enable_circuit_breaker = enabled;
        self
    }

    /// Configure optimized retry settings for different operation types
    pub fn with_network_retry(mut self) -> Self {
        self.retry_config = RetryConfig::network();
        self
    }

    /// Configure optimized retry settings for contract operations
    pub fn with_contract_retry(mut self) -> Self {
        self.retry_config = RetryConfig::contract();
        self
    }

    /// Configure optimized retry settings for GraphQL operations
    pub fn with_graphql_retry(mut self) -> Self {
        self.retry_config = RetryConfig::graphql();
        self
    }

    /// Enable rate limiting with default configurations
    pub fn with_rate_limiting(mut self) -> Self {
        self.rate_limiter = Some(RateLimiterManager::new().with_default_limits());
        self
    }

    /// Enable conservative rate limiting for production environments
    pub fn with_conservative_rate_limiting(mut self) -> Self {
        use crate::rate_limit::RateLimitConfig;
        self.rate_limiter = Some(
            RateLimiterManager::new()
                .with_graphql_rate_limit(RateLimitConfig::conservative())
                .with_rest_rate_limit(RateLimitConfig::conservative())
                .with_blockchain_rate_limit(RateLimitConfig::conservative()),
        );
        self
    }

    /// Set a custom rate limiter manager
    pub fn with_rate_limiter(mut self, rate_limiter: RateLimiterManager) -> Self {
        self.rate_limiter = Some(rate_limiter);
        self
    }

    /// Build the `OstiumClient` instance
    pub async fn build(self) -> Result<OstiumClient> {
        // Validate configuration
        self.config.validate()?;

        // Create the Alloy provider using ProviderBuilder
        let provider = ProviderBuilder::new()
            .connect(self.config.rpc_url.as_str())
            .await
            .map_err(|e| OstiumError::network(format!("Failed to connect to RPC: {}", e)))?;

        // Create HTTP client for GraphQL
        let http_client = self.http_client.unwrap_or_else(|| {
            HttpClient::builder()
                .timeout(std::time::Duration::from_secs(30))
                .build()
                .expect("Failed to create HTTP client")
        });

        info!(
            "Initialized Ostium client for {:?} network",
            self.config.network
        );

        Ok(OstiumClient {
            config: self.config,
            provider: Arc::new(provider),
            signer: self.signer,
            http_client: Arc::new(http_client),
            rate_limiter: Arc::new(self.rate_limiter.unwrap_or_default()),
            network_retry_executor: Arc::new(if self.enable_circuit_breaker {
                RetryExecutor::new(RetryConfig::network())
                    .with_circuit_breaker(5, std::time::Duration::from_secs(60))
            } else {
                RetryExecutor::new(RetryConfig::network())
            }),
            _contract_retry_executor: Arc::new(if self.enable_circuit_breaker {
                RetryExecutor::new(RetryConfig::contract())
                    .with_circuit_breaker(3, std::time::Duration::from_secs(120))
            } else {
                RetryExecutor::new(RetryConfig::contract())
            }),
            graphql_retry_executor: Arc::new(RetryExecutor::new(RetryConfig::graphql())),
        })
    }
}

/// Main client for interacting with the Ostium platform
#[derive(Clone)]
pub struct OstiumClient {
    config: NetworkConfig,
    provider: Arc<Provider>,
    signer: Option<PrivateKeySigner>,
    http_client: Arc<HttpClient>,
    rate_limiter: Arc<RateLimiterManager>,
    network_retry_executor: Arc<RetryExecutor>,
    _contract_retry_executor: Arc<RetryExecutor>,
    graphql_retry_executor: Arc<RetryExecutor>,
}

impl OstiumClient {
    /// Create a new client builder for the specified network
    pub fn builder(network: Network) -> OstiumClientBuilder {
        OstiumClientBuilder::new(network)
    }

    /// Create a new client builder with custom configuration
    pub fn builder_with_config(config: NetworkConfig) -> OstiumClientBuilder {
        OstiumClientBuilder::with_config(config)
    }

    /// Create a new client with default configuration (no signer)
    pub async fn new(network: Network) -> Result<Self> {
        OstiumClientBuilder::new(network).build().await
    }

    /// Get the network configuration
    pub fn config(&self) -> &NetworkConfig {
        &self.config
    }

    /// Get the signer address if available
    pub fn signer_address(&self) -> Option<Address> {
        self.signer.as_ref().map(|s| s.address())
    }

    /// Check if the client has a signer configured
    pub fn has_signer(&self) -> bool {
        self.signer.is_some()
    }

    /// Get USDC contract instance
    fn usdc_contract(&self) -> UsdcContract<Arc<Provider>> {
        UsdcContract::new(self.config.usdc_address, self.provider.clone())
    }

    /// Get Trading contract instance
    fn trading_contract(&self) -> TradingContract<Arc<Provider>> {
        TradingContract::new(self.config.trading_contract, self.provider.clone())
    }

    /// Get Trading Storage contract instance
    fn trading_storage_contract(&self) -> TradingStorageContract<Arc<Provider>> {
        TradingStorageContract::new(self.config.storage_contract, self.provider.clone())
    }

    /// Execute a GraphQL query
    async fn graphql_query(&self, query: &str, variables: Option<Value>) -> Result<Value> {
        // Apply rate limiting
        self.rate_limiter
            .acquire_graphql()
            .await
            .map_err(|e| OstiumError::network(format!("Rate limit error: {}", e)))?;

        let query = query.to_string();
        let variables = variables.unwrap_or(json!({}));
        let http_client = self.http_client.clone();
        let url = self.config.graphql_url.clone();

        self.graphql_retry_executor
            .execute(|| {
                let query = query.clone();
                let variables = variables.clone();
                let http_client = http_client.clone();
                let url = url.clone();

                async move {
                    let body = json!({
                        "query": query,
                        "variables": variables
                    });

                    debug!("Executing GraphQL query: {}", query);

                    let response = http_client
                        .post(url.as_str())
                        .json(&body)
                        .send()
                        .await
                        .map_err(|e| {
                            OstiumError::network(format!("GraphQL request failed: {}", e))
                        })?;

                    if !response.status().is_success() {
                        let status = response.status();
                        let error_text = response.text().await.unwrap_or_default();
                        return Err(OstiumError::graphql(format!(
                            "GraphQL request failed with status {}: {}",
                            status, error_text
                        )));
                    }

                    let json: Value = response.json().await.map_err(|e| {
                        OstiumError::graphql(format!("Failed to parse GraphQL response: {}", e))
                    })?;

                    if let Some(errors) = json.get("errors") {
                        return Err(OstiumError::graphql(format!("GraphQL errors: {}", errors)));
                    }

                    json.get("data").cloned().ok_or_else(|| {
                        OstiumError::graphql("No data in GraphQL response".to_string())
                    })
                }
            })
            .await
    }

    /// Execute a REST API call with retry logic
    async fn rest_api_call(&self, url: String) -> Result<Value> {
        // Apply rate limiting
        self.rate_limiter
            .acquire_rest()
            .await
            .map_err(|e| OstiumError::network(format!("Rate limit error: {}", e)))?;

        let http_client = self.http_client.clone();

        self.network_retry_executor
            .execute(|| {
                let url = url.clone();
                let http_client = http_client.clone();

                async move {
                    debug!("Making REST API call to: {}", url);

                    let response = http_client.get(&url).send().await.map_err(|e| {
                        OstiumError::network(format!("REST API request failed: {}", e))
                    })?;

                    if !response.status().is_success() {
                        let status = response.status();
                        let error_text = response.text().await.unwrap_or_default();
                        return Err(OstiumError::network(format!(
                            "REST API request failed with status {}: {}",
                            status, error_text
                        )));
                    }

                    response.json().await.map_err(|e| {
                        OstiumError::network(format!("Failed to parse REST API response: {}", e))
                    })
                }
            })
            .await
    }

    /// Convert decimal to U256 with proper scaling
    fn decimal_to_u256(&self, value: Decimal, decimals: u8) -> Result<U256> {
        let scale = 10_u128.pow(decimals as u32);
        let scaled = (value * Decimal::from(scale))
            .to_u128()
            .ok_or_else(|| OstiumError::conversion("Value too large for U256".to_string()))?;
        Ok(U256::from(scaled))
    }

    /// Convert decimal to U192 with 18 decimals
    fn decimal_to_u192(&self, value: Decimal) -> Result<U192> {
        let scale = 10_u128.pow(18);
        let scaled = (value * Decimal::from(scale))
            .to_u128()
            .ok_or_else(|| OstiumError::conversion("Value too large for U192".to_string()))?;
        Ok(U192::from(scaled))
    }

    /// Convert optional decimal to U192, returning ZERO if None
    fn convert_optional_price(&self, price: Option<Decimal>) -> Result<U192> {
        match price {
            Some(p) => self.decimal_to_u192(p),
            None => Ok(U192::ZERO),
        }
    }

    /// Maps Ethereum contract error selectors to human-readable messages
    ///
    /// This function takes a contract error and attempts to decode it into
    /// a more meaningful error message based on known Ostium contract error selectors.
    ///
    /// # Arguments
    /// * `error` - The error object or string containing the contract error
    ///
    /// # Returns
    /// A tuple containing (error_message, error_type, error_data)
    pub fn map_contract_error(&self, error: &str) -> (String, String, HashMap<String, String>) {
        // Error selector mapping based on Keccak hashes from Ostium contracts
        let error_selectors: HashMap<&str, &str> = [
            ("0x5863f789", "WrongParams"),
            ("0xcb87b762", "PairNotListed"),
            ("0x1309a563", "IsPaused"),
            ("0x093650d5", "NotGov"),
            ("0x2a19e833", "NotManager"),
            ("0x084986e7", "IsDone"),
            ("0x432b6c83", "NotTradesUpKeep"),
            ("0xe6f47fab", "MaxTradesPerPairReached"),
            ("0x5c12ea62", "MaxPendingMarketOrdersReached"),
            ("0x35fe85c5", "WrongLeverage"),
            ("0x80a71fc5", "AboveMaxAllowedCollateral"),
            ("0xeca695e1", "BelowMinLevPos"),
            ("0xa41bb918", "WrongTP"),
            ("0x083fbd78", "WrongSL"),
            ("0x17e08e97", "NoTradeFound"),
            ("0xdd9397bb", "TriggerPending"),
            ("0xf77a8069", "AlreadyMarketClosed"),
            ("0xa35ee470", "NoLimitFound"),
            ("0x46c4ede2", "ExposureLimits"),
            ("0xefa9e5be", "NoTradeToTimeoutFound"),
            ("0x5ac89f62", "NotYourOrder"),
            ("0x1add0915", "NotOpenMarketTimeoutOrder"),
            ("0x3e0b1869", "WaitTimeout"),
            ("0xc7fe4d00", "NotCloseMarketTimeoutOrder"),
        ]
        .iter()
        .cloned()
        .collect();

        let mut error_message = error.to_string();
        let mut error_type = "UnknownError".to_string();
        let mut error_data = HashMap::new();

        // Store original error
        error_data.insert("original_error".to_string(), error.to_string());

        // Check if this is a gas estimation error containing a contract error
        if error.contains("Gas estimation failed") && error.contains("0x") {
            // Extract contract error selector from gas estimation error
            if let Some(selector) = self.extract_error_selector(error) {
                if let Some(&contract_error) = error_selectors.get(selector.as_str()) {
                    error_type = format!("GasEstimation_{}", contract_error);
                    error_message = format!(
                        "Gas estimation failed due to contract error: {}",
                        contract_error
                    );
                    error_data.insert("contract_error".to_string(), contract_error.to_string());
                    error_data.insert("selector".to_string(), selector.clone());

                    warn!(
                        "Contract error during gas estimation: {} (Selector: {})",
                        contract_error, selector
                    );
                    return (error_message, error_type, error_data);
                }
            }
        }

        // Check for execution reverted errors with data
        if error.contains("execution reverted") {
            if let Some(selector) = self.extract_error_selector(error) {
                if let Some(&contract_error) = error_selectors.get(selector.as_str()) {
                    error_type = contract_error.to_string();
                    error_message = format!("Contract error: {}", contract_error);
                    error_data.insert("contract_error".to_string(), contract_error.to_string());
                    error_data.insert("selector".to_string(), selector.clone());

                    warn!(
                        "Contract execution reverted: {} (Selector: {})",
                        contract_error, selector
                    );
                    return (error_message, error_type, error_data);
                }
            }
        }

        // Check for specific error patterns
        if error.contains("insufficient funds") || error.contains("insufficient balance") {
            error_type = "InsufficientFunds".to_string();
            error_message = "Insufficient funds for transaction".to_string();
        } else if error.contains("nonce too low") {
            error_type = "NonceTooLow".to_string();
            error_message = "Transaction nonce is too low".to_string();
        } else if error.contains("gas required exceeds allowance") {
            error_type = "OutOfGas".to_string();
            error_message = "Transaction requires more gas than allowed".to_string();
        } else if error.contains("replacement transaction underpriced") {
            error_type = "UnderpricedReplacement".to_string();
            error_message = "Replacement transaction gas price too low".to_string();
        }

        (error_message, error_type, error_data)
    }

    /// Extracts error selector (0x + 8 hex chars) from error message
    pub fn extract_error_selector(&self, error: &str) -> Option<String> {
        // Look for pattern: 0x followed by exactly 8 hexadecimal characters
        // Simple implementation without regex
        let error_lower = error.to_lowercase();
        let mut start_pos = 0;

        while let Some(pos) = error_lower[start_pos..].find("0x") {
            let actual_pos = start_pos + pos;
            if actual_pos + 10 <= error_lower.len() {
                let candidate = &error_lower[actual_pos..actual_pos + 10];
                if candidate.len() == 10 && candidate.starts_with("0x") {
                    let hex_part = &candidate[2..];
                    if hex_part.chars().all(|c| c.is_ascii_hexdigit()) {
                        return Some(candidate.to_string());
                    }
                }
            }
            start_pos = actual_pos + 2;
        }

        None
    }

    /// Get human-readable error message for a specific error selector
    pub fn get_error_description(&self, selector: &str) -> Option<&'static str> {
        match selector {
            "0x5863f789" => Some("Wrong parameters provided to the contract function"),
            "0xcb87b762" => Some("Trading pair is not listed or supported"),
            "0x1309a563" => Some("Contract is currently paused"),
            "0x093650d5" => Some("Caller is not the contract governor"),
            "0x2a19e833" => Some("Caller is not a contract manager"),
            "0x084986e7" => Some("Operation is already completed"),
            "0x432b6c83" => Some("Caller is not authorized for trades upkeep"),
            "0xe6f47fab" => Some("Maximum number of trades per pair reached"),
            "0x5c12ea62" => Some("Maximum pending market orders reached"),
            "0x35fe85c5" => Some("Leverage value is outside allowed range"),
            "0x80a71fc5" => Some("Collateral amount exceeds maximum allowed"),
            "0xeca695e1" => Some("Position size is below minimum leverage requirement"),
            "0xa41bb918" => Some("Take profit price is invalid"),
            "0x083fbd78" => Some("Stop loss price is invalid"),
            "0x17e08e97" => Some("Trade not found"),
            "0xdd9397bb" => Some("Trigger order is pending"),
            "0xf77a8069" => Some("Market is already closed"),
            "0xa35ee470" => Some("Limit order not found"),
            "0x46c4ede2" => Some("Exposure limits exceeded"),
            "0xefa9e5be" => Some("No trade found for timeout"),
            "0x5ac89f62" => Some("Not your order"),
            "0x1add0915" => Some("Not an open market timeout order"),
            "0x3e0b1869" => Some("Must wait for timeout period"),
            "0xc7fe4d00" => Some("Not a close market timeout order"),
            _ => None,
        }
    }

    /// Enhanced error mapping that includes suggestions for common issues
    pub fn map_contract_error_with_suggestions(
        &self,
        error: &str,
    ) -> (String, String, HashMap<String, String>, Option<String>) {
        let (error_message, error_type, mut error_data) = self.map_contract_error(error);

        let suggestion = match error_type.as_str() {
            "WrongParams" | "GasEstimation_WrongParams" => Some(
                "Check that all parameters (collateral, leverage, prices) are within valid ranges"
                    .to_string(),
            ),
            "PairNotListed" | "GasEstimation_PairNotListed" => {
                Some("Verify the trading pair symbol is correct and supported".to_string())
            }
            "IsPaused" | "GasEstimation_IsPaused" => {
                Some("Trading is temporarily paused. Please try again later".to_string())
            }
            "MaxTradesPerPairReached" | "GasEstimation_MaxTradesPerPairReached" => {
                Some("Close some existing positions before opening new ones".to_string())
            }
            "MaxPendingMarketOrdersReached" | "GasEstimation_MaxPendingMarketOrdersReached" => {
                Some("Cancel some pending orders before placing new ones".to_string())
            }
            "WrongLeverage" | "GasEstimation_WrongLeverage" => {
                Some("Adjust leverage to be within the allowed range for this pair".to_string())
            }
            "AboveMaxAllowedCollateral" | "GasEstimation_AboveMaxAllowedCollateral" => {
                Some("Reduce the position size or collateral amount".to_string())
            }
            "BelowMinLevPos" | "GasEstimation_BelowMinLevPos" => Some(
                "Increase position size or reduce leverage to meet minimum requirements"
                    .to_string(),
            ),
            "WrongTP" | "GasEstimation_WrongTP" => Some(
                "Check that take profit price is reasonable relative to entry price".to_string(),
            ),
            "WrongSL" | "GasEstimation_WrongSL" => {
                Some("Check that stop loss price is reasonable relative to entry price".to_string())
            }
            "NoTradeFound" | "GasEstimation_NoTradeFound" => {
                Some("Verify the trade ID and ensure the position still exists".to_string())
            }
            "AlreadyMarketClosed" | "GasEstimation_AlreadyMarketClosed" => {
                Some("This position has already been closed".to_string())
            }
            "NoLimitFound" | "GasEstimation_NoLimitFound" => {
                Some("The limit order may have been executed or cancelled".to_string())
            }
            "ExposureLimits" | "GasEstimation_ExposureLimits" => {
                Some("Reduce position size to stay within exposure limits".to_string())
            }
            "InsufficientFunds" => {
                Some("Ensure sufficient USDC balance and allowance for the trade".to_string())
            }
            "OutOfGas" => Some("Increase gas limit for the transaction".to_string()),
            _ => None,
        };

        if let Some(ref suggestion_text) = suggestion {
            error_data.insert("suggestion".to_string(), suggestion_text.clone());
        }

        (error_message, error_type, error_data, suggestion)
    }

    /// Get minimum position size for a given symbol
    /// Returns the minimum position size in the base asset units
    pub async fn get_minimum_position_size(&self, symbol: &str) -> Result<Decimal> {
        debug!("Getting minimum position size for symbol: {}", symbol);

        // Try to get minimum size from contract data first
        match self.get_contract_minimum_size(symbol).await {
            Ok(min_size) => Ok(min_size),
            Err(_) => {
                // Fallback to asset-type-based minimum sizes
                self.get_fallback_minimum_size(symbol)
            }
        }
    }

    /// Validate trading constraints before executing a trade
    /// Checks: 1) Trading hours, 2) Minimum position size, 3) Open interest caps
    pub async fn validate_trading_constraints(
        &self,
        symbol: &str,
        side: PositionSide,
        size: Decimal,
        leverage: Decimal,
    ) -> Result<()> {
        debug!(
            "Validating trading constraints for {} {} {} at {}x leverage",
            symbol,
            match side {
                PositionSide::Long => "Long",
                PositionSide::Short => "Short",
            },
            size,
            leverage
        );

        // 1. Check trading hours
        self.validate_trading_hours(symbol).await?;

        // 2. Check minimum position size
        self.validate_minimum_position_size(symbol, size, leverage)
            .await?;

        // 3. Check open interest caps
        self.validate_open_interest_caps(symbol, side, size, leverage)
            .await?;

        Ok(())
    }

    /// Get minimum position size from contract data
    async fn get_contract_minimum_size(&self, symbol: &str) -> Result<Decimal> {
        // Try to get from trading pairs data
        let pairs = self.get_pairs().await?;

        for pair in pairs {
            if pair.symbol == symbol {
                // For now, return a calculated minimum based on spread and volume
                // This would ideally come from contract configuration
                return Ok(self.calculate_minimum_size_from_pair(&pair));
            }
        }

        Err(OstiumError::validation(format!(
            "Symbol {} not found",
            symbol
        )))
    }

    /// Calculate minimum size from pair data
    fn calculate_minimum_size_from_pair(&self, pair: &crate::types::TradingPair) -> Decimal {
        // Use a reasonable minimum based on the asset type
        // This is a fallback calculation when contract data isn't available
        if pair.symbol.starts_with("BTC") {
            dec!(0.0001) // 0.0001 BTC minimum
        } else if pair.symbol.starts_with("ETH") {
            dec!(0.001) // 0.001 ETH minimum
        } else if pair.symbol.contains("USD") {
            dec!(1.0) // $1 minimum for fiat pairs
        } else {
            dec!(0.01) // Default 0.01 for other assets
        }
    }

    /// Get fallback minimum sizes based on asset type
    fn get_fallback_minimum_size(&self, symbol: &str) -> Result<Decimal> {
        let min_size = if symbol.starts_with("BTC") {
            dec!(0.0001) // 0.0001 BTC (~$4-5 at $50k BTC)
        } else if symbol.starts_with("ETH") {
            dec!(0.001) // 0.001 ETH (~$2-4 at $3k ETH)
        } else if symbol.starts_with("SOL") {
            dec!(0.01) // 0.01 SOL
        } else if symbol.contains("EUR") || symbol.contains("GBP") || symbol.contains("JPY") {
            // Forex pairs - typically have larger minimum sizes
            dec!(1000.0) // 1000 units of base currency
        } else if symbol.contains("GOLD") || symbol.contains("SILVER") {
            dec!(0.01) // 0.01 oz
        } else if symbol.contains("SPX") || symbol.contains("NAS") {
            dec!(0.1) // 0.1 index units
        } else {
            dec!(1.0) // Default minimum
        };

        Ok(min_size)
    }

    /// Validate trading hours for the given symbol
    async fn validate_trading_hours(&self, symbol: &str) -> Result<()> {
        match self.get_trading_hours(symbol).await {
            Ok(hours) => {
                if !hours.is_open {
                    return Err(OstiumError::validation(format!(
                        "Market is closed for {}. {}",
                        symbol,
                        if let Some(next_open) = hours.next_open {
                            format!("Next opening: {}", next_open)
                        } else {
                            "Trading hours: Please check market schedule".to_string()
                        }
                    )));
                }
                Ok(())
            }
            Err(_e) => {
                // If we can't get trading hours, assume crypto is 24/7 and others might be closed
                if symbol.contains("BTC") || symbol.contains("ETH") || symbol.contains("SOL") {
                    Ok(()) // Crypto markets are typically 24/7
                } else {
                    // For traditional markets, be conservative and allow the trade
                    // but warn that hours couldn't be verified
                    warn!("Could not verify trading hours for {}", symbol);
                    Ok(())
                }
            }
        }
    }

    /// Validate minimum position size requirements
    async fn validate_minimum_position_size(
        &self,
        symbol: &str,
        size: Decimal,
        leverage: Decimal,
    ) -> Result<()> {
        let min_size = self.get_minimum_position_size(symbol).await?;

        if size < min_size {
            // Try to get current price for better error message
            let price_info = match self.get_price(symbol).await {
                Ok(price) => {
                    let min_collateral = min_size * price.mark_price / leverage;
                    format!(
                        "\n\nCurrent {} price: ${:.2}\nMinimum collateral required: ${:.2} USDC\n\nSolutions:\n• Increase position size to at least {} {}\n• Use higher leverage to reduce collateral requirements",
                        symbol,
                        price.mark_price,
                        min_collateral,
                        min_size,
                        symbol.split('/').next().unwrap_or("units")
                    )
                }
                Err(_) => format!(
                    "\n\nSolutions:\n• Increase position size to at least {} {}\n• Check minimum collateral requirements (typically 7+ USDC)",
                    min_size,
                    symbol.split('/').next().unwrap_or("units")
                )
            };

            return Err(OstiumError::validation(format!(
                "Position size {} is below minimum required size of {} for {}.{}",
                size, min_size, symbol, price_info
            )));
        }

        Ok(())
    }

    /// Validate open interest caps to prevent excessive exposure
    async fn validate_open_interest_caps(
        &self,
        symbol: &str,
        side: PositionSide,
        size: Decimal,
        leverage: Decimal,
    ) -> Result<()> {
        // Calculate notional value of the position
        let price = match self.get_price(symbol).await {
            Ok(p) => p.mark_price,
            Err(_) => {
                // If we can't get price, skip this validation
                warn!(
                    "Could not get price for {} to validate open interest caps",
                    symbol
                );
                return Ok(());
            }
        };

        let notional_value = size * price * leverage;

        // Define reasonable exposure limits (these would ideally come from contract)
        let max_single_position = match symbol {
            s if s.contains("BTC") => dec!(10_000_000), // $10M max BTC position
            s if s.contains("ETH") => dec!(5_000_000),  // $5M max ETH position
            s if s.contains("SOL") => dec!(1_000_000),  // $1M max SOL position
            _ => dec!(2_000_000),                       // $2M max for other assets
        };

        if notional_value > max_single_position {
            return Err(OstiumError::validation(format!(
                "Position notional value ${:.2} exceeds maximum allowed exposure of ${:.2} for {}.\n\nSolutions:\n• Reduce position size\n• Use lower leverage\n• Split into multiple smaller positions",
                notional_value,
                max_single_position,
                symbol
            )));
        }

        // Additional check for very large positions that might affect market
        let market_impact_threshold = max_single_position / dec!(2); // 50% of max
        if notional_value > market_impact_threshold {
            warn!(
                "Large position detected: ${:.2} notional value for {} {} position",
                notional_value,
                symbol,
                match side {
                    PositionSide::Long => "Long",
                    PositionSide::Short => "Short",
                }
            );
        }

        Ok(())
    }
}

// Trading API implementation
impl OstiumClient {
    /// Open a new trading position
    pub async fn open_position(&self, params: OpenPositionParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Opening position: {:?}", params);

        let trader = self.signer_address().unwrap();

        // Get pair index from symbol
        let storage = self.trading_storage_contract();
        let (base, quote) = params.symbol.split_once('/').ok_or_else(|| {
            OstiumError::validation("Invalid symbol format, expected 'BASE/QUOTE'".to_string())
        })?;

        let pair_index = storage.get_pair_index(base, quote).await?;

        // Calculate collateral amount (USDC has 6 decimals)
        let collateral = self.decimal_to_u256(params.size / params.leverage, 6)?;

        // Convert prices to U192 (18 decimals)
        let tp = match params.take_profit {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::ZERO,
        };
        let sl = match params.stop_loss {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::ZERO,
        };

        let trade = Trade {
            collateral,
            open_price: 0, // Will be set by the contract
            tp: tp.try_into().map_err(|e| {
                OstiumError::conversion(format!("Failed to convert take profit price: {}", e))
            })?,
            sl: sl.try_into().map_err(|e| {
                OstiumError::conversion(format!("Failed to convert stop loss price: {}", e))
            })?,
            trader,
            leverage: (params.leverage * Decimal::from(100))
                .to_u32()
                .ok_or_else(|| OstiumError::validation("Leverage value too large".to_string()))?,
            pair_index,
            index: 0, // Will be set by the contract
            buy: params.side == PositionSide::Long,
        };

        let slippage_p = self.decimal_to_u256(params.slippage_tolerance * Decimal::from(100), 0)?; // Convert to percentage

        let trading = self.trading_contract();
        trading
            .open_trade(trade, OpenOrderType::Market, slippage_p)
            .await?;

        // Return a placeholder transaction hash for now
        // In a real implementation, this would come from the transaction receipt
        Ok(alloy_primitives::TxHash::ZERO)
    }

    /// Close an existing position
    pub async fn close_position(&self, params: ClosePositionParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Closing position: {:?}", params);

        // Parse position ID to get pair_index and index
        // Format: "trader_address:pair_index:index"
        let parts: Vec<&str> = params.position_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid position ID format".to_string(),
            ));
        }

        let pair_index: u16 = parts[1].parse().map_err(|_| {
            OstiumError::validation("Invalid pair index in position ID".to_string())
        })?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in position ID".to_string()))?;

        let close_percentage = if let Some(_size) = params.size {
            // Calculate percentage based on size
            warn!("Partial close not fully implemented, closing 100%");
            10000 // 100% in basis points
        } else {
            10000 // 100% in basis points
        };

        let trading = self.trading_contract();
        trading
            .close_trade_market(pair_index, index, close_percentage)
            .await?;

        Ok(alloy_primitives::TxHash::ZERO)
    }

    /// Update take profit and stop loss for a position
    pub async fn update_tp_sl(&self, params: UpdateTPSLParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Updating TP/SL: {:?}", params);

        // Parse position ID
        let parts: Vec<&str> = params.position_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid position ID format".to_string(),
            ));
        }

        let pair_index: u16 = parts[1].parse().map_err(|_| {
            OstiumError::validation("Invalid pair index in position ID".to_string())
        })?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in position ID".to_string()))?;

        let trading = self.trading_contract();

        // Update take profit if provided
        if let Some(tp) = params.take_profit {
            let tp_u192 = self.decimal_to_u192(tp)?;
            trading.update_tp(pair_index, index, tp_u192).await?;
        }

        // Update stop loss if provided
        if let Some(sl) = params.stop_loss {
            let sl_u192 = self.decimal_to_u192(sl)?;
            trading.update_sl(pair_index, index, sl_u192).await?;
        }

        Ok(alloy_primitives::TxHash::ZERO)
    }

    // ==================== UNSIGNED TRANSACTION METHODS ====================

    /// Build unsigned transaction for opening a position
    pub async fn open_position_unsigned(
        &self,
        params: OpenPositionParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        debug!(
            "Building unsigned transaction for opening position: {:?}",
            params
        );

        // Get pair index from symbol
        let storage = self.trading_storage_contract();
        let (base, quote) = params.symbol.split_once('/').ok_or_else(|| {
            OstiumError::validation("Invalid symbol format, expected 'BASE/QUOTE'".to_string())
        })?;

        let pair_index = storage.get_pair_index(base, quote).await?;

        // Calculate collateral amount (USDC has 6 decimals)
        let collateral = self.decimal_to_u256(params.size / params.leverage, 6)?;

        // Convert prices to U192 (18 decimals)
        let tp = match params.take_profit {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::ZERO,
        };
        let sl = match params.stop_loss {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::ZERO,
        };

        let trade = Trade {
            collateral,
            open_price: 0, // Will be set by the contract
            tp: tp.try_into().map_err(|e| {
                OstiumError::conversion(format!("Failed to convert take profit price: {}", e))
            })?,
            sl: sl.try_into().map_err(|e| {
                OstiumError::conversion(format!("Failed to convert stop loss price: {}", e))
            })?,
            trader: trader_address,
            leverage: (params.leverage * Decimal::from(100))
                .to_u32()
                .ok_or_else(|| OstiumError::validation("Leverage value too large".to_string()))?,
            pair_index,
            index: 0, // Will be set by the contract
            buy: params.side == PositionSide::Long,
        };

        let slippage_p = self.decimal_to_u256(params.slippage_tolerance * Decimal::from(100), 0)?;

        let trading = self.trading_contract();
        trading
            .open_trade_unsigned(trade, OpenOrderType::Market, slippage_p, tx_params)
            .await
    }

    /// Build unsigned transaction for closing a position
    pub async fn close_position_unsigned(
        &self,
        params: ClosePositionParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        debug!(
            "Building unsigned transaction for closing position: {:?}",
            params
        );

        // Parse position ID to get pair_index and index
        let parts: Vec<&str> = params.position_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid position ID format".to_string(),
            ));
        }

        let pair_index: u16 = parts[1].parse().map_err(|_| {
            OstiumError::validation("Invalid pair index in position ID".to_string())
        })?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in position ID".to_string()))?;

        let close_percentage = if let Some(_size) = params.size {
            // Calculate percentage based on size
            warn!("Partial close not fully implemented, closing 100%");
            10000 // 100% in basis points
        } else {
            10000 // 100% in basis points
        };

        let trading = self.trading_contract();
        trading
            .close_trade_market_unsigned(pair_index, index, close_percentage, tx_params)
            .await
    }

    /// Build unsigned transactions for updating TP/SL
    pub async fn update_tp_sl_unsigned(
        &self,
        params: UpdateTPSLParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<Vec<UnsignedTransaction>> {
        debug!(
            "Building unsigned transactions for updating TP/SL: {:?}",
            params
        );

        // Parse position ID
        let parts: Vec<&str> = params.position_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid position ID format".to_string(),
            ));
        }

        let pair_index: u16 = parts[1].parse().map_err(|_| {
            OstiumError::validation("Invalid pair index in position ID".to_string())
        })?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in position ID".to_string()))?;

        let trading = self.trading_contract();
        let mut transactions = Vec::new();

        // Build transaction for updating take profit if provided
        if let Some(tp) = params.take_profit {
            let tp_u192 = self.decimal_to_u192(tp)?;
            let tx = trading
                .update_tp_unsigned(pair_index, index, tp_u192, tx_params.clone())
                .await?;
            transactions.push(tx);
        }

        // Build transaction for updating stop loss if provided
        if let Some(sl) = params.stop_loss {
            let sl_u192 = self.decimal_to_u192(sl)?;
            let tx = trading
                .update_sl_unsigned(pair_index, index, sl_u192, tx_params.clone())
                .await?;
            transactions.push(tx);
        }

        Ok(transactions)
    }

    /// Build unsigned transaction for placing an advanced order
    pub async fn place_advanced_order_unsigned(
        &self,
        params: AdvancedOrderParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        debug!(
            "Building unsigned transaction for advanced order: {:?}",
            params
        );

        // Validate order parameters
        match params.order_type {
            OrderExecutionType::Limit | OrderExecutionType::Stop => {
                if params.price.is_none() {
                    return Err(OstiumError::validation(
                        "Price is required for limit and stop orders".to_string(),
                    ));
                }
            }
            OrderExecutionType::Market => {
                // Market orders don't need a price
            }
        }

        // Get pair index from symbol
        let storage = self.trading_storage_contract();
        let (base, quote) = params.symbol.split_once('/').ok_or_else(|| {
            OstiumError::validation("Invalid symbol format, expected 'BASE/QUOTE'".to_string())
        })?;

        let pair_index = storage.get_pair_index(base, quote).await?;

        // Calculate collateral amount (USDC has 6 decimals)
        let collateral = self.decimal_to_u256(params.size / params.leverage, 6)?;

        // Convert prices to U192 (18 decimals)
        let tp = self.convert_optional_price(params.take_profit)?;
        let sl = self.convert_optional_price(params.stop_loss)?;

        // For limit and stop orders, set the open_price to the specified price
        let open_price = if let Some(price) = params.price {
            self.decimal_to_u192(price)?.try_into().unwrap_or(0)
        } else {
            0 // Will be set by the contract for market orders
        };

        let trade = Trade {
            collateral,
            open_price,
            tp: tp.try_into().unwrap_or(0),
            sl: sl.try_into().unwrap_or(0),
            trader: trader_address,
            leverage: (params.leverage * Decimal::from(100))
                .to_u32()
                .unwrap_or(100),
            pair_index,
            index: 0,
            buy: params.side == PositionSide::Long,
        };

        // Convert order type
        let order_type = match params.order_type {
            OrderExecutionType::Market => OpenOrderType::Market,
            OrderExecutionType::Limit => OpenOrderType::Limit,
            OrderExecutionType::Stop => OpenOrderType::Stop,
        };

        let slippage_p = self.decimal_to_u256(params.slippage_tolerance * Decimal::from(100), 0)?;

        let trading = self.trading_contract();
        trading
            .open_trade_unsigned(trade, order_type, slippage_p, tx_params)
            .await
    }

    /// Build unsigned transaction for canceling an order
    pub async fn cancel_order_unsigned(
        &self,
        params: CancelOrderParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        debug!(
            "Building unsigned transaction for canceling order: {:?}",
            params
        );

        // Parse order ID
        let parts: Vec<&str> = params.order_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid order ID format, expected 'trader:pair_index:index'".to_string(),
            ));
        }

        let pair_index: u16 = parts[1]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid pair index in order ID".to_string()))?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in order ID".to_string()))?;

        let trading = self.trading_contract();
        trading
            .cancel_open_limit_order_unsigned(pair_index, index, tx_params)
            .await
    }
}

// Advanced Order API implementation
impl OstiumClient {
    /// Place an advanced order (market, limit, or stop)
    pub async fn place_advanced_order(&self, params: AdvancedOrderParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Placing advanced order: {:?}", params);

        // Validate order parameters
        match params.order_type {
            OrderExecutionType::Limit | OrderExecutionType::Stop => {
                if params.price.is_none() {
                    return Err(OstiumError::validation(
                        "Price is required for limit and stop orders".to_string(),
                    ));
                }
            }
            OrderExecutionType::Market => {
                // Market orders don't need a price
            }
        }

        let trader = self.signer_address().unwrap();

        // Get pair index from symbol
        let storage = self.trading_storage_contract();
        let (base, quote) = params.symbol.split_once('/').ok_or_else(|| {
            OstiumError::validation("Invalid symbol format, expected 'BASE/QUOTE'".to_string())
        })?;

        let pair_index = storage.get_pair_index(base, quote).await?;

        // Calculate collateral amount (USDC has 6 decimals)
        let collateral = self.decimal_to_u256(params.size / params.leverage, 6)?;

        // Convert prices to U192 (18 decimals)
        let tp = self.convert_optional_price(params.take_profit)?;
        let sl = self.convert_optional_price(params.stop_loss)?;

        // For limit and stop orders, set the open_price to the specified price
        let open_price = if let Some(price) = params.price {
            self.decimal_to_u192(price)?.try_into().unwrap_or(0)
        } else {
            0 // Will be set by the contract for market orders
        };

        let trade = Trade {
            collateral,
            open_price,
            tp: tp.try_into().unwrap_or(0),
            sl: sl.try_into().unwrap_or(0),
            trader,
            leverage: (params.leverage * Decimal::from(100))
                .to_u32()
                .unwrap_or(100), // Convert to basis points
            pair_index,
            index: 0, // Will be set by the contract
            buy: params.side == PositionSide::Long,
        };

        // Convert order type
        let order_type = match params.order_type {
            OrderExecutionType::Market => OpenOrderType::Market,
            OrderExecutionType::Limit => OpenOrderType::Limit,
            OrderExecutionType::Stop => OpenOrderType::Stop,
        };

        let slippage_p = self.decimal_to_u256(params.slippage_tolerance * Decimal::from(100), 0)?;

        let trading = self.trading_contract();
        trading.open_trade(trade, order_type, slippage_p).await?;

        Ok(alloy_primitives::TxHash::ZERO)
    }

    /// Place a limit order
    pub async fn place_limit_order(&self, params: LimitOrderParams) -> Result<TxHash> {
        let advanced_params = AdvancedOrderParams {
            symbol: params.symbol,
            side: params.side,
            size: params.size,
            leverage: params.leverage,
            order_type: OrderExecutionType::Limit,
            price: Some(params.limit_price),
            take_profit: params.take_profit,
            stop_loss: params.stop_loss,
            slippage_tolerance: Decimal::from(2) / Decimal::from(100), // Default 2% slippage
        };

        self.place_advanced_order(advanced_params).await
    }

    /// Place a stop order
    pub async fn place_stop_order(&self, params: StopOrderParams) -> Result<TxHash> {
        let advanced_params = AdvancedOrderParams {
            symbol: params.symbol,
            side: params.side,
            size: params.size,
            leverage: params.leverage,
            order_type: OrderExecutionType::Stop,
            price: Some(params.stop_price),
            take_profit: params.take_profit,
            stop_loss: params.stop_loss,
            slippage_tolerance: Decimal::from(2) / Decimal::from(100), // Default 2% slippage
        };

        self.place_advanced_order(advanced_params).await
    }

    /// Cancel an open limit or stop order
    pub async fn cancel_order(&self, params: CancelOrderParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Canceling order: {:?}", params);

        // Parse order ID
        let parts: Vec<&str> = params.order_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid order ID format, expected 'trader:pair_index:index'".to_string(),
            ));
        }

        let pair_index: u16 = parts[1]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid pair index in order ID".to_string()))?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in order ID".to_string()))?;

        let trading = self.trading_contract();
        trading.cancel_open_limit_order(pair_index, index).await?;

        Ok(alloy_primitives::TxHash::ZERO)
    }

    /// Update an existing limit order
    pub async fn update_limit_order(&self, params: UpdateLimitOrderParams) -> Result<TxHash> {
        if !self.has_signer() {
            return Err(OstiumError::wallet("No signer configured"));
        }

        debug!("Updating limit order: {:?}", params);

        // Parse order ID
        let parts: Vec<&str> = params.order_id.split(':').collect();
        if parts.len() != 3 {
            return Err(OstiumError::validation(
                "Invalid order ID format, expected 'trader:pair_index:index'".to_string(),
            ));
        }

        let pair_index: u16 = parts[1]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid pair index in order ID".to_string()))?;
        let index: u8 = parts[2]
            .parse()
            .map_err(|_| OstiumError::validation("Invalid index in order ID".to_string()))?;

        // Get current order details if we need to preserve some values
        let storage = self.trading_storage_contract();
        let trader = self.signer_address().unwrap();
        let current_order = storage
            .get_open_limit_order(trader, pair_index, index)
            .await?;

        // Use new values if provided, otherwise keep current values
        let new_price = match params.limit_price {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::from(current_order.target_price),
        };

        let new_tp = match params.take_profit {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::from(current_order.tp),
        };

        let new_sl = match params.stop_loss {
            Some(p) => self.decimal_to_u192(p)?,
            None => U192::from(current_order.sl),
        };

        let trading = self.trading_contract();
        trading
            .update_open_limit_order(pair_index, index, new_price, new_tp, new_sl)
            .await?;

        Ok(alloy_primitives::TxHash::ZERO)
    }

    /// Get current market price for validation purposes
    pub async fn validate_order_price(
        &self,
        symbol: &str,
        order_type: OrderExecutionType,
        price: Decimal,
    ) -> Result<bool> {
        let current_price = self.get_price(symbol).await?.mark_price;

        match order_type {
            OrderExecutionType::Market => Ok(true), // Market orders are always valid
            OrderExecutionType::Limit => {
                // For limit orders, the price should be reasonable compared to current market
                let price_diff = (price - current_price).abs() / current_price;
                Ok(price_diff <= Decimal::from(50) / Decimal::from(100)) // Within 50% of current price
            }
            OrderExecutionType::Stop => {
                // For stop orders, the price should also be reasonable
                let price_diff = (price - current_price).abs() / current_price;
                Ok(price_diff <= Decimal::from(50) / Decimal::from(100)) // Within 50% of current price
            }
        }
    }
}

// Market Data API implementation
impl OstiumClient {
    /// Get all available trading pairs
    pub async fn get_pairs(&self) -> Result<Vec<TradingPair>> {
        debug!("Fetching trading pairs");

        let query = r#"
            query GetTradingPairs {
                pairs {
                    id
                    from
                    to
                    feed
                    spreadP
                    maxLeverage
                    volume
                }
            }
        "#;

        let response = self.graphql_query(query, None).await?;

        // Parse the response and convert to TradingPair structs
        let pairs = response
            .get("pairs")
            .and_then(|p| p.as_array())
            .ok_or_else(|| OstiumError::network("Invalid pairs response".to_string()))?;

        let mut trading_pairs = Vec::new();
        for pair in pairs {
            let id = pair.get("id").and_then(|v| v.as_str()).ok_or_else(|| {
                OstiumError::network("Missing 'id' field in pair data".to_string())
            })?;
            let from = pair.get("from").and_then(|v| v.as_str()).ok_or_else(|| {
                OstiumError::network("Missing 'from' field in pair data".to_string())
            })?;
            let to = pair.get("to").and_then(|v| v.as_str()).ok_or_else(|| {
                OstiumError::network("Missing 'to' field in pair data".to_string())
            })?;
            let max_leverage = pair
                .get("maxLeverage")
                .and_then(|v| v.as_str())
                .and_then(|s| s.parse::<u64>().ok())
                .unwrap_or(1);

            trading_pairs.push(TradingPair {
                id: id.to_string(),
                base_asset: from.to_string(),
                quote_asset: to.to_string(),
                symbol: format!("{}/{}", from, to),
                is_active: max_leverage > 0, // Assume active if max leverage > 0
                min_position_size: Decimal::from(1), // Default values - would need to get from contract
                max_position_size: Decimal::from(1000000),
                price_precision: 8,
                quantity_precision: 8,
            });
        }

        Ok(trading_pairs)
    }

    /// Get current price for a trading pair
    pub async fn get_price(&self, symbol: &str) -> Result<Price> {
        debug!("Fetching price for symbol: {}", symbol);

        // Try to get price from the REST API first
        let rest_url = "https://metadata-backend.ostium.io/PricePublish/latest-price";
        let asset = symbol.replace("/", ""); // Convert BTC/USD to BTCUSD
        let url = format!("{}?asset={}", rest_url, asset);

        match self.rest_api_call(url).await {
            Ok(price_data) => {
                // Parse the price data from the REST API
                // The API returns: {"bid": 108502.06, "mid": 108502.97, "ask": 108503.87, "isMarketOpen": true, ...}
                if let (Some(mid), Some(bid), Some(ask)) = (
                    price_data.get("mid").and_then(|p| p.as_f64()),
                    price_data.get("bid").and_then(|p| p.as_f64()),
                    price_data.get("ask").and_then(|p| p.as_f64()),
                ) {
                    let mark_price = Decimal::try_from(mid).map_err(|e| {
                        OstiumError::network(format!("Invalid price format: {}", e))
                    })?;
                    let _bid_price = Decimal::try_from(bid)
                        .map_err(|e| OstiumError::network(format!("Invalid bid format: {}", e)))?;
                    let _ask_price = Decimal::try_from(ask)
                        .map_err(|e| OstiumError::network(format!("Invalid ask format: {}", e)))?;

                    // Calculate 24h high/low as estimates (±2% from current price)
                    let high_24h = mark_price * Decimal::try_from(1.02).unwrap();
                    let low_24h = mark_price * Decimal::try_from(0.98).unwrap();

                    return Ok(Price {
                        symbol: symbol.to_string(),
                        mark_price,
                        index_price: mark_price, // Use mid price for both mark and index
                        high_24h,
                        low_24h,
                        volume_24h: Decimal::from(1000000), // Still placeholder - would need different API
                        timestamp: chrono::Utc::now(),
                    });
                }
            }
            Err(e) => {
                debug!("Failed to fetch price from REST API: {}", e);
                // Continue to fallback
            }
        }

        // Fallback: get the pair data and use placeholder prices
        let pairs = self.get_pairs().await?;
        let pair = pairs
            .iter()
            .find(|p| p.symbol == symbol)
            .ok_or_else(|| OstiumError::network(format!("Pair {} not found", symbol)))?;

        // Return placeholder price data if REST API fails
        Ok(Price {
            symbol: pair.symbol.clone(),
            mark_price: Decimal::from(50000), // Placeholder values
            index_price: Decimal::from(50000),
            high_24h: Decimal::from(52000),
            low_24h: Decimal::from(48000),
            volume_24h: Decimal::from(1000000),
            timestamp: chrono::Utc::now(),
        })
    }

    /// Get trading hours for a symbol
    pub async fn get_trading_hours(&self, symbol: &str) -> Result<TradingHours> {
        debug!("Fetching trading hours for symbol: {}", symbol);

        // Try to get trading hours from the REST API
        let rest_url = "https://metadata-backend.ostium.io/trading-hours/asset-schedule";
        let asset = symbol.replace("/", ""); // Convert BTC/USD to BTCUSD
        let url = format!("{}?asset={}", rest_url, asset);

        match self.rest_api_call(url).await {
            Ok(hours_data) => {
                // Check if we got an error response
                if let Some(error) = hours_data.get("error") {
                    debug!("Trading hours API error: {}", error);
                    // Fall through to default behavior
                } else {
                    // Parse the trading hours data from the REST API
                    let is_open = hours_data
                        .get("isOpenNow")
                        .and_then(|v| v.as_bool())
                        .unwrap_or(true); // Default to open for crypto markets when field is missing

                    return Ok(TradingHours {
                        symbol: symbol.to_string(),
                        is_open,
                        next_open: None, // Could parse opening hours if needed
                        next_close: None,
                    });
                }
            }
            Err(e) => {
                debug!("Failed to fetch trading hours from REST API: {}", e);
                // Continue to fallback
            }
        }

        // Fallback: For crypto markets (BTC, ETH), trading is typically 24/7
        // For traditional markets, we'd need more sophisticated logic
        let is_crypto = symbol.contains("BTC")
            || symbol.contains("ETH")
            || symbol.contains("SOL")
            || symbol.contains("COIN");

        Ok(TradingHours {
            symbol: symbol.to_string(),
            is_open: is_crypto, // Crypto markets are always open, others might be closed
            next_open: None,
            next_close: None,
        })
    }
}

// Account API implementation
impl OstiumClient {
    /// Get account balance
    pub async fn get_balance(&self, address: Option<Address>) -> Result<Balance> {
        let account = address
            .or_else(|| self.signer_address())
            .ok_or_else(|| OstiumError::wallet("No address provided and no signer configured"))?;

        debug!("Fetching balance for address: {}", account);

        let usdc = self.usdc_contract();
        let balance = usdc.balance_of(account).await?;

        // Convert from USDC decimals (6) to Decimal
        let balance_decimal = Decimal::from(balance.to::<u128>()) / Decimal::from(1_000_000);

        Ok(Balance {
            asset: "USDC".to_string(),
            available: balance_decimal,
            locked: Decimal::ZERO, // Would need to calculate from open positions
            total: balance_decimal,
        })
    }

    /// Get open positions for an account
    pub async fn get_positions(&self, address: Option<Address>) -> Result<Vec<Position>> {
        let account = address
            .or_else(|| self.signer_address())
            .ok_or_else(|| OstiumError::wallet("No address provided and no signer configured"))?;

        debug!("Fetching positions for address: {}", account);

        let storage = self.trading_storage_contract();
        let mut positions = Vec::new();

        // Get all trading pairs to iterate through
        let pairs = self.get_pairs().await?;

        for (pair_index, pair) in pairs.iter().enumerate() {
            let pair_index = pair_index as u16;

            // Get the count of trades for this pair
            match storage.get_trades_count(account, pair_index).await {
                Ok(count) => {
                    // Iterate through all trades for this pair
                    for index in 0..count {
                        match storage.get_trade(account, pair_index, index).await {
                            Ok(trade) => {
                                // Convert contract Trade to SDK Position
                                let position = Position {
                                    id: format!("{}:{}:{}", account, pair_index, index),
                                    symbol: pair.symbol.clone(),
                                    side: if trade.buy {
                                        PositionSide::Long
                                    } else {
                                        PositionSide::Short
                                    },
                                    size: Decimal::from(trade.collateral.to::<u128>())
                                        / Decimal::from(1_000_000), // Convert from USDC decimals
                                    entry_price: Decimal::from(trade.open_price)
                                        / Decimal::from(10_u128.pow(18)), // Convert from 18 decimals
                                    mark_price: Decimal::ZERO, // Would need to fetch current price
                                    unrealized_pnl: Decimal::ZERO, // Would need to calculate
                                    realized_pnl: Decimal::ZERO, // Would need to track
                                    margin: Decimal::from(trade.collateral.to::<u128>())
                                        / Decimal::from(1_000_000),
                                    leverage: Decimal::from(trade.leverage) / Decimal::from(100), // Convert from basis points
                                    liquidation_price: None, // Would need to calculate
                                    take_profit: if trade.tp > 0 {
                                        Some(
                                            Decimal::from(trade.tp)
                                                / Decimal::from(10_u128.pow(18)),
                                        )
                                    } else {
                                        None
                                    },
                                    stop_loss: if trade.sl > 0 {
                                        Some(
                                            Decimal::from(trade.sl)
                                                / Decimal::from(10_u128.pow(18)),
                                        )
                                    } else {
                                        None
                                    },
                                    created_at: chrono::Utc::now(), // Would need to get from events
                                    updated_at: chrono::Utc::now(),
                                };
                                positions.push(position);
                            }
                            Err(_) => {
                                // Trade might not exist or be closed, continue
                                continue;
                            }
                        }
                    }
                }
                Err(_) => {
                    // Pair might not have any trades, continue
                    continue;
                }
            }
        }

        Ok(positions)
    }

    /// Get open orders for an account
    pub async fn get_orders(&self, address: Option<Address>) -> Result<Vec<Order>> {
        let account = address
            .or_else(|| self.signer_address())
            .ok_or_else(|| OstiumError::wallet("No address provided and no signer configured"))?;

        debug!("Fetching orders for address: {}", account);

        let storage = self.trading_storage_contract();
        let mut orders = Vec::new();

        // Get all trading pairs to iterate through
        let pairs = self.get_pairs().await?;

        for (pair_index, pair) in pairs.iter().enumerate() {
            let pair_index = pair_index as u16;

            // Get the count of open limit orders for this pair
            match storage
                .get_open_limit_orders_count(account, pair_index)
                .await
            {
                Ok(count) => {
                    // Iterate through all open limit orders for this pair
                    for index in 0..count {
                        match storage
                            .get_open_limit_order(account, pair_index, index)
                            .await
                        {
                            Ok(limit_order) => {
                                // Convert contract OpenLimitOrder to SDK Order
                                let order_type = match limit_order.order_type {
                                    1 => OrderType::Limit,
                                    2 => OrderType::StopMarket,
                                    _ => OrderType::Market,
                                };

                                let order = Order {
                                    id: format!("{}:{}:{}", account, pair_index, index),
                                    symbol: pair.symbol.clone(),
                                    order_type,
                                    side: if limit_order.buy {
                                        PositionSide::Long
                                    } else {
                                        PositionSide::Short
                                    },
                                    size: Decimal::from(limit_order.collateral.to::<u128>())
                                        / Decimal::from(1_000_000), // Convert from USDC decimals
                                    price: Some(
                                        Decimal::from(limit_order.target_price)
                                            / Decimal::from(10_u128.pow(18)),
                                    ), // Convert from 18 decimals
                                    stop_price: None, // Would need additional logic for stop orders
                                    status: OrderStatus::Pending, // Assume pending if it exists
                                    filled_size: Decimal::ZERO, // Would need to track fills
                                    avg_fill_price: None,
                                    created_at: chrono::DateTime::from_timestamp(
                                        limit_order.created_at as i64,
                                        0,
                                    )
                                    .unwrap_or_else(chrono::Utc::now),
                                    updated_at: chrono::DateTime::from_timestamp(
                                        limit_order.last_updated as i64,
                                        0,
                                    )
                                    .unwrap_or_else(chrono::Utc::now),
                                };
                                orders.push(order);
                            }
                            Err(_) => {
                                // Order might not exist, continue
                                continue;
                            }
                        }
                    }
                }
                Err(_) => {
                    // Pair might not have any orders, continue
                    continue;
                }
            }
        }

        Ok(orders)
    }
}

/// Trait for trading operations
#[allow(async_fn_in_trait)]
pub trait TradingApi {
    /// Open a new position
    async fn open_position(&self, params: OpenPositionParams) -> Result<TxHash>;

    /// Close an existing position
    async fn close_position(&self, params: ClosePositionParams) -> Result<TxHash>;

    /// Update take profit and stop loss
    async fn update_tp_sl(&self, params: UpdateTPSLParams) -> Result<TxHash>;
}

/// Trait for market data operations
#[allow(async_fn_in_trait)]
pub trait MarketDataApi {
    /// Get all trading pairs
    async fn get_pairs(&self) -> Result<Vec<TradingPair>>;

    /// Get price for a symbol
    async fn get_price(&self, symbol: &str) -> Result<Price>;

    /// Get trading hours for a symbol
    async fn get_trading_hours(&self, symbol: &str) -> Result<TradingHours>;
}

/// Trait for account operations
#[allow(async_fn_in_trait)]
pub trait AccountApi {
    /// Get account balance
    async fn get_balance(&self, address: Option<Address>) -> Result<Balance>;

    /// Get open positions
    async fn get_positions(&self, address: Option<Address>) -> Result<Vec<Position>>;

    /// Get open orders
    async fn get_orders(&self, address: Option<Address>) -> Result<Vec<Order>>;
}

/// Trait for advanced order operations (market, limit, stop orders)
#[allow(async_fn_in_trait)]
pub trait AdvancedOrderApi {
    /// Place an advanced order (market, limit, or stop)
    async fn place_advanced_order(&self, params: AdvancedOrderParams) -> Result<TxHash>;

    /// Place a limit order
    async fn place_limit_order(&self, params: LimitOrderParams) -> Result<TxHash>;

    /// Place a stop order
    async fn place_stop_order(&self, params: StopOrderParams) -> Result<TxHash>;

    /// Cancel an open order
    async fn cancel_order(&self, params: CancelOrderParams) -> Result<TxHash>;

    /// Update an existing limit order
    async fn update_limit_order(&self, params: UpdateLimitOrderParams) -> Result<TxHash>;

    /// Validate order price against current market
    async fn validate_order_price(
        &self,
        symbol: &str,
        order_type: OrderExecutionType,
        price: Decimal,
    ) -> Result<bool>;
}

/// Trait for unsigned transaction operations (for frontend integration)
#[allow(async_fn_in_trait)]
pub trait UnsignedTransactionApi {
    /// Build unsigned transaction for opening a position
    async fn open_position_unsigned(
        &self,
        params: OpenPositionParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction>;

    /// Build unsigned transaction for closing a position
    async fn close_position_unsigned(
        &self,
        params: ClosePositionParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction>;

    /// Build unsigned transactions for updating TP/SL
    async fn update_tp_sl_unsigned(
        &self,
        params: UpdateTPSLParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<Vec<UnsignedTransaction>>;

    /// Build unsigned transaction for placing an advanced order
    async fn place_advanced_order_unsigned(
        &self,
        params: AdvancedOrderParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction>;

    /// Build unsigned transaction for canceling an order
    async fn cancel_order_unsigned(
        &self,
        params: CancelOrderParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction>;
}

// Implement the traits for OstiumClient
impl TradingApi for OstiumClient {
    async fn open_position(&self, params: OpenPositionParams) -> Result<TxHash> {
        OstiumClient::open_position(self, params).await
    }

    async fn close_position(&self, params: ClosePositionParams) -> Result<TxHash> {
        OstiumClient::close_position(self, params).await
    }

    async fn update_tp_sl(&self, params: UpdateTPSLParams) -> Result<TxHash> {
        OstiumClient::update_tp_sl(self, params).await
    }
}

impl MarketDataApi for OstiumClient {
    async fn get_pairs(&self) -> Result<Vec<TradingPair>> {
        OstiumClient::get_pairs(self).await
    }

    async fn get_price(&self, symbol: &str) -> Result<Price> {
        OstiumClient::get_price(self, symbol).await
    }

    async fn get_trading_hours(&self, symbol: &str) -> Result<TradingHours> {
        OstiumClient::get_trading_hours(self, symbol).await
    }
}

impl AccountApi for OstiumClient {
    async fn get_balance(&self, address: Option<Address>) -> Result<Balance> {
        OstiumClient::get_balance(self, address).await
    }

    async fn get_positions(&self, address: Option<Address>) -> Result<Vec<Position>> {
        OstiumClient::get_positions(self, address).await
    }

    async fn get_orders(&self, address: Option<Address>) -> Result<Vec<Order>> {
        OstiumClient::get_orders(self, address).await
    }
}

impl AdvancedOrderApi for OstiumClient {
    async fn place_advanced_order(&self, params: AdvancedOrderParams) -> Result<TxHash> {
        self.place_advanced_order(params).await
    }

    async fn place_limit_order(&self, params: LimitOrderParams) -> Result<TxHash> {
        self.place_limit_order(params).await
    }

    async fn place_stop_order(&self, params: StopOrderParams) -> Result<TxHash> {
        self.place_stop_order(params).await
    }

    async fn cancel_order(&self, params: CancelOrderParams) -> Result<TxHash> {
        self.cancel_order(params).await
    }

    async fn update_limit_order(&self, params: UpdateLimitOrderParams) -> Result<TxHash> {
        self.update_limit_order(params).await
    }

    async fn validate_order_price(
        &self,
        symbol: &str,
        order_type: OrderExecutionType,
        price: Decimal,
    ) -> Result<bool> {
        self.validate_order_price(symbol, order_type, price).await
    }
}

impl UnsignedTransactionApi for OstiumClient {
    async fn open_position_unsigned(
        &self,
        params: OpenPositionParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        OstiumClient::open_position_unsigned(self, params, trader_address, tx_params).await
    }

    async fn close_position_unsigned(
        &self,
        params: ClosePositionParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        OstiumClient::close_position_unsigned(self, params, tx_params).await
    }

    async fn update_tp_sl_unsigned(
        &self,
        params: UpdateTPSLParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<Vec<UnsignedTransaction>> {
        OstiumClient::update_tp_sl_unsigned(self, params, tx_params).await
    }

    async fn place_advanced_order_unsigned(
        &self,
        params: AdvancedOrderParams,
        trader_address: Address,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        OstiumClient::place_advanced_order_unsigned(self, params, trader_address, tx_params).await
    }

    async fn cancel_order_unsigned(
        &self,
        params: CancelOrderParams,
        tx_params: UnsignedTransactionParams,
    ) -> Result<UnsignedTransaction> {
        OstiumClient::cancel_order_unsigned(self, params, tx_params).await
    }
}