moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
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
//! Concrete [`PublicDataProvider`] backed by a Midnight indexer.
//!
//! Port of `@midnight-ntwrk/midnight-js-indexer-public-data-provider`.
//!
//! # Design
//!
//! - **One-shot queries** (`queryContractState`, `queryUnshielded
//!   Balances`, etc.) are plain HTTP POSTs against
//!   `<indexer>/api/v4/graphql`, issued via `reqwest`. Inline GraphQL
//!   query strings mirror the TS reference verbatim so field drift is
//!   caught with a schema diff, not a runtime surprise.
//! - **Watch-for-\*** methods poll the same one-shot queries at
//!   [`DEFAULT_POLL_INTERVAL_MS`] until a result arrives — mirrors the
//!   TS `watchQuery({ pollInterval: 1000 })` idiom. The "waits
//!   indefinitely" contract of [`PublicDataProvider`] is preserved:
//!   callers that want a timeout wrap the returned future.
//! - **Reactive streams** (`contractStateObservable`,
//!   `unshieldedBalancesObservable`) delegate to
//!   [`subscribe_contract_actions`] — the indexer's native
//!   `contractActions` subscription replays historic ticks from the
//!   requested offset and then hands over to live ticks, so no separate
//!   replay-then-merge dance is required.
//!
//! # Pure vs. transport
//!
//! The JSON → domain parsing lives in small pure functions at the
//! bottom of this file (`parse_finalized_tx_from_json`,
//! `parse_unshielded_balances_from_json`, …). They're unit-tested with
//! hand-crafted GraphQL responses and require no HTTP transport.

use std::sync::Arc;
use std::time::Duration;

use futures::stream::StreamExt;
use moonproof_macros::async_trait;
use serde_json::{json, Value};

use moonproof_indexer_client::{subscribe_contract_actions, BlockOffset, ContractActionTickRaw};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::onchain_runtime::state::ContractState;
use moonproof_ledger::storage::db::InMemoryDB;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::public_data::{
    BlockInfo, ContractEvent, ContractEventFilter, ContractEventsPage, PublicDataProvider,
    PublicDataStream, ZSwapAndContractState,
};
use crate::types::{
    BlockHash as MoonBlockHash, ContractStateQueryAt, ContractStateStreamStart, Fees,
    FinalizedTxData, SegmentStatus, TransactionHash, TransactionId, TxStatus, UnshieldedBalance,
    UnshieldedBalances, UnshieldedUtxo, UnshieldedUtxos,
};
use moonproof_runtime::state::{contract_address_to_hex, decode_contract_state};

/// Milliseconds between poll attempts in the `watch_for_*` methods.
/// Matches the TS reference's `DEFAULT_POLL_INTERVAL`.
pub const DEFAULT_POLL_INTERVAL_MS: u64 = 1_000;

/// Concrete [`PublicDataProvider`] wrapping a Midnight indexer's
/// GraphQL endpoint.
///
/// Cheap to clone — internally an [`Arc`] of reusable transport bits.
#[derive(Clone)]
pub struct IndexerPublicDataProvider {
    inner: Arc<Inner>,
}

struct Inner {
    /// Full GraphQL URL (e.g. `http://127.0.0.1:8088/api/v4/graphql`).
    graphql_url: String,
    /// Base URL used to build websocket subscription URLs (same URL as
    /// [`Inner::graphql_url`]; kept separately so callers can override
    /// in tests without reconstructing the whole client).
    subscription_http_url: String,
    http: reqwest::Client,
    poll_interval_ms: u64,
}

impl std::fmt::Debug for IndexerPublicDataProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IndexerPublicDataProvider")
            .field("graphql_url", &self.inner.graphql_url)
            .field("poll_interval_ms", &self.inner.poll_interval_ms)
            .finish_non_exhaustive()
    }
}

impl IndexerPublicDataProvider {
    /// Build a provider from an indexer base URL or full GraphQL URL.
    ///
    /// - `http://host:port` → appends `/api/v4/graphql`.
    /// - `http://host:port/api/v4/graphql` → used verbatim.
    ///
    /// # Errors
    ///
    /// Returns [`ContractRuntimeError::Provider`] if `base_url` is not
    /// a parseable URL.
    pub fn new(base_url: &str) -> Result<Self> {
        let invalid = |e: moonproof_indexer_client::IndexerError| ContractRuntimeError::Provider {
            provider: "public_data",
            message: format!(
                "invalid indexer URL `{}`: {e}",
                moonproof_indexer_client::redact_project_id(base_url)
            ),
        };
        let endpoint =
            moonproof_indexer_client::IndexerEndpoint::parse(base_url).map_err(invalid)?;
        let http = endpoint.http_client().map_err(invalid)?;
        Ok(Self {
            inner: Arc::new(Inner {
                graphql_url: endpoint.url.to_string(),
                // The WebSocket handshake carries the project id in the
                // URL; HTTP requests carry it as a header.
                subscription_http_url: endpoint.url_with_project_id().to_string(),
                http,
                poll_interval_ms: DEFAULT_POLL_INTERVAL_MS,
            }),
        })
    }

    /// Override the poll interval used by `watch_for_*` methods.
    /// Mainly useful for tests that want tighter polling than the
    /// default one-second beat.
    #[must_use]
    pub fn with_poll_interval(mut self, interval: Duration) -> Self {
        let inner = Arc::make_mut(&mut self.inner);
        inner.poll_interval_ms = u64::try_from(interval.as_millis()).unwrap_or(u64::MAX);
        self
    }

    fn poll_interval(&self) -> Duration {
        Duration::from_millis(self.inner.poll_interval_ms)
    }

    /// Execute a GraphQL query + variables pair. Returns the `data`
    /// field of the response; propagates `errors` as a
    /// [`ContractRuntimeError::Indexer`] payload.
    async fn execute(&self, query: &str, variables: Value) -> Result<Value> {
        let body = json!({
            "query": query,
            "variables": variables,
        });
        let response = self
            .inner
            .http
            .post(&self.inner.graphql_url)
            .json(&body)
            .send()
            .await
            .map_err(|e| ContractRuntimeError::Indexer(format!("HTTP request failed: {e}")))?;
        let status = response.status();
        let body: Value = response.json().await.map_err(|e| {
            ContractRuntimeError::Indexer(format!("decode indexer response (status={status}): {e}"))
        })?;
        if let Some(errors) = body.get("errors").filter(|v| !v.is_null()) {
            return Err(ContractRuntimeError::Indexer(format!(
                "graphql errors: {errors}"
            )));
        }
        let data = body
            .get("data")
            .cloned()
            .ok_or_else(|| ContractRuntimeError::Indexer("response missing `data` field".into()))?;
        Ok(data)
    }
}

impl Clone for Inner {
    fn clone(&self) -> Self {
        Self {
            graphql_url: self.graphql_url.clone(),
            subscription_http_url: self.subscription_http_url.clone(),
            http: self.http.clone(),
            poll_interval_ms: self.poll_interval_ms,
        }
    }
}

