Skip to content

Commit

Permalink
Handle LangError from instantiate (fails for success case)
Browse files Browse the repository at this point in the history
This commit lets us grab what's in the output buffer after our call to
`instantiate`, however we are unable to succesfully decode the
`AccountId` from the success case.
  • Loading branch information
HCastano committed Nov 25, 2022
1 parent dc62b4f commit 8796a62
Show file tree
Hide file tree
Showing 9 changed files with 131 additions and 50 deletions.
8 changes: 5 additions & 3 deletions crates/env/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,16 +319,18 @@ where
/// - If the instantiation process runs out of gas.
/// - If given insufficient endowment.
/// - If the returned account ID failed to decode properly.
pub fn instantiate_contract<E, Args, Salt, C>(
pub fn instantiate_contract<E, Args, Salt, C, R>(
params: &CreateParams<E, Args, Salt, C>,
) -> Result<E::AccountId>
) -> Result<R>
// ) -> Result<E::AccountId>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: scale::Decode,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::instantiate_contract::<E, Args, Salt, C>(instance, params)
TypedEnvBackend::instantiate_contract::<E, Args, Salt, C, R>(instance, params)
})
}

Expand Down
8 changes: 5 additions & 3 deletions crates/env/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,14 +439,16 @@ pub trait TypedEnvBackend: EnvBackend {
/// # Note
///
/// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`]
fn instantiate_contract<E, Args, Salt, C>(
fn instantiate_contract<E, Args, Salt, C, R>(
&mut self,
params: &CreateParams<E, Args, Salt, C>,
) -> Result<E::AccountId>
) -> Result<R>
// ) -> Result<E::AccountId>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>;
Salt: AsRef<[u8]>,
R: scale::Decode;

/// Terminates a smart contract.
///
Expand Down
49 changes: 40 additions & 9 deletions crates/env/src/call/create_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,13 @@ where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: FromAccountId<E>,
R: scale::Decode,
// R: FromAccountId<E>,
{
/// Instantiates the contract and returns its account ID back to the caller.
#[inline]
pub fn instantiate(&self) -> Result<R, crate::Error> {
crate::instantiate_contract(self).map(FromAccountId::from_account_id)
crate::instantiate_contract(self) //.map(FromAccountId::from_account_id)
}
}

Expand All @@ -135,7 +136,7 @@ where
endowment: Endowment,
exec_input: Args,
salt: Salt,
return_type: ReturnType<R>,
return_type: R,
_phantom: PhantomData<fn() -> E>,
}

Expand Down Expand Up @@ -195,11 +196,12 @@ pub fn build_create<E, R>() -> CreateBuilder<
Unset<E::Balance>,
Unset<ExecutionInput<EmptyArgumentList>>,
Unset<state::Salt>,
R,
Unset<ReturnType<R>>,
>
where
E: Environment,
R: FromAccountId<E>,
R: scale::Decode,
// R: FromAccountId<E>,
{
CreateBuilder {
code_hash: Default::default(),
Expand Down Expand Up @@ -281,6 +283,34 @@ where
}
}

impl<E, CodeHash, GasLimit, Endowment, Args, Salt>
CreateBuilder<E, CodeHash, GasLimit, Endowment, Args, Salt, Unset<ReturnType<()>>>
where
E: Environment,
{
/// Sets the type of the returned value upon the execution of the call.
///
/// # Note
///
/// Either use `.returns::<()>` to signal that the call does not return a value
/// or use `.returns::<T>` to signal that the call returns a value of type `T`.
#[inline]
pub fn returns<R>(
self,
) -> CreateBuilder<E, CodeHash, GasLimit, Endowment, Args, Salt, Set<ReturnType<R>>>
{
CreateBuilder {
code_hash: self.code_hash,
gas_limit: self.gas_limit,
endowment: self.endowment,
exec_input: self.exec_input,
salt: self.salt,
return_type: Set(Default::default()),
_phantom: Default::default(),
}
}
}

