digdigdig3 0.1.29

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
//! # CosmosProvider — cosmrs-backed Cosmos SDK chain provider
//!
//! Implements [`ChainProvider`] and [`CosmosChain`] for all Cosmos SDK chains
//! (dYdX, Osmosis, Cosmos Hub, etc.).
//!
//! ## Feature gate
//!
//! This entire module is gated behind the `onchain-cosmos` feature. Enable it
//! in your `Cargo.toml`:
//!
//! ```toml
//! digdigdig3 = { version = "...", features = ["onchain-cosmos"] }
//! ```
//!
//! ## Key feature: sequence number management
//!
//! Cosmos SDK transactions require a monotonically increasing sequence number
//! per address. Concurrent `place_order` calls with the same sequence number
//! will fail on-chain — only the first tx with a given sequence is accepted.
//!
//! `CosmosProvider` maintains an internal `Mutex<HashMap<address, sequence>>`
//! cache. `next_sequence()` increments and returns atomically, so concurrent
//! callers always get distinct sequence numbers even without awaiting the
//! on-chain result.
//!
//! The cache is refreshed from the chain when a new address is seen or when
//! `refresh_sequence()` is called explicitly (e.g. after a tx fails with a
//! "sequence mismatch" error).
//!
//! ## Usage
//!
//! ```rust,ignore
//! use digdigdig3::core::chain::{CosmosProvider, CosmosChain};
//!
//! let provider = CosmosProvider::dydx_mainnet();
//! let height = provider.get_height().await?;
//! let (account_number, sequence) = provider.query_account("dydx1abc...").await?;
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::Mutex;

use super::provider::{ChainFamily, ChainProvider, TxStatus};
use crate::core::types::ExchangeError;

// ═══════════════════════════════════════════════════════════════════════════════
// COSMOS CHAIN EXTENSION TRAIT
// ═══════════════════════════════════════════════════════════════════════════════

/// Cosmos SDK-specific chain operations.
///
/// Extends [`ChainProvider`] with sequence number management, tx simulation,
/// account queries specific to the Cosmos SDK transaction model, and
/// IBC/DeFi monitoring methods useful across all Cosmos chains.
///
/// ## Object safety
///
/// This trait is object-safe: all methods take `&self` with no generics.
/// It can be stored as `Arc<dyn CosmosChain>`.
#[async_trait]
pub trait CosmosChain: ChainProvider {
    /// Return the currently cached sequence number for `address`.
    ///
    /// If the address has not been seen before, queries the chain first
    /// and populates the cache. Use [`next_sequence`] when building a new tx.
    async fn get_sequence(&self, address: &str) -> Result<u64, ExchangeError>;

    /// Atomically increment and return the next sequence number.
    ///
    /// This is the method to call when building a new transaction. It
    /// ensures that concurrent callers always get distinct values, even if
    /// multiple txs are in-flight simultaneously without waiting for on-chain
    /// inclusion.
    ///
    /// If the address is not in the cache, the chain is queried once to
    /// obtain the current on-chain sequence, then incremented before
    /// returning.
    async fn next_sequence(&self, address: &str) -> Result<u64, ExchangeError>;

    /// Force-refresh the sequence from the chain and return the new value.
    ///
    /// Call this after a tx fails with a "sequence mismatch" error so that
    /// subsequent txs use the correct on-chain sequence.
    async fn refresh_sequence(&self, address: &str) -> Result<u64, ExchangeError>;

    /// Query the chain for `(account_number, sequence)` of `address`.
    ///
    /// This is a direct chain query — the result is not cached. Prefer
    /// [`get_sequence`] / [`next_sequence`] for normal tx building.
    async fn query_account(&self, address: &str) -> Result<(u64, u64), ExchangeError>;

    /// Simulate a tx and return the estimated gas units.
    ///
    /// `tx_bytes` is the protobuf-serialised `TxRaw`. The simulation
    /// endpoint on most Cosmos nodes returns the `gas_used` field; add a
    /// safety multiplier (e.g. × 1.5) before setting `gas_limit`.
    async fn simulate(&self, tx_bytes: &[u8]) -> Result<u64, ExchangeError>;

    /// Broadcast a signed `TxRaw` and return the tx hash.
    ///
    /// Equivalent to `ChainProvider::broadcast_tx` but named explicitly for
    /// Cosmos to match the Cosmos SDK vocabulary.
    async fn broadcast_tx_sync(&self, tx_bytes: &[u8]) -> Result<String, ExchangeError>;

