xrpl-rust 1.2.0

A 100% Rust library to interact with the XRPL
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
pub mod account_delete;
pub mod account_set;
pub mod amm_bid;
pub mod amm_create;
pub mod amm_delete;
pub mod amm_deposit;
pub mod amm_vote;
pub mod amm_withdraw;
pub mod check_cancel;
pub mod check_cash;
pub mod check_create;
pub mod clawback;
pub mod credential_accept;
pub mod credential_create;
pub mod credential_delete;
pub mod deposit_preauth;
pub mod did_delete;
pub mod did_set;
pub mod escrow_cancel;
pub mod escrow_create;
pub mod escrow_finish;
pub mod exceptions;
pub mod metadata;
pub mod mptoken_authorize;
pub mod mptoken_issuance_create;
pub mod mptoken_issuance_destroy;
pub mod mptoken_issuance_set;
pub mod nftoken_accept_offer;
pub mod nftoken_burn;
pub mod nftoken_cancel_offer;
pub mod nftoken_create_offer;
pub mod nftoken_mint;
pub mod offer_cancel;
pub mod offer_create;
pub mod oracle_delete;
pub mod oracle_set;
pub mod payment;
pub mod payment_channel_claim;
pub mod payment_channel_create;
pub mod payment_channel_fund;
pub mod pseudo_transactions;
pub mod set_regular_key;
pub mod signer_list_set;
pub mod ticket_create;
pub mod trust_set;
pub mod vault_clawback;
pub(crate) mod vault_common;
pub mod vault_create;
pub mod vault_delete;
pub mod vault_deposit;
pub mod vault_set;
pub mod vault_withdraw;
pub mod xchain_account_create_commit;
pub mod xchain_add_account_create_attestation;
pub mod xchain_add_claim_attestation;
pub mod xchain_claim;
pub mod xchain_commit;
pub mod xchain_create_bridge;
pub mod xchain_create_claim_id;
pub mod xchain_modify_bridge;

use super::{FlagCollection, XRPLModelException, XRPLModelResult};
use crate::core::binarycodec::encode;
use crate::models::amount::XRPAmount;
use crate::{_serde::txn_flags, serde_with_tag};
use alloc::borrow::Cow;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt::Debug;
use core::str::FromStr;
use derive_new::new;
use exceptions::XRPLTransactionException;
use serde::de::DeserializeOwned;
use serde::ser::SerializeMap;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use sha2::{Digest, Sha512};
use strum::IntoEnumIterator;
use strum_macros::{AsRefStr, Display};

const TRANSACTION_HASH_PREFIX: u32 = 0x54584E00;

fn is_hex(value: &str) -> bool {
    value.chars().all(|c| c.is_ascii_hexdigit())
}

/// Validate that a `CredentialType` field is a non-empty hex string up to 64 bytes (128 hex chars).
///
/// Note: rippled accepts any arbitrary blob up to 64 bytes for `CredentialType` and does not
/// enforce hex encoding at the protocol level (`kMaxCredentialTypeLength` in `Protocol.h`).
/// This SDK enforces hex intentionally to match xrpl.js (`validateCredentialType` in `common.ts`),
/// providing an extra client-side guard before a transaction reaches the network.
pub(crate) fn validate_credential_type(credential_type: &str) -> XRPLModelResult<()> {
    let len = credential_type.len();
    if len == 0 {
        Err(XRPLModelException::ValueTooShort {
            field: "credential_type".into(),
            min: 1,
            found: 0,
        })
    } else if len > 128 {
        Err(XRPLModelException::ValueTooLong {
            field: "credential_type".into(),
            max: 128,
            found: len,
        })
    } else if !len.is_multiple_of(2) {
        // Odd-length hex strings cannot represent whole bytes; rippled's binary
        // codec would reject them at serialization time.
        Err(XRPLModelException::InvalidValueFormat {
            field: "credential_type".into(),
            format: "even-length hexadecimal (whole bytes)".into(),
            found: credential_type.into(),
        })
    } else if !is_hex(credential_type) {
        Err(XRPLModelException::InvalidValueFormat {
            field: "credential_type".into(),
            format: "hexadecimal".into(),
            found: credential_type.into(),
        })
    } else {
        Ok(())
    }
}

/// Validate that a hex-encoded string contains only hexadecimal characters.
fn validate_hex(field: &str, value: &str) -> XRPLModelResult<()> {
    if !is_hex(value) {
        Err(XRPLModelException::InvalidValueFormat {
            field: field.into(),
            format: "hexadecimal".into(),
            found: value.into(),
        })
    } else {
        Ok(())
    }
}