impl<E, CodeHash, GasLimit, Endowment, Salt, R>
CreateBuilder<
E,
Expand Down Expand Up @@ -347,7 +377,7 @@ impl<E, GasLimit, Args, Salt, R>
Set<E::Balance>,
Set<ExecutionInput<Args>>,
Set<Salt>,
R,
Set<ReturnType<R>>,
>
where
E: Environment,
Expand All @@ -362,7 +392,7 @@ where
endowment: self.endowment.value(),
exec_input: self.exec_input.value(),
salt_bytes: self.salt.value(),
_return_type: self.return_type,
_return_type: Default::default(),
}
}
}
Expand All @@ -375,14 +405,15 @@ impl<E, GasLimit, Args, Salt, R>
Set<E::Balance>,
Set<ExecutionInput<Args>>,
Set<Salt>,
R,
Set<ReturnType<R>>,
>
where
E: Environment,
GasLimit: Unwrap<Output = u64>,
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: FromAccountId<E>,
R: scale::Decode,
// R: FromAccountId<E>,
{
/// Instantiates the contract using the given instantiation parameters.
#[inline]
Expand Down
6 changes: 4 additions & 2 deletions crates/env/src/engine/off_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,14 +469,16 @@ impl TypedEnvBackend for EnvInstance {
)
}

fn instantiate_contract<E, Args, Salt, C>(
fn instantiate_contract<E, Args, Salt, C, R>(
&mut self,
params: &CreateParams<E, Args, Salt, C>,
) -> Result<E::AccountId>
) -> Result<R>
// ) -> Result<E::AccountId>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: scale::Decode,
{
let _code_hash = params.code_hash();
let _gas_limit = params.gas_limit();
Expand Down
38 changes: 32 additions & 6 deletions crates/env/src/engine/on_chain/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -479,14 +479,16 @@ impl TypedEnvBackend for EnvInstance {
}
}