    // ─────────────────────────────────────────────────────────────────────────
    // IBC / DeFi monitoring
    // ─────────────────────────────────────────────────────────────────────────

    /// Query any module's state via ABCI query path.
    ///
    /// `path` is the ABCI query path (e.g. `"/cosmos.bank.v1beta1.Query/Balance"`).
    /// `data` is hex-encoded protobuf request bytes, or an empty string for
    /// queries that take no additional data.
    ///
    /// Returns the raw JSON response from the node's ABCI query endpoint.
    async fn abci_query(
        &self,
        path: &str,
        data: &str,
    ) -> Result<serde_json::Value, ExchangeError>;

    /// Get all coin balances for an address (all denoms).
    ///
    /// Returns the `balances` array from `cosmos/bank/v1beta1/balances/{address}`.
    /// Each element is a `{denom, amount}` JSON object.
    async fn get_all_balances(
        &self,
        address: &str,
    ) -> Result<Vec<serde_json::Value>, ExchangeError>;

    /// Get IBC channel information.
    ///
    /// Queries `ibc/core/channel/v1/channels/{channel_id}/ports/{port_id}`.
    /// Returns the full channel JSON object.
    async fn get_ibc_channel(
        &self,
        channel_id: &str,
        port_id: &str,
    ) -> Result<serde_json::Value, ExchangeError>;

    /// Resolve an IBC denom hash to its original path and base denom.
    ///
    /// `hash` is the hex hash portion only (without the `ibc/` prefix).
    /// Queries `ibc/apps/transfer/v1/denom_traces/{hash}`.
    async fn get_denom_trace(
        &self,
        hash: &str,
    ) -> Result<serde_json::Value, ExchangeError>;

    /// Query a CosmWasm smart contract.
    ///
    /// `contract` is the bech32 contract address.
    /// `query_msg` is the JSON query message — it will be base64-encoded
    /// and passed to `cosmwasm/wasm/v1/contract/{contract}/smart/{base64}`.
    ///
    /// Available on chains with CosmWasm: Osmosis, Neutron, Sei, etc.
    async fn query_contract_smart(
        &self,
        contract: &str,
        query_msg: serde_json::Value,
    ) -> Result<serde_json::Value, ExchangeError>;

    /// Get the current validator set.
    ///
    /// Returns the `validators` array from
    /// `cosmos/staking/v1beta1/validators`.
    async fn get_validators(&self) -> Result<Vec<serde_json::Value>, ExchangeError>;

    /// Get all delegations for a delegator address.
    ///
    /// Returns the `delegation_responses` array from
    /// `cosmos/staking/v1beta1/delegations/{delegator}`.
    async fn get_delegations(
        &self,
        delegator: &str,
    ) -> Result<Vec<serde_json::Value>, ExchangeError>;

    /// Get governance proposals.
    ///
    /// `status` filters by proposal status string:
    /// `"PROPOSAL_STATUS_VOTING_PERIOD"`, `"PROPOSAL_STATUS_PASSED"`, etc.
    /// Pass `None` to retrieve all proposals.
    ///
    /// Returns the `proposals` array from `cosmos/gov/v1/proposals`.
    async fn get_proposals(
        &self,
        status: Option<&str>,
    ) -> Result<Vec<serde_json::Value>, ExchangeError>;

    /// Fetch a transaction by hash.
    ///
    /// Returns the full JSON object from `cosmos/tx/v1beta1/txs/{hash}`.
    async fn get_tx(&self, hash: &str) -> Result<serde_json::Value, ExchangeError>;

    /// Search transactions by Tendermint events filter string.
    ///
    /// `events` is a URL-encoded events query, e.g.
    /// `"message.sender='osmo1abc...'&message.action='/osmosis.gamm.v1beta1.MsgSwapExactAmountIn'"`.
    /// `page` is 1-based pagination (defaults to page 1 when `None`).
    ///
    /// Returns the raw JSON response from `cosmos/tx/v1beta1/txs?events={events}`.
    async fn search_txs(
        &self,
        events: &str,
        page: Option<u32>,
    ) -> Result<serde_json::Value, ExchangeError>;

    /// Get pool information by pool ID.
    ///
    /// On Osmosis this queries `osmosis/gamm/v1beta1/pools/{pool_id}`.
    /// On other chains the path may differ — returns the raw JSON response.
    ///
    /// Returns `ExchangeError::UnsupportedOperation` on chains that expose no
    /// pool endpoint.
    async fn get_pool(&self, pool_id: &str) -> Result<serde_json::Value, ExchangeError>;

