accumulate-sdk 2.1.0

Accumulate Rust SDK (V2/V3 unified) with DevNet-first flows
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
//! GENERATED BY Accumulate gen-sdk. DO NOT EDIT.

#![allow(missing_docs)]

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// Generated types would go here - for now using handcrafted common types

// Common types that are always needed

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct StatusResponse {
    pub network: String,
    pub version: String,
    pub commit: String,
    pub node_info: NodeInfo,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NodeInfo {
    pub id: String,
    pub listen_addr: String,
    pub network: String,
    pub version: String,
    pub channels: String,
    pub moniker: String,
    pub other: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct QueryResponse<T> {
    pub result: T,
    pub height: i64,
    pub proof: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionResponse {
    pub txid: String,
    pub hash: String,
    pub height: i64,
    pub index: i32,
    pub tx: serde_json::Value,
    pub tx_result: TransactionResult,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionResult {
    pub code: i32,
    pub data: Option<String>,
    pub log: String,
    pub info: String,
    pub gas_wanted: String,
    pub gas_used: String,
    pub events: Vec<Event>,
    pub codespace: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Event {
    #[serde(rename = "type")]
    pub event_type: String,
    pub attributes: Vec<Attribute>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attribute {
    pub key: String,
    pub value: String,
    pub index: bool,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SignedTransaction {
    pub body: serde_json::Value,
    pub signatures: Vec<Signature>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Signature {
    pub public_key: String,
    pub signature: String,
    #[serde(rename = "type")]
    pub signature_type: String,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Account {
    pub url: String,
    #[serde(rename = "type")]
    pub account_type: String,
    pub data: serde_json::Value,
    pub credits: Option<i64>,
    pub nonce: Option<i64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FaucetResponse {
    /// Transaction ID - may be "txid", "transactionHash", or "hash"
    #[serde(default, alias = "transactionHash", alias = "hash")]
    pub txid: String,
    #[serde(default)]
    pub link: String,
    #[serde(default)]
    pub account: String,
    #[serde(default)]
    pub amount: String,
    /// Simple hash (V3 response)
    #[serde(default, alias = "simpleHash")]
    pub simple_hash: Option<String>,
}

/// Merkle receipt entry - a node in the proof path
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerkleReceiptEntry {
    /// Whether this hash should be applied on the right side
    #[serde(default)]
    pub right: bool,
    /// The hash value at this position in the proof
    #[serde(with = "hex::serde")]
    pub hash: Vec<u8>,
}

/// Merkle receipt - cryptographic proof of inclusion in a Merkle tree
/// Used for anchoring transactions and proving state inclusion
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerkleReceipt {
    /// The starting entry hash for which we want a proof
    #[serde(with = "hex::serde")]
    pub start: Vec<u8>,
    /// Index of the start entry in the chain
    #[serde(default)]
    pub start_index: i64,
    /// The ending entry hash at the anchor point
    #[serde(with = "hex::serde")]
    pub end: Vec<u8>,
    /// Index of the end entry in the chain
    #[serde(default)]
    pub end_index: i64,
    /// The Merkle root hash expected after applying all proof entries
    #[serde(with = "hex::serde")]
    pub anchor: Vec<u8>,
    /// The list of hashes in the proof path
    #[serde(default)]
    pub entries: Vec<MerkleReceiptEntry>,
}

impl MerkleReceipt {
    /// Create an empty receipt
    pub fn new() -> Self {
        Self {
            start: Vec::new(),
            start_index: 0,
            end: Vec::new(),
            end_index: 0,
            anchor: Vec::new(),
            entries: Vec::new(),
        }
    }

    /// Validate the receipt structure
    pub fn validate(&self) -> Result<(), crate::errors::Error> {
        use crate::errors::ValidationError;

        // Start hash should be 32 bytes (SHA-256) or empty
        if !self.start.is_empty() && self.start.len() != 32 {
            return Err(ValidationError::InvalidHash {
                expected: 32,
                actual: self.start.len(),
            }.into());
        }

        // End hash should be 32 bytes (SHA-256) or empty
        if !self.end.is_empty() && self.end.len() != 32 {
            return Err(ValidationError::InvalidHash {
                expected: 32,
                actual: self.end.len(),
            }.into());
        }

        // Anchor hash should be 32 bytes (SHA-256) or empty
        if !self.anchor.is_empty() && self.anchor.len() != 32 {
            return Err(ValidationError::InvalidHash {
                expected: 32,
                actual: self.anchor.len(),
            }.into());
        }

        // Validate each entry hash
        for (i, entry) in self.entries.iter().enumerate() {
            if entry.hash.len() != 32 {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("entries[{}].hash", i),
                    reason: format!("expected 32 bytes, got {}", entry.hash.len()),
                }.into());
            }
        }

        // Start index should not be negative
        if self.start_index < 0 {
            return Err(ValidationError::OutOfRange {
                field: "startIndex".to_string(),
                min: "0".to_string(),
                max: "i64::MAX".to_string(),
            }.into());
        }

        // End index should not be negative
        if self.end_index < 0 {
            return Err(ValidationError::OutOfRange {
                field: "endIndex".to_string(),
                min: "0".to_string(),
                max: "i64::MAX".to_string(),
            }.into());
        }

        // End index should be >= start index
        if self.end_index < self.start_index {
            return Err(ValidationError::InvalidFieldValue {
                field: "endIndex".to_string(),
                reason: format!("endIndex ({}) must be >= startIndex ({})", self.end_index, self.start_index),
            }.into());
        }

        Ok(())
    }

    /// Verify the receipt by computing the Merkle proof
    /// Returns true if applying the entries produces the expected anchor
    pub fn verify(&self) -> Result<bool, crate::errors::Error> {
        use sha2::{Sha256, Digest};

        self.validate()?;

        if self.start.is_empty() || self.anchor.is_empty() {
            return Ok(false);
        }

        let mut current: [u8; 32] = self.start.clone().try_into()
            .map_err(|_| crate::errors::Error::General("Invalid start hash length".to_string()))?;

        // Apply each entry in the proof path
        for entry in &self.entries {
            let entry_hash: [u8; 32] = entry.hash.clone().try_into()
                .map_err(|_| crate::errors::Error::General("Invalid entry hash length".to_string()))?;

            let mut hasher = Sha256::new();
            if entry.right {
                // Entry goes on the right: hash(current || entry)
                hasher.update(&current);
                hasher.update(&entry_hash);
            } else {
                // Entry goes on the left: hash(entry || current)
                hasher.update(&entry_hash);
                hasher.update(&current);
            }
            current = hasher.finalize().into();
        }

        // Compare computed root with expected anchor
        Ok(current.as_slice() == self.anchor.as_slice())
    }

    /// Check if the receipt is empty
    pub fn is_empty(&self) -> bool {
        self.start.is_empty() && self.end.is_empty() && self.anchor.is_empty() && self.entries.is_empty()
    }
}

impl Default for MerkleReceipt {
    fn default() -> Self {
        Self::new()
    }
}

impl std::hash::Hash for MerkleReceipt {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.start.hash(state);
        self.start_index.hash(state);
        self.end.hash(state);
        self.end_index.hash(state);
        self.anchor.hash(state);
        self.entries.hash(state);
    }
}

// V3 specific types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct V3SubmitRequest {
    pub envelope: TransactionEnvelope,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct V3SubmitResponse {
    pub hash: String,
    pub result: SubmitResult,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SubmitResult {
    pub code: i32,
    pub message: String,
    pub data: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TransactionEnvelope {
    pub transaction: serde_json::Value,
    pub signatures: Vec<V3Signature>,
    pub metadata: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct V3Signature {
    pub public_key: Vec<u8>,
    pub signature: Vec<u8>,
    pub timestamp: i64,
    pub vote: Option<String>,
}

// ============================================================================
// V3 API Service Types
// ============================================================================

/// Node information returned by NodeInfo service
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3NodeInfo {
    /// The peer ID of this node
    #[serde(default)]
    pub peer_id: String,
    /// Network name
    #[serde(default)]
    pub network: String,
    /// Services provided by this node
    #[serde(default)]
    pub services: Vec<ServiceAddress>,
    /// Node software version
    #[serde(default)]
    pub version: String,
    /// Git commit hash
    #[serde(default)]
    pub commit: String,
}

/// Service address identifying a network service
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServiceAddress {
    /// Service type identifier
    #[serde(rename = "type")]
    pub service_type: String,
    /// Optional service argument
    #[serde(skip_serializing_if = "Option::is_none")]
    pub argument: Option<String>,
}

/// Options for NodeInfo request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NodeInfoOptions {
    /// Optional peer ID to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub peer_id: Option<String>,
}

/// Consensus status information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3ConsensusStatus {
    /// Whether the node is operational
    #[serde(default)]
    pub ok: bool,
    /// Last block information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_block: Option<LastBlock>,
    /// Node software version
    #[serde(default)]
    pub version: String,
    /// Git commit hash
    #[serde(default)]
    pub commit: String,
    /// Hash of the node's public key
    #[serde(default)]
    pub node_key_hash: String,
    /// Hash of the validator's public key
    #[serde(default)]
    pub validator_key_hash: String,
    /// Partition identifier
    #[serde(default)]
    pub partition_id: String,
    /// Partition type (Directory, BlockValidator)
    #[serde(default)]
    pub partition_type: String,
    /// Connected peers
    #[serde(default)]
    pub peers: Vec<ConsensusPeerInfo>,
}

/// Last block information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LastBlock {
    /// Block height
    #[serde(default)]
    pub height: i64,
    /// Block timestamp
    #[serde(default)]
    pub time: String,
    /// Chain root hash
    #[serde(default)]
    pub chain_root: String,
    /// State root hash
    #[serde(default)]
    pub state_root: String,
    /// Directory anchor height
    #[serde(default)]
    pub directory_anchor_height: u64,
}

/// Consensus peer information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ConsensusPeerInfo {
    /// Node ID
    #[serde(default)]
    pub node_id: String,
    /// Host address
    #[serde(default)]
    pub host: String,
    /// Port number
    #[serde(default)]
    pub port: u64,
}

/// Options for ConsensusStatus request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ConsensusStatusOptions {
    /// Node ID to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<String>,
    /// Partition to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
    /// Include connected peers in response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_peers: Option<bool>,
    /// Include Accumulate-specific info
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_accumulate: Option<bool>,
}

/// Network status information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3NetworkStatus {
    /// ACME oracle price information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub oracle: Option<AcmeOracle>,
    /// Network global settings
    #[serde(skip_serializing_if = "Option::is_none")]
    pub globals: Option<serde_json::Value>,
    /// Network definition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<serde_json::Value>,
    /// Routing table
    #[serde(skip_serializing_if = "Option::is_none")]
    pub routing: Option<serde_json::Value>,
    /// Active executor version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub executor_version: Option<String>,
    /// Directory network height
    #[serde(default)]
    pub directory_height: u64,
    /// Major block height
    #[serde(default)]
    pub major_block_height: u64,
    /// BVN executor versions
    #[serde(default)]
    pub bvn_executor_versions: Vec<PartitionExecutorVersion>,
}

/// ACME oracle price
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcmeOracle {
    /// Price in micro-USD per ACME
    #[serde(default)]
    pub price: u64,
}

/// Partition executor version
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PartitionExecutorVersion {
    /// Partition identifier
    #[serde(default)]
    pub partition: String,
    /// Executor version
    #[serde(default)]
    pub version: String,
}

/// Options for NetworkStatus request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct NetworkStatusOptions {
    /// Partition to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
}

/// Metrics information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3Metrics {
    /// Transactions per second
    #[serde(default)]
    pub tps: f64,
}

/// Options for Metrics request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct MetricsOptions {
    /// Partition to query metrics for
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
    /// Window span in blocks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub span: Option<u64>,
}

/// Submission result for validate/submit operations
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3Submission {
    /// Transaction status
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<serde_json::Value>,
    /// Whether the submission was successful
    #[serde(default)]
    pub success: bool,
    /// Message from the consensus engine
    #[serde(default)]
    pub message: String,
}

/// Options for Submit request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SubmitOptions {
    /// Verify envelope is well-formed before submitting (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub verify: Option<bool>,
    /// Wait until envelope is accepted or rejected (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wait: Option<bool>,
}