// =====================================================================
// GraphQL query strings — ports of TS reference verbatim.
// =====================================================================

const CONTRACT_STATE_QUERY: &str = r"
    query ContractStateQuery($address: HexEncoded!, $offset: ContractActionOffset) {
        contractAction(address: $address, offset: $offset) {
            state
        }
    }
";

// All three read from one block, as the indexer schema prescribes for
// building a transaction. The parameters carry the fee prices the
// transcript's gas budget is partitioned against, and they move per
// block, so the block of the contract's last action is the wrong one;
// the zswap tree from that block can also have aged out of the root
// window.
const CONTRACT_AND_ZSWAP_STATE_QUERY: &str = r"
    query ZSwapAndContractStateQuery($address: HexEncoded!, $offset: BlockOffset) {
        block(offset: $offset) {
            ledgerParameters
            contractZswapState(address: $address)
        }
        contract(address: $address, offset: $offset) {
            state
        }
    }
";

const BLOCK_INFO_QUERY: &str = r"
    query BlockInfoQuery($offset: BlockOffset) {
        block(offset: $offset) {
            hash
            height
            protocolVersion
        }
    }
";

const DEPLOY_CONTRACT_STATE_TX_QUERY: &str = r"
    query DeployContractStateQuery($address: HexEncoded!) {
        contractAction(address: $address) {
            __typename
            ... on ContractDeploy { state }
            ... on ContractUpdate { state }
            ... on ContractCall {
                deploy {
                    transaction {
                        contractActions {
                            address
                            state
                        }
                    }
                }
            }
        }
    }
";

const QUERY_UNSHIELDED_BALANCES: &str = r"
    query UnshieldedBalancesQuery($address: HexEncoded!, $offset: ContractActionOffset) {
        contractAction(address: $address, offset: $offset) {
            __typename
            ... on ContractDeploy { unshieldedBalances { tokenType amount } }
            ... on ContractCall  { unshieldedBalances { tokenType amount } }
            ... on ContractUpdate { unshieldedBalances { tokenType amount } }
        }
    }
";

const TX_ID_QUERY: &str = r"
    query TxIdQuery($offset: TransactionOffset!) {
        transactions(offset: $offset) {
            __typename
            id
            protocolVersion
            raw
            hash
            unshieldedCreatedOutputs { owner intentHash tokenType value }
            unshieldedSpentOutputs { owner intentHash tokenType value }
            block { height hash author timestamp }
            ... on RegularTransaction {
                identifiers
                fees { paidFees estimatedFees }
                transactionResult {
                    status
                    segments { id success }
                }
            }
        }
    }
";

const DEPLOY_TX_QUERY: &str = r"
    query DeployTxQuery($address: HexEncoded!) {
        contractAction(address: $address) {
            __typename
            ... on ContractDeploy { transaction { ...TxFields } }
            ... on ContractUpdate { transaction { ...TxFields } }
            ... on ContractCall   { deploy { transaction { ...TxFields } } }
        }
    }
    fragment TxFields on Transaction {
        __typename
        id
        protocolVersion
        raw
        hash
        contractActions { address }
        block { height hash author timestamp }
        unshieldedCreatedOutputs { owner intentHash tokenType value }
        unshieldedSpentOutputs { owner intentHash tokenType value }
        ... on RegularTransaction {
            identifiers
            fees { paidFees estimatedFees }
            transactionResult {
                status
                segments { id success }
            }
        }
    }
";

// =====================================================================
// `PublicDataProvider` impl.
// =====================================================================

#[async_trait]
impl PublicDataProvider for IndexerPublicDataProvider {
    async fn query_block(&self, at: Option<ContractStateQueryAt>) -> Result<Option<BlockInfo>> {
        let data = self
            .execute(
                BLOCK_INFO_QUERY,
                json!({ "offset": block_offset_variable(at.as_ref()) }),
            )
            .await?;
        match data.get("block") {
            None | Some(Value::Null) => Ok(None),
            Some(block) => Ok(Some(parse_block_info(block)?)),
        }
    }

    async fn query_latest_protocol_version(&self) -> Result<u32> {
        self.query_block(None)
            .await?
            .map(|b| b.protocol_version)
            .ok_or_else(|| {
                ContractRuntimeError::Indexer("the indexer reported no block".to_owned())
            })
    }

    async fn query_contract_events(
        &self,
        filter: &ContractEventFilter,
        page: ContractEventsPage,
    ) -> Result<Vec<ContractEvent>> {
        let data = self
            .execute(
                &moonproof_indexer_client::events::contract_events_query(),
                json!({ "filter": filter.to_graphql(), "limit": page.limit, "offset": page.offset }),
            )
            .await?;
        data.get("contractEvents")
            .and_then(Value::as_array)
            .ok_or_else(|| {
                ContractRuntimeError::Indexer("response field `contractEvents` missing".to_owned())
            })?
            .iter()
            .map(|e| {
                moonproof_indexer_client::events::parse_contract_event(e)
                    .map_err(|err| ContractRuntimeError::Indexer(err.to_string()))
            })
            .collect()
    }

    async fn contract_events_stream(
        &self,
        filter: &ContractEventFilter,
        after_id: Option<u64>,
    ) -> Result<PublicDataStream<ContractEvent>> {
        let stream = moonproof_indexer_client::events::subscribe_contract_events(
            &self.inner.subscription_http_url,
            filter,
            after_id,
        )
        .await
        .map_err(|e| {
            ContractRuntimeError::Indexer(format!("open contractEvents subscription: {e}"))
        })?;
        Ok(Box::pin(stream.map(|item| {
            item.map_err(|e| {
                ContractRuntimeError::Indexer(format!("contractEvents stream error: {e}"))
            })
        })))
    }