    /// List all pools (paginated).
    ///
    /// `pagination_key` is the base64-encoded pagination key from a previous
    /// response; pass `None` to start from the first page.
    ///
    /// On Osmosis this queries `osmosis/gamm/v1beta1/pools`.
    /// Returns the raw JSON response.
    async fn get_pools(
        &self,
        pagination_key: Option<&str>,
    ) -> Result<serde_json::Value, ExchangeError>;
}

// ═══════════════════════════════════════════════════════════════════════════════
// COSMOS PROVIDER STRUCT
// ═══════════════════════════════════════════════════════════════════════════════

/// Concrete Cosmos SDK chain provider.
///
/// Communicates with the chain via REST (LCD/API) endpoints. The sequence
/// number cache prevents nonce collisions when multiple transactions are
/// built in close succession without waiting for on-chain inclusion.
///
/// ## Construction
///
/// Use the chain-specific convenience constructors for known networks:
///
/// ```rust,ignore
/// let provider = CosmosProvider::dydx_mainnet();
/// let provider = CosmosProvider::dydx_testnet();
/// let provider = CosmosProvider::new("https://lcd.osmosis.zone", "osmosis-1");
/// ```
///
/// ## Thread safety
///
/// `CosmosProvider` is `Send + Sync` and intended to be wrapped in `Arc`
/// and shared across multiple connectors on the same chain.
pub struct CosmosProvider {
    /// LCD/REST endpoint (e.g. `"https://dydx-rest.publicnode.com"`)
    endpoint: String,
    /// Cosmos chain ID (e.g. `"dydx-mainnet-1"`)
    chain_id: String,
    /// HTTP client shared by all requests
    http: reqwest::Client,
    /// Sequence number cache: address → next usable sequence
    ///
    /// The stored value is the **next** sequence to use, not the last used.
    /// When `next_sequence` is called, the value is returned and incremented
    /// atomically under the lock.
    sequences: Arc<Mutex<HashMap<String, u64>>>,
}

impl CosmosProvider {
    // ─────────────────────────────────────────────────────────────────────────
    // Constructors
    // ─────────────────────────────────────────────────────────────────────────

    /// Create a `CosmosProvider` for any Cosmos SDK chain.
    ///
    /// `endpoint` is the LCD/REST URL (no trailing slash).
    /// `chain_id` is the Cosmos chain identifier string.
    pub fn new(endpoint: &str, chain_id: &str) -> Self {
        let http = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(30))
            .build()
            .expect("reqwest client construction is infallible with valid config");

