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] method to generate and fund unique accounts #1615

Merged
merged 215 commits into from
Jan 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
215 commits
Select commit Hold shift + click to select a range
8796a62
Handle `LangError` from instantiate (fails for success case)
HCastano Nov 19, 2022
95b80c4
Change generic in `CreateBuilder` to be more consistent
HCastano Nov 25, 2022
a49fcb7
Remove extra generic parameter
HCastano Nov 25, 2022
8312fa8
Remove generic return type parameter from `CreateBuidler` codegen
HCastano Nov 25, 2022
6e70be0
Hardcode assumption that `instantiate` returns a `ConstructorResult`
HCastano Nov 25, 2022
2fd4a82
Update `CreateBuilder` codegen to just return `Self`
HCastano Nov 25, 2022
4d1f2bf
Remove generic usage to fix formatting
HCastano Nov 28, 2022
f107cb1
Unwrap `ConstructorResult` in `contract-ref` E2E test
HCastano Nov 28, 2022
b6de9fc
Clean up some comments
HCastano Nov 28, 2022
5d221c3
Bring back the assumption that we expect an `AccountId`
HCastano Nov 28, 2022
7d94f75
Remove unused method
HCastano Nov 28, 2022
798f946
Update doc tests for new builder pattern
HCastano Nov 28, 2022
18d0922
Clean up some comments
HCastano Nov 28, 2022
06bba81
Fix Clippy warning
HCastano Nov 28, 2022
612537e
Fix typo
HCastano Nov 28, 2022
2175174
Add `try_instantiate` method to `CreateBuilder`
HCastano Nov 28, 2022
44a8324
Remove unneeded `unwrap`
HCastano Nov 29, 2022
84d257d
Remove debug logging
HCastano Nov 29, 2022
ffcca2c
Update doc test
HCastano Nov 29, 2022
91cd98f
Fix some typos
HCastano Nov 29, 2022
e701230
Mention panicking behaviour of `instantiate` methods
HCastano Nov 29, 2022
f2d85dd
Improve error messages from wrong `returns()` type
HCastano Nov 29, 2022
addcda2
Actually check return values from `call_instantiate`
HCastano Nov 29, 2022
4c99daf
Add test showing a reverting constructor with `Ok` in error buffer
HCastano Nov 29, 2022
99c859b
Check that we're only returning `LangError`s if the contract reverted
HCastano Nov 29, 2022
323ed2d
Clean up the manual encoding test a bit
HCastano Nov 30, 2022
b6fc625
Add test for constructors which return a contract level error
HCastano Dec 1, 2022
ac6b197
Add `CreateBuilder` message which calls a fallible constructor
HCastano Dec 3, 2022
b06a9f8
Add test which calls falliable constructor for success case
HCastano Dec 5, 2022
7d664a0
Get verbose `instantiate_contract_with_result` decoding past typechecker
HCastano Dec 5, 2022
f874c97
Add `try_instantiate_with_result` to `CreateBuilder`
HCastano Dec 5, 2022
c29895a
Clean up decoding logic for output from `seal_instatiate`
HCastano Dec 5, 2022
dbb079e
Small cleanups in `call-builder` E2E tests
HCastano Dec 5, 2022
6125690
RustFmt `env_access`
HCastano Dec 5, 2022
aa4f897
Remove unused import
HCastano Dec 5, 2022
053218f
Flip decoding logic so that it's more strict initially
HCastano Dec 6, 2022
77c790f
Add test which revert a fallible constructor
HCastano Dec 6, 2022
713ad1e
Remove note about removing `assert` statement
HCastano Dec 6, 2022
64a711c
Check return value from fallible constructor tests
HCastano Dec 6, 2022
54fcf90
Merge branch 'master' into hc-get-lang-error-from-create-builder
HCastano Dec 6, 2022
c17fc3b
Update E2E Builder typedef to match changes
HCastano Dec 6, 2022
32f4a75
Update E2E test for new call syntax
HCastano Dec 6, 2022
a3cfbb8
Use `selector_bytes!` macro in more places
HCastano Dec 6, 2022
283e182
Change order to accounts used in tests
HCastano Dec 6, 2022
cc98baf
Update function names to use `fallible`
HCastano Dec 6, 2022
f01b5ca
Add note about docs
HCastano Dec 6, 2022
c794ec9
Merge branch 'master' into hc-get-lang-error-from-create-builder
HCastano Dec 7, 2022
b4290cb
Update `ContractRef` codegen to use fallible constructor return types
HCastano Dec 7, 2022
d47bf8f
Stop returning an `AccountId` directly from `CreateBuilder::try_insta…
HCastano Dec 7, 2022
b720ede
Add panicking version of `try_instantiate_fallible`
HCastano Dec 7, 2022
75cad9e
Add test for using fallible constructors through ContractRefs
HCastano Dec 7, 2022
cf2516f
Add test for instantiation failure too
HCastano Dec 7, 2022
f9b3004
Add `instantiate_fallible` to `CreateParams`
HCastano Dec 7, 2022
d511b3f
Add a couple of missing docs
HCastano Dec 7, 2022
550b728
Convert `call-builder` test return type to `AccountId`
HCastano Dec 7, 2022
1668ae0
Extract reverted fallible constructor fn for testing
ascjones Dec 8, 2022
acf23b9
Fmt
ascjones Dec 8, 2022
e69e7ce
Add fallible_constructor_reverted_lang_error FAILs
ascjones Dec 8, 2022
f084763
Rename tests
ascjones Dec 8, 2022
74f2392
Add test for a decode error
ascjones Dec 8, 2022
e3a99f9
Rename some tests
ascjones Dec 8, 2022
56e8d52
Make `Result` types more explicit
HCastano Dec 8, 2022
50c227b
Add another test
HCastano Dec 8, 2022
8ce1d92
Clean up decoding match statement
HCastano Dec 8, 2022
c291b3c
Andrew was right
HCastano Dec 9, 2022
f0561e5
Small cleanups to naming and imports
HCastano Dec 11, 2022
1742a01
Couple more import and comment fixes
HCastano Dec 11, 2022
25d8326
Use decode trait method directly
HCastano Dec 11, 2022
24e9424
Fix `call-builder` E2E tests
HCastano Dec 11, 2022
e7bba67
Remove leading colons from non-codegen contexts
HCastano Dec 11, 2022
ebd42f3
Add doc test for `instantiate_fallible_contract`
HCastano Dec 11, 2022
0a99f16
Add doc test to `build_create` function
HCastano Dec 11, 2022
6cf60e6
Remove leftover trait bound
HCastano Dec 11, 2022
581291b
Remove a few more leading colons
HCastano Dec 11, 2022
95f9e6e
Panic in case where we get `Ok` encoded into error buffer
HCastano Dec 12, 2022
0d40825
Add some links to env docs
HCastano Dec 12, 2022
c8e5cfa
Add more docs to `call-builder` E2E tests
HCastano Dec 12, 2022
1e323f4
Use correct path in `call-builder` docs
HCastano Dec 12, 2022
57a7a6b
Remove fallible create_builder.rs methods
ascjones Jan 13, 2023
99a37b8
WIP experiment
ascjones Jan 14, 2023
2bd176b
InstantiateResult blanket impl for T and Result
ascjones Jan 14, 2023
fa47e25
Introduce ContractRef type parameter
ascjones Jan 14, 2023
9ac5f02
Fix up env access
ascjones Jan 14, 2023
361a0b6
WIP...
ascjones Jan 14, 2023
d1d11a7
Make it compile
ascjones Jan 15, 2023
f7b8571
Add ContractStorage parameter
ascjones Jan 16, 2023
448b380
Remove commented out instantiate_fallible_contract
ascjones Jan 16, 2023
a0799d0
Convert to env Error in helper
ascjones Jan 16, 2023
83c9ea2
Return Decode errors in case of invalid Result first byte
ascjones Jan 16, 2023
89c7740
Fix impls::instantiate_contract
ascjones Jan 16, 2023
7e7979a
Remove ContractStorage generic parameter
ascjones Jan 17, 2023
aca74ac
Fix env access
ascjones Jan 17, 2023
604a16a
Use generated constructor ref, introduces update_selector
ascjones Jan 17, 2023
fcc7b1e
Fix e2e
ascjones Jan 17, 2023
0b31392
Merge branch 'master' into hc-get-lang-error-from-create-builder
ascjones Jan 18, 2023
9a14e21
Use return_value() method in e2e test
ascjones Jan 18, 2023
cde8f6d
Merge branch 'hc-get-lang-error-from-create-builder' into aj/get-lang…
ascjones Jan 18, 2023
1af170b
Remove commented out code
ascjones Jan 17, 2023
a7a2f7a
Typos
ascjones Jan 18, 2023
e259331
Clippy
ascjones Jan 18, 2023
9cb02cb
Rename some instantiate_fallible
ascjones Jan 18, 2023
24f8e83
Restore `returns` method
ascjones Jan 18, 2023
5fb5736
Remove ContractReference Result impl
ascjones Jan 19, 2023
167a216
WIP implementing ConstructorReturnType
ascjones Jan 19, 2023
ac70452
Reorder ContractRef parameter, move ContractRef and ContractEnv trait…
ascjones Jan 19, 2023
1736a6a
Fmt and fix
ascjones Jan 19, 2023
252a5ef
Remove E param from build_create
ascjones Jan 19, 2023
f3bf476
Fix up build_create
ascjones Jan 20, 2023
8684af8
Fix up e2e creat builder
ascjones Jan 20, 2023
a1d6fc7
Implement ContstructorReturnType for the storage_ident
ascjones Jan 20, 2023
7b9f6e4
Fmt
ascjones Jan 20, 2023
54ea022
Fix envaccess test
ascjones Jan 20, 2023
9657d95
Fully qualify Result in macro
ascjones Jan 20, 2023
e6c8e1c
More fully qualify Result in macro
ascjones Jan 20, 2023
ed3136f
Fix up build_create examples
ascjones Jan 20, 2023
19aaec2
Add test for different combos of Self and struct name
ascjones Jan 20, 2023
e9fe0e7
Fix ui test
ascjones Jan 20, 2023
431aa2b
Fmt
ascjones Jan 20, 2023
f9c474d
Remove unused assoc type
ascjones Jan 20, 2023
7286c4e
Change error fn to return Option<Result>
ascjones Jan 20, 2023
698f7e3
Remove commented out code
ascjones Jan 20, 2023
69946de
Merge branch 'master' into hc-get-lang-error-from-create-builder
HCastano Jan 20, 2023
e9cd71c
Fmt
ascjones Jan 20, 2023
37d8e80
Fix `call-builder` E2E test compilation
HCastano Jan 20, 2023
0c568b5
Fix `contract-ref` E2E test compilation
HCastano Jan 20, 2023
612fae4
ConstructorReturnType comments
ascjones Jan 20, 2023
36e396c
Merge branch 'hc-get-lang-error-from-create-builder' into aj/get-lang…
ascjones Jan 20, 2023
6993240
Fix up return types after merge
ascjones Jan 20, 2023
a15a20c
Fmt
ascjones Jan 20, 2023
d7b83c5
Clippy
ascjones Jan 20, 2023
417dca5
Fix create_builder tests
ascjones Jan 20, 2023
7d20051
Fix some of the comment links
HCastano Jan 21, 2023
eeb7b85
Unwrap errors from default `instantiate_fallible` codepath
HCastano Jan 21, 2023
658fed1
Fix `contract-ref` E2E test
HCastano Jan 21, 2023
aac62db
Wrap long line
HCastano Jan 21, 2023
619cc71
Remove TODO
HCastano Jan 21, 2023
dd41485
Fix instatiation doc test
HCastano Jan 21, 2023
b41ca87
Merge branch 'master' into hc-get-lang-error-from-create-builder
HCastano Jan 21, 2023
cd33f29
Fix cross-contract compile test
HCastano Jan 21, 2023
4897616
Clean up some comments
HCastano Jan 21, 2023
459c4e0
Fix `contract-ref` compilation
HCastano Jan 21, 2023
19d5b4b
Remove outdated doc
HCastano Jan 21, 2023
193c801
Update comment
HCastano Jan 21, 2023
5ff122e
Another comment fix
HCastano Jan 21, 2023
229c4c2
Merge branch 'hc-get-lang-error-from-create-builder' into aj/get-lang…
HCastano Jan 21, 2023
4dd4a3f
Bump `contract-metadata`
HCastano Jan 21, 2023
3758e09
Remove fallible create_builder.rs methods
ascjones Jan 13, 2023
cdcc502
WIP experiment
ascjones Jan 14, 2023
6f59077
InstantiateResult blanket impl for T and Result
ascjones Jan 14, 2023
baecba9
Introduce ContractRef type parameter
ascjones Jan 14, 2023
af69cd5
Fix up env access
ascjones Jan 14, 2023
e134a8c
WIP...
ascjones Jan 14, 2023
115dd9f
Make it compile
ascjones Jan 15, 2023
718d475
Add ContractStorage parameter
ascjones Jan 16, 2023
bb5042e
Remove commented out instantiate_fallible_contract
ascjones Jan 16, 2023
528cfe0
Convert to env Error in helper
ascjones Jan 16, 2023
7b4c5e9
Return Decode errors in case of invalid Result first byte
ascjones Jan 16, 2023
4de38f5
Fix impls::instantiate_contract
ascjones Jan 16, 2023
09545fe
Remove ContractStorage generic parameter
ascjones Jan 17, 2023
2ef624d
Fix env access
ascjones Jan 17, 2023
02f97b1
Use generated constructor ref, introduces update_selector
ascjones Jan 17, 2023
39b45b0
Fix e2e
ascjones Jan 17, 2023
dc2f7bb
Remove commented out code
ascjones Jan 17, 2023
39ab13f
Typos
ascjones Jan 18, 2023
60e7e90
Clippy
ascjones Jan 18, 2023
43c2fe0
Rename some instantiate_fallible
ascjones Jan 18, 2023
bf3055c
Restore `returns` method
ascjones Jan 18, 2023
322ab26
Remove ContractReference Result impl
ascjones Jan 19, 2023
e61a12b
WIP implementing ConstructorReturnType
ascjones Jan 19, 2023
62052a6
Reorder ContractRef parameter, move ContractRef and ContractEnv trait…
ascjones Jan 19, 2023
2ed5093
Fmt and fix
ascjones Jan 19, 2023
df4a067
Remove E param from build_create
ascjones Jan 19, 2023
0e69431
Fix up build_create
ascjones Jan 20, 2023
e8feae9
Fix up e2e creat builder
ascjones Jan 20, 2023
2265258
Implement ContstructorReturnType for the storage_ident
ascjones Jan 20, 2023
10d7268
Fmt
ascjones Jan 20, 2023
ea65c47
Fix envaccess test
ascjones Jan 20, 2023
258c27b
Fully qualify Result in macro
ascjones Jan 20, 2023
08dc991
More fully qualify Result in macro
ascjones Jan 20, 2023
4be979d
Fix up build_create examples
ascjones Jan 20, 2023
0994c67
Add test for different combos of Self and struct name
ascjones Jan 20, 2023
f1f4930
Fix ui test
ascjones Jan 20, 2023
12f51dc
Fmt
ascjones Jan 20, 2023
1bceab3
Remove unused assoc type
ascjones Jan 20, 2023
8e0a9ef
Change error fn to return Option<Result>
ascjones Jan 20, 2023
aea1238
Remove commented out code
ascjones Jan 20, 2023
163fa6b
Fmt
ascjones Jan 20, 2023
1dd00d6
ConstructorReturnType comments
ascjones Jan 20, 2023
327967d
Fix `contract-ref` E2E test compilation
HCastano Jan 20, 2023
0bb7a8d
Fix up return types after merge
ascjones Jan 20, 2023
75ab4e6
Fmt
ascjones Jan 20, 2023
77a5bab
Clippy
ascjones Jan 20, 2023
7d03708
Fix create_builder tests
ascjones Jan 20, 2023
ca47caf
Fix cross-contract compile test
HCastano Jan 21, 2023
2cc8a22
Clean up some comments
HCastano Jan 21, 2023
fa0436a
Remove outdated doc
HCastano Jan 21, 2023
016b102
Update comment
HCastano Jan 21, 2023
9655072
Another comment fix
HCastano Jan 21, 2023
7aecb5f
Wrap long line
HCastano Jan 21, 2023
6f92033
Remove TODO
HCastano Jan 21, 2023
498c640
Bump `contract-metadata`
HCastano Jan 21, 2023
8e60ec2
Fix `CreateBuilder` compilation
HCastano Jan 24, 2023
a9c0223
Fix one of the doc tests
HCastano Jan 24, 2023
db1a808
Clean up doc tests a bit
HCastano Jan 24, 2023
810e0aa
WIP create accounts
ascjones Jan 24, 2023
5aff43c
Try transfer balance
ascjones Jan 24, 2023
23130ec
WIP try creating and funding account for single test.
ascjones Jan 24, 2023
e102f43
Update all tests to use create_and_fund_account
ascjones Jan 24, 2023
9ff6e6a
Merge branch 'aj/get-lang-error-from-create-builder' into aj/e2e-acco…
ascjones Jan 24, 2023
7ad477b
Fix error
ascjones Jan 24, 2023
2f4df64
Fmt
ascjones Jan 24, 2023
7f8016b
SP
ascjones Jan 24, 2023
6c2beb9
Clippy
ascjones Jan 24, 2023
b584734
Remove commented out code
ascjones Jan 24, 2023
1159ab6
Update crates/e2e/src/xts.rs
ascjones Jan 24, 2023
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
2 changes: 1 addition & 1 deletion crates/e2e/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ ink = { version = "4.0.0-beta", path = "../ink" }
ink_env = { version = "4.0.0-beta", path = "../env" }
ink_primitives = { version = "4.0.0-beta", path = "../primitives" }

contract-metadata = { version = "2.0.0-beta.1" }
contract-metadata = { version = "2.0.0-rc" }
impl-serde = { version = "0.3.1", default-features = false }
jsonrpsee = { version = "0.16.0", features = ["ws-client"] }
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
Expand Down
12 changes: 8 additions & 4 deletions crates/e2e/src/builders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ use scale::Encode;

/// The type returned from `ContractRef` constructors, partially initialized with the execution
/// input arguments.
pub type CreateBuilderPartial<E, Args, R> = CreateBuilder<
pub type CreateBuilderPartial<E, ContractRef, Args, R> = CreateBuilder<
E,
ContractRef,
Unset<<E as Environment>::Hash>,
Unset<u64>,
Unset<<E as Environment>::Balance>,
Expand All @@ -43,9 +44,12 @@ pub type CreateBuilderPartial<E, Args, R> = CreateBuilder<
>;

/// Get the encoded constructor arguments from the partially initialized `CreateBuilder`
pub fn constructor_exec_input<E: Environment, Args: Encode, R>(
builder: CreateBuilderPartial<E, Args, R>,
) -> Vec<u8> {
pub fn constructor_exec_input<E, ContractRef, Args: Encode, R>(
builder: CreateBuilderPartial<E, ContractRef, Args, R>,
) -> Vec<u8>
where
E: Environment,
{
// set all the other properties to default values, we only require the `exec_input`.
builder
.endowment(0u32.into())
Expand Down
73 changes: 58 additions & 15 deletions crates/e2e/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ use super::{
log_error,
log_info,
sr25519,
xts::{
Call,
InstantiateWithCode,
},
CodeUploadResult,
ContractExecResult,
ContractInstantiateResult,
Expand All @@ -35,6 +31,7 @@ use contract_metadata::ContractMetadata;
use ink_env::Environment;
use ink_primitives::MessageResult;

use sp_core::Pair;
use sp_runtime::traits::{
IdentifyAccount,
Verify,
Expand All @@ -55,7 +52,10 @@ use subxt::{
ValueDef,
},
},
tx::ExtrinsicParams,
tx::{
ExtrinsicParams,
PairSigner,
},
};

/// Result of a contract instantiation.
Expand Down Expand Up @@ -300,11 +300,8 @@ where

E: Environment,
E::AccountId: Debug,
E::Balance: Debug + scale::Encode + serde::Serialize,
E::Balance: Debug + scale::HasCompact + serde::Serialize,
E::Hash: Debug + scale::Encode,

Call<E, E::Balance>: scale::Encode,
InstantiateWithCode<E::Balance>: scale::Encode,
{
/// Creates a new [`Client`] instance.
pub async fn new(url: &str, contracts: impl IntoIterator<Item = &str>) -> Self {
Expand Down Expand Up @@ -342,6 +339,52 @@ where
}
}

/// Generate a new keypair and fund with the given amount from the origin account.
///
/// Because many tests may execute this in parallel, transfers may fail due to a race condition
/// with account indices. Therefore this will reattempt transfers a number of times.
pub async fn create_and_fund_account(
&self,
origin: &Signer<C>,
amount: E::Balance,
) -> Signer<C>
where
E::Balance: Clone,
C::AccountId: Clone + core::fmt::Display,
{
let (pair, _, _) = <sr25519::Pair as Pair>::generate_with_phrase(None);
let account_id =
<C::Signature as Verify>::Signer::from(pair.public()).into_account();

for _ in 0..6 {
let transfer_result = self
.api
.try_transfer_balance(origin, account_id.clone(), amount)
.await;
match transfer_result {
Ok(_) => {
log_info(&format!(
"transfer from {} to {} succeeded",
origin.account_id(),
account_id,
));
break
}
Err(err) => {
log_info(&format!(
"transfer from {} to {} failed with {:?}",
origin.account_id(),
account_id,
err
));
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
}
}
}

PairSigner::new(pair)
}

/// This function extracts the metadata of the contract at the file path
/// `target/ink/$contract_name.contract`.
///
Expand All @@ -350,11 +393,11 @@ where
/// Calling this function multiple times is idempotent, the contract is
/// newly instantiated each time using a unique salt. No existing contract
/// instance is reused!
pub async fn instantiate<Args, R>(
pub async fn instantiate<ContractRef, Args, R>(
&mut self,
contract_name: &str,
signer: &Signer<C>,
constructor: CreateBuilderPartial<E, Args, R>,
constructor: CreateBuilderPartial<E, ContractRef, Args, R>,
value: E::Balance,
storage_deposit_limit: Option<E::Balance>,
) -> Result<InstantiationResult<C, E>, Error<C, E>>
Expand All @@ -374,11 +417,11 @@ where
}

/// Dry run contract instantiation using the given constructor.
pub async fn instantiate_dry_run<Args, R>(
pub async fn instantiate_dry_run<ContractRef, Args, R>(
&mut self,
contract_name: &str,
signer: &Signer<C>,
constructor: CreateBuilderPartial<E, Args, R>,
constructor: CreateBuilderPartial<E, ContractRef, Args, R>,
value: E::Balance,
storage_deposit_limit: Option<E::Balance>,
) -> ContractInstantiateResult<C::AccountId, E::Balance>
Expand Down Expand Up @@ -406,11 +449,11 @@ where
}

/// Executes an `instantiate_with_code` call and captures the resulting events.
async fn exec_instantiate<Args, R>(
async fn exec_instantiate<ContractRef, Args, R>(
&mut self,
signer: &Signer<C>,
code: Vec<u8>,
constructor: CreateBuilderPartial<E, Args, R>,
constructor: CreateBuilderPartial<E, ContractRef, Args, R>,
value: E::Balance,
storage_deposit_limit: Option<E::Balance>,
) -> Result<InstantiationResult<C, E>, Error<C, E>>
Expand Down
58 changes: 54 additions & 4 deletions crates/e2e/src/xts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,25 @@ pub struct Call<E: Environment, B> {
data: Vec<u8>,
}

/// A raw call to `pallet-contracts`'s `call`.
#[derive(Debug, scale::Encode, scale::Decode)]
pub struct Call2<E: Environment, B> {
dest: sp_runtime::MultiAddress<E::AccountId, ()>,
#[codec(compact)]
value: B,
gas_limit: Weight,
storage_deposit_limit: Option<B>,
data: Vec<u8>,
}

/// A raw call to `pallet-contracts`'s `call`.
#[derive(Debug, scale::Encode, scale::Decode)]
pub struct Transfer<E: Environment, C: subxt::Config> {
dest: C::Address,
#[codec(compact)]
value: E::Balance,
}

#[derive(
Debug, Clone, Copy, scale::Encode, scale::Decode, PartialEq, Eq, serde::Serialize,
)]
Expand Down Expand Up @@ -167,10 +186,7 @@ where
sr25519::Signature: Into<C::Signature>,

E: Environment,
E::Balance: scale::Encode + serde::Serialize,

Call<E, E::Balance>: scale::Encode,
InstantiateWithCode<E::Balance>: scale::Encode,
E::Balance: scale::HasCompact + serde::Serialize,
{
/// Creates a new [`ContractsApi`] instance.
pub async fn new(client: OnlineClient<C>, url: &str) -> Self {
Expand All @@ -189,6 +205,40 @@ where
}
}

/// Attempt to transfer the `value` from `origin` to `dest`.
///
/// Returns `Ok` on success, and a [`subxt::Error`] if the extrinsic is
/// invalid (e.g. out of date nonce)
pub async fn try_transfer_balance(
&self,
origin: &Signer<C>,
dest: C::AccountId,
value: E::Balance,
) -> Result<(), subxt::Error> {
let call = subxt::tx::StaticTxPayload::new(
"Balances",
"transfer",
Transfer::<E, C> {
dest: dest.into(),
value,
},
Default::default(),
)
.unvalidated();

let tx_progress = self
.client
.tx()
.sign_and_submit_then_watch_default(&call, origin)
.await?;

tx_progress.wait_for_in_block().await.unwrap_or_else(|err| {
panic!("error on call `wait_for_in_block`: {:?}", err);
});

Ok(())
}

/// Dry runs the instantiation of the given `code`.
pub async fn instantiate_with_code_dry_run(
&self,
Expand Down
3 changes: 3 additions & 0 deletions crates/env/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ secp256k1 = { version = "0.26.0", features = ["recovery", "global-context"], opt
# Never use this crate outside the off-chain environment!
scale-info = { version = "2.3", default-features = false, features = ["derive"], optional = true }

[dev-dependencies]
ink = { path = "../ink" }

[features]
default = ["std"]
std = [
Expand Down
44 changes: 8 additions & 36 deletions crates/env/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,10 @@ use crate::{
call::{
Call,
CallParams,
ConstructorReturnType,
CreateParams,
DelegateCall,
FromAccountId,
},
engine::{
EnvInstance,
Expand Down Expand Up @@ -323,50 +325,20 @@ 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, R>(
params: &CreateParams<E, Args, Salt, R>,
) -> Result<ink_primitives::ConstructorResult<E::AccountId>>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::instantiate_contract::<E, Args, Salt, R>(instance, params)
})
}

/// Attempts to instantiate another contract, returning the instantiation result back to the
/// caller.
///
/// # Note
///
/// This is a low level way to instantiate another smart contract.
///
/// Prefer to use methods on a `ContractRef` or the [`CreateBuilder`](`crate::call::CreateBuilder`)
/// through [`build_create`](`crate::call::build_create`) instead.
///
/// # Errors
///
/// - If the code hash is invalid.
/// - If the arguments passed to the instantiation process are invalid.
/// - If the instantiation process traps.
/// - If the instantiation process runs out of gas.
/// - If given insufficient endowment.
/// - If the returned account ID failed to decode properly.
pub fn instantiate_fallible_contract<E, Args, Salt, R, ContractError>(
params: &CreateParams<E, Args, Salt, R>,
pub fn instantiate_contract<E, ContractRef, Args, Salt, R>(
params: &CreateParams<E, ContractRef, Args, Salt, R>,
) -> Result<
ink_primitives::ConstructorResult<core::result::Result<E::AccountId, ContractError>>,
ink_primitives::ConstructorResult<<R as ConstructorReturnType<ContractRef>>::Output>,
>
where
E: Environment,
ContractRef: FromAccountId<E>,
Args: scale::Encode,
Salt: AsRef<[u8]>,
ContractError: scale::Decode,
R: ConstructorReturnType<ContractRef>,
{
<EnvInstance as OnInstance>::on_instance(|instance| {
TypedEnvBackend::instantiate_fallible_contract::<E, Args, Salt, R, ContractError>(
TypedEnvBackend::instantiate_contract::<E, ContractRef, Args, Salt, R>(
instance, params,
)
})
Expand Down
26 changes: 7 additions & 19 deletions crates/env/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ use crate::{
call::{
Call,
CallParams,
ConstructorReturnType,
CreateParams,
DelegateCall,
FromAccountId,
},
hash::{
CryptoHash,
Expand Down Expand Up @@ -439,34 +441,20 @@ pub trait TypedEnvBackend: EnvBackend {
/// # Note
///
/// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`]
fn instantiate_contract<E, Args, Salt, R>(
fn instantiate_contract<E, ContractRef, Args, Salt, R>(
&mut self,
params: &CreateParams<E, Args, Salt, R>,
) -> Result<ink_primitives::ConstructorResult<E::AccountId>>
where
E: Environment,
Args: scale::Encode,
Salt: AsRef<[u8]>;

/// Attempts to instantiate another contract, returning the instantiation result back to the
/// caller.
///
/// # Note
///
/// For more details visit: [`instantiate_fallible_contract`][`crate::instantiate_fallible_contract`]
fn instantiate_fallible_contract<E, Args, Salt, R, ContractError>(
&mut self,
params: &CreateParams<E, Args, Salt, R>,
params: &CreateParams<E, ContractRef, Args, Salt, R>,
) -> Result<
ink_primitives::ConstructorResult<
core::result::Result<E::AccountId, ContractError>,
<R as ConstructorReturnType<ContractRef>>::Output,
>,
>
where
E: Environment,
ContractRef: FromAccountId<E>,
Args: scale::Encode,
Salt: AsRef<[u8]>,
ContractError: scale::Decode;
R: ConstructorReturnType<ContractRef>;

/// Terminates a smart contract.
///
Expand Down
Loading