    async fn query_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        let data = self
            .execute(
                CONTRACT_STATE_QUERY,
                json!({
                    "address": contract_address_to_hex(address),
                    "offset": contract_action_offset_variable(at.as_ref()),
                }),
            )
            .await?;
        match data.get("contractAction") {
            None | Some(Value::Null) => Ok(None),
            Some(action) => {
                let state_hex = required_str(action, "state")?;
                Ok(Some(decode_contract_state(&state_hex)?))
            }
        }
    }

    async fn query_zswap_and_contract_state(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<ZSwapAndContractState>> {
        let data = self
            .execute(
                CONTRACT_AND_ZSWAP_STATE_QUERY,
                json!({
                    "address": contract_address_to_hex(address),
                    "offset": block_offset_variable(at.as_ref()),
                }),
            )
            .await?;
        parse_zswap_and_contract_state(&data)
    }

    async fn query_deploy_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<Option<ContractState<InMemoryDB>>> {
        let addr_hex = contract_address_to_hex(address);
        let data = self
            .execute(
                DEPLOY_CONTRACT_STATE_TX_QUERY,
                json!({ "address": addr_hex }),
            )
            .await?;
        match data.get("contractAction") {
            None | Some(Value::Null) => Ok(None),
            Some(action) => parse_deploy_contract_state_action(action, &addr_hex),
        }
    }

    async fn query_unshielded_balances(
        &self,
        address: &ContractAddress,
        at: Option<ContractStateQueryAt>,
    ) -> Result<Option<UnshieldedBalances>> {
        let data = self
            .execute(
                QUERY_UNSHIELDED_BALANCES,
                json!({
                    "address": contract_address_to_hex(address),
                    "offset": contract_action_offset_variable(at.as_ref()),
                }),
            )
            .await?;
        match data.get("contractAction") {
            None | Some(Value::Null) => Ok(None),
            Some(action) => Ok(Some(parse_unshielded_balances_from_action(action)?)),
        }
    }

    async fn watch_for_deploy_tx_data(&self, address: &ContractAddress) -> Result<FinalizedTxData> {
        let addr_hex = contract_address_to_hex(address);
        let variables = json!({ "address": addr_hex });
        let interval = self.poll_interval();
        loop {
            let data = self.execute(DEPLOY_TX_QUERY, variables.clone()).await?;
            if let Some(action) = data.get("contractAction").filter(|v| !v.is_null()) {
                if let Some(tx_json) = deploy_tx_from_action(action) {
                    if is_regular_transaction(tx_json) {
                        return parse_finalized_tx_from_json(tx_json, None);
                    }
                }
            }
            moonproof_utils::rt::sleep(interval).await;
        }
    }

    async fn watch_for_tx_data(&self, tx_id: &TransactionId) -> Result<FinalizedTxData> {
        // The `TransactionOffset` input is `oneOf` — either `hash` or
        // `identifier`. The submission pipeline feeds a chain-level
        // hex **hash** here (that's what
        // [`crate::providers::NodeClientMidnightProvider::submit_tx`]
        // emits), not an indexer-assigned identifier. Query by hash
        // accordingly; the returned transaction's `.identifiers[0]`
        // surfaces the indexer-side identifier for callers that need
        // it (it lands in [`FinalizedTxData::identifiers`]).
        //
        // A leading `0x` on the hash is tolerated by trimming —
        // moonproof's node client returns `0x`-prefixed hashes while
        // the indexer expects un-prefixed hex.
        let hash_hex = tx_id
            .as_str()
            .strip_prefix("0x")
            .unwrap_or_else(|| tx_id.as_str());
        let variables = json!({
            "offset": { "hash": hash_hex },
        });
        let interval = self.poll_interval();
        let max_attempts = (180_000_u128 / interval.as_millis().max(1)).max(1);
        for _ in 0..max_attempts {
            let data = self.execute(TX_ID_QUERY, variables.clone()).await?;
            if let Some(arr) = data.get("transactions").and_then(|v| v.as_array()) {
                if let Some(tx_json) = arr.iter().find(|tx| is_regular_transaction(tx)) {
                    return parse_finalized_tx_from_json(tx_json, Some(tx_id));
                }
            }
            moonproof_utils::rt::sleep(interval).await;
        }
        Err(ContractRuntimeError::Provider {
            provider: "indexer",
            message: format!(
                "timed out after 180s waiting for transaction {hash_hex} to appear on the indexer"
            ),
        })
    }

    async fn watch_for_contract_state(
        &self,
        address: &ContractAddress,
    ) -> Result<ContractState<InMemoryDB>> {
        let addr_hex = contract_address_to_hex(address);
        let interval = self.poll_interval();
        loop {
            let data = self
                .execute(
                    CONTRACT_STATE_QUERY,
                    json!({ "address": addr_hex, "offset": Value::Null }),
                )
                .await?;
            if let Some(action) = data.get("contractAction").filter(|v| !v.is_null()) {
                let state_hex = required_str(action, "state")?;
                return Ok(decode_contract_state(&state_hex)?);
            }
            moonproof_utils::rt::sleep(interval).await;
        }
    }

    async fn watch_for_unshielded_balances(
        &self,
        address: &ContractAddress,
    ) -> Result<UnshieldedBalances> {
        let addr_hex = contract_address_to_hex(address);
        let interval = self.poll_interval();
        loop {
            let data = self
                .execute(
                    QUERY_UNSHIELDED_BALANCES,
                    json!({ "address": addr_hex, "offset": Value::Null }),
                )
                .await?;
            if let Some(action) = data.get("contractAction").filter(|v| !v.is_null()) {
                return parse_unshielded_balances_from_action(action);
            }
            moonproof_utils::rt::sleep(interval).await;
        }
    }

    async fn contract_state_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
        let (offset, skip_first) = self.resolve_stream_offset(address, &start).await?;
        let addr_hex = contract_address_to_hex(address);
        let inner = open_contract_actions_stream(
            self.inner.subscription_http_url.clone(),
            addr_hex,
            offset,
        )
        .await?;
        let mapped = inner
            .map(|tick_res| match tick_res {
                Ok(tick) => decode_contract_state(&tick.state).map_err(Into::into),
                Err(e) => Err(e),
            })
            .skip(usize::from(skip_first));
        Ok(Box::pin(mapped))
    }

    async fn unshielded_balances_stream(
        &self,
        address: &ContractAddress,
        start: ContractStateStreamStart,
    ) -> Result<PublicDataStream<UnshieldedBalances>> {
        let (offset, skip_first) = self.resolve_stream_offset(address, &start).await?;
        let addr_hex = contract_address_to_hex(address);
        let inner = open_contract_actions_stream(
            self.inner.subscription_http_url.clone(),
            addr_hex,
            offset,
        )
        .await?;
        let mapped = inner
            .map(|tick_res| match tick_res {
                Ok(tick) => Ok(tick
                    .unshielded_balances
                    .iter()
                    .map(parse_contract_balance)
                    .collect::<Result<Vec<_>>>()?),
                Err(e) => Err(e),
            })
            .skip(usize::from(skip_first));
        Ok(Box::pin(mapped))
    }
}

impl IndexerPublicDataProvider {
    /// Resolve a [`ContractStateStreamStart`] into the concrete
    /// subscription offset + a "skip first tick" flag.
    ///
    /// The indexer's `contractActions(address, offset)` subscription
    /// begins at `offset` inclusively. The TS reference treats
    /// `inclusive: false` as "skip the first tick" — we apply that via
    /// `StreamExt::skip(1)` in the caller.
    async fn resolve_stream_offset(
        &self,
        address: &ContractAddress,
        start: &ContractStateStreamStart,
    ) -> Result<(Option<BlockOffset>, bool)> {
        match start {
            ContractStateStreamStart::All => Ok((None, false)),
            ContractStateStreamStart::Latest => {
                let height = self.query_latest_block_height(address).await?;
                Ok((height.map(BlockOffset::Height), false))
            }
            ContractStateStreamStart::TxId { tx_id, inclusive } => {
                let height = self.query_tx_block_height(tx_id).await?;
                Ok((height.map(BlockOffset::Height), !inclusive))
            }
            ContractStateStreamStart::BlockHeight { height, inclusive } => Ok((
                Some(BlockOffset::Height(
                    i64::try_from(*height).unwrap_or(i64::MAX),
                )),
                !inclusive,
            )),
            ContractStateStreamStart::BlockHash { hash, inclusive } => Ok((
                Some(BlockOffset::Hash(hash.as_str().to_owned())),
                !inclusive,
            )),
        }
    }

