moonproof-indexer-client 0.2.2

Rust client for the Midnight indexer's GraphQL API
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
//! Domain types mirroring the indexer GraphQL schema.
//!
//! These are the shapes consumers hold — deliberately distinct from the codegen'd
//! `graphql_client` response types so the public API stays stable across schema revisions.
//!
//! Numeric schema fields declared as `Int` use `i64` (`graphql_client`'s default for
//! GraphQL `Int`). String-amount fields (NIGHT/DUST balances, stake lovelace) stay as
//! `String` to preserve precision — these can exceed the i64 range on mainnet scales.

use serde::{Deserialize, Serialize};

// --- Blocks ----------------------------------------------------------------

/// A block offset — either a block hash (hex) or a block height.
///
/// Matches the `BlockOffset` input union in the indexer schema. At most one
/// variant should be populated per request.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum BlockOffset {
    Hash(String),
    Height(i64),
}

/// A minimal reference to a block (hash + height only).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct BlockRef {
    pub hash: String,
    pub height: i64,
}

/// Full block metadata as returned by the indexer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct Block {
    pub hash: String,
    pub height: i64,
    pub protocol_version: i64,
    pub timestamp: i64,
    pub author: Option<String>,
    pub ledger_parameters: String,
    /// The dust commitment tree's root after this block, in the ledger's
    /// untagged serialization, hex-encoded. Absent when the indexer does
    /// not report it.
    pub dust_commitment_merkle_tree_root: Option<String>,
    /// The dust generation tree's root after this block, encoded like
    /// [`Self::dust_commitment_merkle_tree_root`].
    pub dust_generation_merkle_tree_root: Option<String>,
    pub parent: Option<BlockRef>,
}

// --- Contract actions ------------------------------------------------------

/// Which concrete variant of `ContractAction` this is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum ContractActionKind {
    Deploy,
    Call,
    Update,
}

/// A contract balance entry (unshielded token).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ContractBalance {
    pub token_type: String,
    pub amount: String,
}

/// A contract action (deploy, call, or update) at a specific chain position.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ContractAction {
    pub kind: ContractActionKind,
    pub address: String,
    pub state: String,
    pub zswap_state: String,
    pub transaction_hash: String,
    pub unshielded_balances: Vec<ContractBalance>,
    /// Populated only when `kind == Call`.
    pub entry_point: Option<String>,
}

/// Offset locating a specific contract action — by block or by transaction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum ContractActionOffset {
    Block(BlockOffset),
    Transaction(TransactionOffset),
}

// --- Transactions ----------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum TransactionOffset {
    Hash(String),
    Identifier(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum TransactionKind {
    Regular,
    System,
    /// A `ClaimRewards` transaction whose `ClaimKind` is `CardanoBridge`.
    BridgeClaim,
}

/// Fields exclusive to `RegularTransaction`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct RegularTransactionData {
    pub fee: String,
    pub zswap_merkle_tree_root: String,
    pub zswap_start_index: i64,
    pub zswap_end_index: i64,
    pub identifiers: Vec<String>,
    pub transaction_result: TransactionResult,
}

/// What applying a regular transaction did to the ledger.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct TransactionResult {
    pub status: TransactionResultStatus,
    /// Each segment the ledger reported, with whether it applied. The
    /// indexer lists them only for a partial success; empty otherwise.
    pub segments: Vec<TransactionSegment>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum TransactionResultStatus {
    Success,
    PartialSuccess,
    Failure,
}

/// One segment of a [`TransactionResult`]. Segment 0 is the guaranteed
/// segment; every other id is a fallible one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct TransactionSegment {
    pub id: u16,
    pub success: bool,
}

/// Fields exclusive to `BridgeClaimTransaction`. `amount` is a
/// 16-byte big-endian u128.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct BridgeClaimTransactionData {
    pub recipient: String,
    pub amount: String,
}

