xrpl-rust 1.1.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
use alloc::borrow::Cow;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
use serde_repr::{Deserialize_repr, Serialize_repr};
use serde_with::skip_serializing_none;
use strum_macros::{AsRefStr, Display, EnumIter};

use crate::models::{
    amount::Amount,
    transactions::{Memo, Signer, Transaction, TransactionType},
    Model, PathStep, ValidateCurrencies, XRPLModelResult,
};

use crate::models::amount::XRPAmount;
use crate::models::transactions::exceptions::XRPLPaymentException;

use super::{CommonFields, CommonTransactionBuilder, FlagCollection};

/// Transactions of the Payment type support additional values
/// in the Flags field. This enum represents those options.
///
/// See Payment flags:
/// `<https://xrpl.org/docs/references/protocol/transactions/types/payment>`
#[derive(
    Default,
    Debug,
    Eq,
    PartialEq,
    Clone,
    Copy,
    Serialize_repr,
    Deserialize_repr,
    Display,
    AsRefStr,
    EnumIter,
)]
#[repr(u32)]
pub enum PaymentFlag {
    /// Do not use the default path; only use paths included in the Paths field.
    /// This is intended to force the transaction to take arbitrage opportunities.
    /// Most clients do not need this.
    TfNoDirectRipple = 0x00010000,
    /// If the specified Amount cannot be sent without spending more than SendMax,
    /// reduce the received amount instead of failing outright.
    /// See Partial Payments for more details.
    TfPartialPayment = 0x00020000,
    /// Only take paths where all the conversions have an input:output ratio that
    /// is equal or better than the ratio of Amount:SendMax.
    /// See Limit Quality for details.
    #[default]
    TfLimitQuality = 0x00040000,
}

/// Transfers value from one account to another.
///
/// See Payment:
/// `<https://xrpl.org/docs/references/protocol/transactions/types/payment>`
#[skip_serializing_none]
#[derive(
    Debug,
    Default,
    Serialize,
    Deserialize,
    PartialEq,
    Eq,
    Clone,
    xrpl_rust_macros::ValidateCurrencies,
)]
#[serde(rename_all = "PascalCase")]
pub struct Payment<'a> {
    /// The base fields for all transaction models.
    ///
    /// See Transaction Common Fields:
    /// `<https://xrpl.org/transaction-common-fields.html>`
    #[serde(flatten)]
    pub common_fields: CommonFields<'a, PaymentFlag>,
    /// The amount of currency to deliver. For non-XRP amounts, the nested field names
    /// MUST be lower-case. If the tfPartialPayment flag is set, deliver up to this
    /// amount instead.
    pub amount: Amount<'a>,
    /// The unique address of the account receiving the payment.
    pub destination: Cow<'a, str>,
    /// Arbitrary tag that identifies the reason for the payment to the destination,
    /// or a hosted recipient to pay.
    pub destination_tag: Option<u32>,
    /// Arbitrary 256-bit hash representing a specific reason or identifier for this payment.
    pub invoice_id: Option<u32>,
    /// Array of payment paths to be used for this transaction. Must be omitted for
    /// XRP-to-XRP transactions.
    pub paths: Option<Vec<Vec<PathStep<'a>>>>,
    /// Highest amount of source currency this transaction is allowed to cost, including
    /// transfer fees, exchange rates, and slippage . Does not include the XRP destroyed
    /// as a cost for submitting the transaction. For non-XRP amounts, the nested field
    /// names MUST be lower-case. Must be supplied for cross-currency/cross-issue payments.
    /// Must be omitted for XRP-to-XRP payments.
    pub send_max: Option<Amount<'a>>,
    /// Minimum amount of destination currency this transaction should deliver. Only valid
    /// if this is a partial payment. For non-XRP amounts, the nested field names are lower-case.
    pub deliver_min: Option<Amount<'a>>,
}

impl<'a: 'static> Model for Payment<'a> {
    fn get_errors(&self) -> XRPLModelResult<()> {
        self._get_xrp_transaction_error()?;
        self._get_partial_payment_error()?;
        self._get_exchange_error()?;
        self.validate_currencies()
    }
}

impl<'a> Transaction<'a, PaymentFlag> for Payment<'a> {
    fn has_flag(&self, flag: &PaymentFlag) -> bool {
        self.common_fields.has_flag(flag)
    }

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

    fn get_common_fields(&self) -> &CommonFields<'_, PaymentFlag> {
        self.common_fields.get_common_fields()
    }

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

impl<'a> CommonTransactionBuilder<'a, PaymentFlag> for Payment<'a> {
    fn get_mut_common_fields(&mut self) -> &mut CommonFields<'a, PaymentFlag> {
        &mut self.common_fields
    }

    fn into_self(self) -> Self {
        self
    }
}