/// Options for Validate request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ValidateOptions {
    /// Full validation (default: true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub full: Option<bool>,
}

/// Options for Faucet request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct V3FaucetOptions {
    /// Token URL (default: ACME)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
}

/// Snapshot information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct V3SnapshotInfo {
    /// Snapshot header
    #[serde(skip_serializing_if = "Option::is_none")]
    pub header: Option<serde_json::Value>,
    /// Consensus genesis document
    #[serde(skip_serializing_if = "Option::is_none")]
    pub consensus_info: Option<serde_json::Value>,
}

/// Options for ListSnapshots request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListSnapshotsOptions {
    /// Node ID to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub node_id: Option<String>,
    /// Partition to query
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
}

/// Options for FindService request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct FindServiceOptions {
    /// Network to search in
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network: Option<String>,
    /// Service to find
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service: Option<ServiceAddress>,
    /// Restrict to known peers only
    #[serde(skip_serializing_if = "Option::is_none")]
    pub known: Option<bool>,
    /// Timeout for DHT query (milliseconds)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timeout: Option<u64>,
}

/// FindService result
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FindServiceResult {
    /// Peer ID
    #[serde(default)]
    pub peer_id: String,
    /// Known peer status
    #[serde(default)]
    pub status: String,
    /// Peer addresses
    #[serde(default)]
    pub addresses: Vec<String>,
}

