waves_rust/model/transaction/action/
invoke_action.rs

1use crate::error::{Error, Result};
2use crate::model::{Address, Amount, AssetId, Function, StateChanges};
3use crate::util::JsonDeserializer;
4use serde_json::Value;
5use std::borrow::Borrow;
6
7#[derive(Clone, Eq, PartialEq, Debug)]
8pub struct InvokeAction {
9    dapp: Address,
10    function: Function,
11    payment: Vec<Amount>,
12    state_changes: StateChanges,
13}
14
15impl InvokeAction {
16    pub fn new(
17        dapp: Address,
18        function: Function,
19        payment: Vec<Amount>,
20        state_changes: StateChanges,
21    ) -> InvokeAction {
22        InvokeAction {
23            dapp,
24            function,
25            payment,
26            state_changes,
27        }
28    }
29
30    pub fn dapp(&self) -> Address {
31        self.dapp.clone()
32    }
33
34    pub fn function(&self) -> Function {
35        self.function.clone()
36    }
37
38    pub fn payment(&self) -> Vec<Amount> {
39        self.payment.clone()
40    }
41
42    pub fn state_changes(&self) -> StateChanges {
43        self.state_changes.clone()
44    }
45}
46
47impl TryFrom<&Value> for InvokeAction {
48    type Error = Error;
49
50    fn try_from(value: &Value) -> Result<Self> {
51        let dapp = JsonDeserializer::safe_to_string_from_field(value, "dApp")?;
52        let function: Function = value.try_into()?;
53        let payment: Vec<Amount> = map_payment(value)?;
54        let state_changes: StateChanges = value["stateChanges"].borrow().try_into()?;
55        Ok(InvokeAction {
56            dapp: Address::from_string(&dapp)?,
57            function,
58            payment,
59            state_changes,
60        })
61    }
62}
63
64//todo rm copy past
65fn map_payment(value: &Value) -> Result<Vec<Amount>> {
66    JsonDeserializer::safe_to_array_from_field(value, "payment")?
67        .iter()
68        .map(|payment| {
69            let value = JsonDeserializer::safe_to_int_from_field(payment, "amount")?;
70            let asset_id = match payment["assetId"].as_str() {
71                Some(asset) => Some(AssetId::from_string(asset)?),
72                None => None,
73            };
74            Ok(Amount::new(value as u64, asset_id))
75        })
76        .collect::<Result<Vec<Amount>>>()
77}