        Self {
            endpoint: endpoint.trim_end_matches('/').to_string(),
            chain_id: chain_id.to_string(),
            http,
            sequences: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    /// dYdX v4 mainnet (`dydx-mainnet-1`).
    ///
    /// Uses the public PublicNode LCD endpoint.
    pub fn dydx_mainnet() -> Self {
        Self::new(
            "https://dydx-rest.publicnode.com",
            "dydx-mainnet-1",
        )
    }

    /// dYdX v4 testnet (`dydx-testnet-4`).
    pub fn dydx_testnet() -> Self {
        Self::new(
            "https://dydx-testnet-rest.publicnode.com",
            "dydx-testnet-4",
        )
    }

    /// Osmosis mainnet (`osmosis-1`).
    pub fn osmosis_mainnet() -> Self {
        Self::new("https://lcd.osmosis.zone", "osmosis-1")
    }

    /// Osmosis mainnet — short alias matching the task spec.
    #[inline]
    pub fn osmosis() -> Self {
        Self::osmosis_mainnet()
    }

    /// Injective Protocol mainnet (`injective-1`).
    pub fn injective() -> Self {
        Self::new("https://lcd.injective.network", "injective-1")
    }

    /// Sei Network mainnet (`pacific-1`).
    pub fn sei() -> Self {
        Self::new("https://rest.sei-apis.com", "pacific-1")
    }

    /// Neutron mainnet (`neutron-1`).
    pub fn neutron() -> Self {
        Self::new("https://rest.neutron.quasar.fi", "neutron-1")
    }

    /// dYdX v4 mainnet — short alias.
    #[inline]
    pub fn dydx() -> Self {
        Self::dydx_mainnet()
    }

    /// Celestia mainnet (`celestia`).
    pub fn celestia() -> Self {
        Self::new("https://api.celestia.nodestake.top", "celestia")
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Internal helpers
    // ─────────────────────────────────────────────────────────────────────────

    /// Query `cosmos/auth/v1beta1/accounts/{address}` and parse
    /// `(account_number, sequence)`.
    async fn fetch_account_info(
        &self,
        address: &str,
    ) -> Result<(u64, u64), ExchangeError> {
        let url = format!(
            "{}/cosmos/auth/v1beta1/accounts/{}",
            self.endpoint, address
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: account query failed for {}: {}",
                address, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: account query HTTP {} for {}: {}",
                status, address, body
            )));
        }

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: account JSON parse error: {}",
                e
            )))?;

        let account = json
            .get("account")
            .ok_or_else(|| ExchangeError::Parse(
                "CosmosProvider: missing 'account' field in response".to_string()
            ))?;

        Self::extract_account_fields(account)
    }

    /// Extract `(account_number, sequence)` from a JSON account object.
    ///
    /// Handles both the flat layout (`{account_number, sequence}`) and
    /// the wrapped layout (`{base_account: {account_number, sequence}}`).
    fn extract_account_fields(
        account: &serde_json::Value,
    ) -> Result<(u64, u64), ExchangeError> {
        // Try flat layout — fields may be strings or integers
        let num_opt = account.get("account_number")
            .and_then(|v| {
                v.as_str()
                    .and_then(|s| s.parse::<u64>().ok())
                    .or_else(|| v.as_u64())
            });

        let seq_opt = account.get("sequence")
            .and_then(|v| {
                v.as_str()
                    .and_then(|s| s.parse::<u64>().ok())
                    .or_else(|| v.as_u64())
            });

        if let (Some(num), Some(seq)) = (num_opt, seq_opt) {
            return Ok((num, seq));
        }

        // Try nested under base_account (many vesting/module account types)
        if let Some(base) = account.get("base_account") {
            return Self::extract_account_fields(base);
        }

        // Try nested under value.base_account (older Cosmos SDK layout)
        if let Some(val) = account.get("value") {
            if let Some(base) = val.get("base_account") {
                return Self::extract_account_fields(base);
            }
            // Or value itself is the account
            return Self::extract_account_fields(val);
        }

        Err(ExchangeError::Parse(format!(
            "CosmosProvider: cannot extract account_number/sequence from: {}",
            account
        )))
    }

    /// Query the latest block height via
    /// `cosmos/base/tendermint/v1beta1/blocks/latest`.
    async fn fetch_latest_height(&self) -> Result<u64, ExchangeError> {
        let url = format!(
            "{}/cosmos/base/tendermint/v1beta1/blocks/latest",
            self.endpoint
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: block height query failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: blocks/latest HTTP {}: {}",
                status, body
            )));
        }

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: block JSON parse error: {}",
                e
            )))?;

        let height_str = json
            .pointer("/block/header/height")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ExchangeError::Parse(
                "CosmosProvider: missing block.header.height".to_string()
            ))?;

        height_str.parse::<u64>().map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: block height parse error: {}",
                e
            ))
        })
    }

    /// Query native token balance via `cosmos/bank/v1beta1/balances/{address}`.
    ///
    /// Returns the amount of the first coin in the balance list as a decimal
    /// string, or `"0"` if the balance list is empty.
    async fn fetch_native_balance(&self, address: &str) -> Result<String, ExchangeError> {
        let url = format!(
            "{}/cosmos/bank/v1beta1/balances/{}",
            self.endpoint, address
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: balance query failed for {}: {}",
                address, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: balance HTTP {} for {}: {}",
                status, address, body
            )));
        }

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: balance JSON parse error: {}",
                e
            )))?;

        // Balances is an array of {denom, amount} objects.
        // Return the first balance amount as string, or "0" if empty.
        let amount = json
            .get("balances")
            .and_then(|v| v.as_array())
            .and_then(|arr| arr.first())
            .and_then(|coin| coin.get("amount"))
            .and_then(|v| v.as_str())
            .unwrap_or("0")
            .to_string();

        Ok(amount)
    }

    /// Broadcast a `TxRaw` via the REST `cosmos/tx/v1beta1/txs` endpoint.
    ///
    /// Returns the transaction hash on success.
    async fn broadcast_tx_rest(&self, tx_bytes: &[u8]) -> Result<String, ExchangeError> {
        use base64::Engine as _;

        let url = format!("{}/cosmos/tx/v1beta1/txs", self.endpoint);

        // REST broadcast expects the TxRaw as base64 inside JSON:
        //   { "tx_bytes": "<base64>", "mode": "BROADCAST_MODE_SYNC" }
        let encoded = base64::engine::general_purpose::STANDARD.encode(tx_bytes);
        let body = serde_json::json!({
            "tx_bytes": encoded,
            "mode": "BROADCAST_MODE_SYNC"
        });

        let resp = self
            .http
            .post(&url)
            .json(&body)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: broadcast_tx POST failed: {}",
                e
            )))?;

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: broadcast_tx JSON parse error: {}",
                e
            )))?;

        // Non-zero code means the chain rejected the tx
        if let Some(code) = json
            .pointer("/tx_response/code")
            .and_then(|v| v.as_u64())
        {
            if code != 0 {
                let raw_log = json
                    .pointer("/tx_response/raw_log")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown error")
                    .to_string();
                return Err(ExchangeError::Api {
                    code: code as i32,
                    message: format!("CosmosProvider broadcast rejected: {}", raw_log),
                });
            }
        }

        let txhash = json
            .pointer("/tx_response/txhash")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ExchangeError::Parse(
                "CosmosProvider: missing tx_response.txhash in broadcast response".to_string()
            ))?
            .to_string();

        Ok(txhash)
    }

    /// Query tx status via `cosmos/tx/v1beta1/txs/{hash}`.
    async fn fetch_tx_status(&self, tx_hash: &str) -> Result<TxStatus, ExchangeError> {
        let url = format!("{}/cosmos/tx/v1beta1/txs/{}", self.endpoint, tx_hash);

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: tx status query failed: {}",
                e
            )))?;

        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            return Ok(TxStatus::NotFound);
        }

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: tx status HTTP {}: {}",
                status, body
            )));
        }

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: tx status JSON parse error: {}",
                e
            )))?;

        let code = json
            .pointer("/tx_response/code")
            .and_then(|v| v.as_u64())
            .unwrap_or(0);

        let height = json
            .pointer("/tx_response/height")
            .and_then(|v| {
                v.as_str()
                    .and_then(|s| s.parse::<u64>().ok())
                    .or_else(|| v.as_u64())
            })
            .unwrap_or(0);

        if code == 0 {
            Ok(TxStatus::Confirmed { block: height })
        } else {
            let reason = json
                .pointer("/tx_response/raw_log")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown error")
                .to_string();
            Ok(TxStatus::Failed { reason })
        }
    }

    /// Simulate a tx via `cosmos/tx/v1beta1/simulate` and return gas used.
    async fn fetch_simulate(&self, tx_bytes: &[u8]) -> Result<u64, ExchangeError> {
        use base64::Engine as _;

        let url = format!("{}/cosmos/tx/v1beta1/simulate", self.endpoint);

        let encoded = base64::engine::general_purpose::STANDARD.encode(tx_bytes);
        let body = serde_json::json!({ "tx_bytes": encoded });

        let resp = self
            .http
            .post(&url)
            .json(&body)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: simulate POST failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: simulate HTTP {}: {}",
                status, body
            )));
        }

        let json: serde_json::Value = resp
            .json()
            .await
            .map_err(|e| ExchangeError::Parse(format!(
                "CosmosProvider: simulate JSON parse error: {}",
                e
            )))?;

        let gas_used = json
            .pointer("/gas_info/gas_used")
            .and_then(|v| {
                v.as_str()
                    .and_then(|s| s.parse::<u64>().ok())
                    .or_else(|| v.as_u64())
            })
            .ok_or_else(|| ExchangeError::Parse(
                "CosmosProvider: missing gas_info.gas_used in simulate response".to_string()
            ))?;

        Ok(gas_used)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ChainProvider IMPL
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl ChainProvider for CosmosProvider {
    fn chain_family(&self) -> ChainFamily {
        ChainFamily::Cosmos { chain_id: self.chain_id.clone() }
    }

    async fn broadcast_tx(&self, tx_bytes: &[u8]) -> Result<String, ExchangeError> {
        self.broadcast_tx_rest(tx_bytes).await
    }

    async fn get_height(&self) -> Result<u64, ExchangeError> {
        self.fetch_latest_height().await
    }

    /// Returns the current account sequence number (Cosmos nonce).
    async fn get_nonce(&self, address: &str) -> Result<u64, ExchangeError> {
        self.get_sequence(address).await
    }

    async fn get_native_balance(&self, address: &str) -> Result<String, ExchangeError> {
        self.fetch_native_balance(address).await
    }

    async fn get_tx_status(&self, tx_hash: &str) -> Result<TxStatus, ExchangeError> {
        self.fetch_tx_status(tx_hash).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CosmosChain IMPL
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl CosmosChain for CosmosProvider {
    async fn get_sequence(&self, address: &str) -> Result<u64, ExchangeError> {
        {
            let cache = self.sequences.lock().await;
            if let Some(&seq) = cache.get(address) {
                return Ok(seq);
            }
        }
        // Address not in cache — fetch from chain and populate
        let (_account_number, sequence) = self.fetch_account_info(address).await?;
        {
            let mut cache = self.sequences.lock().await;
            // Only insert if not already set by a concurrent caller
            cache.entry(address.to_string()).or_insert(sequence);
        }
        Ok(sequence)
    }

    async fn next_sequence(&self, address: &str) -> Result<u64, ExchangeError> {
        // Ensure the cache is populated before taking the lock for mutation
        {
            let needs_fetch = {
                let cache = self.sequences.lock().await;
                !cache.contains_key(address)
            };

            if needs_fetch {
                let (_account_number, sequence) = self.fetch_account_info(address).await?;
                let mut cache = self.sequences.lock().await;
                // Double-check: another concurrent caller may have set it
                cache.entry(address.to_string()).or_insert(sequence);
            }
        }

        // Atomically take the current value and increment for the next caller
        let mut cache = self.sequences.lock().await;
        let seq = cache
            .get_mut(address)
            .expect("just inserted above; cache entry must exist");
        let current = *seq;
        *seq = current + 1;
        Ok(current)
    }

    async fn refresh_sequence(&self, address: &str) -> Result<u64, ExchangeError> {
        let (_account_number, sequence) = self.fetch_account_info(address).await?;
        let mut cache = self.sequences.lock().await;
        cache.insert(address.to_string(), sequence);
        Ok(sequence)
    }

    async fn query_account(&self, address: &str) -> Result<(u64, u64), ExchangeError> {
        self.fetch_account_info(address).await
    }

    async fn simulate(&self, tx_bytes: &[u8]) -> Result<u64, ExchangeError> {
        self.fetch_simulate(tx_bytes).await
    }

    async fn broadcast_tx_sync(&self, tx_bytes: &[u8]) -> Result<String, ExchangeError> {
        self.broadcast_tx_rest(tx_bytes).await
    }

    // ─────────────────────────────────────────────────────────────────────────
    // IBC / DeFi monitoring implementations
    // ─────────────────────────────────────────────────────────────────────────

    async fn abci_query(
        &self,
        path: &str,
        data: &str,
    ) -> Result<serde_json::Value, ExchangeError> {
        let mut url = format!(
            "{}/abci_query?path={}&data={}",
            self.endpoint,
            urlencoding::encode(path),
            urlencoding::encode(data),
        );
        // Append height=0 to query latest
        url.push_str("&height=0&prove=false");

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: abci_query failed for path '{}': {}",
                path, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: abci_query HTTP {} for '{}': {}",
                status, path, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: abci_query JSON parse error: {}",
            e
        )))
    }

    async fn get_all_balances(
        &self,
        address: &str,
    ) -> Result<Vec<serde_json::Value>, ExchangeError> {
        let url = format!(
            "{}/cosmos/bank/v1beta1/balances/{}",
            self.endpoint, address
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_all_balances failed for {}: {}",
                address, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_all_balances HTTP {} for {}: {}",
                status, address, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: get_all_balances JSON parse error: {}",
                e
            ))
        })?;

        let balances = json
            .get("balances")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        Ok(balances)
    }

    async fn get_ibc_channel(
        &self,
        channel_id: &str,
        port_id: &str,
    ) -> Result<serde_json::Value, ExchangeError> {
        let url = format!(
            "{}/ibc/core/channel/v1/channels/{}/ports/{}",
            self.endpoint, channel_id, port_id
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_ibc_channel failed for {}/{}: {}",
                channel_id, port_id, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_ibc_channel HTTP {} for {}/{}: {}",
                status, channel_id, port_id, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: get_ibc_channel JSON parse error: {}",
            e
        )))
    }

    async fn get_denom_trace(
        &self,
        hash: &str,
    ) -> Result<serde_json::Value, ExchangeError> {
        // Strip the "ibc/" prefix if the caller accidentally included it
        let hash_only = hash.trim_start_matches("ibc/");

        let url = format!(
            "{}/ibc/apps/transfer/v1/denom_traces/{}",
            self.endpoint, hash_only
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_denom_trace failed for {}: {}",
                hash_only, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_denom_trace HTTP {} for {}: {}",
                status, hash_only, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: get_denom_trace JSON parse error: {}",
            e
        )))
    }

    async fn query_contract_smart(
        &self,
        contract: &str,
        query_msg: serde_json::Value,
    ) -> Result<serde_json::Value, ExchangeError> {
        use base64::Engine as _;

        let query_bytes = serde_json::to_vec(&query_msg).map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: query_contract_smart serialize error: {}",
                e
            ))
        })?;

        let encoded = base64::engine::general_purpose::STANDARD.encode(&query_bytes);

        let url = format!(
            "{}/cosmwasm/wasm/v1/contract/{}/smart/{}",
            self.endpoint, contract, encoded
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: query_contract_smart failed for {}: {}",
                contract, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: query_contract_smart HTTP {} for {}: {}",
                status, contract, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: query_contract_smart JSON parse error: {}",
                e
            ))
        })?;

        // Cosmos LCD wraps the result under `data`; return the inner value
        Ok(json.get("data").cloned().unwrap_or(json))
    }

    async fn get_validators(&self) -> Result<Vec<serde_json::Value>, ExchangeError> {
        let url = format!(
            "{}/cosmos/staking/v1beta1/validators",
            self.endpoint
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_validators failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_validators HTTP {}: {}",
                status, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: get_validators JSON parse error: {}",
                e
            ))
        })?;

        let validators = json
            .get("validators")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        Ok(validators)
    }

    async fn get_delegations(
        &self,
        delegator: &str,
    ) -> Result<Vec<serde_json::Value>, ExchangeError> {
        let url = format!(
            "{}/cosmos/staking/v1beta1/delegations/{}",
            self.endpoint, delegator
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_delegations failed for {}: {}",
                delegator, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_delegations HTTP {} for {}: {}",
                status, delegator, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: get_delegations JSON parse error: {}",
                e
            ))
        })?;

        let delegations = json
            .get("delegation_responses")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        Ok(delegations)
    }

    async fn get_proposals(
        &self,
        status: Option<&str>,
    ) -> Result<Vec<serde_json::Value>, ExchangeError> {
        let mut url = format!("{}/cosmos/gov/v1/proposals", self.endpoint);
        if let Some(s) = status {
            url.push_str(&format!("?proposal_status={}", urlencoding::encode(s)));
        }

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_proposals failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status_code = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_proposals HTTP {}: {}",
                status_code, body
            )));
        }

        let json: serde_json::Value = resp.json().await.map_err(|e| {
            ExchangeError::Parse(format!(
                "CosmosProvider: get_proposals JSON parse error: {}",
                e
            ))
        })?;

        let proposals = json
            .get("proposals")
            .and_then(|v| v.as_array())
            .cloned()
            .unwrap_or_default();

        Ok(proposals)
    }

    async fn get_tx(&self, hash: &str) -> Result<serde_json::Value, ExchangeError> {
        let url = format!("{}/cosmos/tx/v1beta1/txs/{}", self.endpoint, hash);

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_tx failed for {}: {}",
                hash, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_tx HTTP {} for {}: {}",
                status, hash, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: get_tx JSON parse error: {}",
            e
        )))
    }

    async fn search_txs(
        &self,
        events: &str,
        page: Option<u32>,
    ) -> Result<serde_json::Value, ExchangeError> {
        let page_num = page.unwrap_or(1);
        let url = format!(
            "{}/cosmos/tx/v1beta1/txs?events={}&page={}",
            self.endpoint,
            urlencoding::encode(events),
            page_num,
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: search_txs failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: search_txs HTTP {}: {}",
                status, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: search_txs JSON parse error: {}",
            e
        )))
    }

    async fn get_pool(&self, pool_id: &str) -> Result<serde_json::Value, ExchangeError> {
        // Osmosis GAMM endpoint — works for all poolmanager-style pools.
        // Other Cosmos chains without a GAMM module will return a 404 which
        // is propagated as a Network error; callers should handle accordingly.
        let url = format!(
            "{}/osmosis/gamm/v1beta1/pools/{}",
            self.endpoint, pool_id
        );

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_pool failed for pool {}: {}",
                pool_id, e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_pool HTTP {} for pool {}: {}",
                status, pool_id, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: get_pool JSON parse error: {}",
            e
        )))
    }

    async fn get_pools(
        &self,
        pagination_key: Option<&str>,
    ) -> Result<serde_json::Value, ExchangeError> {
        let mut url = format!("{}/osmosis/gamm/v1beta1/pools", self.endpoint);
        if let Some(key) = pagination_key {
            url.push_str(&format!(
                "?pagination.key={}",
                urlencoding::encode(key)
            ));
        }

        let resp = self
            .http
            .get(&url)
            .send()
            .await
            .map_err(|e| ExchangeError::Network(format!(
                "CosmosProvider: get_pools failed: {}",
                e
            )))?;

        if !resp.status().is_success() {
            let status = resp.status();
            let body = resp.text().await.unwrap_or_default();
            return Err(ExchangeError::Network(format!(
                "CosmosProvider: get_pools HTTP {}: {}",
                status, body
            )));
        }

        resp.json().await.map_err(|e| ExchangeError::Parse(format!(
            "CosmosProvider: get_pools JSON parse error: {}",
            e
        )))
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TESTS
// ═══════════════════════════════════════════════════════════════════════════════

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

    #[test]
    fn test_cosmos_provider_chain_family() {
        let provider = CosmosProvider::dydx_mainnet();
        assert_eq!(
            provider.chain_family(),
            ChainFamily::Cosmos { chain_id: "dydx-mainnet-1".to_string() }
        );
    }

    #[test]
    fn test_cosmos_provider_testnet_chain_id() {
        let provider = CosmosProvider::dydx_testnet();
        match provider.chain_family() {
            ChainFamily::Cosmos { chain_id } => {
                assert_eq!(chain_id, "dydx-testnet-4");
            }
            _ => panic!("Expected Cosmos chain family"),
        }
    }

    #[test]
    fn test_extract_account_fields_flat_strings() {
        let json = serde_json::json!({
            "account_number": "42",
            "sequence": "7"
        });
        let (num, seq) = CosmosProvider::extract_account_fields(&json).unwrap();
        assert_eq!(num, 42);
        assert_eq!(seq, 7);
    }

    #[test]
    fn test_extract_account_fields_flat_integers() {
        // Some nodes return integers, not strings
        let json = serde_json::json!({
            "account_number": 5,
            "sequence": 12
        });
        let (num, seq) = CosmosProvider::extract_account_fields(&json).unwrap();
        assert_eq!(num, 5);
        assert_eq!(seq, 12);
    }

    #[test]
    fn test_extract_account_fields_nested_base_account() {
        let json = serde_json::json!({
            "@type": "/cosmos.auth.v1beta1.BaseVestingAccount",
            "base_account": {
                "account_number": "100",
                "sequence": "3"
            }
        });
        let (num, seq) = CosmosProvider::extract_account_fields(&json).unwrap();
        assert_eq!(num, 100);
        assert_eq!(seq, 3);
    }

    #[tokio::test]
    async fn test_sequence_cache_atomicity() {
        // Verify that consecutive next_sequence calls return distinct values
        // without hitting the network (cache is pre-seeded).
        let provider = Arc::new(CosmosProvider::dydx_mainnet());

        // Pre-seed the cache to avoid network calls in this unit test
        {
            let mut cache = provider.sequences.lock().await;
            cache.insert("dydx1test".to_string(), 10u64);
        }

        // next_sequence returns the current value and increments
        let seq1 = provider.next_sequence("dydx1test").await.unwrap();
        let seq2 = provider.next_sequence("dydx1test").await.unwrap();
        let seq3 = provider.next_sequence("dydx1test").await.unwrap();

        assert_eq!(seq1, 10, "first call should return the seeded value");
        assert_eq!(seq2, 11, "second call should return seeded + 1");
        assert_eq!(seq3, 12, "third call should return seeded + 2");

        // Cache now holds 13 as the next pending sequence
        let cache = provider.sequences.lock().await;
        assert_eq!(*cache.get("dydx1test").unwrap(), 13u64);
    }

    #[tokio::test]
    async fn test_get_sequence_returns_cached() {
        let provider = CosmosProvider::dydx_mainnet();

        {
            let mut cache = provider.sequences.lock().await;
            cache.insert("dydx1abc".to_string(), 5u64);
        }

        // get_sequence should return the cached value without network
        let seq = provider.get_sequence("dydx1abc").await.unwrap();
        assert_eq!(seq, 5);

        // get_sequence does NOT increment the cache
        let seq2 = provider.get_sequence("dydx1abc").await.unwrap();
        assert_eq!(seq2, 5);
    }
}