/// One element of `Transaction.dustLedgerEvents`. The `raw` field is a
/// hex-encoded, tagged-serialized `moonproof_ledger::ledger::events::Event<InMemoryDB>` —
/// downstream wallet code (the dust sub-wallet) can deserialize it via
/// `tagged_deserialize` and replay into a `DustLocalState`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustLedgerEventRaw {
    /// GraphQL `__typename` — one of `DustInitialUtxo`,
    /// `DustSpendProcessed`, `DustGenerationDtimeUpdate`. We propagate it
    /// for diagnostics; the deserialized event carries the same info.
    pub kind: String,
    /// Per-source-stream sequence id; used for resumable subscription.
    pub id: i64,
    /// Hex-encoded `moonproof_ledger::ledger::events::Event<InMemoryDB>`.
    pub raw: String,
    /// The maximum event id seen by the indexer at the time of this query.
    pub max_id: i64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
    pub kind: TransactionKind,
    pub id: i64,
    pub hash: String,
    pub protocol_version: i64,
    pub raw: String,
    pub block: BlockRef,
    pub regular: Option<RegularTransactionData>,
    pub bridge_claim: Option<BridgeClaimTransactionData>,
    pub dust_ledger_events: Vec<DustLedgerEventRaw>,
}

// --- Unshielded transactions subscription ---------------------------------

/// One unshielded UTXO as returned by the `unshieldedTransactions`
/// subscription — the indexer's own view of a transparent UTXO.
///
/// Fields mirror the GraphQL `UnshieldedUtxo` type verbatim:
/// - `owner`: Bech32m-encoded unshielded address
/// - `token_type`: hex-encoded serialized ledger token type (32 bytes; the
///   all-zero hash is `NIGHT`)
/// - `value`: u128 quantity, sent as a string by the indexer to avoid
///   JS precision loss — parse via `u128::from_str`
/// - `intent_hash`: 32-byte intent hash (hex)
/// - `output_index`: 0-based index within the producing offer
/// - `ctime`: creation time in seconds since the UNIX epoch (optional on
///   UTXOs that haven't yet been stamped — genesis `ClaimRewards` outputs
///   get a ctime once the block applies)
/// - `initial_nonce`: hex-encoded nonce used for DUST generation tracking
/// - `registered_for_dust_generation`: whether this UTXO is currently
///   registered as a dust-generating input
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct UnshieldedUtxoRaw {
    pub owner: String,
    pub token_type: String,
    pub value: String,
    pub intent_hash: String,
    pub output_index: i64,
    pub ctime: Option<i64>,
    pub initial_nonce: String,
    pub registered_for_dust_generation: bool,
}

/// One tick of the `unshieldedTransactions` subscription. The union
/// resolves to either a concrete transaction (with created/spent UTXO
/// lists) or a progress sentinel that carries the current `max` id.
///
/// We flatten the union into a single type rather than a Rust enum so
/// callers can inspect `highest_transaction_id` cheaply without needing
/// to match on every tick — progress events set
/// `highest_transaction_id = Some(max)` and leave the created/spent
/// vectors empty.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct UnshieldedTxRaw {
    /// GraphQL `__typename` — `"UnshieldedTransaction"` or
    /// `"UnshieldedTransactionsProgress"`.
    pub kind: String,
    /// `"SUCCESS"`, `"FAILURE"`, or `"PARTIAL_SUCCESS"` for a
    /// [`RegularTransaction`]; `"SUCCESS"` for a system transaction
    /// (which carries no `transactionResult`); `None` for progress
    /// sentinels.
    pub status: Option<String>,
    /// Id of the containing transaction. `None` on progress sentinels.
    pub transaction_id: Option<i64>,
    /// Hex-encoded transaction hash. `None` on progress sentinels.
    pub transaction_hash: Option<String>,
    /// Block that the transaction landed in. `None` on progress sentinels.
    pub block: Option<BlockRef>,
    /// Block timestamp in **seconds** since the UNIX epoch. The indexer's
    /// `Block.timestamp` field is in milliseconds; this field is the
    /// divided value for direct use as `UtxoMeta.ctime`. `None` on
    /// progress sentinels.
    pub block_time_secs: Option<i64>,
    /// UTXOs created by this transaction that belong to the subscribed
    /// address. Empty on progress sentinels.
    pub created_utxos: Vec<UnshieldedUtxoRaw>,
    /// UTXOs spent by this transaction that belong to the subscribed
    /// address. Empty on progress sentinels.
    pub spent_utxos: Vec<UnshieldedUtxoRaw>,
    /// On `UnshieldedTransactionsProgress` ticks: the highest transaction
    /// id the indexer has seen so far. `None` on real transactions — we
    /// don't echo the transaction id into this field, to keep progress
    /// detection unambiguous.
    pub highest_transaction_id: Option<i64>,
}