    async fn query_latest_block_height(&self, address: &ContractAddress) -> Result<Option<i64>> {
        const Q: &str = r"
            query LatestContractTxBlockHeightQuery($address: HexEncoded!) {
                contractAction(address: $address) {
                    transaction { block { height } }
                }
            }
        ";
        let data = self
            .execute(Q, json!({ "address": contract_address_to_hex(address) }))
            .await?;
        let Some(action) = data.get("contractAction").filter(|v| !v.is_null()) else {
            return Ok(None);
        };
        let tx = action.get("transaction").ok_or_else(|| {
            ContractRuntimeError::Indexer(
                "contractAction missing `transaction` in latest-height query".into(),
            )
        })?;
        let block = tx.get("block").ok_or_else(|| {
            ContractRuntimeError::Indexer("latest-height query: transaction.block missing".into())
        })?;
        Ok(block.get("height").and_then(serde_json::Value::as_i64))
    }

    async fn query_tx_block_height(&self, tx_id: &TransactionId) -> Result<Option<i64>> {
        const Q: &str = r"
            query TxBlockHeightQuery($offset: TransactionOffset!) {
                transactions(offset: $offset) {
                    block { height }
                }
            }
        ";
        // Matches the hash-based offset convention of
        // [`PublicDataProvider::watch_for_tx_data`] above — the runtime
        // tracks transactions by hash end-to-end.
        let hash_hex = tx_id
            .as_str()
            .strip_prefix("0x")
            .unwrap_or_else(|| tx_id.as_str());
        let data = self
            .execute(Q, json!({ "offset": { "hash": hash_hex } }))
            .await?;
        Ok(data
            .get("transactions")
            .and_then(|v| v.as_array())
            .and_then(|arr| arr.first())
            .and_then(|tx| tx.get("block"))
            .and_then(|b| b.get("height"))
            .and_then(serde_json::Value::as_i64))
    }
}

// =====================================================================
// Stream helpers
// =====================================================================

/// Open a `contractActions` subscription and map subscription-level
/// errors into [`ContractRuntimeError::Indexer`].
async fn open_contract_actions_stream(
    http_url: String,
    address_hex: String,
    offset: Option<BlockOffset>,
) -> Result<PublicDataStream<ContractActionTickRaw>> {
    let sub = subscribe_contract_actions(&http_url, &address_hex, offset)
        .await
        .map_err(|e| {
            ContractRuntimeError::Indexer(format!("open contractActions subscription: {e}"))
        })?;
    let mapped = sub.map(|item| match item {
        Ok(tick) => Ok(tick),
        Err(e) => Err(ContractRuntimeError::Indexer(format!(
            "contractActions stream error: {e}"
        ))),
    });
    Ok(Box::pin(mapped))
}

// =====================================================================
// Pure parsing helpers — unit-tested with hand-crafted JSON.
// =====================================================================

fn contract_action_offset_variable(at: Option<&ContractStateQueryAt>) -> Value {
    match at {
        None => Value::Null,
        Some(ContractStateQueryAt::BlockHeight(h)) => {
            let height_i64 = i64::try_from(*h).unwrap_or(i64::MAX);
            json!({ "blockOffset": { "height": height_i64 } })
        }
        Some(ContractStateQueryAt::BlockHash(h)) => {
            json!({ "blockOffset": { "hash": h.as_str() } })
        }
    }
}

fn block_offset_variable(at: Option<&ContractStateQueryAt>) -> Value {
    match at {
        None => Value::Null,
        Some(ContractStateQueryAt::BlockHeight(h)) => {
            json!({ "height": i64::try_from(*h).unwrap_or(i64::MAX) })
        }
        Some(ContractStateQueryAt::BlockHash(h)) => json!({ "hash": h.as_str() }),
    }
}

fn parse_block_info(block: &Value) -> Result<BlockInfo> {
    let height = u64::try_from(required_i64(block, "height")?)
        .map_err(|_| ContractRuntimeError::Indexer("block height is negative".to_owned()))?;
    let protocol_version = u32::try_from(required_i64(block, "protocolVersion")?)
        .map_err(|_| ContractRuntimeError::Indexer("protocolVersion out of range".to_owned()))?;
    Ok(BlockInfo {
        hash: required_str(block, "hash")?,
        height,
        protocol_version,
    })
}

fn required_str(obj: &Value, field: &str) -> Result<String> {
    obj.get(field)
        .and_then(|v| v.as_str())
        .map(ToOwned::to_owned)
        .ok_or_else(|| {
            ContractRuntimeError::Indexer(format!(
                "response field `{field}` missing or not a string"
            ))
        })
}

fn required_i64(obj: &Value, field: &str) -> Result<i64> {
    obj.get(field)
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| {
            ContractRuntimeError::Indexer(format!("response field `{field}` missing or not Int"))
        })
}

/// `None` when the contract does not exist at the queried block, which
/// the indexer reports as a null `contract` and a null
/// `contractZswapState`.
fn parse_zswap_and_contract_state(data: &Value) -> Result<Option<ZSwapAndContractState>> {
    let contract = match data.get("contract") {
        None | Some(Value::Null) => return Ok(None),
        Some(c) => c,
    };
    let block = match data.get("block") {
        None | Some(Value::Null) => {
            return Err(ContractRuntimeError::Indexer(
                "response field `block` missing for an existing contract".to_owned(),
            ));
        }
        Some(b) => b,
    };
    let Some(zswap_hex) = block.get("contractZswapState").and_then(Value::as_str) else {
        return Ok(None);
    };
    let contract_state = decode_contract_state(&required_str(contract, "state")?)?;
    Ok(Some(ZSwapAndContractState {
        zswap_chain_state_bytes: hex::decode(zswap_hex)?,
        contract_state,
        ledger_parameters_bytes: hex::decode(required_str(block, "ledgerParameters")?)?,
    }))
}