impl<'a> PaymentError for Payment<'a> {
    fn _get_xrp_transaction_error(&self) -> XRPLModelResult<()> {
        if self.amount.is_xrp() && self.send_max.is_none() {
            if self.paths.is_some() {
                Err(XRPLPaymentException::IllegalOption {
                    field: "paths".into(),
                    context: "XRP to XRP payments".into(),
                }
                .into())
            } else if self.common_fields.account == self.destination {
                Err(XRPLPaymentException::ValueEqualsValueInContext {
                    field1: "account".into(),
                    field2: "destination".into(),
                    context: "XRP to XRP Payments".into(),
                }
                .into())
            } else {
                Ok(())
            }
        } else {
            Ok(())
        }
    }

    fn _get_partial_payment_error(&self) -> XRPLModelResult<()> {
        if let Some(send_max) = &self.send_max {
            if !self.has_flag(&PaymentFlag::TfPartialPayment)
                && send_max.is_xrp()
                && self.amount.is_xrp()
            {
                Err(XRPLPaymentException::IllegalOption {
                    field: "send_max".into(),
                    context: "XRP to XRP non-partial payments".into(),
                }
                .into())
            } else {
                Ok(())
            }
        } else if self.has_flag(&PaymentFlag::TfPartialPayment) {
            Err(XRPLPaymentException::FlagRequiresField {
                flag: PaymentFlag::TfPartialPayment,
                field: "send_max".into(),
            }
            .into())
        } else if !self.has_flag(&PaymentFlag::TfPartialPayment) {
            if let Some(_deliver_min) = &self.deliver_min {
                Err(XRPLPaymentException::IllegalOption {
                    field: "deliver_min".into(),
                    context: "XRP to XRP non-partial payments".into(),
                }
                .into())
            } else {
                Ok(())
            }
        } else {
            Ok(())
        }
    }

    fn _get_exchange_error(&self) -> XRPLModelResult<()> {
        if self.common_fields.account == self.destination && self.send_max.is_none() {
            return Err(XRPLPaymentException::OptionRequired {
                field: "send_max".into(),
                context: "exchanges".into(),
            }
            .into());
        }

        Ok(())
    }
}

impl<'a> Payment<'a> {
    pub fn new(
        account: Cow<'a, str>,
        account_txn_id: Option<Cow<'a, str>>,
        fee: Option<XRPAmount<'a>>,
        flags: Option<FlagCollection<PaymentFlag>>,
        last_ledger_sequence: Option<u32>,
        memos: Option<Vec<Memo>>,
        sequence: Option<u32>,
        signers: Option<Vec<Signer>>,
        source_tag: Option<u32>,
        ticket_sequence: Option<u32>,
        amount: Amount<'a>,
        destination: Cow<'a, str>,
        deliver_min: Option<Amount<'a>>,
        destination_tag: Option<u32>,
        invoice_id: Option<u32>,
        paths: Option<Vec<Vec<PathStep<'a>>>>,
        send_max: Option<Amount<'a>>,
    ) -> Self {
        Self {
            common_fields: CommonFields::new(
                account,
                TransactionType::Payment,
                account_txn_id,
                fee,
                Some(flags.unwrap_or_default()),
                last_ledger_sequence,
                memos,
                None,
                sequence,
                signers,
                None,
                source_tag,
                ticket_sequence,
                None,
            ),
            amount,
            destination,
            destination_tag,
            invoice_id,
            paths,
            send_max,
            deliver_min,
        }
    }

    /// Set destination tag
    pub fn with_destination_tag(mut self, tag: u32) -> Self {
        self.destination_tag = Some(tag);
        self
    }

    /// Set invoice ID
    pub fn with_invoice_id(mut self, invoice_id: u32) -> Self {
        self.invoice_id = Some(invoice_id);
        self
    }

    /// Set send max
    pub fn with_send_max(mut self, send_max: Amount<'a>) -> Self {
        self.send_max = Some(send_max);
        self
    }

    /// Set deliver min
    pub fn with_deliver_min(mut self, deliver_min: Amount<'a>) -> Self {
        self.deliver_min = Some(deliver_min);
        self
    }

    /// Set paths
    pub fn with_paths(mut self, paths: Vec<Vec<PathStep<'a>>>) -> Self {
        self.paths = Some(paths);
        self
    }

    /// Add a single path
    pub fn add_path(mut self, path: Vec<PathStep<'a>>) -> Self {
        match &mut self.paths {
            Some(paths) => paths.push(path),
            None => self.paths = Some(alloc::vec![path]),
        }
        self
    }