impl UnshieldedTxRaw {
    /// True when this tick is a `UnshieldedTransactionsProgress` sentinel
    /// (carries no transaction payload, only `highest_transaction_id`).
    #[inline]
    #[must_use]
    pub fn is_progress(&self) -> bool {
        self.kind == "UnshieldedTransactionsProgress"
    }

    /// True when this tick is a concrete `UnshieldedTransaction`.
    #[inline]
    #[must_use]
    pub fn is_transaction(&self) -> bool {
        self.kind == "UnshieldedTransaction"
    }
}

// --- Shielded transactions subscription ----------------------------------

/// One tick of the `shieldedTransactions` subscription. The union
/// resolves to either a [`RelevantTransaction`] (a regular transaction
/// relevant for the subscribing wallet, with optional zswap-tree
/// collapsed update) or a [`ShieldedTransactionsProgress`] sentinel.
///
/// Flattened into a single type so callers don't have to match on
/// every tick; progress entries leave `transaction_id` / `block` etc.
/// empty and populate the `highest_*_zswap_end_index` fields.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ShieldedTxRaw {
    /// GraphQL `__typename` — `"RelevantTransaction"` or
    /// `"ShieldedTransactionsProgress"`.
    pub kind: String,
    /// `"SUCCESS"`, `"FAILURE"`, or `"PARTIAL_SUCCESS"` for a
    /// [`RegularTransaction`]. `None` on progress sentinels.
    pub status: Option<String>,
    /// Transaction id — `None` on progress sentinels.
    pub transaction_id: Option<i64>,
    /// Transaction hash — `None` on progress sentinels.
    pub transaction_hash: Option<String>,
    /// Block that the transaction landed in. `None` on progress sentinels.
    pub block: Option<BlockRef>,
    /// Block timestamp in **seconds** since the UNIX epoch. Indexer's
    /// `Block.timestamp` is milliseconds; this field is pre-divided so
    /// callers can feed it into ledger `Timestamp::from_secs` directly.
    /// `None` on progress sentinels.
    pub block_time_secs: Option<i64>,
    /// Exclusive zswap end index — the next free slot in the zswap
    /// commitment tree after applying this tx. `None` on progress.
    pub zswap_end_index: Option<i64>,
    /// Hex-encoded, tagged-serialized zswap ledger events for this
    /// transaction. Empty on progress sentinels.
    pub zswap_ledger_events: Vec<ZswapLedgerEventRaw>,
    /// Collapsed zswap-tree update filling in the gap between the
    /// subscription's current index and this transaction's start
    /// index. `None` if there was no gap. Always `None` on progress.
    pub zswap_collapsed_update: Option<MerkleTreeCollapsedUpdate>,
    /// On progress ticks: the highest zswap end index the indexer has
    /// seen. Drives `SyncProgress::highest_index`. `None` on real
    /// transactions.
    pub highest_zswap_end_index: Option<i64>,
    /// On progress ticks: the highest zswap end index checked for
    /// relevance (== `highest_*` eventually). `None` on real
    /// transactions.
    pub highest_checked_zswap_end_index: Option<i64>,
    /// On progress ticks: the highest zswap end index for all
    /// transactions that proved relevant for the subscribing wallet.
    /// Drives `SyncProgress::highest_relevant_wallet_index`.
    pub highest_relevant_zswap_end_index: Option<i64>,
}