fn instantiate_contract<E, Args, Salt, C>(
fn instantiate_contract<E, Args, Salt, C, R>(
&mut self,
params: &CreateParams<E, Args, Salt, C>,
) -> Result<E::AccountId>
) -> Result<R>
// ) -> Result<E::AccountId>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: scale::Decode,
{
let mut scoped = self.scoped_buffer();
let gas_limit = params.gas_limit();
Expand All @@ -503,17 +505,41 @@ impl TypedEnvBackend for EnvInstance {
// This should change in the future but for that we need to add support
// for constructors that may return values.
// This is useful to support fallible constructors for example.
ext::instantiate(
//
// TODO: Support this output buffer?
let instantiate_result = ext::instantiate(
enc_code_hash,
gas_limit,
enc_endowment,
enc_input,
out_address,
out_return_value,
salt,
)?;
let account_id = scale::Decode::decode(&mut &out_address[..])?;
Ok(account_id)
);

match instantiate_result {
Ok(()) => {
// The Ok case always needs to decode into an address
//
// This decodes to an `E::AccountId`
//
// But here I want an `Ok(E::AccountId)`
let account_id = scale::Decode::decode(&mut &out_address[..])?;
Ok(account_id)

// let out = scale::Decode::decode(&mut &out_return_value[..])?;
// Ok(out)
}
Err(ext::Error::CalleeReverted) => {
// This decodes to an `Err(CouldNotReadInput)`
let out = scale::Decode::decode(&mut &out_return_value[..])?;
Ok(out)
}
Err(actual_error) => Err(actual_error.into()),
}

// let account_id = scale::Decode::decode(&mut &out_address[..])?;
// Ok(account_id)
}

fn terminate_contract<E>(&mut self, beneficiary: E::AccountId) -> !
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,7 @@ impl ContractRef<'_> {
let input_bindings = generator::input_bindings(constructor.inputs());
let input_types = generator::input_types(constructor.inputs());
let arg_list = generator::generate_argument_list(input_types.iter().cloned());
let return_type = constructor.wrapped_output();
quote_spanned!(span =>
#( #attrs )*
#[inline]
Expand All @@ -416,9 +417,10 @@ impl ContractRef<'_> {
::ink::env::call::utils::Unset<Balance>,
::ink::env::call::utils::Set<::ink::env::call::ExecutionInput<#arg_list>>,
::ink::env::call::utils::Unset<::ink::env::call::state::Salt>,
Self,
::ink::env::call::utils::Unset<::ink::env::call::utils::ReturnType<#return_type>>,
// Self,
> {
::ink::env::call::build_create::<Environment, Self>()
::ink::env::call::build_create::<Environment, #return_type>()
.exec_input(
::ink::env::call::ExecutionInput::new(
::ink::env::call::Selector::new([ #( #selector_bytes ),* ])
Expand Down
15 changes: 15 additions & 0 deletions crates/ink/ir/src/ir/item_impl/constructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,21 @@ impl Constructor {
syn::ReturnType::Type(_, return_type) => Some(return_type),
}
}

/// Returns the return type of the constructor, but wrapped within a `Result`.
///
/// This is used to to allow callers to handle certain types of errors which are not exposed
/// by constructors.
pub fn wrapped_output(&self) -> syn::Type {
let return_type = self
.output()
.map(quote::ToTokens::to_token_stream)
.unwrap_or_else(|| quote::quote! { Self });

syn::parse_quote! {
::ink::ConstructorResult<#return_type>
}
}
}

#[cfg(test)]
Expand Down
8 changes: 5 additions & 3 deletions crates/ink/src/env_access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,15 +469,17 @@ where
/// # Note
///
/// For more details visit: [`ink_env::instantiate_contract`]
pub fn instantiate_contract<Args, Salt, C>(
pub fn instantiate_contract<Args, Salt, C, R>(
self,
params: &CreateParams<E, Args, Salt, C>,
) -> Result<E::AccountId>
) -> Result<R>
// ) -> Result<E::AccountId>
where
Args: scale::Encode,
Salt: AsRef<[u8]>,
R: scale::Decode,
{
ink_env::instantiate_contract::<E, Args, Salt, C>(params)
ink_env::instantiate_contract::<E, Args, Salt, C, R>(params)
}

/// Invokes a contract message and returns its result.
Expand Down
43 changes: 21 additions & 22 deletions examples/lang-err-integration-tests/call-builder/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,24 +62,35 @@ mod call_builder {
code_hash: Hash,
selector: [u8; 4],
init_value: bool,
) -> Option<AccountId> {
) -> Option<::ink::LangError> {
use ink::env::call::build_create;

let result = build_create::<
DefaultEnvironment,
constructors_return_value::ConstructorsReturnValueRef,
_,
// constructors_return_value::ConstructorsReturnValueRef,
>()
.code_hash(code_hash)
.gas_limit(0)
.endowment(0)
.exec_input(ExecutionInput::new(Selector::new(selector)).push_arg(init_value))
.salt_bytes(&[0xDE, 0xAD, 0xBE, 0xEF])
.returns::<Result<
constructors_return_value::ConstructorsReturnValueRef,
::ink::LangError,
>>()
.params()
.instantiate();
.instantiate()
.expect("Error from the Contracts pallet.");
::ink::env::debug_println!("Result from `instantiate` {:?}", &result);

// NOTE: Right now we can't handle any `LangError` from `instantiate`, we can only tell
// that our contract reverted (i.e we see error from the Contracts pallet).
result.ok().map(|id| ink::ToAccountId::to_account_id(&id))
match result {
Ok(_) => None,
Err(e @ ink::LangError::CouldNotReadInput) => Some(e),
Err(_) => {
unimplemented!("No other `LangError` variants exist at the moment.")
}
}
}
}

Expand Down Expand Up @@ -205,14 +216,8 @@ mod call_builder {
None,
)
.await
.expect("Client failed to call `call_builder::call_instantiate`.")
.value
.expect("Dispatching `call_builder::call_instantiate` failed.");

assert!(
call_result.is_some(),
"Call using valid selector failed, when it should've succeeded."
);
.expect("Calling `call_builder::call_instantiate` failed");
dbg!(&call_result.value);

Ok(())
}
Expand Down Expand Up @@ -254,14 +259,8 @@ mod call_builder {
None,
)
.await
.expect("Client failed to call `call_builder::call_instantiate`.")
.value
.expect("Dispatching `call_builder::call_instantiate` failed.");

assert!(
call_result.is_none(),
"Call using invalid selector succeeded, when it should've failed."
);
.expect("Client failed to call `call_builder::call_instantiate`.");
dbg!(&call_result.value);

Ok(())
}
Expand Down

0 comments on commit 8796a62

Please sign in to comment.