    /// Add flag (in addition to CommonTransactionBuilder flags)
    pub fn with_flag(mut self, flag: PaymentFlag) -> Self {
        self.common_fields.flags.0.push(flag);
        self
    }

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

pub trait PaymentError {
    fn _get_xrp_transaction_error(&self) -> XRPLModelResult<()>;
    fn _get_partial_payment_error(&self) -> XRPLModelResult<()>;
    fn _get_exchange_error(&self) -> XRPLModelResult<()>;
}

#[cfg(test)]
mod tests {
    use alloc::string::ToString;
    use alloc::vec;

    use crate::models::amount::{Amount, IssuedCurrencyAmount, XRPAmount};
    use crate::models::{Model, PathStep};
    use crate::{
        asynch::{exceptions::XRPLHelperResult, transaction::sign},
        models::transactions::Transaction,
        wallet::Wallet,
    };

    use super::*;

    #[cfg(all(feature = "helpers", feature = "wallet"))]
    #[test]
    fn test_payment_sign_with_memo() -> XRPLHelperResult<()> {
        let mut payment = Payment {
            common_fields: CommonFields {
                account: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
                transaction_type: TransactionType::Payment,
                memos: Some(vec![Memo {
                    memo_data: Some("68656c6c6f".into()),
                    memo_format: None,
                    memo_type: Some("74657874".into()),
                }]),
                ..Default::default()
            },
            amount: Amount::XRPAmount("1000000".into()),
            destination: "rLSn6Z3T8uCxbcd1oxwfGQN1Fdn5CyGujK".into(),
            ..Default::default()
        };

        let wallet = Wallet::create(None)?;
        sign(&mut payment, &wallet, false)?;

        assert!(payment.get_common_fields().is_signed());

        Ok(())
    }

    #[test]
    fn test_xrp_to_xrp_error() {
        let mut payment = Payment {
            common_fields: CommonFields {
                account: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::XRPAmount(XRPAmount::from("1000000")),
            destination: "rLSn6Z3T8uCxbcd1oxwfGQN1Fdn5CyGujK".into(),
            paths: Some(vec![vec![
                PathStep::default().with_account("rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B".into())
            ]]),
            ..Default::default()
        };

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "The optional field `\"paths\"` is not allowed to be defined for \"XRP to XRP payments\""
        );

        payment.paths = None;
        payment.send_max = Some(Amount::XRPAmount(XRPAmount::from("99999")));

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "The optional field `\"send_max\"` is not allowed to be defined for \"XRP to XRP non-partial payments\""
        );