impl ShieldedTxRaw {
    #[inline]
    #[must_use]
    pub fn is_progress(&self) -> bool {
        self.kind == "ShieldedTransactionsProgress"
    }

    #[inline]
    #[must_use]
    pub fn is_transaction(&self) -> bool {
        self.kind == "RelevantTransaction"
    }
}

/// One zswap ledger event as delivered by the indexer. The `raw` field
/// is a hex-encoded, tagged-serialized
/// `moonproof_ledger::ledger::events::Event<InMemoryDB>` — downstream wallet
/// code can deserialize it via `tagged_deserialize` and replay into a
/// `ZswapLocalState`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ZswapLedgerEventRaw {
    /// Per-source-stream sequence id.
    pub id: i64,
    /// Hex-encoded `moonproof_ledger::ledger::events::Event<InMemoryDB>`.
    pub raw: String,
    /// Highest event id the indexer has seen.
    pub max_id: i64,
}

// --- Zswap / merkle --------------------------------------------------------

/// A collapsed Merkle tree update between two indices.
///
/// Used for zswap state, dust commitment tree, and dust generation tree —
/// all three expose the same shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct MerkleTreeCollapsedUpdate {
    pub start_index: i64,
    pub end_index: i64,
    pub update: String,
    pub protocol_version: i64,
}

// --- Dust ------------------------------------------------------------------

/// Dust-generation snapshot for one Cardano reward address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerationStatus {
    pub cardano_reward_address: String,
    pub dust_address: Option<String>,
    pub registered: bool,
    pub night_balance: String,
    pub generation_rate: String,
    pub max_capacity: String,
    pub current_capacity: String,
    pub utxo_tx_hash: Option<String>,
    pub utxo_output_index: Option<i64>,
}

/// All active dust registrations for a Cardano reward address.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerations {
    pub cardano_reward_address: String,
    pub registrations: Vec<DustRegistration>,
}

/// A single dust registration with aggregated generation stats.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustRegistration {
    pub dust_address: String,
    pub valid: bool,
    pub night_balance: String,
    pub generation_rate: String,
    pub max_capacity: String,
    pub current_capacity: String,
    pub utxo_tx_hash: Option<String>,
    pub utxo_output_index: Option<i64>,
}

// --- Block subscription ---------------------------------------------------

/// One tick from the `blocks` subscription — the full
/// [`Block`]-equivalent metadata plus a list of the transactions that
/// landed in this block (by id + hash). The raw transaction bytes are
/// not fetched here; callers that need them can issue a
/// [`PublicDataProvider::transaction`](crate::PublicDataProvider)
/// lookup keyed by id or hash.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct BlockTickRaw {
    pub hash: String,
    pub height: i64,
    pub protocol_version: i64,
    /// Milliseconds since the UNIX epoch — the indexer's native unit
    /// (see VISION.md "Lessons learned"). Callers that care about
    /// seconds should divide by 1000.
    pub timestamp_ms: i64,
    pub author: Option<String>,
    pub zswap_merkle_tree_root: String,
    pub ledger_parameters: String,
    pub parent_hash: Option<String>,
    pub parent_height: Option<i64>,
    pub transactions: Vec<BlockTickTransactionRef>,
}

/// Minimal transaction descriptor returned inside [`BlockTickRaw::transactions`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct BlockTickTransactionRef {
    pub kind: TransactionKind,
    pub id: i64,
    pub hash: String,
}

// --- Contract actions subscription ----------------------------------------

/// One tick from the `contractActions(address)` subscription. Carries the
/// action kind (Deploy / Call / Update), its serialized state blobs, its
/// unshielded balance list, and the parent transaction descriptor.
///
/// This mirrors [`ContractAction`] but is sourced from the subscription
/// stream — callers that need the full transaction body should issue a
/// [`PublicDataProvider::transaction`](crate::PublicDataProvider) lookup
/// keyed by the returned `transaction_hash`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ContractActionTickRaw {
    pub kind: ContractActionKind,
    pub address: String,
    pub state: String,
    pub zswap_state: String,
    pub unshielded_balances: Vec<ContractBalance>,
    /// Populated only for [`ContractActionKind::Call`].
    pub entry_point: Option<String>,
    pub transaction_id: i64,
    pub transaction_hash: String,
    pub block: BlockRef,
}

