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
use std::marker::PhantomData;

use async_trait::async_trait;
use multiversx_sc::codec::TopDecodeMulti;
use num_bigint::BigUint;

use novax_data::{NativeConvertible, parse_query_return_string_data};

use crate::{BlockchainProxy, ExecutorError, NetworkQueryError, QueryExecutor, TokenTransfer, VmValuesQueryRequest};
use crate::network::query::proxy::NetworkBlockchainProxy;
use crate::utils::transaction::normalization::NormalizationInOut;

/// A convenient type alias for `QueryNetworkExecutor` with `NetworkBlockchainProxy` as the generic type.
/// This is the privileged query executor for network interaction.
pub type ProxyQueryExecutor = QueryNetworkExecutor<NetworkBlockchainProxy>;

/// A structure to execute smart contract queries on a real blockchain environment via a specified gateway.
///
/// This executor utilizes a blockchain proxy to communicate with the blockchain network and
/// execute the queries.
#[derive(Clone, Debug)]
pub struct QueryNetworkExecutor<Proxy: BlockchainProxy> {
    /// The URL of the gateway to the blockchain network.
    pub gateway_url: String,
    /// A phantom data field to keep the generic `Proxy` type.
    _data: PhantomData<Proxy>
}

impl<Proxy: BlockchainProxy> QueryNetworkExecutor<Proxy> {
    /// Constructs a new `QueryNetworkExecutor` with the specified gateway URL.
    ///
    /// # Parameters
    /// - `gateway_url`: The URL of the gateway to the blockchain network.
    ///
    /// # Returns
    /// A new instance of `QueryNetworkExecutor`.
    pub fn new(gateway_url: String) -> Self {
        QueryNetworkExecutor {
            gateway_url,
            _data: PhantomData
        }
    }
}

#[async_trait]
impl<Proxy: BlockchainProxy> QueryExecutor for QueryNetworkExecutor<Proxy> {
    /// Executes a smart contract query on the real blockchain environment.
    async fn execute<OutputManaged>(
        &self,
        to: &novax_data::Address,
        function: String,
        arguments: Vec<Vec<u8>>,
        egld_value: BigUint,
        esdt_transfers: Vec<TokenTransfer>
    ) -> Result<OutputManaged::Native, ExecutorError>
        where
            OutputManaged: TopDecodeMulti + NativeConvertible + Send + Sync
    {
        let sc_address = to.to_bech32_string()?;

        let normalized = NormalizationInOut {
            sender: sc_address.clone(),
            receiver: sc_address,
            function_name: Some(function),
            arguments,
            egld_value,
            esdt_transfers,
        }.normalize()?;

        let vm_request = VmValuesQueryRequest {
            sc_address: normalized.receiver,
            func_name: normalized.function_name.unwrap_or_default(),
            caller: Some(normalized.sender),
            value: Some(normalized.egld_value.to_string()),
            args: encode_arguments(&normalized.arguments),
        };

        let blockchain = Proxy::new(self.gateway_url.clone());
        let result = blockchain.execute_vmquery(&vm_request).await?;
        let Some(return_data) = result.data.return_data else {
            return Err(NetworkQueryError::ErrorInResponse { message: result.data.return_message }.into())
        };

        let data: Vec<&str> = return_data.iter().map(AsRef::as_ref).collect();

        Ok(parse_query_return_string_data::<OutputManaged>(data.as_slice())?.to_native())
    }
}

#[async_trait]
impl QueryExecutor for &str {
    /// Convenience implementation which allows using a string representing the gateway URL to execute a query on the real blockchain environment.
    ///
    /// This implementation creates a new `ProxyQueryExecutor` instance using the string as the gateway URL,
    /// and delegates the query execution to it.
    async fn execute<OutputManaged>(
        &self,
        to: &novax_data::Address,
        function: String,
        arguments: Vec<Vec<u8>>,
        egld_value: BigUint,
        esdt_transfers: Vec<TokenTransfer>
    ) -> Result<OutputManaged::Native, ExecutorError>
        where
            OutputManaged: TopDecodeMulti + NativeConvertible + Send + Sync
    {
        self.to_string()
            .execute::<OutputManaged>(
                to,
                function,
                arguments,
                egld_value,
                esdt_transfers
            )
            .await
    }
}

#[async_trait]
impl QueryExecutor for String {
    /// Convenience implementation which allows using a string representing the gateway URL to execute a query on the real blockchain environment.
    ///
    /// This implementation creates a new `ProxyQueryExecutor` instance using the string as the gateway URL,
    /// and delegates the query execution to it.
    async fn execute<OutputManaged>(
        &self,
        to: &novax_data::Address,
        function: String,
        arguments: Vec<Vec<u8>>,
        egld_value: BigUint,
        esdt_transfers: Vec<TokenTransfer>
    ) -> Result<OutputManaged::Native, ExecutorError>
        where
            OutputManaged: TopDecodeMulti + NativeConvertible + Send + Sync
    {
        ProxyQueryExecutor::new(self.to_string())
            .execute::<OutputManaged>(
                to,
                function,
                arguments,
                egld_value,
                esdt_transfers
            )
            .await
    }
}

fn encode_arguments(arguments: &[Vec<u8>]) -> Vec<String> {
    arguments.iter()
        .map(hex::encode)
        .collect()
}

#[cfg(test)]
mod tests {
    use multiversx_sc::codec::TopEncode;
    use multiversx_sc::imports::ManagedVec;
    use multiversx_sc::types::ManagedBuffer;
    use multiversx_sc_scenario::imports::StaticApi;

    use crate::network::query::executor::encode_arguments;

    #[test]
    fn test_encode_arguments_empty() {
        let result = encode_arguments(&[]);
        let expected: Vec<String> = vec![];

        assert_eq!(result, expected);
    }

    #[test]
    fn test_encode_one_type() {
        let vec: ManagedVec<StaticApi, ManagedBuffer<StaticApi>> = ManagedVec::from_single_item(ManagedBuffer::from("Hey!"));

        let mut arguments: Vec<Vec<u8>> = vec![];
        for item in vec.into_iter() {
            let mut encoded_buffer: ManagedBuffer<StaticApi> = ManagedBuffer::new();
            _ = item.top_encode(&mut encoded_buffer);

            arguments.push(encoded_buffer.to_boxed_bytes().into_vec());
        }

        let result = encode_arguments(&arguments);
        let expected = vec!["48657921".to_string()];

        assert_eq!(result, expected)
    }

    #[test]
    fn test_encode_two_type() {
        let mut vec: ManagedVec<StaticApi, ManagedBuffer<StaticApi>> = ManagedVec::new();
        vec.push(ManagedBuffer::from("Hey!"));
        vec.push(ManagedBuffer::from("Hi!"));

        let mut arguments: Vec<Vec<u8>> = vec![];
        for item in vec.into_iter() {
            let mut encoded_buffer: ManagedBuffer<StaticApi> = ManagedBuffer::new();
            _ = item.top_encode(&mut encoded_buffer);

            arguments.push(encoded_buffer.to_boxed_bytes().into_vec());
        }

        let result = encode_arguments(&arguments);
        let expected = vec!["48657921".to_string(), "486921".to_string()];

        assert_eq!(result, expected)
    }

}