waves_rust/model/
transfer.rs

1use crate::error::{Error, Result};
2use crate::model::{Address, ByteString};
3use crate::util::JsonDeserializer;
4use crate::waves_proto::mass_transfer_transaction_data::Transfer as ProtoTransfer;
5use crate::waves_proto::{recipient, Recipient};
6use serde_json::{Map, Value};
7
8#[derive(Clone, Eq, PartialEq, Debug)]
9pub struct Transfer {
10    recipient: Address,
11    amount: u64,
12}
13
14impl Transfer {
15    pub fn new(recipient: Address, amount: u64) -> Self {
16        Self { recipient, amount }
17    }
18
19    pub fn recipient(&self) -> Address {
20        self.recipient.clone()
21    }
22
23    pub fn amount(&self) -> u64 {
24        self.amount
25    }
26}
27
28impl TryFrom<&Value> for Transfer {
29    type Error = Error;
30
31    fn try_from(value: &Value) -> Result<Self> {
32        let recipient = JsonDeserializer::safe_to_string_from_field(value, "recipient")?;
33        let amount = JsonDeserializer::safe_to_int_from_field(value, "amount")?;
34        Ok(Transfer {
35            recipient: Address::from_string(&recipient)?,
36            amount: amount as u64,
37        })
38    }
39}
40
41impl TryFrom<&Transfer> for Value {
42    type Error = Error;
43
44    fn try_from(value: &Transfer) -> Result<Self> {
45        let mut transfer = Map::new();
46
47        transfer.insert("recipient".to_owned(), value.recipient().encoded().into());
48        transfer.insert("amount".to_owned(), value.amount().into());
49        Ok(transfer.into())
50    }
51}
52
53impl TryFrom<&Transfer> for ProtoTransfer {
54    type Error = Error;
55
56    fn try_from(value: &Transfer) -> Result<Self> {
57        let recipient = Recipient {
58            recipient: Some(recipient::Recipient::PublicKeyHash(
59                value.recipient().public_key_hash(),
60            )),
61        };
62        Ok(ProtoTransfer {
63            recipient: Some(recipient),
64            amount: value.amount() as i64,
65        })
66    }
67}