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
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
//! GENERATED FILE - DO NOT EDIT
//! Sources: protocol/transaction.yml, user_transactions.yml, system.yml, synthetic_transactions.yml
//! Generated: 2025-10-03 21:53:38

#![allow(missing_docs)]

use serde::{Serialize, Deserialize};
use crate::errors::{Error, ValidationError};

/// Validates that a string is a valid Accumulate URL
/// Accumulate URLs must:
/// - Start with "acc://"
/// - Contain only ASCII characters
/// - Have at least one character after the scheme
/// - Not contain whitespace or control characters
fn validate_accumulate_url(url: &str, field_name: &str) -> Result<(), Error> {
    if url.is_empty() {
        return Err(ValidationError::RequiredFieldMissing(field_name.to_string()).into());
    }

    if !url.starts_with("acc://") {
        return Err(ValidationError::InvalidUrl(
            format!("{}: must start with 'acc://', got '{}'", field_name, url)
        ).into());
    }

    if !url.is_ascii() {
        return Err(ValidationError::InvalidUrl(
            format!("{}: must contain only ASCII characters", field_name)
        ).into());
    }

    // Check for whitespace or control characters
    if url.chars().any(|c| c.is_whitespace() || c.is_control()) {
        return Err(ValidationError::InvalidUrl(
            format!("{}: must not contain whitespace or control characters", field_name)
        ).into());
    }

    // Must have content after acc://
    if url.len() <= 6 {
        return Err(ValidationError::InvalidUrl(
            format!("{}: URL path cannot be empty", field_name)
        ).into());
    }

    Ok(())
}

/// Validates that an amount string represents a valid positive integer
fn validate_amount_string(amount: &str, field_name: &str) -> Result<(), Error> {
    if amount.is_empty() {
        return Err(ValidationError::RequiredFieldMissing(field_name.to_string()).into());
    }

    // Check if it's a valid integer (can be very large, so use string validation)
    if !amount.chars().all(|c| c.is_ascii_digit()) {
        return Err(ValidationError::InvalidAmount(
            format!("{}: must be a valid non-negative integer, got '{}'", field_name, amount)
        ).into());
    }

    // Check it's not all zeros (unless it's literally "0")
    if amount != "0" && amount.chars().all(|c| c == '0') {
        return Err(ValidationError::InvalidAmount(
            format!("{}: invalid zero representation", field_name)
        ).into());
    }

    Ok(())
}