/// Options for Subscribe (events) request
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SubscribeOptions {
    /// Partition to subscribe to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub partition: Option<String>,
    /// Account to subscribe to
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account: Option<String>,
}

// ============================================================================
// V3 Query Types
// ============================================================================

/// Range options for paginated queries
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct RangeOptions {
    /// Starting index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<u64>,
    /// Number of results to return
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<u64>,
    /// Expand results with full data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expand: Option<bool>,
    /// Query from the end of the range
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_end: Option<bool>,
}

/// Receipt options for queries
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ReceiptOptions {
    /// Include receipt for any height
    #[serde(skip_serializing_if = "Option::is_none")]
    pub for_any: Option<bool>,
    /// Include receipt for specific height
    #[serde(skip_serializing_if = "Option::is_none")]
    pub for_height: Option<u64>,
}

/// Default query - basic account/transaction query
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DefaultQuery {
    /// Include receipt in response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_receipt: Option<ReceiptOptions>,
}

/// Chain query - query chain data for an account
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ChainQuery {
    /// Chain name (e.g., "main", "signature", "pending")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Query specific index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<u64>,
    /// Query by entry hash
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry: Option<String>,
    /// Range options for paginated results
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<RangeOptions>,
    /// Include receipt in response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_receipt: Option<ReceiptOptions>,
}