        payment.send_max = None;
        payment.destination = "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into();

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "The value of the field `\"account\"` is not allowed to be the same as the value of the field `\"destination\"`, for \"XRP to XRP Payments\""
        );
    }

    #[test]
    fn test_partial_payments_error() {
        let payment = Payment {
            common_fields: CommonFields {
                account: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
                transaction_type: TransactionType::Payment,
                flags: vec![PaymentFlag::TfPartialPayment].into(),
                ..Default::default()
            },
            amount: Amount::XRPAmount("1000000".into()),
            destination: "rLSn6Z3T8uCxbcd1oxwfGQN1Fdn5CyGujK".into(),
            ..Default::default()
        };

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "For the flag `TfPartialPayment` to be set it is required to define the field `\"send_max\"`"
        );

        let payment = Payment {
            common_fields: CommonFields {
                account: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::XRPAmount("1000000".into()),
            destination: "rLSn6Z3T8uCxbcd1oxwfGQN1Fdn5CyGujK".into(),
            deliver_min: Some(Amount::XRPAmount("99999".into())),
            ..Default::default()
        };

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "The optional field `\"deliver_min\"` is not allowed to be defined for \"XRP to XRP non-partial payments\""
        );
    }

    #[test]
    fn test_exchange_error() {
        let payment = Payment {
            common_fields: CommonFields {
                account: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::IssuedCurrencyAmount(IssuedCurrencyAmount::new(
                "USD".into(),
                "rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B".into(),
                "10".into(),
            )),
            destination: "rU4EE1FskCPJw5QkLx1iGgdWiJa6HeqYyb".into(),
            ..Default::default()
        };

        assert_eq!(
            payment.validate().unwrap_err().to_string().as_str(),
            "The optional field `\"send_max\"` is required to be defined for \"exchanges\""
        );
    }

    #[test]
    fn test_serde() {
        let default_txn = Payment {
            common_fields: CommonFields {
                account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                transaction_type: TransactionType::Payment,
                fee: Some("12".into()),
                flags: vec![PaymentFlag::TfPartialPayment].into(),
                sequence: Some(2),
                signing_pub_key: Some("".into()),
                ..Default::default()
            },
            amount: Amount::IssuedCurrencyAmount(IssuedCurrencyAmount::new(
                "USD".into(),
                "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                "1".into(),
            )),
            destination: "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX".into(),
            ..Default::default()
        };

        let default_json_str = r#"{"Account":"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn","TransactionType":"Payment","Fee":"12","Flags":131072,"Sequence":2,"SigningPubKey":"","Amount":{"currency":"USD","issuer":"rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn","value":"1"},"Destination":"ra5nK24KXen9AHvsdFTKHSANinZseWnPcX"}"#;

        // Serialize
        let default_json_value = serde_json::to_value(default_json_str).unwrap();
        let serialized_string = serde_json::to_string(&default_txn).unwrap();
        let serialized_value = serde_json::to_value(&serialized_string).unwrap();
        assert_eq!(serialized_value, default_json_value);

        // Deserialize
        let deserialized: Payment = serde_json::from_str(default_json_str).unwrap();
        assert_eq!(default_txn, deserialized);
    }

    #[test]
    fn test_builder_pattern() {
        let payment = Payment {
            common_fields: CommonFields {
                account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::XRPAmount("1000000".into()),
            destination: "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX".into(),
            ..Default::default()
        }
        .with_destination_tag(12345)
        .with_send_max(Amount::XRPAmount("1100000".into()))
        .with_flag(PaymentFlag::TfPartialPayment)
        .with_fee("12".into())
        .with_sequence(2)
        .with_last_ledger_sequence(7108682)
        .with_source_tag(54321);

        assert_eq!(payment.destination_tag, Some(12345));
        assert!(payment.send_max.is_some());
        assert!(payment.has_flag(&PaymentFlag::TfPartialPayment));
        assert_eq!(payment.common_fields.fee.as_ref().unwrap().0, "12");
        assert_eq!(payment.common_fields.sequence, Some(2));
        assert_eq!(payment.common_fields.last_ledger_sequence, Some(7108682));
        assert_eq!(payment.common_fields.source_tag, Some(54321));
    }

    #[test]
    fn test_cross_currency_payment() {
        let payment = Payment {
            common_fields: CommonFields {
                account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::IssuedCurrencyAmount(IssuedCurrencyAmount::new(
                "USD".into(),
                "rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq".into(),
                "100".into(),
            )),
            destination: "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX".into(),
            ..Default::default()
        }
        .with_send_max(Amount::XRPAmount("110000000".into())) // 110 XRP max
        .with_destination_tag(987654)
        .with_fee("12".into());

        assert!(payment.send_max.is_some());
        assert_eq!(payment.destination_tag, Some(987654));
        assert!(payment.validate().is_ok());
    }

    #[test]
    fn test_partial_payment() {
        let payment = Payment {
            common_fields: CommonFields {
                account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::XRPAmount("1000000".into()),
            destination: "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX".into(),
            ..Default::default()
        }
        .with_send_max(Amount::XRPAmount("1100000".into()))
        .with_deliver_min(Amount::XRPAmount("900000".into()))
        .with_flag(PaymentFlag::TfPartialPayment)
        .with_fee("12".into());

        assert!(payment.has_flag(&PaymentFlag::TfPartialPayment));
        assert!(payment.send_max.is_some());
        assert!(payment.deliver_min.is_some());
        assert!(payment.validate().is_ok());
    }

    #[test]
    fn test_path_building() {
        let path1 = vec![
            PathStep::default().with_account("rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh".into()),
            PathStep::default().with_currency("USD".into()),
        ];
        let path2 = vec![
            PathStep::default().with_currency("EUR".into()),
            PathStep::default().with_issuer("rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq".into()),
        ];

        let payment = Payment {
            common_fields: CommonFields {
                account: "rf1BiGeXwwQoi8Z2ueFYTEXSwuJYfV2Jpn".into(),
                transaction_type: TransactionType::Payment,
                ..Default::default()
            },
            amount: Amount::IssuedCurrencyAmount(IssuedCurrencyAmount::new(
                "USD".into(),
                "rhub8VRN55s94qWKDv6jmDy1pUykJzF3wq".into(),
                "100".into(),
            )),
            destination: "ra5nK24KXen9AHvsdFTKHSANinZseWnPcX".into(),
            ..Default::default()
        }
        .add_path(path1)
        .add_path(path2)
        .with_send_max(Amount::XRPAmount("110000000".into()))
        .with_fee("12".into());

        assert_eq!(payment.paths.as_ref().unwrap().len(), 2);
        assert!(payment.validate().is_ok());
    }
}