// --- Dust generations subscription ----------------------------------------

/// One tick from the
/// `dustGenerations(dustAddress, blockHash, dtimeCutoffHeight)`
/// subscription — a [`DustGenerationsItemRaw`] entry, a
/// [`DustGenerationDtimeUpdateRaw`] delta, or a
/// [`DustGenerationsProgressRaw`] sentinel.
///
/// Items and the progress sentinel carry an optional
/// [`MerkleTreeCollapsedUpdate`] that fills the gap between the previous
/// entry and this one (for items) or covers the remaining range (for the
/// terminal progress tick). Dtime updates are emitted first, ahead of
/// the snapshot, and carry no tree update.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerationsTickRaw {
    pub kind: String,
    pub item: Option<DustGenerationsItemRaw>,
    pub dtime_update: Option<DustGenerationDtimeUpdateRaw>,
    pub progress: Option<DustGenerationsProgressRaw>,
}

impl DustGenerationsTickRaw {
    #[inline]
    #[must_use]
    pub fn is_item(&self) -> bool {
        self.item.is_some()
    }

    #[inline]
    #[must_use]
    pub fn is_dtime_update(&self) -> bool {
        self.dtime_update.is_some()
    }

    #[inline]
    #[must_use]
    pub fn is_progress(&self) -> bool {
        self.progress.is_some()
    }
}

/// The `DustGenerationDtimeUpdateItem` payload — the dtime a generation
/// was stamped with when its backing NIGHT UTXO was spent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerationDtimeUpdateRaw {
    pub generation_mt_index: i64,
    pub owner: String,
    pub night_utxo_hash: String,
    /// Destruction time, seconds since the UNIX epoch.
    pub new_dtime: i64,
    pub transaction_id: i64,
    pub transaction_hash: String,
    pub tree_insertion_path: String,
}

/// The `DustGenerationsItem` payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerationsItemRaw {
    pub commitment_mt_index: i64,
    pub generation_mt_index: i64,
    pub owner: String,
    /// String-encoded `u128` — STAR value backing the generation.
    pub value: String,
    /// String-encoded `u128` — DUST at creation (SPECK).
    pub initial_value: String,
    pub backing_night: String,
    /// Creation timestamp, seconds since the UNIX epoch.
    pub ctime: i64,
    pub transaction_id: i64,
    pub transaction_hash: String,
    pub collapsed_merkle_tree: Option<MerkleTreeCollapsedUpdate>,
}

/// The `DustGenerationsProgress` payload.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustGenerationsProgressRaw {
    pub highest_index: i64,
    pub collapsed_merkle_tree: Option<MerkleTreeCollapsedUpdate>,
}

// --- Nullifier match subscriptions ----------------------------------------

/// One tick from the
/// `dustNullifierTransactions(nullifierLeBytesPrefixes)` subscription —
/// a block-context reference to a transaction that contains a matching
/// dust nullifier.
///
/// Callers use this to know WHICH transactions they need to fetch and
/// replay without the indexer learning the full nullifier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DustNullifierMatchRaw {
    pub nullifier_le_bytes: String,
    pub commitment_le_bytes: String,
    pub transaction_id: i64,
    pub transaction_hash: String,
    pub block_hash: String,
    pub block_height: i64,
}

/// One tick from the `shieldedNullifierTransactions(nullifierPrefixes)`
/// subscription — the zswap equivalent of [`DustNullifierMatchRaw`].
///
/// The schema exposes fewer fields than the dust variant (no
/// `commitment`), matching the TS reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ShieldedNullifierMatchRaw {
    pub nullifier: String,
    pub transaction_id: i64,
    pub block_hash: String,
    pub block_height: i64,
}