/// Validate that a `credential_ids` field, when present, contains 1..=8 unique entries
/// as required by the XLS-70 specification (sections 8.1 and 8.2).
pub fn validate_credential_ids(credential_ids: &Option<Vec<Cow<'_, str>>>) -> XRPLModelResult<()> {
    if let Some(ids) = credential_ids {
        if ids.is_empty() {
            return Err(XRPLModelException::ValueTooShort {
                field: "credential_ids".into(),
                min: 1,
                found: 0,
            });
        }
        if ids.len() > 8 {
            return Err(XRPLModelException::ValueTooLong {
                field: "credential_ids".into(),
                max: 8,
                found: ids.len(),
            });
        }
        for (i, id) in ids.iter().enumerate() {
            validate_hex("credential_ids", id)?;
            // Credential IDs are SHA-512Half ledger-object hashes: 256 bits = 32 bytes = 64 hex chars.
            if id.len() != 64 {
                return Err(XRPLModelException::InvalidValueFormat {
                    field: "credential_ids".into(),
                    format: "64-character hexadecimal ledger-object hash".into(),
                    found: id.as_ref().into(),
                });
            }
            // Hex credential IDs are compared case-insensitively: rippled normalizes
            // the raw bytes, so "ABCD" and "abcd" refer to the same credential.
            if ids[..i].iter().any(|prev| prev.eq_ignore_ascii_case(id)) {
                return Err(XRPLModelException::ValueEqualsValue {
                    field1: "credential_ids".into(),
                    field2: "credential_ids (duplicate entry)".into(),
                });
            }
        }
    }
    Ok(())
}

/// Enum containing the different Transaction types.
#[derive(Debug, Clone, Serialize, Deserialize, Display, PartialEq, Eq, Default)]
pub enum TransactionType {
    AccountDelete,
    AccountSet,
    AMMBid,
    AMMCreate,
    AMMDelete,
    AMMDeposit,
    AMMVote,
    AMMWithdraw,
    CheckCancel,
    CheckCash,
    CheckCreate,
    Clawback,
    DIDDelete,
    DIDSet,
    CredentialAccept,
    CredentialCreate,
    CredentialDelete,
    DepositPreauth,
    EscrowCancel,
    EscrowCreate,
    EscrowFinish,
    MPTokenAuthorize,
    MPTokenIssuanceCreate,
    MPTokenIssuanceDestroy,
    MPTokenIssuanceSet,
    NFTokenAcceptOffer,
    NFTokenBurn,
    NFTokenCancelOffer,
    NFTokenCreateOffer,
    NFTokenMint,
    OfferCancel,
    OfferCreate,
    OracleDelete,
    OracleSet,
    #[default]
    Payment,
    PaymentChannelClaim,
    PaymentChannelCreate,
    PaymentChannelFund,
    SetRegularKey,
    SignerListSet,
    TicketCreate,
    TrustSet,
    VaultClawback,
    VaultCreate,
    VaultDelete,
    VaultDeposit,
    VaultSet,
    VaultWithdraw,
    XChainAccountCreateCommit,
    XChainAddAccountCreateAttestation,
    XChainAddClaimAttestation,
    XChainClaim,
    XChainCommit,
    XChainCreateBridge,
    XChainCreateClaimID,
    XChainModifyBridge,
    // Psuedo-Transaction types,
    EnableAmendment,
    SetFee,
    UNLModify,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, new)]
#[serde(rename_all = "PascalCase")]
pub struct PreparedTransaction<'a, T> {
    #[serde(flatten)]
    pub transaction: T,
    /// Hex representation of the public key that corresponds to the
    /// private key used to sign this transaction. If an empty string,
    /// indicates a multi-signature is present in the Signers field instead.
    pub signing_pub_key: Cow<'a, str>,
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone, new)]
#[serde(rename_all = "PascalCase")]
pub struct SignedTransaction<'a, T> {
    #[serde(flatten)]
    pub prepared_transaction: PreparedTransaction<'a, T>,
    /// The signature that verifies this transaction as originating
    /// from the account it says it is from.
    pub txn_signature: Cow<'a, str>,
}

