ink_e2e/
contract_results.rs

1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::{
16    fmt,
17    fmt::Debug,
18    marker::PhantomData,
19};
20
21use frame_support::pallet_prelude::{
22    Decode,
23    Encode,
24};
25use ink::codegen::ContractCallBuilder;
26use ink_env::{
27    Environment,
28    call::{
29        FromAddr,
30        utils::DecodeMessageResult,
31    },
32};
33use ink_primitives::{
34    Address,
35    ConstructorResult,
36    H256,
37    MessageResult,
38};
39use ink_revive_types::{
40    CodeUploadResult,
41    ExecReturnValue,
42    InstantiateReturnValue,
43    StorageDeposit,
44    evm::CallTrace,
45};
46use sp_runtime::{
47    DispatchError,
48    Weight,
49};
50
51/// Alias for the contract instantiate result.
52pub type ContractInstantiateResultFor<E> =
53    ContractResult<InstantiateReturnValue, <E as Environment>::Balance>;
54
55// todo use the obj one from `pallet-revive` instead
56/// Result type of a `bare_call`, `bare_instantiate`, `ReviveApi::call`, and
57/// `ReviveApi::instantiate`.
58///
59/// It contains the execution result together with some auxiliary information.
60///
61/// # Note
62///
63/// It has been extended to include `events` at the end of the struct while not bumping
64/// the `ReviveApi` version. Therefore when SCALE decoding a `ContractResult` its
65/// trailing data should be ignored to avoid any potential compatibility issues.
66#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode)]
67pub struct ContractResult<R, Balance> {
68    /// How much weight was consumed during execution.
69    pub gas_consumed: Weight,
70    /// How much weight is required as gas limit in order to execute this call.
71    ///
72    /// This value should be used to determine the weight limit for on-chain execution.
73    ///
74    /// # Note
75    ///
76    /// This can only different from [`Self::gas_consumed`] when weight pre-charging
77    /// is used. Currently, only `seal_call_runtime` makes use of pre-charging.
78    /// Additionally, any `seal_call` or `seal_instantiate` makes use of pre-charging
79    /// when a non-zero `gas_limit` argument is supplied.
80    pub gas_required: Weight,
81    /// How much balance was paid by the origin into the contract's deposit account in
82    /// order to pay for storage.
83    ///
84    /// The storage deposit is never actually charged from the origin in case of
85    /// [`Self::result`] is `Err`. This is because on error all storage changes are
86    /// rolled back including the payment of the deposit.
87    pub storage_deposit: StorageDeposit<Balance>,
88    /// The execution result of the code.
89    pub result: Result<R, DispatchError>,
90}
91
92/// Alias for the contract exec result.
93pub type ContractExecResultFor<E> =
94    ContractResult<ExecReturnValue, <E as Environment>::Balance>;
95
96/// Result of a contract instantiation using bare call.
97pub struct BareInstantiationResult<E: Environment, EventLog> {
98    // The address at which the contract was instantiated.
99    pub addr: Address,
100    // The account id at which the contract was instantiated.
101    pub account_id: E::AccountId,
102    /// Events that happened with the contract instantiation.
103    pub events: EventLog,
104    /// Trace of the instantiated contract.
105    pub trace: Option<CallTrace>,
106    /// Code hash of the instantiated contract.
107    pub code_hash: H256,
108}
109
110/// We implement a custom `Debug` here, as to avoid requiring the trait bound
111/// `Debug` for `E`.
112impl<E: Environment, EventLog> Debug for BareInstantiationResult<E, EventLog>
113where
114    EventLog: Debug,
115{
116    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
117        f.debug_struct("BareInstantiationResult")
118            .field("addr", &self.addr)
119            .field("account_id", &self.account_id.encode())
120            .field("events", &self.events)
121            .field("trace", &self.trace)
122            .field("code_hash", &self.code_hash)
123            .finish()
124    }
125}
126
127/// Result of a contract instantiation.
128pub struct InstantiationResult<E: Environment, EventLog, Abi> {
129    /// The address at which the contract was instantiated.
130    pub addr: Address,
131    /// The account id at which the contract was instantiated.
132    pub account_id: E::AccountId,
133    /// The result of the dry run, contains debug messages
134    /// if there were any.
135    pub dry_run: InstantiateDryRunResult<E, Abi>,
136    /// Events that happened with the contract instantiation.
137    pub events: EventLog,
138    /// todo
139    pub trace: Option<CallTrace>,
140    /// todo
141    pub code_hash: H256,
142}
143
144impl<E: Environment, EventLog, Abi> InstantiationResult<E, EventLog, Abi> {
145    /// Returns a call builder for the contract which was instantiated.
146    ///
147    /// # Note
148    ///
149    /// This uses the ABI used for the contract instantiation call.
150    pub fn call_builder<Contract>(&self) -> <Contract as ContractCallBuilder>::Type<Abi>
151    where
152        Contract: ContractCallBuilder,
153        <Contract as ContractCallBuilder>::Type<Abi>: FromAddr,
154    {
155        <<Contract as ContractCallBuilder>::Type<Abi> as FromAddr>::from_addr(self.addr)
156    }
157
158    /// Returns a call builder for the specified ABI for the contract which was
159    /// instantiated.
160    ///
161    /// # Note
162    ///
163    /// This is useful for contracts that support multiple ABIs.
164    pub fn call_builder_abi<Contract, CallAbi>(
165        &self,
166    ) -> <Contract as ContractCallBuilder>::Type<CallAbi>
167    where
168        Contract: ContractCallBuilder,
169        <Contract as ContractCallBuilder>::Type<CallAbi>: FromAddr,
170    {
171        <<Contract as ContractCallBuilder>::Type<CallAbi> as FromAddr>::from_addr(
172            self.addr,
173        )
174    }
175}
176
177/// We implement a custom `Debug` here, as to avoid requiring the trait bound `Debug` for
178/// `E`.
179impl<E: Environment, EventLog, Abi> Debug for InstantiationResult<E, EventLog, Abi>
180where
181    E::AccountId: Debug,
182    E::Balance: Debug,
183    E::EventRecord: Debug,
184    EventLog: Debug,
185{
186    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
187        // todo add missing fields
188        f.debug_struct("InstantiationResult")
189            .field("addr", &self.addr)
190            .field("dry_run", &self.dry_run)
191            .field("events", &self.events)
192            .finish()
193    }
194}
195
196/// Result of a contract upload.
197pub struct UploadResult<E: Environment, EventLog> {
198    /// The hash with which the contract can be instantiated.
199    pub code_hash: H256,
200    /// The result of the dry run, contains debug messages if there were any.
201    pub dry_run: CodeUploadResult<E::Balance>,
202    /// Events that happened with the contract instantiation.
203    pub events: EventLog,
204}
205
206/// We implement a custom `Debug` here, to avoid requiring the trait bound `Debug` for
207/// `E`.
208impl<E: Environment, EventLog> Debug for UploadResult<E, EventLog>
209where
210    E::Balance: Debug,
211    H256: Debug,
212    EventLog: Debug,
213{
214    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
215        f.debug_struct("UploadResult")
216            .field("code_hash", &self.code_hash)
217            .field("dry_run", &self.dry_run)
218            .field("events", &self.events)
219            .finish()
220    }
221}
222
223/// Result of a contract call.
224pub struct CallResult<E: Environment, V, EventLog, Abi> {
225    /// The result of the dry run, contains debug messages if there were any.
226    pub dry_run: CallDryRunResult<E, V, Abi>,
227    /// Events that happened with the contract instantiation.
228    pub events: EventLog,
229    /// todo
230    pub trace: Option<CallTrace>,
231}
232
233impl<E: Environment, V: DecodeMessageResult<Abi>, EventLog, Abi>
234    CallResult<E, V, EventLog, Abi>
235{
236    /// Returns the [`MessageResult`] from the execution of the dry-run message
237    /// call.
238    ///
239    /// # Panics
240    /// - if the dry-run message call failed to execute.
241    /// - if message result cannot be decoded into the expected return value type.
242    pub fn message_result(&self) -> MessageResult<V> {
243        self.dry_run.message_result()
244    }
245
246    /// Returns the decoded return value of the message from the dry-run.
247    ///
248    /// Panics if the value could not be decoded. The raw bytes can be accessed
249    /// via [`CallResult::return_data`].
250    pub fn return_value(self) -> V {
251        self.dry_run.return_value()
252    }
253}
254
255impl<E: Environment, V, EventLog, Abi> CallResult<E, V, EventLog, Abi> {
256    /// Returns the return value of the message dry-run as raw bytes.
257    ///
258    /// Panics if the dry-run message call failed to execute.
259    pub fn return_data(&self) -> &[u8] {
260        &self.dry_run.exec_return_value().data
261    }
262}
263
264// TODO(#xxx) Improve the `Debug` implementation.
265impl<E: Environment, V, EventLog, Abi> Debug for CallResult<E, V, EventLog, Abi>
266where
267    E: Debug,
268    E::Balance: Debug,
269    E::EventRecord: Debug,
270    V: Debug,
271    EventLog: Debug,
272{
273    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
274        f.debug_struct("CallResult")
275            .field("dry_run", &self.dry_run)
276            .field("events", &self.events)
277            .field("trace", &self.trace)
278            .finish()
279    }
280}
281
282/// Result of the dry run of a contract call.
283pub struct CallDryRunResult<E: Environment, V, Abi> {
284    /// The result of the dry run, contains debug messages if there were any.
285    pub exec_result: ContractExecResultFor<E>,
286    /// The execution trace (if any).
287    pub trace: Option<CallTrace>,
288    /// Phantom data for return type and its ABI encoding.
289    pub _marker: PhantomData<(V, Abi)>,
290}
291
292/// We implement a custom `Debug` here, as to avoid requiring the trait bound `Debug` for
293/// `E`.
294impl<E: Environment, V, Abi> Debug for CallDryRunResult<E, V, Abi>
295where
296    E::Balance: Debug,
297    E::EventRecord: Debug,
298{
299    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
300        f.debug_struct("CallDryRunResult")
301            .field("exec_result", &self.exec_result)
302            .finish()
303    }
304}
305
306impl<E: Environment, V, Abi> CallDryRunResult<E, V, Abi> {
307    /// Returns true if the dry-run execution resulted in an error.
308    pub fn is_err(&self) -> bool {
309        self.exec_result.result.is_err() || self.did_revert()
310    }
311
312    /// Returns the [`ExecReturnValue`] resulting from the dry-run message call.
313    ///
314    /// Panics if the dry-run message call failed to execute.
315    pub fn exec_return_value(&self) -> &ExecReturnValue {
316        self.exec_result
317            .result
318            .as_ref()
319            .unwrap_or_else(|call_err| panic!("Call dry-run failed: {call_err:?}"))
320    }
321
322    /// Returns true if the message call reverted.
323    pub fn did_revert(&self) -> bool {
324        let res = self.exec_result.result.clone().expect("no result found");
325        res.did_revert()
326    }
327
328    /// Returns the return value as raw bytes of the message from the dry-run.
329    ///
330    /// Panics if the dry-run message call failed to execute.
331    pub fn return_data(&self) -> &[u8] {
332        &self.exec_return_value().data
333    }
334}
335
336impl<E: Environment, V: DecodeMessageResult<Abi>, Abi> CallDryRunResult<E, V, Abi> {
337    /// Returns the [`MessageResult`] from the execution of the dry-run message call.
338    ///
339    /// # Panics
340    /// - if the dry-run message call failed to execute.
341    /// - if message result cannot be decoded into the expected return value type.
342    pub fn message_result(&self) -> MessageResult<V> {
343        let data = &self.exec_return_value().data;
344        DecodeMessageResult::decode_output(data.as_ref(), self.did_revert()).unwrap_or_else(|env_err| {
345            panic!(
346                "Decoding dry run result to ink! message return type failed: {env_err:?} {:?}\n\n\
347                Attempt to stringify returned data: {:?}",
348                self.exec_return_value(),
349                String::from_utf8_lossy(&self.exec_return_value().data[..])
350            )
351        })
352    }
353
354    /// Returns the decoded return value of the message from the dry-run.
355    ///
356    /// Panics if the value could not be decoded. The raw bytes can be accessed via
357    /// [`CallResult::return_data`].
358    pub fn return_value(&self) -> V {
359        self.message_result()
360            .unwrap_or_else(|lang_err| {
361                panic!(
362                    "Encountered a `LangError` while decoding dry run result to ink! message: {lang_err:?}"
363                )
364            })
365    }
366}
367
368/// Result of the dry run of a contract call.
369#[derive(Clone)]
370pub struct InstantiateDryRunResult<E: Environment, Abi> {
371    /// The result of the dry run, contains debug messages if there were any.
372    pub contract_result: ContractInstantiateResultFor<E>,
373    /// Phantom data for return type and its ABI encoding.
374    pub _marker: PhantomData<Abi>,
375}
376
377impl<E: Environment, Abi> From<ContractInstantiateResultFor<E>>
378    for InstantiateDryRunResult<E, Abi>
379{
380    fn from(contract_result: ContractInstantiateResultFor<E>) -> Self {
381        Self {
382            contract_result,
383            _marker: PhantomData,
384        }
385    }
386}
387
388impl<E: Environment, Abi> InstantiateDryRunResult<E, Abi> {
389    /// Returns true if the dry-run execution resulted in an error.
390    pub fn is_err(&self) -> bool {
391        self.contract_result.result.is_err() || self.did_revert()
392    }
393
394    /// Returns the [`InstantiateReturnValue`] resulting from the dry-run message call.
395    ///
396    /// Panics if the dry-run message call failed to execute.
397    pub fn instantiate_return_value(&self) -> &InstantiateReturnValue {
398        self.contract_result
399            .result
400            .as_ref()
401            .unwrap_or_else(|call_err| panic!("Instantiate dry-run failed: {call_err:?}"))
402    }
403
404    /// Returns the encoded return value from the constructor.
405    ///
406    /// # Panics
407    /// - if the dry-run message instantiate failed to execute.
408    /// - if message result cannot be decoded into the expected return value type.
409    pub fn constructor_result<V: DecodeMessageResult<Abi>>(
410        &self,
411    ) -> ConstructorResult<V> {
412        let data = &self.instantiate_return_value().result.data;
413        DecodeMessageResult::decode_output(data.as_ref(), self.did_revert()).unwrap_or_else(|env_err| {
414            panic!("Decoding dry run result to constructor return type failed: {env_err:?}")
415        })
416    }
417
418    /// Returns the return value of the instantiation dry-run as raw bytes.
419    ///
420    /// Panics if the dry-run message call failed to execute.
421    pub fn return_data(&self) -> &[u8] {
422        &self.instantiate_return_value().result.data
423    }
424
425    /// Returns true if the instantiation dry-run reverted.
426    pub fn did_revert(&self) -> bool {
427        let res = self.instantiate_return_value().clone().result;
428        res.did_revert()
429    }
430}
431
432impl<E, Abi> Debug for InstantiateDryRunResult<E, Abi>
433where
434    E: Environment,
435    E::AccountId: Debug,
436    E::Balance: Debug,
437    E::EventRecord: Debug,
438{
439    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
440        f.debug_struct("InstantiateDryRunResult")
441            .field("contract_result", &self.contract_result)
442            .finish()
443    }
444}