fn parse_deploy_contract_state_action(
    action: &Value,
    wanted_address_hex: &str,
) -> Result<Option<ContractState<InMemoryDB>>> {
    let typename = action
        .get("__typename")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    match typename {
        "ContractDeploy" | "ContractUpdate" => {
            let state_hex = required_str(action, "state")?;
            Ok(Some(decode_contract_state(&state_hex)?))
        }
        "ContractCall" => {
            // Walk action.deploy.transaction.contractActions to find
            // the entry whose address matches the one we asked about,
            // then decode its `state`.
            let deploy = action.get("deploy").ok_or_else(|| {
                ContractRuntimeError::Indexer("ContractCall missing `deploy` field".into())
            })?;
            let tx = deploy.get("transaction").ok_or_else(|| {
                ContractRuntimeError::Indexer("ContractCall.deploy missing `transaction`".into())
            })?;
            let Some(actions) = tx.get("contractActions").and_then(|v| v.as_array()) else {
                return Ok(None);
            };
            for a in actions {
                let addr = a.get("address").and_then(|v| v.as_str()).unwrap_or("");
                if addr == wanted_address_hex {
                    let state_hex = required_str(a, "state")?;
                    return Ok(Some(decode_contract_state(&state_hex)?));
                }
            }
            Ok(None)
        }
        other => Err(ContractRuntimeError::Indexer(format!(
            "unexpected contractAction __typename `{other}` in deploy-state query"
        ))),
    }
}

fn parse_unshielded_balances_from_action(action: &Value) -> Result<UnshieldedBalances> {
    // ContractDeploy / ContractCall / ContractUpdate all expose
    // `unshieldedBalances: [ContractBalance!]!` directly. Some TS
    // branches fall through to `deploy.unshieldedBalances` — our query
    // shape is simpler: we always ask for the direct field on all
    // three variants, so the JSON has it at the top of the inline
    // fragment.
    let Some(arr) = action.get("unshieldedBalances").and_then(|v| v.as_array()) else {
        return Ok(Vec::new());
    };
    let mut out = Vec::with_capacity(arr.len());
    for entry in arr {
        let balance = parse_contract_balance_json(entry)?;
        out.push(balance);
    }
    Ok(out)
}

fn parse_contract_balance(
    balance: &moonproof_indexer_client::ContractBalance,
) -> Result<UnshieldedBalance> {
    let balance_u128 = balance.amount.parse::<u128>().map_err(|e| {
        ContractRuntimeError::Indexer(format!(
            "ContractBalance.amount `{}` not a valid u128: {e}",
            balance.amount
        ))
    })?;
    let token_bytes = hex::decode(&balance.token_type)?;
    if token_bytes.len() != 32 {
        return Err(ContractRuntimeError::Indexer(format!(
            "ContractBalance.tokenType expected 32 bytes, got {}",
            token_bytes.len()
        )));
    }
    let mut token_type = [0u8; 32];
    token_type.copy_from_slice(&token_bytes);
    Ok(UnshieldedBalance {
        balance: balance_u128,
        token_type,
    })
}

fn parse_contract_balance_json(entry: &Value) -> Result<UnshieldedBalance> {
    let amount = required_str(entry, "amount")?;
    let token_type = required_str(entry, "tokenType")?;
    let balance_u128 = amount.parse::<u128>().map_err(|e| {
        ContractRuntimeError::Indexer(format!(
            "ContractBalance.amount `{amount}` not a valid u128: {e}"
        ))
    })?;
    let token_bytes = hex::decode(&token_type)?;
    if token_bytes.len() != 32 {
        return Err(ContractRuntimeError::Indexer(format!(
            "ContractBalance.tokenType expected 32 bytes, got {}",
            token_bytes.len()
        )));
    }
    let mut token_type_bytes = [0u8; 32];
    token_type_bytes.copy_from_slice(&token_bytes);
    Ok(UnshieldedBalance {
        balance: balance_u128,
        token_type: token_type_bytes,
    })
}

/// Returns `true` iff the tx JSON has `__typename == "RegularTransaction"`
/// (or carries the `identifiers` array, which only `RegularTransaction`
/// exposes — matches TS `isRegularTransaction`).
fn is_regular_transaction(tx: &Value) -> bool {
    if tx
        .get("__typename")
        .and_then(|v| v.as_str())
        .is_some_and(|t| t == "RegularTransaction")
    {
        return true;
    }
    tx.get("identifiers").and_then(|v| v.as_array()).is_some()
        && tx.get("hash").and_then(|v| v.as_str()).is_some()
}

/// Walk a `contractAction` JSON and return the transaction-level
/// payload the TS `watchForDeployTxData` code treats as the deploy tx.
/// - `ContractDeploy`/`ContractUpdate` → `action.transaction`
/// - `ContractCall` → `action.deploy.transaction`
fn deploy_tx_from_action(action: &Value) -> Option<&Value> {
    let typename = action.get("__typename").and_then(|v| v.as_str())?;
    match typename {
        "ContractDeploy" | "ContractUpdate" => action.get("transaction"),
        "ContractCall" => action.get("deploy").and_then(|d| d.get("transaction")),
        _ => None,
    }
}

fn decode_tx_status(s: &str) -> Result<TxStatus> {
    match s {
        "SUCCESS" => Ok(TxStatus::SucceedEntirely),
        "PARTIAL_SUCCESS" => Ok(TxStatus::FailFallible),
        "FAILURE" => Ok(TxStatus::FailEntirely),
        other => Err(ContractRuntimeError::Indexer(format!(
            "unexpected TransactionResult.status `{other}`"
        ))),
    }
}

fn parse_segment_status_map(
    result: &Value,
) -> Result<Option<std::collections::BTreeMap<u16, SegmentStatus>>> {
    let status = result.get("status").and_then(|v| v.as_str()).unwrap_or("");
    if status != "PARTIAL_SUCCESS" {
        return Ok(None);
    }
    let Some(arr) = result.get("segments").and_then(|v| v.as_array()) else {
        return Ok(None);
    };
    let mut map = std::collections::BTreeMap::new();
    for seg in arr {
        let id_i64 = required_i64(seg, "id")?;
        let id = u16::try_from(id_i64).map_err(|_| {
            ContractRuntimeError::Indexer(format!("segment id `{id_i64}` out of u16 range"))
        })?;
        let success = seg
            .get("success")
            .and_then(serde_json::Value::as_bool)
            .ok_or_else(|| {
                ContractRuntimeError::Indexer("segment missing `success` bool".into())
            })?;
        map.insert(
            id,
            if success {
                SegmentStatus::Success
            } else {
                SegmentStatus::Fail
            },
        );
    }
    Ok(Some(map))
}