/// The base fields for all transaction models.
///
/// See Transaction Common Fields:
/// `<https://xrpl.org/transaction-common-fields.html>`
#[skip_serializing_none]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Clone)]
#[serde(rename_all = "PascalCase")]
pub struct CommonFields<'a, F>
where
    F: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    /// The unique address of the account that initiated the transaction.
    pub account: Cow<'a, str>,
    /// The type of transaction.
    ///
    /// See Transaction Types:
    /// `<https://xrpl.org/transaction-types.html>`
    pub transaction_type: TransactionType,
    /// Hash value identifying another transaction. If provided, this
    /// transaction is only valid if the sending account's
    /// previously-sent transaction matches the provided hash.
    #[serde(rename = "AccountTxnID")]
    pub account_txn_id: Option<Cow<'a, str>>,
    /// Integer amount of XRP, in drops, to be destroyed as a cost
    /// for distributing this transaction to the network. Some
    /// transaction types have different minimum requirements.
    /// See Transaction Cost for details.
    pub fee: Option<XRPAmount<'a>>,
    /// Set of bit-flags for this transaction.
    #[serde(with = "txn_flags")]
    #[serde(default = "flag_collection_default")]
    pub flags: FlagCollection<F>,
    /// Highest ledger index this transaction can appear in.
    /// Specifying this field places a strict upper limit on how long
    /// the transaction can wait to be validated or rejected.
    /// See Reliable Transaction Submission for more details.
    pub last_ledger_sequence: Option<u32>,
    /// Additional arbitrary information used to identify this transaction.
    pub memos: Option<Vec<Memo>>,
    /// The network ID of the chain this transaction is intended for.
    /// MUST BE OMITTED for Mainnet and some test networks.
    /// REQUIRED on chains whose network ID is 1025 or higher.
    #[serde(rename = "NetworkID")]
    pub network_id: Option<u32>,
    /// The sequence number of the account sending the transaction.
    /// A transaction is only valid if the Sequence number is exactly
    /// 1 greater than the previous transaction from the same account.
    /// The special case 0 means the transaction is using a Ticket instead.
    pub sequence: Option<u32>,
    /// Arbitrary integer used to identify the reason for this
    /// payment, or a sender on whose behalf this transaction is
    /// made. Conventionally, a refund should specify the initial
    /// payment's SourceTag as the refund payment's DestinationTag.
    pub signers: Option<Vec<Signer>>,
    /// Hex representation of the public key that corresponds to the
    /// private key used to sign this transaction. If an empty string,
    /// indicates a multi-signature is present in the Signers field instead.
    pub signing_pub_key: Option<Cow<'a, str>>,
    /// Arbitrary integer used to identify the reason for this
    /// payment, or a sender on whose behalf this transaction
    /// is made. Conventionally, a refund should specify the initial
    /// payment's SourceTag as the refund payment's DestinationTag.
    pub source_tag: Option<u32>,
    /// The sequence number of the ticket to use in place
    /// of a Sequence number. If this is provided, Sequence must
    /// be 0. Cannot be used with AccountTxnID.
    pub ticket_sequence: Option<u32>,
    /// The signature that verifies this transaction as originating
    /// from the account it says it is from.
    pub txn_signature: Option<Cow<'a, str>>,
}

impl<'a, T> CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    pub fn new(
        account: Cow<'a, str>,
        transaction_type: TransactionType,
        account_txn_id: Option<Cow<'a, str>>,
        fee: Option<XRPAmount<'a>>,
        flags: Option<FlagCollection<T>>,
        last_ledger_sequence: Option<u32>,
        memos: Option<Vec<Memo>>,
        network_id: Option<u32>,
        sequence: Option<u32>,
        signers: Option<Vec<Signer>>,
        signing_pub_key: Option<Cow<'a, str>>,
        source_tag: Option<u32>,
        ticket_sequence: Option<u32>,
        txn_signature: Option<Cow<'a, str>>,
    ) -> Self {
        CommonFields {
            account,
            transaction_type,
            account_txn_id,
            fee,
            flags: flags.unwrap_or_default(),
            last_ledger_sequence,
            memos,
            network_id,
            sequence,
            signers,
            signing_pub_key: Some(signing_pub_key.unwrap_or("".into())),
            source_tag,
            ticket_sequence,
            txn_signature,
        }
    }

    /// Add a flag
    pub fn with_flag(mut self, flag: T) -> Self {
        self.flags.0.push(flag);
        self
    }

    /// Set multiple flags
    pub fn with_flags(mut self, flags: Vec<T>) -> Self {
        self.flags = flags.into();
        self
    }

    /// Add a signer
    pub fn with_signer(mut self, signer: Signer) -> Self {
        if let Some(ref mut signers) = self.signers {
            signers.push(signer);
        } else {
            self.signers = Some(alloc::vec![signer]);
        }
        self
    }
}

impl<T> CommonFields<'_, T>
where
    T: IntoEnumIterator + Serialize + Debug + PartialEq + Clone,
{
    pub fn is_signed(&self) -> bool {
        if let Some(signers) = &self.signers {
            signers.iter().all(|signer| {
                !signer.txn_signature.is_empty() && !signer.signing_pub_key.is_empty()
            })
        } else {
            self.txn_signature.is_some() && self.signing_pub_key.is_some()
        }
    }
}

impl<'a, T> Transaction<'a, T> for CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + PartialEq + core::fmt::Debug,
{
    fn has_flag(&self, flag: &T) -> bool {
        self.flags.0.contains(flag)
    }

    fn get_transaction_type(&self) -> &TransactionType {
        &self.transaction_type
    }

    fn get_common_fields(&self) -> &CommonFields<'_, T> {
        self
    }

    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, T> {
        self
    }
}

impl<'a, T> Default for CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    fn default() -> Self {
        Self {
            account: "".into(),
            transaction_type: TransactionType::Payment, // Temporary default, will be overridden
            account_txn_id: None,
            fee: None,
            flags: FlagCollection::default(),
            last_ledger_sequence: None,
            memos: None,
            network_id: None,
            sequence: None,
            signers: None,
            signing_pub_key: None,
            source_tag: None,
            ticket_sequence: None,
            txn_signature: None,
        }
    }
}