/// Validates a list of authority URLs
fn validate_authorities(authorities: &Option<Vec<String>>) -> Result<(), Error> {
    if let Some(ref auths) = authorities {
        for (i, auth) in auths.iter().enumerate() {
            validate_accumulate_url(auth, &format!("authorities[{}]", i))?;
        }
    }
    Ok(())
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AcmeFaucetBody {
    #[serde(rename = "Url")]
    pub url: String,
}

impl AcmeFaucetBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Faucet URL must be a valid Accumulate URL (typically a lite token account)
        validate_accumulate_url(&self.url, "url")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ActivateProtocolVersionBody {
    #[serde(rename = "Version")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

impl ActivateProtocolVersionBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Version is optional, but if present must not be empty
        if let Some(ref version) = self.version {
            if version.is_empty() {
                return Err(ValidationError::InvalidFieldValue {
                    field: "version".to_string(),
                    reason: "version string cannot be empty if provided".to_string(),
                }.into());
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddCreditsBody {
    #[serde(rename = "Recipient")]
    pub recipient: String,
    #[serde(rename = "Amount")]
    pub amount: String,
    #[serde(rename = "Oracle")]
    pub oracle: u64,
}

impl AddCreditsBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Recipient must be a valid Accumulate URL
        validate_accumulate_url(&self.recipient, "recipient")?;

        // Amount must be a valid positive integer string
        validate_amount_string(&self.amount, "amount")?;

        // Oracle price must be positive (represents ACME price in credits)
        if self.oracle == 0 {
            return Err(ValidationError::InvalidFieldValue {
                field: "oracle".to_string(),
                reason: "oracle price must be positive".to_string(),
            }.into());
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlockValidatorAnchorBody {
    #[serde(rename = "AcmeBurnt")]
    pub acme_burnt: String,
}

impl BlockValidatorAnchorBody {
    pub fn validate(&self) -> Result<(), Error> {
        // AcmeBurnt must be a valid amount string (can be zero for no burn)
        validate_amount_string(&self.acme_burnt, "acmeBurnt")?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BurnCreditsBody {
    #[serde(rename = "Amount")]
    pub amount: u64,
}

impl BurnCreditsBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Amount must be positive (can't burn zero credits)
        if self.amount == 0 {
            return Err(ValidationError::InvalidAmount(
                "amount: must be greater than zero to burn credits".to_string()
            ).into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BurnTokensBody {
    #[serde(rename = "Amount")]
    pub amount: String,
}

impl BurnTokensBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Amount must be a valid positive integer string (can't burn zero)
        validate_amount_string(&self.amount, "amount")?;

        // Ensure amount is not "0"
        if self.amount == "0" {
            return Err(ValidationError::InvalidAmount(
                "amount: must be greater than zero to burn tokens".to_string()
            ).into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateDataAccountBody {
    #[serde(rename = "Url")]
    pub url: String,
    #[serde(rename = "Authorities")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorities: Option<Vec<String>>,
}

impl CreateDataAccountBody {
    pub fn validate(&self) -> Result<(), Error> {
        // URL must be a valid Accumulate URL
        validate_accumulate_url(&self.url, "url")?;

        // Validate authorities if provided
        validate_authorities(&self.authorities)?;

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateIdentityBody {
    #[serde(rename = "Url")]
    pub url: String,
    #[serde(rename = "KeyHash")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_hash: Option<Vec<u8>>,
    #[serde(rename = "KeyBookUrl")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub key_book_url: Option<String>,
    #[serde(rename = "Authorities")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorities: Option<Vec<String>>,
}

impl CreateIdentityBody {
    pub fn validate(&self) -> Result<(), Error> {
        // URL must be a valid Accumulate URL for the new identity
        validate_accumulate_url(&self.url, "url")?;

        // If key_book_url is provided, it must be valid
        if let Some(ref key_book_url) = self.key_book_url {
            validate_accumulate_url(key_book_url, "keyBookUrl")?;
        }

        // If key_hash is provided, it should be 32 bytes (SHA-256 hash)
        if let Some(ref key_hash) = self.key_hash {
            if key_hash.len() != 32 {
                return Err(ValidationError::InvalidHash {
                    expected: 32,
                    actual: key_hash.len(),
                }.into());
            }
        }

        // Validate authorities if provided
        validate_authorities(&self.authorities)?;

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateKeyBookBody {
    #[serde(rename = "Url")]
    pub url: String,
    #[serde(rename = "PublicKeyHash")]
    #[serde(with = "hex::serde")]
    pub public_key_hash: Vec<u8>,
    #[serde(rename = "Authorities")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorities: Option<Vec<String>>,
}

impl CreateKeyBookBody {
    pub fn validate(&self) -> Result<(), Error> {
        // URL must be a valid Accumulate URL
        validate_accumulate_url(&self.url, "url")?;

        // Public key hash must be 32 bytes (SHA-256)
        if self.public_key_hash.len() != 32 {
            return Err(ValidationError::InvalidHash {
                expected: 32,
                actual: self.public_key_hash.len(),
            }.into());
        }

        // Validate authorities if provided
        validate_authorities(&self.authorities)?;

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateKeyPageBody {
    #[serde(rename = "Keys")]
    pub keys: Vec<serde_json::Value>,
}

impl CreateKeyPageBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Must have at least one key entry
        if self.keys.is_empty() {
            return Err(ValidationError::EmptyCollection(
                "keys: at least one key is required".to_string()
            ).into());
        }

        // Each key entry should be a valid JSON object
        for (i, key) in self.keys.iter().enumerate() {
            if !key.is_object() {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("keys[{}]", i),
                    reason: "each key must be a valid key specification object".to_string(),
                }.into());
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateLiteTokenAccountBody {
    // No fields defined
}

impl CreateLiteTokenAccountBody {
    pub fn validate(&self) -> Result<(), Error> {
        // No fields to validate - lite token accounts are created implicitly
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTokenBody {
    #[serde(rename = "Url")]
    pub url: String,
    #[serde(rename = "Symbol")]
    pub symbol: String,
    #[serde(rename = "Precision")]
    pub precision: u64,
    #[serde(rename = "Properties")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<String>,
    #[serde(rename = "SupplyLimit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub supply_limit: Option<String>,
    #[serde(rename = "Authorities")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorities: Option<Vec<String>>,
}

impl CreateTokenBody {
    pub fn validate(&self) -> Result<(), Error> {
        // URL must be a valid Accumulate URL
        validate_accumulate_url(&self.url, "url")?;

        // Symbol must be non-empty and alphanumeric (1-10 characters typically)
        if self.symbol.is_empty() {
            return Err(ValidationError::InvalidTokenSymbol(
                "symbol cannot be empty".to_string()
            ).into());
        }

        if !self.symbol.chars().all(|c| c.is_ascii_alphanumeric()) {
            return Err(ValidationError::InvalidTokenSymbol(
                format!("symbol must be alphanumeric, got '{}'", self.symbol)
            ).into());
        }

        if self.symbol.len() > 10 {
            return Err(ValidationError::InvalidTokenSymbol(
                format!("symbol too long (max 10 chars), got {} chars", self.symbol.len())
            ).into());
        }

        // Precision must be between 0 and 18 (standard decimal precision)
        if self.precision > 18 {
            return Err(ValidationError::InvalidPrecision(self.precision).into());
        }

        // If supply_limit is provided, it must be a valid amount
        if let Some(ref supply_limit) = self.supply_limit {
            validate_amount_string(supply_limit, "supplyLimit")?;
        }

        // Validate authorities if provided
        validate_authorities(&self.authorities)?;

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTokenAccountBody {
    #[serde(rename = "Url")]
    pub url: String,
    #[serde(rename = "TokenUrl")]
    pub token_url: String,
    #[serde(rename = "Authorities")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authorities: Option<Vec<String>>,
    #[serde(rename = "Proof")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proof: Option<serde_json::Value>,
}

impl CreateTokenAccountBody {
    pub fn validate(&self) -> Result<(), Error> {
        // URL must be a valid Accumulate URL
        validate_accumulate_url(&self.url, "url")?;

        // TokenUrl must be a valid Accumulate URL
        validate_accumulate_url(&self.token_url, "tokenUrl")?;

        // Validate authorities if provided
        validate_authorities(&self.authorities)?;

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectoryAnchorBody {
    #[serde(rename = "Updates")]
    pub updates: Vec<serde_json::Value>,
    #[serde(rename = "Receipts")]
    pub receipts: Vec<serde_json::Value>,
    #[serde(rename = "MakeMajorBlock")]
    pub make_major_block: u64,
    #[serde(rename = "MakeMajorBlockTime")]
    pub make_major_block_time: u64,
}

impl DirectoryAnchorBody {
    pub fn validate(&self) -> Result<(), Error> {
        // System transaction - validates structure only
        // Updates and receipts can be empty arrays
        // MakeMajorBlock and MakeMajorBlockTime are informational
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IssueTokensBody {
    #[serde(rename = "Recipient")]
    pub recipient: String,
    #[serde(rename = "Amount")]
    pub amount: String,
    #[serde(rename = "To")]
    pub to: Vec<serde_json::Value>,
}

impl IssueTokensBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Recipient must be a valid Accumulate URL
        validate_accumulate_url(&self.recipient, "recipient")?;

        // Amount must be a valid positive integer string
        validate_amount_string(&self.amount, "amount")?;

        // Amount must be positive for issuance
        if self.amount == "0" {
            return Err(ValidationError::InvalidAmount(
                "amount: must be greater than zero to issue tokens".to_string()
            ).into());
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LockAccountBody {
    #[serde(rename = "Height")]
    pub height: u64,
}

impl LockAccountBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Height must be positive (lock until block height)
        if self.height == 0 {
            return Err(ValidationError::InvalidFieldValue {
                field: "height".to_string(),
                reason: "lock height must be greater than zero".to_string(),
            }.into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkMaintenanceBody {
    #[serde(rename = "Operations")]
    pub operations: Vec<serde_json::Value>,
}

impl NetworkMaintenanceBody {
    pub fn validate(&self) -> Result<(), Error> {
        // System transaction - operations can be empty
        // Validation of individual operations is done at the protocol level
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteTransactionBody {
    #[serde(rename = "Hash")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hash: Option<Vec<u8>>,
}

impl RemoteTransactionBody {
    pub fn validate(&self) -> Result<(), Error> {
        // If hash is provided, it should be 32 bytes (SHA-256)
        if let Some(ref hash) = self.hash {
            if hash.len() != 32 {
                return Err(ValidationError::InvalidHash {
                    expected: 32,
                    actual: hash.len(),
                }.into());
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SendTokensBody {
    #[serde(rename = "Hash")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hash: Option<Vec<u8>>,
    #[serde(rename = "Meta")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<serde_json::Value>,
    #[serde(rename = "To")]
    pub to: Vec<serde_json::Value>,
}

impl SendTokensBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Must have at least one recipient
        if self.to.is_empty() {
            return Err(ValidationError::EmptyCollection(
                "to: at least one recipient is required".to_string()
            ).into());
        }

        // Each recipient should be a valid object with url and amount
        for (i, recipient) in self.to.iter().enumerate() {
            if !recipient.is_object() {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("to[{}]", i),
                    reason: "each recipient must be a valid object with url and amount".to_string(),
                }.into());
            }

            // Validate url field if present
            if let Some(url) = recipient.get("url").and_then(|v| v.as_str()) {
                validate_accumulate_url(url, &format!("to[{}].url", i))?;
            }

            // Validate amount field if present
            if let Some(amount) = recipient.get("amount").and_then(|v| v.as_str()) {
                validate_amount_string(amount, &format!("to[{}].amount", i))?;
            }
        }

        // If hash is provided, it should be 32 bytes
        if let Some(ref hash) = self.hash {
            if hash.len() != 32 {
                return Err(ValidationError::InvalidHash {
                    expected: 32,
                    actual: hash.len(),
                }.into());
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SystemGenesisBody {
    // No fields defined
}

impl SystemGenesisBody {
    pub fn validate(&self) -> Result<(), Error> {
        // System transaction - no fields to validate
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SystemWriteDataBody {
    #[serde(rename = "Entry")]
    pub entry: serde_json::Value,
    #[serde(rename = "WriteToState")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_to_state: Option<bool>,
}

impl SystemWriteDataBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Entry must be a valid object
        if !self.entry.is_object() {
            return Err(ValidationError::InvalidFieldValue {
                field: "entry".to_string(),
                reason: "entry must be a valid data entry object".to_string(),
            }.into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TransferCreditsBody {
    #[serde(rename = "To")]
    pub to: Vec<serde_json::Value>,
}

impl TransferCreditsBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Must have at least one recipient
        if self.to.is_empty() {
            return Err(ValidationError::EmptyCollection(
                "to: at least one credit recipient is required".to_string()
            ).into());
        }

        // Each recipient should be a valid object
        for (i, recipient) in self.to.iter().enumerate() {
            if !recipient.is_object() {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("to[{}]", i),
                    reason: "each recipient must be a valid object with url and amount".to_string(),
                }.into());
            }

            // Validate url field if present
            if let Some(url) = recipient.get("url").and_then(|v| v.as_str()) {
                validate_accumulate_url(url, &format!("to[{}].url", i))?;
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAccountAuthBody {
    #[serde(rename = "Operations")]
    pub operations: Vec<serde_json::Value>,
}

impl UpdateAccountAuthBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Must have at least one operation
        if self.operations.is_empty() {
            return Err(ValidationError::EmptyCollection(
                "operations: at least one auth operation is required".to_string()
            ).into());
        }

        // Each operation should be a valid object
        for (i, op) in self.operations.iter().enumerate() {
            if !op.is_object() {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("operations[{}]", i),
                    reason: "each operation must be a valid auth operation object".to_string(),
                }.into());
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateKeyBody {
    #[serde(rename = "NewKeyHash")]
    #[serde(with = "hex::serde")]
    pub new_key_hash: Vec<u8>,
}

impl UpdateKeyBody {
    pub fn validate(&self) -> Result<(), Error> {
        // New key hash must be 32 bytes (SHA-256)
        if self.new_key_hash.len() != 32 {
            return Err(ValidationError::InvalidHash {
                expected: 32,
                actual: self.new_key_hash.len(),
            }.into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateKeyPageBody {
    #[serde(rename = "Operation")]
    pub operation: Vec<serde_json::Value>,
}

impl UpdateKeyPageBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Must have at least one operation
        if self.operation.is_empty() {
            return Err(ValidationError::EmptyCollection(
                "operation: at least one key page operation is required".to_string()
            ).into());
        }

        // Each operation should be a valid object
        for (i, op) in self.operation.iter().enumerate() {
            if !op.is_object() {
                return Err(ValidationError::InvalidFieldValue {
                    field: format!("operation[{}]", i),
                    reason: "each operation must be a valid key page operation object".to_string(),
                }.into());
            }
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteDataBody {
    #[serde(rename = "Entry")]
    pub entry: serde_json::Value,
    #[serde(rename = "Scratch")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scratch: Option<bool>,
    #[serde(rename = "WriteToState")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub write_to_state: Option<bool>,
}

impl WriteDataBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Entry must be a valid object
        if !self.entry.is_object() {
            return Err(ValidationError::InvalidFieldValue {
                field: "entry".to_string(),
                reason: "entry must be a valid data entry object".to_string(),
            }.into());
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteDataToBody {
    #[serde(rename = "Recipient")]
    pub recipient: String,
    #[serde(rename = "Entry")]
    pub entry: serde_json::Value,
}

impl WriteDataToBody {
    pub fn validate(&self) -> Result<(), Error> {
        // Recipient must be a valid Accumulate URL
        validate_accumulate_url(&self.recipient, "recipient")?;

        // Entry must be a valid object
        if !self.entry.is_object() {
            return Err(ValidationError::InvalidFieldValue {
                field: "entry".to_string(),
                reason: "entry must be a valid data entry object".to_string(),
            }.into());
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum TransactionBody {
    #[serde(rename = "acmeFaucet")]
    AcmeFaucet(AcmeFaucetBody),
    #[serde(rename = "activateProtocolVersion")]
    ActivateProtocolVersion(ActivateProtocolVersionBody),
    #[serde(rename = "addCredits")]
    AddCredits(AddCreditsBody),
    #[serde(rename = "blockValidatorAnchor")]
    BlockValidatorAnchor(BlockValidatorAnchorBody),
    #[serde(rename = "burnCredits")]
    BurnCredits(BurnCreditsBody),
    #[serde(rename = "burnTokens")]
    BurnTokens(BurnTokensBody),
    #[serde(rename = "createDataAccount")]
    CreateDataAccount(CreateDataAccountBody),
    #[serde(rename = "createIdentity")]
    CreateIdentity(CreateIdentityBody),
    #[serde(rename = "createKeyBook")]
    CreateKeyBook(CreateKeyBookBody),
    #[serde(rename = "createKeyPage")]
    CreateKeyPage(CreateKeyPageBody),
    #[serde(rename = "createLiteTokenAccount")]
    CreateLiteTokenAccount(CreateLiteTokenAccountBody),
    #[serde(rename = "createToken")]
    CreateToken(CreateTokenBody),
    #[serde(rename = "createTokenAccount")]
    CreateTokenAccount(CreateTokenAccountBody),
    #[serde(rename = "directoryAnchor")]
    DirectoryAnchor(DirectoryAnchorBody),
    #[serde(rename = "issueTokens")]
    IssueTokens(IssueTokensBody),
    #[serde(rename = "lockAccount")]
    LockAccount(LockAccountBody),
    #[serde(rename = "networkMaintenance")]
    NetworkMaintenance(NetworkMaintenanceBody),
    #[serde(rename = "remoteTransaction")]
    RemoteTransaction(RemoteTransactionBody),
    #[serde(rename = "sendTokens")]
    SendTokens(SendTokensBody),
    #[serde(rename = "systemGenesis")]
    SystemGenesis(SystemGenesisBody),
    #[serde(rename = "systemWriteData")]
    SystemWriteData(SystemWriteDataBody),
    #[serde(rename = "transferCredits")]
    TransferCredits(TransferCreditsBody),
    #[serde(rename = "updateAccountAuth")]
    UpdateAccountAuth(UpdateAccountAuthBody),
    #[serde(rename = "updateKey")]
    UpdateKey(UpdateKeyBody),
    #[serde(rename = "updateKeyPage")]
    UpdateKeyPage(UpdateKeyPageBody),
    #[serde(rename = "writeData")]
    WriteData(WriteDataBody),
    #[serde(rename = "writeDataTo")]
    WriteDataTo(WriteDataToBody),
}

impl TransactionBody {
    pub fn validate(&self) -> Result<(), Error> {
        match self {
            TransactionBody::AcmeFaucet(b) => b.validate(),
            TransactionBody::ActivateProtocolVersion(b) => b.validate(),
            TransactionBody::AddCredits(b) => b.validate(),
            TransactionBody::BlockValidatorAnchor(b) => b.validate(),
            TransactionBody::BurnCredits(b) => b.validate(),
            TransactionBody::BurnTokens(b) => b.validate(),
            TransactionBody::CreateDataAccount(b) => b.validate(),
            TransactionBody::CreateIdentity(b) => b.validate(),
            TransactionBody::CreateKeyBook(b) => b.validate(),
            TransactionBody::CreateKeyPage(b) => b.validate(),
            TransactionBody::CreateLiteTokenAccount(b) => b.validate(),
            TransactionBody::CreateToken(b) => b.validate(),
            TransactionBody::CreateTokenAccount(b) => b.validate(),
            TransactionBody::DirectoryAnchor(b) => b.validate(),
            TransactionBody::IssueTokens(b) => b.validate(),
            TransactionBody::LockAccount(b) => b.validate(),
            TransactionBody::NetworkMaintenance(b) => b.validate(),
            TransactionBody::RemoteTransaction(b) => b.validate(),
            TransactionBody::SendTokens(b) => b.validate(),
            TransactionBody::SystemGenesis(b) => b.validate(),
            TransactionBody::SystemWriteData(b) => b.validate(),
            TransactionBody::TransferCredits(b) => b.validate(),
            TransactionBody::UpdateAccountAuth(b) => b.validate(),
            TransactionBody::UpdateKey(b) => b.validate(),
            TransactionBody::UpdateKeyPage(b) => b.validate(),
            TransactionBody::WriteData(b) => b.validate(),
            TransactionBody::WriteDataTo(b) => b.validate(),
        }
    }
}

#[cfg(test)]
pub fn __minimal_tx_body_json(wire_tag: &str) -> serde_json::Value {
    match wire_tag {
        "acmeFaucet" => serde_json::json!({
            "type": "acmeFaucet",
            "Url": ""
        }),
        "activateProtocolVersion" => serde_json::json!({
            "type": "activateProtocolVersion"
        }),
        "addCredits" => serde_json::json!({
            "type": "addCredits",
            "Recipient": "",
            "Amount": "0",
            "Oracle": 0
        }),
        "blockValidatorAnchor" => serde_json::json!({
            "type": "blockValidatorAnchor",
            "AcmeBurnt": "0"
        }),
        "burnCredits" => serde_json::json!({
            "type": "burnCredits",
            "Amount": 0
        }),
        "burnTokens" => serde_json::json!({
            "type": "burnTokens",
            "Amount": "0"
        }),
        "createDataAccount" => serde_json::json!({
            "type": "createDataAccount",
            "Url": ""
        }),
        "createIdentity" => serde_json::json!({
            "type": "createIdentity",
            "Url": ""
        }),
        "createKeyBook" => serde_json::json!({
            "type": "createKeyBook",
            "Url": "",
            "PublicKeyHash": "00"
        }),
        "createKeyPage" => serde_json::json!({
            "type": "createKeyPage",
            "Keys": []
        }),
        "createLiteTokenAccount" => serde_json::json!({
            "type": "createLiteTokenAccount"
        }),
        "createToken" => serde_json::json!({
            "type": "createToken",
            "Url": "",
            "Symbol": "",
            "Precision": 0
        }),
        "createTokenAccount" => serde_json::json!({
            "type": "createTokenAccount",
            "Url": "",
            "TokenUrl": ""
        }),
        "directoryAnchor" => serde_json::json!({
            "type": "directoryAnchor",
            "Updates": [],
            "Receipts": [],
            "MakeMajorBlock": 0,
            "MakeMajorBlockTime": {}
        }),
        "issueTokens" => serde_json::json!({
            "type": "issueTokens",
            "Recipient": "",
            "Amount": "0",
            "To": []
        }),
        "lockAccount" => serde_json::json!({
            "type": "lockAccount",
            "Height": 0
        }),
        "networkMaintenance" => serde_json::json!({
            "type": "networkMaintenance",
            "Operations": []
        }),
        "remoteTransaction" => serde_json::json!({
            "type": "remoteTransaction"
        }),
        "sendTokens" => serde_json::json!({
            "type": "sendTokens",
            "To": []
        }),
        "systemGenesis" => serde_json::json!({
            "type": "systemGenesis"
        }),
        "systemWriteData" => serde_json::json!({
            "type": "systemWriteData",
            "Entry": {}
        }),
        "transferCredits" => serde_json::json!({
            "type": "transferCredits",
            "To": []
        }),
        "updateAccountAuth" => serde_json::json!({
            "type": "updateAccountAuth",
            "Operations": []
        }),
        "updateKey" => serde_json::json!({
            "type": "updateKey",
            "NewKeyHash": "00"
        }),
        "updateKeyPage" => serde_json::json!({
            "type": "updateKeyPage",
            "Operation": []
        }),
        "writeData" => serde_json::json!({
            "type": "writeData",
            "Entry": {}
        }),
        "writeDataTo" => serde_json::json!({
            "type": "writeDataTo",
            "Recipient": "",
            "Entry": {}
        }),
        _ => serde_json::json!({"type": wire_tag}),
    }
}

#[cfg(test)]
pub fn __tx_roundtrip_one(wire_tag: &str) -> Result<(), Box<dyn std::error::Error>> {
    let original = __minimal_tx_body_json(wire_tag);
    let body: TransactionBody = serde_json::from_value(original.clone())?;
    let serialized = serde_json::to_value(&body)?;

    if original != serialized {
        return Err(format!("Roundtrip mismatch for {}: original != serialized", wire_tag).into());
    }

    body.validate()?;
    Ok(())
}

#[cfg(test)]
pub fn __test_all_tx_roundtrips() -> Result<(), Box<dyn std::error::Error>> {
        __tx_roundtrip_one("acmeFaucet");
        __tx_roundtrip_one("activateProtocolVersion");
        __tx_roundtrip_one("addCredits");
        __tx_roundtrip_one("blockValidatorAnchor");
        __tx_roundtrip_one("burnCredits");
        __tx_roundtrip_one("burnTokens");
        __tx_roundtrip_one("createDataAccount");
        __tx_roundtrip_one("createIdentity");
        __tx_roundtrip_one("createKeyBook");
        __tx_roundtrip_one("createKeyPage");
        __tx_roundtrip_one("createLiteTokenAccount");
        __tx_roundtrip_one("createToken");
        __tx_roundtrip_one("createTokenAccount");
        __tx_roundtrip_one("directoryAnchor");
        __tx_roundtrip_one("issueTokens");
        __tx_roundtrip_one("lockAccount");
        __tx_roundtrip_one("networkMaintenance");
        __tx_roundtrip_one("remoteTransaction");
        __tx_roundtrip_one("sendTokens");
        __tx_roundtrip_one("systemGenesis");
        __tx_roundtrip_one("systemWriteData");
        __tx_roundtrip_one("transferCredits");
        __tx_roundtrip_one("updateAccountAuth");
        __tx_roundtrip_one("updateKey");
        __tx_roundtrip_one("updateKeyPage");
        __tx_roundtrip_one("writeData");
        __tx_roundtrip_one("writeDataTo");
    Ok(())
}