fn parse_unshielded_utxo(v: &Value) -> Result<UnshieldedUtxo> {
    let owner_hex = required_str(v, "owner")?;
    let intent_hash_hex = required_str(v, "intentHash")?;
    let token_type_hex = required_str(v, "tokenType")?;
    let value_str = required_str(v, "value")?;
    // The schema types `owner` as a Bech32m `UnshieldedAddress`, which is
    // what the indexer serves; a bare hex owner is still read as hex.
    let owner_bytes = match moonproof_wallet::address::UnshieldedAddress::parse(&owner_hex) {
        Ok(address) => address.0.to_vec(),
        Err(_) => hex::decode(&owner_hex)?,
    };
    if owner_bytes.len() != 32 {
        return Err(ContractRuntimeError::Indexer(format!(
            "UnshieldedUtxo.owner expected 32 bytes, got {}",
            owner_bytes.len()
        )));
    }
    let intent_bytes = hex::decode(&intent_hash_hex)?;
    if intent_bytes.len() != 32 {
        return Err(ContractRuntimeError::Indexer(format!(
            "UnshieldedUtxo.intentHash expected 32 bytes, got {}",
            intent_bytes.len()
        )));
    }
    let token_bytes = hex::decode(&token_type_hex)?;
    if token_bytes.len() != 32 {
        return Err(ContractRuntimeError::Indexer(format!(
            "UnshieldedUtxo.tokenType expected 32 bytes, got {}",
            token_bytes.len()
        )));
    }
    let value_u128 = value_str.parse::<u128>().map_err(|e| {
        ContractRuntimeError::Indexer(format!(
            "UnshieldedUtxo.value `{value_str}` not a valid u128: {e}"
        ))
    })?;
    let mut owner = [0u8; 32];
    owner.copy_from_slice(&owner_bytes);
    let mut intent_hash = [0u8; 32];
    intent_hash.copy_from_slice(&intent_bytes);
    let mut token_type = [0u8; 32];
    token_type.copy_from_slice(&token_bytes);
    // Wrap the raw 32 bytes into a ContractAddress — the TS SDK
    // treats owner bytes as a UInt256 identity regardless of address
    // kind, so we use the ContractAddress newtype as a uniform
    // 32-byte carrier. Callers that need the typed unshielded-address
    // form convert via their own boundary.
    let owner = ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(owner));
    Ok(UnshieldedUtxo {
        owner,
        intent_hash,
        token_type,
        value: value_u128,
    })
}

/// Parse a `RegularTransaction`-shaped JSON blob into
/// [`FinalizedTxData`]. The optional `tx_id_override` is used by
/// [`PublicDataProvider::watch_for_tx_data`] to preserve the original
/// identifier the caller asked about (matches TS `txId: TransactionId`
/// parameter threading).
fn parse_finalized_tx_from_json(
    tx: &Value,
    tx_id_override: Option<&TransactionId>,
) -> Result<FinalizedTxData> {
    let hash = required_str(tx, "hash")?;
    let raw_hex = required_str(tx, "raw")?;
    let indexer_id = required_i64(tx, "id")?;
    let protocol_version_i64 = required_i64(tx, "protocolVersion")?;
    let block = tx
        .get("block")
        .ok_or_else(|| ContractRuntimeError::Indexer("transaction missing `block`".into()))?;
    let block_hash = required_str(block, "hash")?;
    let block_height_i64 = required_i64(block, "height")?;
    let block_ts_ms = required_i64(block, "timestamp")?;
    let block_author = block
        .get("author")
        .and_then(|v| v.as_str())
        .map(ToOwned::to_owned);

    let identifiers_raw = tx
        .get("identifiers")
        .and_then(|v| v.as_array())
        .ok_or_else(|| {
            ContractRuntimeError::Indexer("RegularTransaction missing `identifiers`".into())
        })?;
    let identifiers: Vec<TransactionId> = identifiers_raw
        .iter()
        .filter_map(|v| v.as_str())
        .map(|s| TransactionId::new(s.to_owned()))
        .collect();

    // TS uses `identifiers[contractActions.findIndex(addr == ...)]`
    // but this helper is called AFTER find_deployed_contract already
    // knows which address / tx it's looking for. We keep the chosen
    // tx_id_override for watch_for_tx_data (where the caller gave us
    // an id explicitly) and fall back to the first identifier
    // otherwise — matches TS watchForDeployTxData's behaviour for the
    // non-ContractCall cases, which use the tx's primary identifier.
    let tx_id = match tx_id_override {
        Some(id) => id.clone(),
        None => identifiers
            .first()
            .cloned()
            .unwrap_or_else(|| TransactionId::new(hash.clone())),
    };

    let fees_obj = tx
        .get("fees")
        .ok_or_else(|| ContractRuntimeError::Indexer("RegularTransaction missing `fees`".into()))?;
    let fees = Fees {
        paid_fees: required_str(fees_obj, "paidFees")?,
        estimated_fees: required_str(fees_obj, "estimatedFees")?,
    };
    let result_obj = tx.get("transactionResult").ok_or_else(|| {
        ContractRuntimeError::Indexer("RegularTransaction missing `transactionResult`".into())
    })?;
    let status_str = required_str(result_obj, "status")?;
    let status = decode_tx_status(&status_str)?;
    let segment_status_map = parse_segment_status_map(result_obj)?;

    let created = tx
        .get("unshieldedCreatedOutputs")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .map(parse_unshielded_utxo)
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?
        .unwrap_or_default();
    let spent = tx
        .get("unshieldedSpentOutputs")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .map(parse_unshielded_utxo)
                .collect::<Result<Vec<_>>>()
        })
        .transpose()?
        .unwrap_or_default();
    let unshielded = UnshieldedUtxos { created, spent };

    let tx_bytes = hex::decode(&raw_hex)?;

    let block_height = u64::try_from(block_height_i64).unwrap_or(0);
    let protocol_version = u64::try_from(protocol_version_i64).unwrap_or(0);

    Ok(FinalizedTxData {
        tx_id,
        identifiers,
        tx_hash: TransactionHash::new(hash),
        block_hash: MoonBlockHash::new(block_hash),
        block_height,
        block_timestamp_ms: block_ts_ms,
        block_author,
        indexer_id,
        protocol_version: moonproof_wallet::ProtocolVersion(protocol_version),
        status,
        segment_status_map,
        fees,
        unshielded,
        tx_bytes,
    })
}

