Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ink_e2e] expose call dry-run method #1624

Merged
merged 28 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 107 additions & 38 deletions crates/e2e/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ use sp_runtime::traits::{
use std::{
collections::BTreeMap,
fmt::Debug,
marker::PhantomData,
path::Path,
};
use subxt::{
Expand Down Expand Up @@ -120,39 +121,23 @@ where
pub struct CallResult<C: subxt::Config, E: Environment, V> {
/// The result of the dry run, contains debug messages
/// if there were any.
pub dry_run: ContractExecResult<E::Balance>,
pub dry_run: CallDryRunResult<E, V>,
/// Events that happened with the contract instantiation.
pub events: ExtrinsicEvents<C>,
/// Contains the result of decoding the return value of the called
/// function.
pub value: Result<MessageResult<V>, scale::Error>,
/// Returns the bytes of the encoded dry-run return value.
pub data: Vec<u8>,
}

impl<C, E, V> CallResult<C, E, V>
where
C: subxt::Config,
E: Environment,
V: scale::Decode,
{
/// Returns the decoded return value of the message from the dry-run.
///
/// Panics if the value could not be decoded. The raw bytes can be accessed
/// via [`return_data`].
pub fn return_value(self) -> V {
self.value
.unwrap_or_else(|env_err| {
panic!(
"Decoding dry run result to ink! message return type failed: {}",
env_err
)
})
.unwrap_or_else(|lang_err| {
panic!(
"Encountered a `LangError` while decoding dry run result to ink! message: {:?}",
lang_err
)
})
self.dry_run.return_value()
}

/// Returns true if the specified event was triggered by the call.
Expand All @@ -175,12 +160,74 @@ where
{
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.debug_struct("CallResult")
.field("dry_run", &self.dry_run)
.field("dry_run", &self.dry_run.exec_result)
.field("events", &self.events)
.finish()
}
}

/// Result of the dry run of a contract call.
pub struct CallDryRunResult<E: Environment, V> {
/// The result of the dry run, contains debug messages
/// if there were any.
exec_result: ContractExecResult<E::Balance>,
_marker: PhantomData<V>,
}

impl<E, V> CallDryRunResult<E, V>
where
E: Environment,
V: scale::Decode,
{
/// Returns the [`ExecReturnValue`] resulting from the dry-run message call.
///
/// Panics if the dry-run message call failed to execute.
pub fn exec_return_value(&self) -> &pallet_contracts_primitives::ExecReturnValue {
self.exec_result
.result
.as_ref()
.unwrap_or_else(|call_err| panic!("Call dry-run failed: {:?}", call_err))
}

/// Returns the [`MessageResult`] from the execution of the dry-run message
/// call.
///
/// # Panics
/// - if the dry-run message call failed to execute.
/// - if message result cannot be decoded into the expected return value
/// type.
pub fn message_result(&self) -> MessageResult<V> {
let data = &self.exec_return_value().data;
scale::Decode::decode(&mut data.as_ref()).unwrap_or_else(|env_err| {
panic!(
"Decoding dry run result to ink! message return type failed: {}",
env_err
)
})
}

/// Returns the return value as raw bytes of the message from the dry-run.
///
/// Panics if the dry-run message call failed to execute.
pub fn return_data(&self) -> &[u8] {
ascjones marked this conversation as resolved.
Show resolved Hide resolved
&self.exec_return_value().data
}

/// Returns the decoded return value of the message from the dry-run.
///
/// Panics if the value could not be decoded. The raw bytes can be accessed
/// via [`return_data`].
pub fn return_value(self) -> V {
self.message_result()
.unwrap_or_else(|lang_err| {
panic!(
"Encountered a `LangError` while decoding dry run result to ink! message: {:?}",
lang_err
)
})
}
}

/// An error occurred while interacting with the Substrate node.
///
/// We only convey errors here that are caused by the contract's
Expand Down Expand Up @@ -664,25 +711,18 @@ where
{
log_info(&format!("call: {:02X?}", message.exec_input()));

let dry_run = self
.api
.call_dry_run(signer.account_id().clone(), &message, value, None)
.await;
log_info(&format!("call dry run: {:?}", &dry_run.result));
log_info(&format!(
"call dry run debug message: {}",
String::from_utf8_lossy(&dry_run.debug_message)
));
if dry_run.result.is_err() {
return Err(Error::CallDryRun(dry_run))
let dry_run = self.call_dry_run(signer, &message, value, None).await;

if dry_run.exec_result.result.is_err() {
return Err(Error::CallDryRun(dry_run.exec_result))
}

let tx_events = self
.api
.call(
sp_runtime::MultiAddress::Id(message.account_id().clone()),
value,
dry_run.gas_required,
dry_run.exec_result.gas_required,
storage_deposit_limit,
message.exec_input().to_vec(),
signer,
Expand All @@ -705,18 +745,47 @@ where
}
}

let bytes = &dry_run.result.as_ref().unwrap().data;
let value: Result<MessageResult<RetType>, scale::Error> =
scale::Decode::decode(&mut bytes.as_ref());

Ok(CallResult {
value,
data: bytes.clone(),
dry_run,
events: tx_events,
})
}

/// Executes a dry-run `call`.
///
/// Returns the result of the dry run, together with the decoded return value of the invoked
/// message.
pub async fn call_dry_run<RetType>(
&mut self,
signer: &Signer<C>,
message: &Message<E, RetType>,
value: E::Balance,
storage_deposit_limit: Option<E::Balance>,
) -> CallDryRunResult<E, RetType>
where
RetType: scale::Decode,
{
let exec_result = self
.api
.call_dry_run(
signer.account_id().clone(),
message,
value,
storage_deposit_limit,
)
.await;
log_info(&format!("call dry run: {:?}", &exec_result.result));
log_info(&format!(
"call dry run debug message: {}",
String::from_utf8_lossy(&exec_result.debug_message)
));

CallDryRunResult {
exec_result,
_marker: Default::default(),
}
}

/// Returns the balance of `account_id`.
pub async fn balance(
&self,
Expand Down
15 changes: 6 additions & 9 deletions examples/flipper/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,8 @@ pub mod flipper {
let get = build_message::<FlipperRef>(contract_acc_id.clone())
.call(|flipper| flipper.get());
let get_res = client
.call(&ink_e2e::bob(), get, 0, None)
.await
.expect("get failed");
.call_dry_run(&ink_e2e::bob(), &get, 0, None)
.await;
assert!(matches!(get_res.return_value(), false));

// when
Expand All @@ -89,9 +88,8 @@ pub mod flipper {
let get = build_message::<FlipperRef>(contract_acc_id.clone())
.call(|flipper| flipper.get());
let get_res = client
.call(&ink_e2e::bob(), get, 0, None)
.await
.expect("get failed");
.call_dry_run(&ink_e2e::bob(), &get, 0, None)
.await;
assert!(matches!(get_res.return_value(), true));

Ok(())
Expand All @@ -113,9 +111,8 @@ pub mod flipper {
let get = build_message::<FlipperRef>(contract_acc_id.clone())
.call(|flipper| flipper.get());
let get_res = client
.call(&ink_e2e::bob(), get, 0, None)
.await
.expect("get failed");
.call_dry_run(&ink_e2e::bob(), &get, 0, None)
.await;
assert!(matches!(get_res.return_value(), false));

Ok(())
Expand Down