/// A trait providing common builder methods for all transaction types.
/// This eliminates code duplication across transaction implementations.
pub trait CommonTransactionBuilder<'a, F>
where
    F: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    /// Get mutable reference to common fields
    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, F>;

    /// Return self after modification (for method chaining)
    fn into_self(self) -> Self;

    /// Set fee
    fn with_fee(mut self, fee: XRPAmount<'a>) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().fee = Some(fee);
        self.into_self()
    }

    /// Set sequence
    fn with_sequence(mut self, sequence: u32) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().sequence = Some(sequence);
        self.into_self()
    }

    /// Set last ledger sequence
    fn with_last_ledger_sequence(mut self, last_ledger_sequence: u32) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().last_ledger_sequence = Some(last_ledger_sequence);
        self.into_self()
    }

    /// Add memo
    fn with_memo(mut self, memo: Memo) -> Self
    where
        Self: Sized,
    {
        let common_fields = self.get_mut_common_fields();
        if let Some(ref mut memos) = common_fields.memos {
            memos.push(memo);
        } else {
            common_fields.memos = Some(alloc::vec![memo]);
        }
        self.into_self()
    }

    /// Set source tag
    fn with_source_tag(mut self, source_tag: u32) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().source_tag = Some(source_tag);
        self.into_self()
    }

    /// Set ticket sequence
    fn with_ticket_sequence(mut self, ticket_sequence: u32) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().ticket_sequence = Some(ticket_sequence);
        self.into_self()
    }

    /// Set account transaction ID
    fn with_account_txn_id(mut self, account_txn_id: Cow<'a, str>) -> Self
    where
        Self: Sized,
    {
        self.get_mut_common_fields().account_txn_id = Some(account_txn_id);
        self.into_self()
    }
}

impl<'a, T> FromStr for CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    type Err = core::convert::Infallible;

    fn from_str(account: &str) -> Result<Self, Self::Err> {
        Ok(Self {
            account: Cow::Owned(account.to_string()),
            ..Default::default()
        })
    }
}

impl<'a, T> From<String> for CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    fn from(account: String) -> Self {
        Self {
            account: account.into(),
            ..Default::default()
        }
    }
}

impl<'a, T> From<Cow<'a, str>> for CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    fn from(account: Cow<'a, str>) -> Self {
        Self {
            account,
            ..Default::default()
        }
    }
}

impl<'a, T> CommonFields<'a, T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    pub fn with_transaction_type(mut self, transaction_type: TransactionType) -> Self {
        self.transaction_type = transaction_type;
        self
    }

    pub fn with_fee(mut self, fee: XRPAmount<'a>) -> Self {
        self.fee = Some(fee);
        self
    }

    pub fn with_sequence(mut self, sequence: u32) -> Self {
        self.sequence = Some(sequence);
        self
    }

    pub fn with_last_ledger_sequence(mut self, last_ledger_sequence: u32) -> Self {
        self.last_ledger_sequence = Some(last_ledger_sequence);
        self
    }

    pub fn with_source_tag(mut self, source_tag: u32) -> Self {
        self.source_tag = Some(source_tag);
        self
    }

    pub fn with_memo(mut self, memo: Memo) -> Self {
        match self.memos {
            Some(ref mut memos) => memos.push(memo),
            None => self.memos = Some(alloc::vec![memo]),
        }
        self
    }

    pub fn with_memos(mut self, memos: Vec<Memo>) -> Self {
        self.memos = Some(memos);
        self
    }

    pub fn with_network_id(mut self, network_id: u32) -> Self {
        self.network_id = Some(network_id);
        self
    }

    pub fn with_ticket_sequence(mut self, ticket_sequence: u32) -> Self {
        self.ticket_sequence = Some(ticket_sequence);
        self
    }

    pub fn with_account_txn_id(mut self, account_txn_id: Cow<'a, str>) -> Self {
        self.account_txn_id = Some(account_txn_id);
        self
    }

    pub fn with_signers(mut self, signers: Vec<Signer>) -> Self {
        self.signers = Some(signers);
        self
    }

    pub fn with_signing_pub_key(mut self, signing_pub_key: Cow<'a, str>) -> Self {
        self.signing_pub_key = Some(signing_pub_key);
        self
    }

    pub fn with_txn_signature(mut self, txn_signature: Cow<'a, str>) -> Self {
        self.txn_signature = Some(txn_signature);
        self
    }

    /// Create CommonFields from an account string (takes ownership)
    pub fn from_account(account: impl Into<Cow<'a, str>>) -> Self {
        Self {
            account: account.into(),
            ..Default::default()
        }
    }
}

fn flag_collection_default<T>() -> FlagCollection<T>
where
    T: IntoEnumIterator + Serialize + core::fmt::Debug,
{
    FlagCollection::<T>::default()
}

serde_with_tag! {
/// An arbitrary piece of data attached to a transaction. A
/// transaction can have multiple Memo objects as an array
/// in the Memos field.
///
/// Must contain one or more of `memo_data`, `memo_format`,
/// and `memo_type`.
///
/// See Memos Field:
/// `<https://xrpl.org/transaction-common-fields.html#memos-field>`
// `#[derive(Serialize)]` is defined in the macro
#[derive(Debug, PartialEq, Eq, Default, Clone, new)]
pub struct Memo {
    pub memo_data: Option<String>,
    pub memo_format: Option<String>,
    pub memo_type: Option<String>,
}
}