// --- Governance history ----------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct DParameterChange {
    pub block_height: i64,
    pub block_hash: String,
    pub timestamp: i64,
    pub num_permissioned_candidates: i64,
    pub num_registered_candidates: i64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct TermsAndConditionsChange {
    pub block_height: i64,
    pub block_hash: String,
    pub timestamp: i64,
    pub hash: String,
    pub url: String,
}

// --- SPO identity / metadata ----------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct SpoIdentity {
    pub pool_id_hex: String,
    pub mainchain_pubkey_hex: String,
    pub sidechain_pubkey_hex: String,
    pub aura_pubkey_hex: Option<String>,
    pub validator_class: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct PoolMetadata {
    pub pool_id_hex: String,
    pub hex_id: Option<String>,
    pub name: Option<String>,
    pub ticker: Option<String>,
    pub homepage_url: Option<String>,
    pub logo_url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct Spo {
    pub pool_id_hex: String,
    pub validator_class: String,
    pub sidechain_pubkey_hex: String,
    pub aura_pubkey_hex: Option<String>,
    pub name: Option<String>,
    pub ticker: Option<String>,
    pub homepage_url: Option<String>,
    pub logo_url: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct SpoComposite {
    pub identity: Option<SpoIdentity>,
    pub metadata: Option<PoolMetadata>,
    pub performance: Vec<EpochPerf>,
}

// --- Epoch / committee -----------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct EpochInfo {
    pub epoch_no: i64,
    pub duration_seconds: i64,
    pub elapsed_seconds: i64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct EpochPerf {
    pub epoch_no: i64,
    pub spo_sk_hex: String,
    pub produced: i64,
    pub expected: i64,
    pub identity_label: Option<String>,
    pub stake_snapshot: Option<String>,
    pub pool_id_hex: Option<String>,
    pub validator_class: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct CommitteeMember {
    pub epoch_no: i64,
    pub position: i64,
    pub sidechain_pubkey_hex: String,
    pub expected_slots: i64,
    pub aura_pubkey_hex: Option<String>,
    pub pool_id_hex: Option<String>,
    pub spo_sk_hex: Option<String>,
}

// --- Registration stats ----------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct RegisteredTotals {
    pub epoch_no: i64,
    pub total_registered: i64,
    pub newly_registered: i64,
}

/// Registration statistics for an epoch.
///
/// `dparam` is a `Float` in schema and is therefore not `Eq`-comparable; omitted
/// from the `Eq` derive. We still keep `PartialEq` for convenience.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct RegisteredStat {
    pub epoch_no: i64,
    pub federated_valid_count: i64,
    pub federated_invalid_count: i64,
    pub registered_valid_count: i64,
    pub registered_invalid_count: i64,
    pub dparam: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct PresenceEvent {
    pub epoch_no: i64,
    pub id_key: String,
    pub source: String,
    pub status: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct FirstValidEpoch {
    pub id_key: String,
    pub first_valid_epoch: i64,
}

// --- Stake distribution ----------------------------------------------------

/// Stake share information for an SPO (mainchain-sourced, e.g. Blockfrost).
///
/// `Float` fields are not `Eq`-comparable.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct StakeShare {
    pub pool_id_hex: String,
    pub name: Option<String>,
    pub ticker: Option<String>,
    pub homepage_url: Option<String>,
    pub logo_url: Option<String>,
    pub live_stake: Option<String>,
    pub active_stake: Option<String>,
    pub live_delegators: Option<i64>,
    pub live_saturation: Option<f64>,
    pub declared_pledge: Option<String>,
    pub live_pledge: Option<String>,
    pub stake_share: Option<f64>,
}

// --- Session ---------------------------------------------------------------

/// Options passed to the `connect` mutation to seed wallet-session scanning.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "camelCase")]
pub struct ConnectOptions {
    /// Transaction index to start searching for relevant transactions (inclusive).
    pub start_index: Option<i64>,
}