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
use std::fmt::{Debug, Formatter};

use async_trait::async_trait;
use base64::Engine;
use multiversx_sc::codec::TopDecodeMulti;
use num_bigint::BigUint;
use tokio::join;

use novax_data::{Address, NativeConvertible};
use novax_request::gateway::client::GatewayClient;

use crate::{ExecutorError, GatewayError, SimulationError, SimulationGatewayRequest, SimulationGatewayResponse, TransactionExecutor, TransactionOnNetwork, TransactionOnNetworkTransactionSmartContractResult};
use crate::call_result::CallResult;
use crate::error::transaction::TransactionError;
use crate::network::models::simulate::request::SimulationGatewayRequestBody;
use crate::network::utils::address::get_address_info;
use crate::network::utils::network::get_network_config;
use crate::utils::transaction::normalization::NormalizationInOut;
use crate::utils::transaction::results::find_smart_contract_result;
use crate::utils::transaction::token_transfer::TokenTransfer;

/// Type alias for `BaseSimulationNetworkExecutor` with the `String` type as the generic `Client`.
pub type SimulationNetworkExecutor = BaseSimulationNetworkExecutor<String>;

/// A struct for executing transactions in a simulated blockchain environment.
/// It interacts with a blockchain network for transaction simulation purposes.
pub struct BaseSimulationNetworkExecutor<Client: GatewayClient> {
    /// The client used to interact with the blockchain network gateway for transaction simulations.
    pub client: Client,

    /// The blockchain address of the transaction sender.
    pub sender_address: Address,
}

impl<Client: GatewayClient> BaseSimulationNetworkExecutor<Client> {
    /// Constructs a new `BaseSimulationNetworkExecutor`.
    ///
    /// # Parameters
    /// - `client`: The client for interacting with the blockchain network gateway.
    /// - `sender_address`: The blockchain address that will be used as the sender in the transactions.
    ///
    /// # Returns
    /// A new instance of `BaseSimulationNetworkExecutor`.
    pub fn new(client: Client, sender_address: Address) -> Self {
        Self {
            client,
            sender_address,
        }
    }
}

impl<Client: GatewayClient> BaseSimulationNetworkExecutor<Client> {
    /// Simulates a blockchain transaction and fetches the result.
    ///
    /// # Parameters
    /// - `data`: The transaction data encapsulated in `SimulationGatewayRequest`.
    ///
    /// # Returns
    /// A `Result` containing `SimulationGatewayResponse` on success, or an `ExecutorError` on failure.
    async fn simulate_transaction(&self, data: SimulationGatewayRequest) -> Result<SimulationGatewayResponse, ExecutorError> {
        let sender_address = Address::from_bech32_string(&data.sender)?;

        let (
            address_info,
            network_config
        ) = join!(
            get_address_info(&self.client, sender_address),
            get_network_config(&self.client)
        );

        let address_info = address_info?.account;
        let network_config = network_config?.config;

        let body = SimulationGatewayRequestBody {
            nonce: address_info.nonce,
            value: data.value,
            receiver: data.receiver,
            sender: data.sender,
            gas_price: network_config.erd_min_gas_price,
            gas_limit: data.gas_limit,
            data: base64::engine::general_purpose::STANDARD.encode(data.data),
            chain_id: network_config.erd_chain_id,
            version: network_config.erd_min_transaction_version,
        };

        let Ok((_, Some(text))) = self.client.with_appended_url("/transaction/cost").post(&body).await else {
            return Err(GatewayError::CannotSimulateTransaction.into())
        };

        let Ok(results) = serde_json::from_str(&text) else {
            return Err(GatewayError::CannotParseSimulationResponse.into())
        };

        Ok(results)
    }
}

impl<Client> Clone for BaseSimulationNetworkExecutor<Client>
    where
        Client: GatewayClient + Clone
{
    /// Creates a clone of the `BaseSimulationNetworkExecutor` instance.
    fn clone(&self) -> Self {
        Self {
            client: self.client.clone(),
            sender_address: self.sender_address.clone(),
        }
    }
}

impl<Client> Debug for BaseSimulationNetworkExecutor<Client>
    where
        Client: GatewayClient
{
    /// Formats the `BaseSimulationNetworkExecutor` instance for use with the `Debug` trait.
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BaseSimulationNetworkExecutor")
            .field("client's url", &self.client.get_gateway_url())
            .field("sender address", &self.sender_address)
            .finish()
    }
}

#[async_trait]
impl<Client: GatewayClient> TransactionExecutor for BaseSimulationNetworkExecutor<Client> {
    /// Executes a smart contract call in a simulated environment.
    async fn sc_call<OutputManaged>(
        &mut self,
        to: &Address,
        function: String,
        arguments: Vec<Vec<u8>>,
        gas_limit: u64,
        egld_value: BigUint,
        esdt_transfers: Vec<TokenTransfer>
    ) -> Result<CallResult<OutputManaged::Native>, ExecutorError>
        where
            OutputManaged: TopDecodeMulti + NativeConvertible + Send + Sync
    {
        let function_name = if function.is_empty() {
            None
        } else {
            Some(function)
        };

        let normalized = NormalizationInOut {
            sender: self.sender_address.to_bech32_string()?,
            receiver: to.to_bech32_string()?,
            function_name,
            arguments,
            egld_value,
            esdt_transfers,
        }.normalize()?;

        let normalized_egld_value = normalized.egld_value.clone();
        let normalized_receiver = normalized.receiver.clone();
        let normalized_sender = normalized.sender.clone();

        let simulation_data = SimulationGatewayRequest {
            value: normalized_egld_value.to_string(),
            receiver: normalized_receiver,
            sender: normalized_sender,
            gas_limit,
            data: normalized.get_transaction_data(),
        };

        let response = self.simulate_transaction(simulation_data).await?;

        let Some(data) = response.data else {
            return Err(SimulationError::ErrorInTx { code: response.code, error: response.error }.into())
        };

        let scrs = data.smart_contract_results
            .into_iter()
            .map(|(hash, result)| {
                TransactionOnNetworkTransactionSmartContractResult {
                    hash,
                    nonce: result.nonce,
                    data: result.data,
                }
            })
            .collect();

        let mut raw_result = find_smart_contract_result(&Some(scrs), None)?
            .unwrap_or_default();

        let Ok(output_managed) = OutputManaged::multi_decode(&mut raw_result) else {
            return Err(TransactionError::CannotDecodeSmartContractResult.into())
        };

        let mut response = TransactionOnNetwork::default();
        response.transaction.status = "success".to_string();

        let call_result = CallResult {
            response,
            result: Some(output_managed.to_native()),
        };

        Ok(call_result)
    }
}