serde_with_tag! {
    /// Represents one entry in a list of AuthAccounts used in AMMBid transaction.
    #[derive(Debug, Clone, PartialEq, Eq, new)]
    pub struct AuthAccount {
        pub account: String,
    }
}

serde_with_tag! {
/// One Signer in a multi-signature. A multi-signed transaction
/// can have an array of up to 8 Signers, each contributing a
/// signature, in the Signers field.
///
/// See Signers Field:
/// `<https://xrpl.org/transaction-common-fields.html#signers-field>`
#[derive(Debug, PartialEq, Eq, Default, Clone, new)]
pub struct Signer {
    pub account: String,
    pub txn_signature: String,
    pub signing_pub_key: String,
}
}

serde_with_tag! {
/// Represents a single price data entry in an Oracle's PriceDataSeries.
///
/// See OracleSet:
/// `<https://xrpl.org/docs/references/protocol/transactions/types/oracleset>`
#[derive(Debug, PartialEq, Eq, Clone, Default)]
pub struct PriceData {
    pub base_asset: String,
    pub quote_asset: String,
    /// The token pair's price. When omitted on an OracleSet update, rippled
    /// deletes the existing price data entry for this base/quote pair.
    pub asset_price: Option<String>,
    /// Decimal scale factor. Actual price = asset_price × 10^(−scale). Range 0–20.
    /// Must be present when asset_price is present, and absent when asset_price is absent.
    pub scale: Option<u8>,
}
}

/// Maximum allowed value for the `scale` field of a `PriceData` entry.
pub const MAX_PRICE_DATA_SCALE: u8 = 20;

impl crate::models::Model for PriceData {
    fn get_errors(&self) -> crate::models::XRPLModelResult<()> {
        if let Some(scale) = self.scale {
            if scale > MAX_PRICE_DATA_SCALE {
                return Err(crate::models::XRPLModelException::ValueTooHigh {
                    field: "scale".into(),
                    max: MAX_PRICE_DATA_SCALE as u32,
                    found: scale as u32,
                });
            }
        }
        if self.asset_price.is_some() != self.scale.is_some() {
            return Err(crate::models::XRPLModelException::InvalidValue {
                field: "price_data".into(),
                expected: "AssetPrice and Scale both present or both omitted".into(),
                found: alloc::format!(
                    "asset_price_present={}, scale_present={}",
                    self.asset_price.is_some(),
                    self.scale.is_some()
                ),
            });
        }
        validate_oracle_currency("base_asset", &self.base_asset)?;
        validate_oracle_currency("quote_asset", &self.quote_asset)?;
        validate_oracle_asset_price(&self.asset_price)?;
        Ok(())
    }
}

/// Maximum allowed value for `AssetPrice`.
pub const MAX_ORACLE_ASSET_PRICE: u64 = u64::MAX;

fn validate_oracle_currency(
    field: &'static str,
    value: &str,
) -> crate::models::XRPLModelResult<()> {
    if crate::utils::is_iso_code(value) || crate::utils::is_iso_hex(value) {
        return Ok(());
    }
    Err(crate::models::XRPLModelException::InvalidValue {
        field: field.into(),
        expected: "a 3-character ISO currency code (including \"XRP\") or 40-character hex code"
            .into(),
        found: value.into(),
    })
}

fn validate_oracle_asset_price(value: &Option<String>) -> crate::models::XRPLModelResult<()> {
    let Some(value) = value else {
        return Ok(());
    };
    match u64::from_str_radix(value, 16) {
        Ok(_) => Ok(()),
        Err(_) => Err(crate::models::XRPLModelException::InvalidValue {
            field: "asset_price".into(),
            expected: "a valid UInt64 hexadecimal string (0x0000000000000000..=0xFFFFFFFFFFFFFFFF)"
                .into(),
            found: value.clone(),
        }),
    }
}