// =====================================================================
// Unit tests — pure parsing paths.
// =====================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use moonproof_ledger::base_crypto::hash::{HashOutput, PERSISTENT_HASH_BYTES};
    use moonproof_ledger::onchain_runtime::state::{
        ContractMaintenanceAuthority, ContractState, EntryPointBuf, StateValue,
    };
    use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
    use moonproof_runtime::state::{contract_address_to_hex, encode_contract_state};

    fn dummy_address(byte: u8) -> ContractAddress {
        ContractAddress(HashOutput([byte; PERSISTENT_HASH_BYTES]))
    }

    fn dummy_contract_state_hex() -> String {
        let op_key: EntryPointBuf = b"noop"[..].into();
        let s = ContractState::<InMemoryDB>::new(
            StateValue::Null,
            StorageHashMap::new().insert(op_key, moonproof_ledger::contract_operation(None)),
            ContractMaintenanceAuthority::default(),
        );
        encode_contract_state(&s).unwrap()
    }

    fn zero_hex_32() -> String {
        "00".repeat(32)
    }

    // --- offset variable encoding ----------------------------------

    #[test]
    fn offset_variable_none() {
        assert_eq!(contract_action_offset_variable(None), Value::Null);
    }

    #[test]
    fn offset_variable_block_height() {
        let at = ContractStateQueryAt::BlockHeight(42);
        let v = contract_action_offset_variable(Some(&at));
        assert_eq!(v, json!({ "blockOffset": { "height": 42 } }));
    }

    #[test]
    fn offset_variable_block_hash() {
        let at = ContractStateQueryAt::BlockHash(MoonBlockHash::new("0xabc"));
        let v = contract_action_offset_variable(Some(&at));
        assert_eq!(v, json!({ "blockOffset": { "hash": "0xabc" } }));
    }

    // --- contract state parsing -----------------------------------

    #[test]
    fn parse_contract_state_from_full_action_json() {
        let state_hex = dummy_contract_state_hex();
        let action = json!({ "state": state_hex });
        let parsed = required_str(&action, "state").unwrap();
        let decoded = decode_contract_state(&parsed).unwrap();
        // Sanity: re-encodes to same hex.
        assert_eq!(encode_contract_state(&decoded).unwrap(), state_hex);
    }

    // --- zswap + contract state + ledger params -------------------

    #[test]
    fn parse_zswap_and_contract_state_reads_one_block() {
        let data = json!({
            "block": { "ledgerParameters": "ccdd", "contractZswapState": "aabb" },
            "contract": { "state": dummy_contract_state_hex() },
        });
        let out = parse_zswap_and_contract_state(&data).unwrap().unwrap();
        assert_eq!(out.zswap_chain_state_bytes, vec![0xaa, 0xbb]);
        assert_eq!(out.ledger_parameters_bytes, vec![0xcc, 0xdd]);
    }

    #[test]
    fn parse_zswap_and_contract_state_missing_ledger_parameters_is_an_error() {
        let data = json!({
            "block": { "contractZswapState": "01" },
            "contract": { "state": dummy_contract_state_hex() },
        });
        assert!(parse_zswap_and_contract_state(&data).is_err());
    }

    #[test]
    fn parse_zswap_and_contract_state_absent_contract_is_none() {
        let data = json!({
            "block": { "ledgerParameters": "ccdd", "contractZswapState": null },
            "contract": null,
        });
        assert!(parse_zswap_and_contract_state(&data).unwrap().is_none());
    }

    // --- deploy-contract-state action parsing ----------------------

    #[test]
    fn parse_deploy_contract_state_for_contract_deploy() {
        let state_hex = dummy_contract_state_hex();
        let action = json!({
            "__typename": "ContractDeploy",
            "state": state_hex,
        });
        let out = parse_deploy_contract_state_action(&action, "ignored").unwrap();
        assert!(out.is_some());
    }

    #[test]
    fn parse_deploy_contract_state_for_contract_update() {
        let state_hex = dummy_contract_state_hex();
        let action = json!({
            "__typename": "ContractUpdate",
            "state": state_hex,
        });
        let out = parse_deploy_contract_state_action(&action, "ignored").unwrap();
        assert!(out.is_some());
    }

    #[test]
    fn parse_deploy_contract_state_for_contract_call_walks_linked_deploy() {
        let state_hex = dummy_contract_state_hex();
        let addr_hex = contract_address_to_hex(&dummy_address(0xab));
        let action = json!({
            "__typename": "ContractCall",
            "deploy": {
                "transaction": {
                    "contractActions": [
                        { "address": addr_hex, "state": state_hex },
                        // Irrelevant sibling action for a different contract.
                        { "address": "ee".repeat(32), "state": "00" },
                    ]
                }
            }
        });
        let out = parse_deploy_contract_state_action(&action, &addr_hex).unwrap();
        assert!(out.is_some());
    }

    #[test]
    fn parse_deploy_contract_state_for_contract_call_returns_none_when_address_absent() {
        let action = json!({
            "__typename": "ContractCall",
            "deploy": { "transaction": { "contractActions": [] } }
        });
        let out = parse_deploy_contract_state_action(
            &action,
            &contract_address_to_hex(&dummy_address(0xcd)),
        )
        .unwrap();
        assert!(out.is_none());
    }

    #[test]
    fn parse_deploy_contract_state_unknown_typename_is_error() {
        let action = json!({ "__typename": "Mystery" });
        let err = parse_deploy_contract_state_action(&action, "x").unwrap_err();
        matches!(err, ContractRuntimeError::Indexer(_));
    }

    // --- unshielded balances ---------------------------------------

    #[test]
    fn parse_unshielded_balances_happy_path() {
        let action = json!({
            "__typename": "ContractDeploy",
            "unshieldedBalances": [
                { "tokenType": zero_hex_32(), "amount": "12345" }
            ]
        });
        let balances = parse_unshielded_balances_from_action(&action).unwrap();
        assert_eq!(balances.len(), 1);
        assert_eq!(balances[0].balance, 12345);
        assert_eq!(balances[0].token_type, [0u8; 32]);
    }

    #[test]
    fn parse_unshielded_balances_missing_field_yields_empty() {
        let action = json!({ "__typename": "ContractDeploy" });
        let balances = parse_unshielded_balances_from_action(&action).unwrap();
        assert_eq!(balances, [] as [UnshieldedBalance; 0]);
    }

    #[test]
    fn parse_unshielded_balances_rejects_non_32_byte_token() {
        let action = json!({
            "__typename": "ContractDeploy",
            "unshieldedBalances": [
                { "tokenType": "aabb", "amount": "1" }
            ]
        });
        let err = parse_unshielded_balances_from_action(&action).unwrap_err();
        matches!(err, ContractRuntimeError::Indexer(_));
    }

    // --- tx status mapping -----------------------------------------

    #[test]
    fn decode_tx_status_handles_all_values() {
        assert_eq!(
            decode_tx_status("SUCCESS").unwrap(),
            TxStatus::SucceedEntirely
        );
        assert_eq!(
            decode_tx_status("PARTIAL_SUCCESS").unwrap(),
            TxStatus::FailFallible
        );
        assert_eq!(decode_tx_status("FAILURE").unwrap(), TxStatus::FailEntirely);
        assert!(decode_tx_status("nonsense").is_err());
    }

    #[test]
    fn parse_segment_status_map_ignores_non_partial_success() {
        let result = json!({ "status": "SUCCESS", "segments": [] });
        let out = parse_segment_status_map(&result).unwrap();
        assert!(out.is_none());
    }

    #[test]
    fn parse_segment_status_map_builds_map_for_partial_success() {
        let result = json!({
            "status": "PARTIAL_SUCCESS",
            "segments": [
                { "id": 1, "success": true },
                { "id": 2, "success": false },
            ]
        });
        let out = parse_segment_status_map(&result).unwrap().unwrap();
        assert_eq!(out.len(), 2);
        assert_eq!(out.get(&1), Some(&SegmentStatus::Success));
        assert_eq!(out.get(&2), Some(&SegmentStatus::Fail));
    }

    // --- UnshieldedUtxo parsing ------------------------------------

    #[test]
    fn parse_unshielded_utxo_accepts_well_formed_json() {
        let utxo = json!({
            "owner": zero_hex_32(),
            "intentHash": zero_hex_32(),
            "tokenType": zero_hex_32(),
            "value": "999",
        });
        let parsed = parse_unshielded_utxo(&utxo).unwrap();
        assert_eq!(parsed.value, 999);
    }

    /// The indexer serves `owner` as the Bech32m `UnshieldedAddress` its
    /// schema declares.
    #[test]
    fn parse_unshielded_utxo_reads_a_bech32m_owner() {
        let owner = moonproof_wallet::address::UnshieldedAddress([0x7E; 32]);
        let encoded = owner
            .encode(&moonproof_wallet::abstractions::NetworkId::Undeployed)
            .unwrap()
            .to_string()
            .unwrap();
        let utxo = json!({
            "owner": encoded,
            "intentHash": zero_hex_32(),
            "tokenType": zero_hex_32(),
            "value": "5",
        });
        let parsed = parse_unshielded_utxo(&utxo).unwrap();
        assert_eq!(parsed.owner.0 .0, [0x7E; 32]);
    }

    #[test]
    fn parse_unshielded_utxo_rejects_short_owner() {
        let utxo = json!({
            "owner": "aa",
            "intentHash": zero_hex_32(),
            "tokenType": zero_hex_32(),
            "value": "1",
        });
        let err = parse_unshielded_utxo(&utxo).unwrap_err();
        matches!(err, ContractRuntimeError::Indexer(_));
    }

    // --- RegularTransaction → FinalizedTxData ---------------------

    fn sample_regular_tx_json() -> Value {
        json!({
            "__typename": "RegularTransaction",
            "id": 42,
            "protocolVersion": 8,
            "raw": "ff",
            "hash": "0xbeef",
            "identifiers": ["0xidfirst", "0xidsecond"],
            "block": {
                "hash": "0xblock",
                "height": 17,
                "timestamp": 1_700_000_000_000_i64,
                "author": "alice",
            },
            "fees": { "paidFees": "1000", "estimatedFees": "900" },
            "transactionResult": {
                "status": "SUCCESS",
                "segments": [],
            },
            "unshieldedCreatedOutputs": [],
            "unshieldedSpentOutputs": [],
        })
    }

    #[test]
    fn parse_finalized_tx_from_json_succeeds_on_happy_path() {
        let tx = sample_regular_tx_json();
        let out = parse_finalized_tx_from_json(&tx, None).unwrap();
        assert_eq!(out.status, TxStatus::SucceedEntirely);
        assert_eq!(out.block_height, 17);
        assert_eq!(out.fees.paid_fees, "1000");
        assert_eq!(out.identifiers.len(), 2);
        assert_eq!(out.tx_id.as_str(), "0xidfirst");
        assert_eq!(out.tx_hash.as_str(), "0xbeef");
        assert_eq!(out.tx_bytes, vec![0xff]);
    }

    #[test]
    fn parse_finalized_tx_from_json_respects_tx_id_override() {
        let tx = sample_regular_tx_json();
        let override_id = TransactionId::new("0xchosen");
        let out = parse_finalized_tx_from_json(&tx, Some(&override_id)).unwrap();
        assert_eq!(out.tx_id.as_str(), "0xchosen");
        // Identifiers remain the indexer-reported list, regardless of override.
        assert_eq!(out.identifiers[0].as_str(), "0xidfirst");
    }

    #[test]
    fn parse_finalized_tx_from_json_rejects_missing_fees() {
        let mut tx = sample_regular_tx_json();
        tx.as_object_mut().unwrap().remove("fees");
        let err = parse_finalized_tx_from_json(&tx, None).unwrap_err();
        matches!(err, ContractRuntimeError::Indexer(_));
    }

    #[test]
    fn deploy_tx_from_action_extracts_transaction_for_deploy() {
        let action = json!({
            "__typename": "ContractDeploy",
            "transaction": { "id": 7 },
        });
        let out = deploy_tx_from_action(&action).unwrap();
        assert_eq!(out.get("id").unwrap().as_i64().unwrap(), 7);
    }

    #[test]
    fn deploy_tx_from_action_extracts_transaction_for_update() {
        let action = json!({
            "__typename": "ContractUpdate",
            "transaction": { "id": 8 },
        });
        let out = deploy_tx_from_action(&action).unwrap();
        assert_eq!(out.get("id").unwrap().as_i64().unwrap(), 8);
    }

    #[test]
    fn deploy_tx_from_action_walks_into_deploy_for_contract_call() {
        let action = json!({
            "__typename": "ContractCall",
            "deploy": { "transaction": { "id": 9 } },
        });
        let out = deploy_tx_from_action(&action).unwrap();
        assert_eq!(out.get("id").unwrap().as_i64().unwrap(), 9);
    }

    #[test]
    fn deploy_tx_from_action_returns_none_for_unknown_typename() {
        let action = json!({ "__typename": "Unknown" });
        assert!(deploy_tx_from_action(&action).is_none());
    }

    #[test]
    fn is_regular_transaction_detects_typename() {
        let tx = json!({ "__typename": "RegularTransaction" });
        assert!(is_regular_transaction(&tx));
    }

    #[test]
    fn is_regular_transaction_detects_identifier_shape() {
        let tx = json!({ "identifiers": ["a"], "hash": "h" });
        assert!(is_regular_transaction(&tx));
    }

    #[test]
    fn is_regular_transaction_rejects_system_transaction() {
        let tx = json!({ "__typename": "SystemTransaction" });
        assert!(!is_regular_transaction(&tx));
    }

    // --- constructor + URL shape -----------------------------------

    #[test]
    fn constructor_appends_default_graphql_path() {
        let p = IndexerPublicDataProvider::new("http://127.0.0.1:8088").unwrap();
        assert!(p.inner.graphql_url.ends_with("/api/v4/graphql"));
    }

    #[test]
    fn constructor_respects_explicit_graphql_url() {
        let p = IndexerPublicDataProvider::new("http://host/api/v4/graphql").unwrap();
        assert_eq!(p.inner.graphql_url, "http://host/api/v4/graphql");
    }

    #[test]
    fn constructor_rejects_invalid_url() {
        let err = IndexerPublicDataProvider::new("not a url").unwrap_err();
        matches!(err, ContractRuntimeError::Provider { .. });
    }

    #[test]
    fn with_poll_interval_updates_interval() {
        let p = IndexerPublicDataProvider::new("http://localhost:8088/api/v4/graphql")
            .unwrap()
            .with_poll_interval(Duration::from_millis(250));
        assert_eq!(p.inner.poll_interval_ms, 250);
    }
}