impl ChainQuery {
    /// Validate the query parameters
    pub fn validate(&self) -> Result<(), crate::errors::Error> {
        let has_name = self.name.is_some();
        let has_index = self.index.is_some();
        let has_entry = self.entry.is_some();
        let has_range = self.range.is_some();

        if has_range && (has_index || has_entry) {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "range".to_string(),
                reason: "range is mutually exclusive with index and entry".to_string(),
            }.into());
        }

        if !has_name && (has_index || has_entry || has_range) {
            return Err(crate::errors::ValidationError::RequiredFieldMissing(
                "name is required when querying by index, entry, or range".to_string(),
            ).into());
        }

        Ok(())
    }
}

/// Data query - query data entries for a data account
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DataQuery {
    /// Query specific index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<u64>,
    /// Query by entry hash
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry: Option<String>,
    /// Range options for paginated results
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<RangeOptions>,
}

impl DataQuery {
    /// Validate the query parameters
    pub fn validate(&self) -> Result<(), crate::errors::Error> {
        let has_index = self.index.is_some();
        let has_entry = self.entry.is_some();
        let has_range = self.range.is_some();

        if has_range && (has_index || has_entry) {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "range".to_string(),
                reason: "range is mutually exclusive with index and entry".to_string(),
            }.into());
        }

        Ok(())
    }
}

/// Directory query - query sub-accounts of an identity
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DirectoryQuery {
    /// Range options for paginated results
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<RangeOptions>,
}

/// Pending query - query pending transactions
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct PendingQuery {
    /// Range options for paginated results
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<RangeOptions>,
}

/// Block query - query block information
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct BlockQuery {
    /// Query by minor block index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minor: Option<u64>,
    /// Query by major block index
    #[serde(skip_serializing_if = "Option::is_none")]
    pub major: Option<u64>,
    /// Range of minor blocks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minor_range: Option<RangeOptions>,
    /// Range of major blocks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub major_range: Option<RangeOptions>,
    /// Range of entries within a block
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entry_range: Option<RangeOptions>,
    /// Omit empty (unrecorded) blocks
    #[serde(skip_serializing_if = "Option::is_none")]
    pub omit_empty: Option<bool>,
}