/// Standard functions for transactions.
pub trait Transaction<'a, T>
where
    Self: Serialize,
    T: IntoEnumIterator + Serialize + Debug + PartialEq,
{
    fn has_flag(&self, flag: &T) -> bool {
        let _txn_flag = flag;
        false
    }

    fn get_transaction_type(&self) -> &TransactionType;

    fn get_common_fields(&self) -> &CommonFields<'_, T>;

    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, T>;

    fn get_field_value(&self, field: &str) -> XRPLModelResult<Option<String>> {
        let value = serde_json::to_value(self)?;

        Ok(value.get(field).map(|v| v.to_string()))
    }

    fn is_signed(&self) -> bool {
        self.get_common_fields().txn_signature.is_some()
            && self.get_common_fields().signing_pub_key.is_some()
    }

    /// Hashes the Transaction object as the ledger does. Only valid for signed
    /// Transaction objects.
    fn get_hash(&self) -> XRPLModelResult<Cow<'_, str>>
    where
        Self: Serialize + DeserializeOwned + Debug + Clone,
    {
        if self.get_common_fields().txn_signature.is_none()
            && self.get_common_fields().signers.is_none()
        {
            return Err(XRPLTransactionException::TxMustBeSigned.into());
        }
        let prefix = format!("{:X}", TRANSACTION_HASH_PREFIX);
        let tx_hex = encode(self).map_err(XRPLTransactionException::XRPLCoreError)?;
        let tx_hex = prefix + &tx_hex;
        let tx_bytes = hex::decode(&tx_hex)?;
        let mut hasher = Sha512::new();
        hasher.update(&tx_bytes);
        let hash = hasher.finalize();
        let hex_string = hex::encode_upper(hash);
        let result = hex_string[..64].to_string();

        Ok(result.into())
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, Display, AsRefStr)]
pub enum Flag {
    AccountSet(account_set::AccountSetFlag),
    NFTokenCreateOffer(nftoken_create_offer::NFTokenCreateOfferFlag),
    NFTokenMint(nftoken_mint::NFTokenMintFlag),
    OfferCreate(offer_create::OfferCreateFlag),
    Payment(payment::PaymentFlag),
    PaymentChannelClaim(payment_channel_claim::PaymentChannelClaimFlag),
    TrustSet(trust_set::TrustSetFlag),
    EnableAmendment(pseudo_transactions::enable_amendment::EnableAmendmentFlag),
}

#[cfg(all(
    feature = "std",
    feature = "websocket",
    feature = "models",
    feature = "helpers",
    feature = "wallet"
))]
#[cfg(test)]
mod tests {
    use alloc::borrow::Cow;

    use super::*;
    use crate::models::transactions::payment::PaymentFlag;
    use crate::models::transactions::{account_set::AccountSet, payment::Payment};
    use crate::models::{Amount, XRPAmount};
    use offer_create::OfferCreate;

    #[tokio::test]
    async fn test_get_hash() {
        let txn_json = r#"{
            "Account": "rLyttXLh7Ttca9CMUaD3exVoXY2fn2zwj3",
            "Fee": "10",
            "Flags": 0,
            "LastLedgerSequence": 16409087,
            "Sequence": 16409064,
            "SigningPubKey": "ED93BFA583E83331E9DC498DE4558CE4861ACFAB9385EBBC43BC56A0D9845A1DF2",
            "TakerGets": "13100000",
            "TakerPays": {
                "currency": "USD",
                "issuer": "rLyttXLh7Ttca9CMUaD3exVoXY2fn2zwj3",
                "value": "10"
            },
            "TransactionType": "OfferCreate",
            "TxnSignature": "71135999783658A0CB4EBCF02E59ACD94C4D06D5BF909E05E6B97588155482BBA598535AD4728ACA1F90C4DE73FFC741B0A6AB87141BDA8BCC2F2DF9CD8C3703"
        }"#;
        let expected_hash = "66F3D6158CAB6E53405F8C264DB39F07D8D0454433A63DDFB98218ED1BC99B60";
        let txn: OfferCreate = serde_json::from_str(txn_json).unwrap();