impl BlockQuery {
    /// Validate the query parameters
    pub fn validate(&self) -> Result<(), crate::errors::Error> {
        let has_minor = self.minor.is_some();
        let has_major = self.major.is_some();
        let has_minor_range = self.minor_range.is_some();
        let has_major_range = self.major_range.is_some();
        let has_entry_range = self.entry_range.is_some();

        if !has_minor && !has_major && !has_minor_range && !has_major_range {
            return Err(crate::errors::ValidationError::RequiredFieldMissing(
                "minor, major, minor_range, or major_range must be specified".to_string(),
            ).into());
        }
        if has_minor && has_major {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "minor/major".to_string(),
                reason: "minor and major are mutually exclusive".to_string(),
            }.into());
        }
        if has_minor_range && has_major_range {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "minor_range/major_range".to_string(),
                reason: "minor_range and major_range are mutually exclusive".to_string(),
            }.into());
        }
        if has_minor && (has_minor_range || has_major_range) {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "minor".to_string(),
                reason: "minor is mutually exclusive with minor_range and major_range".to_string(),
            }.into());
        }
        if has_major && has_major_range {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "major".to_string(),
                reason: "major and major_range are mutually exclusive".to_string(),
            }.into());
        }
        if has_entry_range && (has_major || has_minor_range || has_major_range) {
            return Err(crate::errors::ValidationError::InvalidFieldValue {
                field: "entry_range".to_string(),
                reason: "entry_range is mutually exclusive with major, minor_range, and major_range".to_string(),
            }.into());
        }

        Ok(())
    }
}

/// Anchor search query - search by anchor hash
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AnchorSearchQuery {
    /// Anchor hash to search for (32 bytes, hex-encoded)
    pub anchor: String,
    /// Include receipt in response
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_receipt: Option<ReceiptOptions>,
}

/// Public key search query - search signers by public key
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeySearchQuery {
    /// Public key to search for (hex-encoded)
    pub public_key: String,
    /// Signature type (e.g., "ed25519", "btc", "eth")
    #[serde(rename = "type")]
    pub signature_type: String,
}

/// Public key hash search query - search signers by public key hash
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PublicKeyHashSearchQuery {
    /// Public key hash to search for (hex-encoded)
    pub public_key_hash: String,
}

/// Delegate search query - search for delegated keys
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DelegateSearchQuery {
    /// Delegate URL to search for
    pub delegate: String,
}

/// Message hash search query - search by message/transaction hash
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageHashSearchQuery {
    /// Message hash to search for (32 bytes, hex-encoded)
    pub hash: String,
}

/// Query union type - represents all possible query types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "queryType", rename_all = "camelCase")]
pub enum V3Query {
    /// Default query for account/transaction
    #[serde(rename = "default")]
    Default(DefaultQuery),
    /// Chain query
    #[serde(rename = "chain")]
    Chain(ChainQuery),
    /// Data query
    #[serde(rename = "data")]
    Data(DataQuery),
    /// Directory query
    #[serde(rename = "directory")]
    Directory(DirectoryQuery),
    /// Pending query
    #[serde(rename = "pending")]
    Pending(PendingQuery),
    /// Block query
    #[serde(rename = "block")]
    Block(BlockQuery),
    /// Anchor search query
    #[serde(rename = "anchorSearch")]
    AnchorSearch(AnchorSearchQuery),
    /// Public key search query
    #[serde(rename = "publicKeySearch")]
    PublicKeySearch(PublicKeySearchQuery),
    /// Public key hash search query
    #[serde(rename = "publicKeyHashSearch")]
    PublicKeyHashSearch(PublicKeyHashSearchQuery),
    /// Delegate search query
    #[serde(rename = "delegateSearch")]
    DelegateSearch(DelegateSearchQuery),
    /// Message hash search query
    #[serde(rename = "messageHashSearch")]
    MessageHashSearch(MessageHashSearchQuery),
}

impl V3Query {
    /// Validate the query
    pub fn validate(&self) -> Result<(), crate::errors::Error> {
        match self {
            V3Query::Chain(q) => q.validate(),
            V3Query::Data(q) => q.validate(),
            V3Query::Block(q) => q.validate(),
            _ => Ok(()),
        }
    }
}