        assert_eq!(&txn.get_hash().unwrap(), expected_hash);
    }

    #[test]
    fn test_txn_hash() {
        let tx_json_str = r#"{
            "Account": "rEbY5Tr5B6AjyjuVRhajpnvCWLGkYk5z6",
            "Domain": "6578616d706c652e636f6d",
            "Fee": "10",
            "Flags": 0,
            "LastLedgerSequence": 596447,
            "Sequence": 596427,
            "SigningPubKey": "EDAF73A0E6745EA9C17A2F4EB7043134A055213116CFF6F7888BBFF557B002874F",
            "TransactionType": "AccountSet",
            "TxnSignature": "8666A7E6AF0D6A4B4F19F25D315FA1C31D132FB2E974686C415D5499D43710384FF851C75CCC4E57972DE5C5354289F574B2F604B6AF15E2DADA6BB9F1330A07"
        }"#;
        let expected_hash = "5B765D6C6058CF54F5DBF6230A7F51E23295004FCC043660A77D73AA8537737B";
        let tx: AccountSet = serde_json::from_str(tx_json_str).unwrap();
        assert_eq!(tx.get_hash().unwrap(), expected_hash);
    }

    #[test]
    fn test_common_fields_default() {
        let common_fields: CommonFields<payment::PaymentFlag> = Default::default();

        assert_eq!(common_fields.account, "");
        assert_eq!(common_fields.transaction_type, TransactionType::Payment);
        assert!(common_fields.fee.is_none());
        assert!(common_fields.sequence.is_none());
        assert!(common_fields.memos.is_none());
    }

    #[test]
    fn test_common_fields_from_str() {
        let account = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH";
        let common_fields: CommonFields<payment::PaymentFlag> = account.parse().unwrap();

        assert_eq!(common_fields.account, account);
        assert_eq!(common_fields.transaction_type, TransactionType::Payment);
        assert!(common_fields.fee.is_none());
    }

    #[test]
    fn test_common_fields_from_string() {
        let account = String::from("rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH");
        let common_fields: CommonFields<payment::PaymentFlag> = CommonFields::from(account.clone());

        assert_eq!(common_fields.account, account);
        assert_eq!(common_fields.transaction_type, TransactionType::Payment);
    }

    #[test]
    fn test_common_fields_from_cow() {
        let account: Cow<str> = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH".into();
        let common_fields: CommonFields<payment::PaymentFlag> = CommonFields::from(account.clone());

        assert_eq!(common_fields.account, account);
    }

    #[test]
    fn test_common_fields_builder_methods() {
        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_transaction_type(TransactionType::Payment)
            .with_fee("12".into())
            .with_sequence(100)
            .with_last_ledger_sequence(596447)
            .with_source_tag(42)
            .with_network_id(1025);

        assert_eq!(common_fields.account, "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH");
        assert_eq!(common_fields.transaction_type, TransactionType::Payment);
        assert_eq!(common_fields.fee, Some("12".into()));
        assert_eq!(common_fields.sequence, Some(100));
        assert_eq!(common_fields.last_ledger_sequence, Some(596447));
        assert_eq!(common_fields.source_tag, Some(42));
        assert_eq!(common_fields.network_id, Some(1025));
    }

    #[test]
    fn test_memo_builder() {
        let memo = Memo {
            memo_data: Some("Test memo".to_string()),
            memo_format: Some("text/plain".to_string()),
            memo_type: Some("test".to_string()),
        };

        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_memo(memo.clone());

        assert_eq!(common_fields.memos, Some(alloc::vec![memo]));
    }

    #[test]
    fn test_multiple_memos_builder() {
        let memo1 = Memo {
            memo_data: Some("First memo".to_string()),
            memo_format: Some("text/plain".to_string()),
            memo_type: Some("info".to_string()),
        };

        let memo2 = Memo {
            memo_data: Some("Second memo".to_string()),
            memo_format: Some("text/plain".to_string()),
            memo_type: Some("note".to_string()),
        };

        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_memo(memo1.clone())
            .with_memo(memo2.clone());

        assert_eq!(common_fields.memos, Some(alloc::vec![memo1, memo2]));
    }

    #[test]
    fn test_memos_builder_replace() {
        let memo1 = Memo {
            memo_data: Some("First memo".to_string()),
            memo_format: None,
            memo_type: None,
        };

        let memo2 = Memo {
            memo_data: Some("Second memo".to_string()),
            memo_format: None,
            memo_type: None,
        };

        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_memo(memo1)
            .with_memos(alloc::vec![memo2.clone()]);

        assert_eq!(common_fields.memos, Some(alloc::vec![memo2]));
    }

    #[test]
    fn test_from_account_helper() {
        let common_fields: CommonFields<payment::PaymentFlag> =
            CommonFields::from_account("rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH");

        assert_eq!(common_fields.account, "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH");
        assert_eq!(common_fields.transaction_type, TransactionType::Payment);
    }

    #[test]
    fn test_signers_builder() {
        let signer = Signer {
            account: "rSignerAccount123".to_string(),
            txn_signature: "signature123".to_string(),
            signing_pub_key: "pubkey123".to_string(),
        };

        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_signers(alloc::vec![signer.clone()]);

        assert_eq!(common_fields.signers, Some(alloc::vec![signer]));
    }

    #[test]
    fn test_signature_fields_builder() {
        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_signing_pub_key("ED12345...".into())
            .with_txn_signature("A1B2C3...".into());

        assert_eq!(common_fields.signing_pub_key, Some("ED12345...".into()));
        assert_eq!(common_fields.txn_signature, Some("A1B2C3...".into()));
    }

    #[test]
    fn test_account_txn_id_builder() {
        let txn_id = "F1E2D3C4B5A69788";
        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_account_txn_id(txn_id.into());

        assert_eq!(common_fields.account_txn_id, Some(txn_id.into()));
    }

    #[test]
    fn test_ticket_sequence_builder() {
        let common_fields = "rN7n7otQDd6FczFgLdSqtcsAUxDkw6fzRH"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_ticket_sequence(50);

        assert_eq!(common_fields.ticket_sequence, Some(50));
    }

    #[test]
    fn test_payment_with_builder_pattern() {
        let payment = Payment {
            common_fields: "rSender123"
                .parse::<CommonFields<payment::PaymentFlag>>()
                .unwrap()
                .with_transaction_type(TransactionType::Payment)
                .with_fee("12".into())
                .with_sequence(100),
            amount: Amount::XRPAmount(XRPAmount::from("1000000")),
            destination: "rReceiver456".into(),
            ..Default::default()
        };

        assert_eq!(payment.common_fields.account, "rSender123");
        assert_eq!(
            payment.common_fields.transaction_type,
            TransactionType::Payment
        );
        assert_eq!(payment.common_fields.fee, Some("12".into()));
        assert_eq!(payment.common_fields.sequence, Some(100));
        assert_eq!(payment.destination, "rReceiver456");
    }

    #[test]
    fn test_account_set_with_builder_pattern() {
        let account_set = AccountSet {
            common_fields: CommonFields::from_account("rAccount123")
                .with_transaction_type(TransactionType::AccountSet)
                .with_fee("12".into())
                .with_sequence(50),
            domain: Some("6578616d706c652e636f6d".into()), // "example.com"
            ..Default::default()
        };

        assert_eq!(account_set.common_fields.account, "rAccount123");
        assert_eq!(
            account_set.common_fields.transaction_type,
            TransactionType::AccountSet
        );
        assert_eq!(account_set.common_fields.fee, Some("12".into()));
        assert_eq!(account_set.common_fields.sequence, Some(50));
        assert_eq!(account_set.domain, Some("6578616d706c652e636f6d".into()));
    }

    #[test]
    fn test_complex_payment_with_memos() {
        let memo = Memo {
            memo_data: Some("Payment for services".to_string()),
            memo_format: Some("text/plain".to_string()),
            memo_type: Some("payment".to_string()),
        };

        let payment = Payment {
            common_fields: "rSender123"
                .parse::<CommonFields<payment::PaymentFlag>>()
                .unwrap()
                .with_transaction_type(TransactionType::Payment)
                .with_fee("12".into())
                .with_sequence(100)
                .with_last_ledger_sequence(596447)
                .with_source_tag(12345)
                .with_memo(memo.clone()),
            amount: Amount::XRPAmount(XRPAmount::from("1000000")),
            destination: "rReceiver456".into(),
            destination_tag: Some(67890),
            ..Default::default()
        };

        assert_eq!(payment.common_fields.memos, Some(alloc::vec![memo]));
        assert_eq!(payment.common_fields.source_tag, Some(12345));
        assert_eq!(payment.destination_tag, Some(67890));
    }

    #[test]
    fn test_builder_pattern_fluency() {
        // Test that the builder pattern is truly fluent and readable
        let payment = Payment {
            common_fields: "rSender123"
                .parse::<CommonFields<payment::PaymentFlag>>()
                .unwrap()
                .with_transaction_type(TransactionType::Payment)
                .with_fee("12".into())
                .with_sequence(100)
                .with_last_ledger_sequence(596447)
                .with_source_tag(12345)
                .with_network_id(1025)
                .with_memo(Memo {
                    memo_data: Some("Test payment".to_string()),
                    memo_format: Some("text/plain".to_string()),
                    memo_type: Some("test".to_string()),
                }),
            amount: Amount::XRPAmount(XRPAmount::from("1000000")),
            destination: "rReceiver456".into(),
            destination_tag: Some(67890),
            ..Default::default()
        };

        // Verify all fields are set correctly
        assert_eq!(payment.common_fields.account, "rSender123");
        assert_eq!(payment.common_fields.fee, Some("12".into()));
        assert_eq!(payment.common_fields.sequence, Some(100));
        assert_eq!(payment.common_fields.last_ledger_sequence, Some(596447));
        assert_eq!(payment.common_fields.source_tag, Some(12345));
        assert_eq!(payment.common_fields.network_id, Some(1025));
        assert_eq!(payment.destination_tag, Some(67890));
        assert!(payment.common_fields.memos.is_some());
    }

    #[test]
    fn test_different_from_methods() {
        // Test all different ways to create CommonFields
        let account_str = "rAccount123";
        let account_string = String::from("rAccount123");
        let account_cow: Cow<str> = "rAccount123".into();

        let cf1: CommonFields<payment::PaymentFlag> = account_str.parse().unwrap();
        let cf2: CommonFields<payment::PaymentFlag> = CommonFields::from(account_string);
        let cf3: CommonFields<payment::PaymentFlag> = CommonFields::from(account_cow);
        let cf4: CommonFields<payment::PaymentFlag> = CommonFields::from_account("rAccount123");

        assert_eq!(cf1.account, "rAccount123");
        assert_eq!(cf2.account, "rAccount123");
        assert_eq!(cf3.account, "rAccount123");
        assert_eq!(cf4.account, "rAccount123");
    }

    #[test]
    fn test_fromstr_never_fails() {
        // Test edge cases for FromStr
        let empty: Result<CommonFields<PaymentFlag>, _> = "".parse();
        assert!(empty.is_ok());
        assert_eq!(empty.unwrap().account, "");

        let whitespace: Result<CommonFields<PaymentFlag>, _> = "   ".parse();
        assert!(whitespace.is_ok());
        assert_eq!(whitespace.unwrap().account, "   ");

        let long_string: Result<CommonFields<PaymentFlag>, _> = "r".repeat(1000).parse();
        assert!(long_string.is_ok());
        assert_eq!(long_string.unwrap().account.len(), 1000);
    }

    #[test]
    fn test_builder_pattern_overwrites() {
        // Test that builder methods properly overwrite values
        let common_fields = "rAccount123"
            .parse::<CommonFields<payment::PaymentFlag>>()
            .unwrap()
            .with_fee("10".into())
            .with_fee("20".into()) // Should overwrite the first fee
            .with_sequence(100)
            .with_sequence(200); // Should overwrite the first sequence

        assert_eq!(common_fields.fee, Some("20".into()));
        assert_eq!(common_fields.sequence, Some(200));
    }
}