From 7201353a6421c1fc86c86e70edb5653a58c15f40 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Wed, 27 Sep 2023 17:53:31 -0300 Subject: [PATCH 01/18] Add default accounts in integration test --- crates/env/Cargo.toml | 21 ++++- crates/env/src/engine/off_chain/test_api.rs | 99 +++++++++++++++++---- 2 files changed, 101 insertions(+), 19 deletions(-) diff --git a/crates/env/Cargo.toml b/crates/env/Cargo.toml index 5dd9275d2a3..59657e599cd 100644 --- a/crates/env/Cargo.toml +++ b/crates/env/Cargo.toml @@ -1,7 +1,10 @@ [package] name = "ink_env" version.workspace = true -authors = ["Parity Technologies ", "Robin Freyler "] +authors = [ + "Parity Technologies ", + "Robin Freyler ", +] edition.workspace = true rust-version = "1.68" @@ -41,7 +44,10 @@ sha3 = { workspace = true, optional = true } blake2 = { workspace = true, optional = true } # ECDSA for the off-chain environment. -secp256k1 = { workspace = true, features = ["recovery", "global-context"], optional = true } +secp256k1 = { workspace = true, features = [ + "recovery", + "global-context", +], optional = true } # schnorrkel for the off-chain environment. schnorrkel = { version = "0.11.2", optional = true } @@ -54,6 +60,17 @@ scale-decode = { workspace = true, optional = true } scale-encode = { workspace = true, optional = true } scale-info = { workspace = true, features = ["derive"], optional = true } +[dependencies.lazy_static] +version = "1.4.0" + +[dependencies.sp-core] +version = "21.0.0" + +[dependencies.strum] +version = "0.24.1" +features = ["derive"] +default-features = false + [dev-dependencies] ink = { path = "../ink" } diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index b36c58d2252..f2f70e77969 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -14,17 +14,18 @@ //! Operations on the off-chain testing environment. -use super::{ - EnvInstance, - OnInstance, -}; -use crate::{ - Environment, - Result, -}; +use super::{EnvInstance, OnInstance}; +use crate::{Environment, Result}; use core::fmt::Debug; use ink_engine::test_api::RecordedDebugMessages; -use std::panic::UnwindSafe; +use lazy_static::lazy_static; +pub use sp_core::sr25519; +use sp_core::{ + sr25519::{Pair, Public}, + Pair as PairT, +}; +use std::{collections::HashMap, panic::UnwindSafe}; +use strum::{Display, EnumIter, IntoEnumIterator}; pub use super::call_data::CallData; pub use ink_engine::ChainExtension; @@ -317,13 +318,13 @@ where .set_balance(scale::Encode::encode(&default_accounts.charlie), some); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.django), 0); + .set_balance(scale::Encode::encode(&default_accounts.dave), 0); instance .engine .set_balance(scale::Encode::encode(&default_accounts.eve), 0); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.frank), 0); + .set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); }); f(default_accounts) } @@ -339,9 +340,69 @@ where alice: T::AccountId::from([0x01; 32]), bob: T::AccountId::from([0x02; 32]), charlie: T::AccountId::from([0x03; 32]), - django: T::AccountId::from([0x04; 32]), + dave: T::AccountId::from([0x04; 32]), eve: T::AccountId::from([0x05; 32]), - frank: T::AccountId::from([0x06; 32]), + ferdie: T::AccountId::from([0x06; 32]), + one: T::AccountId::from([0x07; 32]), + two: T::AccountId::from([0x8; 32]), + } +} + +/// Set of test accounts. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumIter)] +pub enum KeyRing { + /// + Alice, + /// + Bob, + /// + Charlie, + /// + Dave, + /// + Eve, + /// + Ferdie, + /// + One, + /// + Two, +} + +lazy_static! { + static ref PRIVATE_KEYS: HashMap = + KeyRing::iter().map(|i| (i, i.pair())).collect(); + static ref PUBLIC_KEYS: HashMap = PRIVATE_KEYS + .iter() + .map(|(&name, pair)| (name, pair.public())) + .collect(); +} + +impl KeyRing { + /// + pub fn pair(self) -> Pair { + Pair::from_string(&format!("//{}", <&'static str>::from(self)), None) + .expect("static values are known good; qed") + } + + /// + pub fn iter() -> impl Iterator { + ::iter() + } +} + +impl From for &'static str { + fn from(k: KeyRing) -> Self { + match k { + KeyRing::Alice => "Alice", + KeyRing::Bob => "Bob", + KeyRing::Charlie => "Charlie", + KeyRing::Dave => "Dave", + KeyRing::Eve => "Eve", + KeyRing::Ferdie => "Ferdie", + KeyRing::One => "One", + KeyRing::Two => "Two", + } } } @@ -356,12 +417,16 @@ where pub bob: T::AccountId, /// The predefined `CHARLIE` account holding some amounts of value. pub charlie: T::AccountId, - /// The predefined `DJANGO` account holding no value. - pub django: T::AccountId, + /// The predefined `DAVE` account holding no value. + pub dave: T::AccountId, /// The predefined `EVE` account holding no value. pub eve: T::AccountId, - /// The predefined `FRANK` account holding no value. - pub frank: T::AccountId, + /// The predefined `FERDIE` account holding no value. + pub ferdie: T::AccountId, + /// The predefined `ONE` account holding no value. + pub one: T::AccountId, + /// The predefined `TWO` account holding no value. + pub two: T::AccountId, } /// Returns the recorded emitted events in order. From b65593ac28522cd3b92e13f1b42b9507d6714557 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Wed, 27 Sep 2023 23:16:34 -0300 Subject: [PATCH 02/18] Add sp_runtime dependency --- crates/env/Cargo.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/env/Cargo.toml b/crates/env/Cargo.toml index 59657e599cd..3f4f31c39e6 100644 --- a/crates/env/Cargo.toml +++ b/crates/env/Cargo.toml @@ -71,6 +71,9 @@ version = "0.24.1" features = ["derive"] default-features = false +[dependencies.sp-runtime] +version = "24.0.0" + [dev-dependencies] ink = { path = "../ink" } From 8780e701946733e810085e0638938492d68006be Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Wed, 27 Sep 2023 23:16:55 -0300 Subject: [PATCH 03/18] Add parsers to KeyRing struct --- crates/env/src/engine/off_chain/test_api.rs | 102 +++++++++++++++++++- 1 file changed, 100 insertions(+), 2 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index f2f70e77969..5cec3333eb4 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -16,14 +16,15 @@ use super::{EnvInstance, OnInstance}; use crate::{Environment, Result}; -use core::fmt::Debug; +use core::{fmt::Debug, ops::Deref}; use ink_engine::test_api::RecordedDebugMessages; use lazy_static::lazy_static; pub use sp_core::sr25519; use sp_core::{ sr25519::{Pair, Public}, - Pair as PairT, + ByteArray, Pair as PairT, H256, }; +use sp_runtime::AccountId32; use std::{collections::HashMap, panic::UnwindSafe}; use strum::{Display, EnumIter, IntoEnumIterator}; @@ -379,6 +380,46 @@ lazy_static! { } impl KeyRing { + /// + pub fn from_public(who: &Public) -> Option { + Self::iter().find(|&k| &Public::from(k) == who) + } + + /// + pub fn from_account_id(who: &AccountId32) -> Option { + Self::iter().find(|&k| &k.to_account_id() == who) + } + + /// + pub fn from_raw_public(who: [u8; 32]) -> Option { + Self::from_public(&Public::from_raw(who)) + } + + /// + pub fn to_raw_public(self) -> [u8; 32] { + *Public::from(self).as_array_ref() + } + + /// + pub fn from_h256_public(who: H256) -> Option { + Self::from_public(&Public::from_raw(who.into())) + } + + /// + pub fn to_h256_public_vec(self) -> H256 { + Public::from(self).as_array_ref().into() + } + + /// + pub fn to_raw_public_vec(self) -> Vec { + Public::from(self).to_raw_vec() + } + + /// + pub fn to_account_id(self) -> AccountId32 { + self.to_raw_public().into() + } + /// pub fn pair(self) -> Pair { Pair::from_string(&format!("//{}", <&'static str>::from(self)), None) @@ -391,6 +432,8 @@ impl KeyRing { } } +/// FROMS + impl From for &'static str { fn from(k: KeyRing) -> Self { match k { @@ -406,6 +449,61 @@ impl From for &'static str { } } +impl From for AccountId32 { + fn from(k: KeyRing) -> Self { + k.to_account_id() + } +} + +impl From for Public { + fn from(k: KeyRing) -> Self { + *(*PUBLIC_KEYS).get(&k).unwrap() + } +} + +impl From for Pair { + fn from(k: KeyRing) -> Self { + k.pair() + } +} + +impl From for [u8; 32] { + fn from(k: KeyRing) -> Self { + *(*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() + } +} + +impl From for H256 { + fn from(k: KeyRing) -> Self { + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref().into() + } +} + +impl From for &'static [u8; 32] { + fn from(k: KeyRing) -> Self { + (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() + } +} + +impl AsRef<[u8; 32]> for KeyRing { + fn as_ref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() + } +} + +impl AsRef for KeyRing { + fn as_ref(&self) -> &Public { + (*PUBLIC_KEYS).get(self).unwrap() + } +} + +impl Deref for KeyRing { + type Target = [u8; 32]; + fn deref(&self) -> &[u8; 32] { + (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() + } +} + /// The default accounts. pub struct DefaultAccounts where From f186cb0513c83007c8d886a9b5393c2b9e2c821d Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Thu, 28 Sep 2023 01:10:50 -0300 Subject: [PATCH 04/18] Add documentation and some functions to parse --- crates/env/src/engine/off_chain/test_api.rs | 191 +++++++++++++------- 1 file changed, 122 insertions(+), 69 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index 5cec3333eb4..9f535104dfb 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -331,173 +331,226 @@ where } /// Returns the default accounts for testing purposes: -/// Alice, Bob, Charlie, Django, Eve and Frank. +/// Alice, Bob, Charlie, Dave, Eve, Ferdie, One and Two. pub fn default_accounts() -> DefaultAccounts where T: Environment, ::AccountId: From<[u8; 32]>, { DefaultAccounts { - alice: T::AccountId::from([0x01; 32]), - bob: T::AccountId::from([0x02; 32]), - charlie: T::AccountId::from([0x03; 32]), - dave: T::AccountId::from([0x04; 32]), - eve: T::AccountId::from([0x05; 32]), - ferdie: T::AccountId::from([0x06; 32]), - one: T::AccountId::from([0x07; 32]), - two: T::AccountId::from([0x8; 32]), + alice: T::AccountId::from(Keyring::Alice.to_raw_public()), + bob: T::AccountId::from(Keyring::Bob.to_raw_public()), + charlie: T::AccountId::from(Keyring::Charlie.to_raw_public()), + dave: T::AccountId::from(Keyring::Dave.to_raw_public()), + eve: T::AccountId::from(Keyring::Eve.to_raw_public()), + ferdie: T::AccountId::from(Keyring::Ferdie.to_raw_public()), + one: T::AccountId::from(Keyring::One.to_raw_public()), + two: T::AccountId::from(Keyring::Two.to_raw_public()), + } +} + +lazy_static! { + static ref PRIVATE_KEYS: HashMap = + Keyring::iter().map(|i| (i, i.pair())).collect(); + static ref PUBLIC_KEYS: HashMap = PRIVATE_KEYS + .iter() + .map(|(&name, pair)| (name, pair.public())) + .collect(); +} + +/// A custom error type representing a failure to parse a keyring. +#[derive(Debug)] +pub struct ParseKeyringError; + +impl std::fmt::Display for ParseKeyringError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "ParseKeyringError") } } /// Set of test accounts. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumIter)] -pub enum KeyRing { - /// +pub enum Keyring { + /// The predefined `ALICE` keyring Alice, - /// + /// The predefined `Bob` keyring Bob, - /// + /// The predefined `Charlie` keyring Charlie, - /// + /// The predefined `Dave` keyring Dave, - /// + /// The predefined `Eve` keyring Eve, - /// + /// The predefined `Ferdie` keyring Ferdie, - /// + /// The predefined `One` keyring One, - /// + /// The predefined `Two` keyring Two, } -lazy_static! { - static ref PRIVATE_KEYS: HashMap = - KeyRing::iter().map(|i| (i, i.pair())).collect(); - static ref PUBLIC_KEYS: HashMap = PRIVATE_KEYS - .iter() - .map(|(&name, pair)| (name, pair.public())) - .collect(); -} - -impl KeyRing { - /// - pub fn from_public(who: &Public) -> Option { +impl Keyring { + /// Creates a `Keyring` from a `Public`. + pub fn from_public(who: &Public) -> Option { Self::iter().find(|&k| &Public::from(k) == who) } - /// - pub fn from_account_id(who: &AccountId32) -> Option { + /// Creates a `Keyring` from an `AccountId32`. + pub fn from_account_id(who: &AccountId32) -> Option { Self::iter().find(|&k| &k.to_account_id() == who) } - /// - pub fn from_raw_public(who: [u8; 32]) -> Option { + /// Creates a `Keyring` from a raw public key in the form of a 32-byte array. + pub fn from_raw_public(who: [u8; 32]) -> Option { Self::from_public(&Public::from_raw(who)) } - /// + /// Converts the public key of the `Keyring` into a 32-byte array. pub fn to_raw_public(self) -> [u8; 32] { *Public::from(self).as_array_ref() } - /// - pub fn from_h256_public(who: H256) -> Option { + /// Creates a `Keyring` from a public key in `H256` format. + pub fn from_h256_public(who: H256) -> Option { Self::from_public(&Public::from_raw(who.into())) } - /// + /// Converts the public key of the `Keyring` into a type `H256`. pub fn to_h256_public_vec(self) -> H256 { Public::from(self).as_array_ref().into() } - /// + /// Converts the public key of the `Keyring` into a vector of bytes. pub fn to_raw_public_vec(self) -> Vec { Public::from(self).to_raw_vec() } - /// + /// Converts the public key of the `Keyring` into an `AccountId32`. pub fn to_account_id(self) -> AccountId32 { self.to_raw_public().into() } - /// + /// Gets a key pair (`Pair`) associated with the `Keyring`. pub fn pair(self) -> Pair { Pair::from_string(&format!("//{}", <&'static str>::from(self)), None) .expect("static values are known good; qed") } - /// - pub fn iter() -> impl Iterator { + /// Returns an iterator over all test accounts. + pub fn iter() -> impl Iterator { ::iter() } + + /// Gets the public key (`Public`) associated with the `Keyring`. + pub fn public(self) -> Public { + self.pair().public() + } + + /// Converts the public key of the `Keyring` into a seed in string format. + pub fn to_seed(self) -> String { + format!("//{}", self) + } + + /// Create a crypto `Pair` from a numeric value. + pub fn numeric(idx: usize) -> Pair { + Pair::from_string(&format!("//{}", idx), None) + .expect("numeric values are known good; qed") + } + + /// Get account id of a `numeric` account. + pub fn numeric_id(idx: usize) -> AccountId32 { + (*Self::numeric(idx).public().as_array_ref()).into() + } +} + +impl From for sp_runtime::MultiSigner { + fn from(x: Keyring) -> Self { + sp_runtime::MultiSigner::Sr25519(x.into()) + } } -/// FROMS +impl std::str::FromStr for Keyring { + type Err = ParseKeyringError; + + fn from_str(s: &str) -> core::result::Result::Err> { + match s { + "alice" => Ok(Keyring::Alice), + "bob" => Ok(Keyring::Bob), + "charlie" => Ok(Keyring::Charlie), + "dave" => Ok(Keyring::Dave), + "eve" => Ok(Keyring::Eve), + "ferdie" => Ok(Keyring::Ferdie), + "one" => Ok(Keyring::One), + "two" => Ok(Keyring::Two), + _ => Err(ParseKeyringError), + } + } +} -impl From for &'static str { - fn from(k: KeyRing) -> Self { +impl From for &'static str { + fn from(k: Keyring) -> Self { match k { - KeyRing::Alice => "Alice", - KeyRing::Bob => "Bob", - KeyRing::Charlie => "Charlie", - KeyRing::Dave => "Dave", - KeyRing::Eve => "Eve", - KeyRing::Ferdie => "Ferdie", - KeyRing::One => "One", - KeyRing::Two => "Two", + Keyring::Alice => "Alice", + Keyring::Bob => "Bob", + Keyring::Charlie => "Charlie", + Keyring::Dave => "Dave", + Keyring::Eve => "Eve", + Keyring::Ferdie => "Ferdie", + Keyring::One => "One", + Keyring::Two => "Two", } } } -impl From for AccountId32 { - fn from(k: KeyRing) -> Self { +impl From for AccountId32 { + fn from(k: Keyring) -> Self { k.to_account_id() } } -impl From for Public { - fn from(k: KeyRing) -> Self { +impl From for Public { + fn from(k: Keyring) -> Self { *(*PUBLIC_KEYS).get(&k).unwrap() } } -impl From for Pair { - fn from(k: KeyRing) -> Self { +impl From for Pair { + fn from(k: Keyring) -> Self { k.pair() } } -impl From for [u8; 32] { - fn from(k: KeyRing) -> Self { +impl From for [u8; 32] { + fn from(k: Keyring) -> Self { *(*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() } } -impl From for H256 { - fn from(k: KeyRing) -> Self { +impl From for H256 { + fn from(k: Keyring) -> Self { (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref().into() } } -impl From for &'static [u8; 32] { - fn from(k: KeyRing) -> Self { +impl From for &'static [u8; 32] { + fn from(k: Keyring) -> Self { (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() } } -impl AsRef<[u8; 32]> for KeyRing { +impl AsRef<[u8; 32]> for Keyring { fn as_ref(&self) -> &[u8; 32] { (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() } } -impl AsRef for KeyRing { +impl AsRef for Keyring { fn as_ref(&self) -> &Public { (*PUBLIC_KEYS).get(self).unwrap() } } -impl Deref for KeyRing { +impl Deref for Keyring { type Target = [u8; 32]; fn deref(&self) -> &[u8; 32] { (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() From 26f89093651f9f3db550b27a8221294864f472db Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Mon, 2 Oct 2023 11:34:39 -0300 Subject: [PATCH 05/18] Delete unnecesary dependencies and code --- crates/env/Cargo.toml | 25 +-- crates/env/src/engine/off_chain/test_api.rs | 229 ++------------------ 2 files changed, 16 insertions(+), 238 deletions(-) diff --git a/crates/env/Cargo.toml b/crates/env/Cargo.toml index 3f4f31c39e6..342ad7e24b8 100644 --- a/crates/env/Cargo.toml +++ b/crates/env/Cargo.toml @@ -1,10 +1,7 @@ [package] name = "ink_env" version.workspace = true -authors = [ - "Parity Technologies ", - "Robin Freyler ", -] +authors = ["Parity Technologies ", "Robin Freyler "] edition.workspace = true rust-version = "1.68" @@ -44,10 +41,7 @@ sha3 = { workspace = true, optional = true } blake2 = { workspace = true, optional = true } # ECDSA for the off-chain environment. -secp256k1 = { workspace = true, features = [ - "recovery", - "global-context", -], optional = true } +secp256k1 = { workspace = true, features = ["recovery", "global-context"], optional = true } # schnorrkel for the off-chain environment. schnorrkel = { version = "0.11.2", optional = true } @@ -59,20 +53,7 @@ schnorrkel = { version = "0.11.2", optional = true } scale-decode = { workspace = true, optional = true } scale-encode = { workspace = true, optional = true } scale-info = { workspace = true, features = ["derive"], optional = true } - -[dependencies.lazy_static] -version = "1.4.0" - -[dependencies.sp-core] -version = "21.0.0" - -[dependencies.strum] -version = "0.24.1" -features = ["derive"] -default-features = false - -[dependencies.sp-runtime] -version = "24.0.0" +sp-keyring = { workspace = true } [dev-dependencies] ink = { path = "../ink" } diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index 9f535104dfb..dd26c46cbfc 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -16,17 +16,10 @@ use super::{EnvInstance, OnInstance}; use crate::{Environment, Result}; -use core::{fmt::Debug, ops::Deref}; +use core::fmt::Debug; use ink_engine::test_api::RecordedDebugMessages; -use lazy_static::lazy_static; -pub use sp_core::sr25519; -use sp_core::{ - sr25519::{Pair, Public}, - ByteArray, Pair as PairT, H256, -}; -use sp_runtime::AccountId32; -use std::{collections::HashMap, panic::UnwindSafe}; -use strum::{Display, EnumIter, IntoEnumIterator}; +pub use sp_keyring::AccountKeyring; +use std::panic::UnwindSafe; pub use super::call_data::CallData; pub use ink_engine::ChainExtension; @@ -338,26 +331,19 @@ where ::AccountId: From<[u8; 32]>, { DefaultAccounts { - alice: T::AccountId::from(Keyring::Alice.to_raw_public()), - bob: T::AccountId::from(Keyring::Bob.to_raw_public()), - charlie: T::AccountId::from(Keyring::Charlie.to_raw_public()), - dave: T::AccountId::from(Keyring::Dave.to_raw_public()), - eve: T::AccountId::from(Keyring::Eve.to_raw_public()), - ferdie: T::AccountId::from(Keyring::Ferdie.to_raw_public()), - one: T::AccountId::from(Keyring::One.to_raw_public()), - two: T::AccountId::from(Keyring::Two.to_raw_public()), + alice: T::AccountId::from(sp_keyring::sr25519::Keyring::Alice.to_raw_public()), + bob: T::AccountId::from(sp_keyring::sr25519::Keyring::Bob.to_raw_public()), + charlie: T::AccountId::from( + sp_keyring::sr25519::Keyring::Charlie.to_raw_public(), + ), + dave: T::AccountId::from(sp_keyring::sr25519::Keyring::Dave.to_raw_public()), + eve: T::AccountId::from(sp_keyring::sr25519::Keyring::Eve.to_raw_public()), + ferdie: T::AccountId::from(sp_keyring::sr25519::Keyring::Ferdie.to_raw_public()), + one: T::AccountId::from(sp_keyring::sr25519::Keyring::One.to_raw_public()), + two: T::AccountId::from(sp_keyring::sr25519::Keyring::Two.to_raw_public()), } } -lazy_static! { - static ref PRIVATE_KEYS: HashMap = - Keyring::iter().map(|i| (i, i.pair())).collect(); - static ref PUBLIC_KEYS: HashMap = PRIVATE_KEYS - .iter() - .map(|(&name, pair)| (name, pair.public())) - .collect(); -} - /// A custom error type representing a failure to parse a keyring. #[derive(Debug)] pub struct ParseKeyringError; @@ -368,195 +354,6 @@ impl std::fmt::Display for ParseKeyringError { } } -/// Set of test accounts. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Display, EnumIter)] -pub enum Keyring { - /// The predefined `ALICE` keyring - Alice, - /// The predefined `Bob` keyring - Bob, - /// The predefined `Charlie` keyring - Charlie, - /// The predefined `Dave` keyring - Dave, - /// The predefined `Eve` keyring - Eve, - /// The predefined `Ferdie` keyring - Ferdie, - /// The predefined `One` keyring - One, - /// The predefined `Two` keyring - Two, -} - -impl Keyring { - /// Creates a `Keyring` from a `Public`. - pub fn from_public(who: &Public) -> Option { - Self::iter().find(|&k| &Public::from(k) == who) - } - - /// Creates a `Keyring` from an `AccountId32`. - pub fn from_account_id(who: &AccountId32) -> Option { - Self::iter().find(|&k| &k.to_account_id() == who) - } - - /// Creates a `Keyring` from a raw public key in the form of a 32-byte array. - pub fn from_raw_public(who: [u8; 32]) -> Option { - Self::from_public(&Public::from_raw(who)) - } - - /// Converts the public key of the `Keyring` into a 32-byte array. - pub fn to_raw_public(self) -> [u8; 32] { - *Public::from(self).as_array_ref() - } - - /// Creates a `Keyring` from a public key in `H256` format. - pub fn from_h256_public(who: H256) -> Option { - Self::from_public(&Public::from_raw(who.into())) - } - - /// Converts the public key of the `Keyring` into a type `H256`. - pub fn to_h256_public_vec(self) -> H256 { - Public::from(self).as_array_ref().into() - } - - /// Converts the public key of the `Keyring` into a vector of bytes. - pub fn to_raw_public_vec(self) -> Vec { - Public::from(self).to_raw_vec() - } - - /// Converts the public key of the `Keyring` into an `AccountId32`. - pub fn to_account_id(self) -> AccountId32 { - self.to_raw_public().into() - } - - /// Gets a key pair (`Pair`) associated with the `Keyring`. - pub fn pair(self) -> Pair { - Pair::from_string(&format!("//{}", <&'static str>::from(self)), None) - .expect("static values are known good; qed") - } - - /// Returns an iterator over all test accounts. - pub fn iter() -> impl Iterator { - ::iter() - } - - /// Gets the public key (`Public`) associated with the `Keyring`. - pub fn public(self) -> Public { - self.pair().public() - } - - /// Converts the public key of the `Keyring` into a seed in string format. - pub fn to_seed(self) -> String { - format!("//{}", self) - } - - /// Create a crypto `Pair` from a numeric value. - pub fn numeric(idx: usize) -> Pair { - Pair::from_string(&format!("//{}", idx), None) - .expect("numeric values are known good; qed") - } - - /// Get account id of a `numeric` account. - pub fn numeric_id(idx: usize) -> AccountId32 { - (*Self::numeric(idx).public().as_array_ref()).into() - } -} - -impl From for sp_runtime::MultiSigner { - fn from(x: Keyring) -> Self { - sp_runtime::MultiSigner::Sr25519(x.into()) - } -} - -impl std::str::FromStr for Keyring { - type Err = ParseKeyringError; - - fn from_str(s: &str) -> core::result::Result::Err> { - match s { - "alice" => Ok(Keyring::Alice), - "bob" => Ok(Keyring::Bob), - "charlie" => Ok(Keyring::Charlie), - "dave" => Ok(Keyring::Dave), - "eve" => Ok(Keyring::Eve), - "ferdie" => Ok(Keyring::Ferdie), - "one" => Ok(Keyring::One), - "two" => Ok(Keyring::Two), - _ => Err(ParseKeyringError), - } - } -} - -impl From for &'static str { - fn from(k: Keyring) -> Self { - match k { - Keyring::Alice => "Alice", - Keyring::Bob => "Bob", - Keyring::Charlie => "Charlie", - Keyring::Dave => "Dave", - Keyring::Eve => "Eve", - Keyring::Ferdie => "Ferdie", - Keyring::One => "One", - Keyring::Two => "Two", - } - } -} - -impl From for AccountId32 { - fn from(k: Keyring) -> Self { - k.to_account_id() - } -} - -impl From for Public { - fn from(k: Keyring) -> Self { - *(*PUBLIC_KEYS).get(&k).unwrap() - } -} - -impl From for Pair { - fn from(k: Keyring) -> Self { - k.pair() - } -} - -impl From for [u8; 32] { - fn from(k: Keyring) -> Self { - *(*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() - } -} - -impl From for H256 { - fn from(k: Keyring) -> Self { - (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref().into() - } -} - -impl From for &'static [u8; 32] { - fn from(k: Keyring) -> Self { - (*PUBLIC_KEYS).get(&k).unwrap().as_array_ref() - } -} - -impl AsRef<[u8; 32]> for Keyring { - fn as_ref(&self) -> &[u8; 32] { - (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() - } -} - -impl AsRef for Keyring { - fn as_ref(&self) -> &Public { - (*PUBLIC_KEYS).get(self).unwrap() - } -} - -impl Deref for Keyring { - type Target = [u8; 32]; - fn deref(&self) -> &[u8; 32] { - (*PUBLIC_KEYS).get(self).unwrap().as_array_ref() - } -} - /// The default accounts. pub struct DefaultAccounts where From 7a3a7de097d2b58ae9a54e88704a34cc25c76cd5 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Mon, 2 Oct 2023 11:55:20 -0300 Subject: [PATCH 06/18] Fix format and delete old code --- crates/env/src/engine/off_chain/test_api.rs | 234 +++++++------------- 1 file changed, 76 insertions(+), 158 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index dd26c46cbfc..ea6ba62912c 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -14,8 +14,14 @@ //! Operations on the off-chain testing environment. -use super::{EnvInstance, OnInstance}; -use crate::{Environment, Result}; +use super::{ + EnvInstance, + OnInstance, +}; +use crate::{ + Environment, + Result, +}; use core::fmt::Debug; use ink_engine::test_api::RecordedDebugMessages; pub use sp_keyring::AccountKeyring; @@ -46,13 +52,11 @@ pub struct EmittedEvent { /// - If the underlying `account` type does not match. /// - If the underlying `new_balance` type does not match. pub fn set_account_balance(account_id: T::AccountId, new_balance: T::Balance) -where - T: Environment, // Just temporary for the MVP! + where T: Environment { + // Just temporary for the MVP! ::on_instance(|instance| { - instance - .engine - .set_balance(scale::Encode::encode(&account_id), new_balance); + instance.engine.set_balance(scale::Encode::encode(&account_id), new_balance); }) } @@ -69,27 +73,18 @@ where /// - If `account` does not exist. /// - If the underlying `account` type does not match. pub fn get_account_balance(account_id: T::AccountId) -> Result -where - T: Environment, // Just temporary for the MVP! + where + T: Environment // Just temporary for the MVP! { ::on_instance(|instance| { - instance - .engine - .get_balance(scale::Encode::encode(&account_id)) - .map_err(Into::into) + instance.engine.get_balance(scale::Encode::encode(&account_id)).map_err(Into::into) }) } /// Registers a new chain extension. -pub fn register_chain_extension(extension: E) -where - E: ink_engine::ChainExtension + 'static, -{ +pub fn register_chain_extension(extension: E) where E: ink_engine::ChainExtension + 'static { ::on_instance(|instance| { - instance - .engine - .chain_extension_handler - .register(Box::new(extension)); + instance.engine.chain_extension_handler.register(Box::new(extension)); }) } @@ -108,16 +103,11 @@ pub fn recorded_debug_messages() -> RecordedDebugMessages { /// runs, because lazy storage structures automatically clear their associated cells when /// they are dropped. pub fn set_clear_storage_disabled(_disable: bool) { - unimplemented!( - "off-chain environment does not yet support `set_clear_storage_disabled`" - ); + unimplemented!("off-chain environment does not yet support `set_clear_storage_disabled`"); } /// Advances the chain by a single block. -pub fn advance_block() -where - T: Environment, -{ +pub fn advance_block() where T: Environment { ::on_instance(|instance| { instance.engine.advance_block(); }) @@ -125,9 +115,7 @@ where /// Sets a caller for the next call. pub fn set_caller(caller: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, + where T: Environment, ::AccountId: From<[u8; 32]> { ::on_instance(|instance| { instance.engine.set_caller(scale::Encode::encode(&caller)); @@ -136,9 +124,7 @@ where /// Sets the callee for the next call. pub fn set_callee(callee: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, + where T: Environment, ::AccountId: From<[u8; 32]> { ::on_instance(|instance| { instance.engine.set_callee(scale::Encode::encode(&callee)); @@ -147,53 +133,38 @@ where /// Sets an account as a contract pub fn set_contract(contract: T::AccountId) -where - T: Environment, - ::AccountId: From<[u8; 32]>, + where T: Environment, ::AccountId: From<[u8; 32]> { ::on_instance(|instance| { - instance - .engine - .set_contract(scale::Encode::encode(&contract)); + instance.engine.set_contract(scale::Encode::encode(&contract)); }) } /// Returns a boolean to indicate whether an account is a contract pub fn is_contract(contract: T::AccountId) -> bool -where - T: Environment, - ::AccountId: From<[u8; 32]>, + where T: Environment, ::AccountId: From<[u8; 32]> { ::on_instance(|instance| { - instance - .engine - .is_contract(scale::Encode::encode(&contract)) + instance.engine.is_contract(scale::Encode::encode(&contract)) }) } /// Gets the currently set callee. /// /// This is account id of the currently executing contract. -pub fn callee() -> T::AccountId -where - T: Environment, -{ +pub fn callee() -> T::AccountId where T: Environment { ::on_instance(|instance| { let callee = instance.engine.get_callee(); - scale::Decode::decode(&mut &callee[..]) + scale::Decode + ::decode(&mut &callee[..]) .unwrap_or_else(|err| panic!("encoding failed: {err}")) }) } /// Returns the total number of reads and writes of the contract's storage. -pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) -where - T: Environment, -{ +pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) where T: Environment { ::on_instance(|instance| { - instance - .engine - .get_contract_storage_rw(scale::Encode::encode(&account_id)) + instance.engine.get_contract_storage_rw(scale::Encode::encode(&account_id)) }) } @@ -201,10 +172,8 @@ where /// /// Please note that the acting accounts should be set with [`set_caller()`] and /// [`set_callee()`] beforehand. -pub fn set_value_transferred(value: T::Balance) -where - T: Environment, // Just temporary for the MVP! -{ +pub fn set_value_transferred(value: T::Balance) where T: Environment { + // Just temporary for the MVP! ::on_instance(|instance| { instance.engine.set_value_transferred(value); }) @@ -214,37 +183,22 @@ where /// /// Please note that the acting accounts should be set with [`set_caller()`] and /// [`set_callee()`] beforehand. -pub fn transfer_in(value: T::Balance) -where - T: Environment, // Just temporary for the MVP! -{ +pub fn transfer_in(value: T::Balance) where T: Environment { + // Just temporary for the MVP! ::on_instance(|instance| { - let caller = instance - .engine - .exec_context - .caller + let caller = instance.engine.exec_context.caller .as_ref() .expect("no caller has been set") .as_bytes() .to_vec(); - let caller_old_balance = instance - .engine - .get_balance(caller.clone()) - .unwrap_or_default(); + let caller_old_balance = instance.engine.get_balance(caller.clone()).unwrap_or_default(); let callee = instance.engine.get_callee(); - let contract_old_balance = instance - .engine - .get_balance(callee.clone()) - .unwrap_or_default(); - - instance - .engine - .set_balance(caller, caller_old_balance - value); - instance - .engine - .set_balance(callee, contract_old_balance + value); + let contract_old_balance = instance.engine.get_balance(callee.clone()).unwrap_or_default(); + + instance.engine.set_balance(caller, caller_old_balance - value); + instance.engine.set_balance(callee, contract_old_balance + value); instance.engine.set_value_transferred(value); }); } @@ -252,33 +206,23 @@ where /// Returns the amount of storage cells used by the account `account_id`. /// /// Returns `None` if the `account_id` is non-existent. -pub fn count_used_storage_cells(account_id: &T::AccountId) -> Result -where - T: Environment, -{ +pub fn count_used_storage_cells(account_id: &T::AccountId) -> Result where T: Environment { ::on_instance(|instance| { - instance - .engine + instance.engine .count_used_storage_cells(&scale::Encode::encode(&account_id)) .map_err(Into::into) }) } /// Sets the block timestamp for the next [`advance_block`] invocation. -pub fn set_block_timestamp(value: T::Timestamp) -where - T: Environment, -{ +pub fn set_block_timestamp(value: T::Timestamp) where T: Environment { ::on_instance(|instance| { instance.engine.set_block_timestamp(value); }) } /// Sets the block number for the next [`advance_block`] invocation. -pub fn set_block_number(value: T::BlockNumber) -where - T: Environment, -{ +pub fn set_block_number(value: T::BlockNumber) where T: Environment { ::on_instance(|instance| { instance.engine.set_block_number(value); }) @@ -287,10 +231,10 @@ where /// Runs the given closure test function with the default configuration /// for the off-chain environment. pub fn run_test(f: F) -> Result<()> -where - T: Environment, - F: FnOnce(DefaultAccounts) -> Result<()>, - ::AccountId: From<[u8; 32]>, + where + T: Environment, + F: FnOnce(DefaultAccounts) -> Result<()>, + ::AccountId: From<[u8; 32]> { let default_accounts = default_accounts::(); ::on_instance(|instance| { @@ -304,21 +248,11 @@ where let substantial = 1_000_000; let some = 1_000; instance.engine.set_balance(encoded_alice, substantial); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.bob), some); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.charlie), some); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.dave), 0); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.eve), 0); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); + instance.engine.set_balance(scale::Encode::encode(&default_accounts.bob), some); + instance.engine.set_balance(scale::Encode::encode(&default_accounts.charlie), some); + instance.engine.set_balance(scale::Encode::encode(&default_accounts.dave), 0); + instance.engine.set_balance(scale::Encode::encode(&default_accounts.eve), 0); + instance.engine.set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); }); f(default_accounts) } @@ -326,16 +260,12 @@ where /// Returns the default accounts for testing purposes: /// Alice, Bob, Charlie, Dave, Eve, Ferdie, One and Two. pub fn default_accounts() -> DefaultAccounts -where - T: Environment, - ::AccountId: From<[u8; 32]>, + where T: Environment, ::AccountId: From<[u8; 32]> { DefaultAccounts { alice: T::AccountId::from(sp_keyring::sr25519::Keyring::Alice.to_raw_public()), bob: T::AccountId::from(sp_keyring::sr25519::Keyring::Bob.to_raw_public()), - charlie: T::AccountId::from( - sp_keyring::sr25519::Keyring::Charlie.to_raw_public(), - ), + charlie: T::AccountId::from(sp_keyring::sr25519::Keyring::Charlie.to_raw_public()), dave: T::AccountId::from(sp_keyring::sr25519::Keyring::Dave.to_raw_public()), eve: T::AccountId::from(sp_keyring::sr25519::Keyring::Eve.to_raw_public()), ferdie: T::AccountId::from(sp_keyring::sr25519::Keyring::Ferdie.to_raw_public()), @@ -344,21 +274,8 @@ where } } -/// A custom error type representing a failure to parse a keyring. -#[derive(Debug)] -pub struct ParseKeyringError; - -impl std::fmt::Display for ParseKeyringError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "ParseKeyringError") - } -} - /// The default accounts. -pub struct DefaultAccounts -where - T: Environment, -{ +pub struct DefaultAccounts where T: Environment { /// The predefined `ALICE` account holding substantial amounts of value. pub alice: T::AccountId, /// The predefined `BOB` account holding some amounts of value. @@ -380,8 +297,7 @@ where /// Returns the recorded emitted events in order. pub fn recorded_events() -> impl Iterator { ::on_instance(|instance| { - instance - .engine + instance.engine .get_emitted_events() .map(|evt: ink_engine::test_api::EmittedEvent| evt.into()) }) @@ -412,24 +328,24 @@ pub fn recorded_events() -> impl Iterator { pub fn assert_contract_termination( should_terminate: F, expected_beneficiary: T::AccountId, - expected_value_transferred_to_beneficiary: T::Balance, -) where - T: Environment, - F: FnMut() + UnwindSafe, - ::AccountId: Debug, - ::Balance: Debug, + expected_value_transferred_to_beneficiary: T::Balance +) + where + T: Environment, + F: FnMut() + UnwindSafe, + ::AccountId: Debug, + ::Balance: Debug { - let value_any = ::std::panic::catch_unwind(should_terminate) + let value_any = ::std::panic + ::catch_unwind(should_terminate) .expect_err("contract did not terminate"); - let encoded_input = value_any - .downcast_ref::>() - .expect("panic object can not be cast"); - let (value_transferred, encoded_beneficiary): (T::Balance, Vec) = - scale::Decode::decode(&mut &encoded_input[..]) - .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); - let beneficiary = - ::decode(&mut &encoded_beneficiary[..]) - .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); + let encoded_input = value_any.downcast_ref::>().expect("panic object can not be cast"); + let (value_transferred, encoded_beneficiary): (T::Balance, Vec) = scale::Decode + ::decode(&mut &encoded_input[..]) + .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); + let beneficiary = + ::decode(&mut &encoded_beneficiary[..]) + .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); assert_eq!(value_transferred, expected_value_transferred_to_beneficiary); assert_eq!(beneficiary, expected_beneficiary); } @@ -438,8 +354,10 @@ pub fn assert_contract_termination( /// environment. #[macro_export] macro_rules! pay_with_call { - ($contract:ident . $message:ident ( $( $params:expr ),* ) , $amount:expr) => {{ + ($contract:ident.$message:ident($($params:expr),*), $amount:expr) => { + { $crate::test::transfer_in::($amount); $contract.$message($ ($params) ,*) - }} + } + }; } From 92ba02b8f352d7792fbcd81c96625c96dc6711f1 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Mon, 2 Oct 2023 12:03:19 -0300 Subject: [PATCH 07/18] Fix format --- crates/env/src/engine/off_chain/test_api.rs | 219 ++++++++++++++------ 1 file changed, 150 insertions(+), 69 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index ea6ba62912c..fdf43c21274 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -24,7 +24,6 @@ use crate::{ }; use core::fmt::Debug; use ink_engine::test_api::RecordedDebugMessages; -pub use sp_keyring::AccountKeyring; use std::panic::UnwindSafe; pub use super::call_data::CallData; @@ -52,11 +51,13 @@ pub struct EmittedEvent { /// - If the underlying `account` type does not match. /// - If the underlying `new_balance` type does not match. pub fn set_account_balance(account_id: T::AccountId, new_balance: T::Balance) - where T: Environment +where + T: Environment, // Just temporary for the MVP! { - // Just temporary for the MVP! ::on_instance(|instance| { - instance.engine.set_balance(scale::Encode::encode(&account_id), new_balance); + instance + .engine + .set_balance(scale::Encode::encode(&account_id), new_balance); }) } @@ -73,18 +74,27 @@ pub fn set_account_balance(account_id: T::AccountId, new_balance: T::Balance) /// - If `account` does not exist. /// - If the underlying `account` type does not match. pub fn get_account_balance(account_id: T::AccountId) -> Result - where - T: Environment // Just temporary for the MVP! +where + T: Environment, // Just temporary for the MVP! { ::on_instance(|instance| { - instance.engine.get_balance(scale::Encode::encode(&account_id)).map_err(Into::into) + instance + .engine + .get_balance(scale::Encode::encode(&account_id)) + .map_err(Into::into) }) } /// Registers a new chain extension. -pub fn register_chain_extension(extension: E) where E: ink_engine::ChainExtension + 'static { +pub fn register_chain_extension(extension: E) +where + E: ink_engine::ChainExtension + 'static, +{ ::on_instance(|instance| { - instance.engine.chain_extension_handler.register(Box::new(extension)); + instance + .engine + .chain_extension_handler + .register(Box::new(extension)); }) } @@ -103,11 +113,16 @@ pub fn recorded_debug_messages() -> RecordedDebugMessages { /// runs, because lazy storage structures automatically clear their associated cells when /// they are dropped. pub fn set_clear_storage_disabled(_disable: bool) { - unimplemented!("off-chain environment does not yet support `set_clear_storage_disabled`"); + unimplemented!( + "off-chain environment does not yet support `set_clear_storage_disabled`" + ); } /// Advances the chain by a single block. -pub fn advance_block() where T: Environment { +pub fn advance_block() +where + T: Environment, +{ ::on_instance(|instance| { instance.engine.advance_block(); }) @@ -115,7 +130,9 @@ pub fn advance_block() where T: Environment { /// Sets a caller for the next call. pub fn set_caller(caller: T::AccountId) - where T: Environment, ::AccountId: From<[u8; 32]> +where + T: Environment, + ::AccountId: From<[u8; 32]>, { ::on_instance(|instance| { instance.engine.set_caller(scale::Encode::encode(&caller)); @@ -124,7 +141,9 @@ pub fn set_caller(caller: T::AccountId) /// Sets the callee for the next call. pub fn set_callee(callee: T::AccountId) - where T: Environment, ::AccountId: From<[u8; 32]> +where + T: Environment, + ::AccountId: From<[u8; 32]>, { ::on_instance(|instance| { instance.engine.set_callee(scale::Encode::encode(&callee)); @@ -133,38 +152,53 @@ pub fn set_callee(callee: T::AccountId) /// Sets an account as a contract pub fn set_contract(contract: T::AccountId) - where T: Environment, ::AccountId: From<[u8; 32]> +where + T: Environment, + ::AccountId: From<[u8; 32]>, { ::on_instance(|instance| { - instance.engine.set_contract(scale::Encode::encode(&contract)); + instance + .engine + .set_contract(scale::Encode::encode(&contract)); }) } /// Returns a boolean to indicate whether an account is a contract pub fn is_contract(contract: T::AccountId) -> bool - where T: Environment, ::AccountId: From<[u8; 32]> +where + T: Environment, + ::AccountId: From<[u8; 32]>, { ::on_instance(|instance| { - instance.engine.is_contract(scale::Encode::encode(&contract)) + instance + .engine + .is_contract(scale::Encode::encode(&contract)) }) } /// Gets the currently set callee. /// /// This is account id of the currently executing contract. -pub fn callee() -> T::AccountId where T: Environment { +pub fn callee() -> T::AccountId +where + T: Environment, +{ ::on_instance(|instance| { let callee = instance.engine.get_callee(); - scale::Decode - ::decode(&mut &callee[..]) + scale::Decode::decode(&mut &callee[..]) .unwrap_or_else(|err| panic!("encoding failed: {err}")) }) } /// Returns the total number of reads and writes of the contract's storage. -pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) where T: Environment { +pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) +where + T: Environment, +{ ::on_instance(|instance| { - instance.engine.get_contract_storage_rw(scale::Encode::encode(&account_id)) + instance + .engine + .get_contract_storage_rw(scale::Encode::encode(&account_id)) }) } @@ -172,8 +206,10 @@ pub fn get_contract_storage_rw(account_id: &T::AccountId) -> (usize, usize) w /// /// Please note that the acting accounts should be set with [`set_caller()`] and /// [`set_callee()`] beforehand. -pub fn set_value_transferred(value: T::Balance) where T: Environment { - // Just temporary for the MVP! +pub fn set_value_transferred(value: T::Balance) +where + T: Environment, // Just temporary for the MVP! +{ ::on_instance(|instance| { instance.engine.set_value_transferred(value); }) @@ -183,22 +219,37 @@ pub fn set_value_transferred(value: T::Balance) where T: Environment(value: T::Balance) where T: Environment { - // Just temporary for the MVP! +pub fn transfer_in(value: T::Balance) +where + T: Environment, // Just temporary for the MVP! +{ ::on_instance(|instance| { - let caller = instance.engine.exec_context.caller + let caller = instance + .engine + .exec_context + .caller .as_ref() .expect("no caller has been set") .as_bytes() .to_vec(); - let caller_old_balance = instance.engine.get_balance(caller.clone()).unwrap_or_default(); + let caller_old_balance = instance + .engine + .get_balance(caller.clone()) + .unwrap_or_default(); let callee = instance.engine.get_callee(); - let contract_old_balance = instance.engine.get_balance(callee.clone()).unwrap_or_default(); - - instance.engine.set_balance(caller, caller_old_balance - value); - instance.engine.set_balance(callee, contract_old_balance + value); + let contract_old_balance = instance + .engine + .get_balance(callee.clone()) + .unwrap_or_default(); + + instance + .engine + .set_balance(caller, caller_old_balance - value); + instance + .engine + .set_balance(callee, contract_old_balance + value); instance.engine.set_value_transferred(value); }); } @@ -206,23 +257,33 @@ pub fn transfer_in(value: T::Balance) where T: Environment { /// Returns the amount of storage cells used by the account `account_id`. /// /// Returns `None` if the `account_id` is non-existent. -pub fn count_used_storage_cells(account_id: &T::AccountId) -> Result where T: Environment { +pub fn count_used_storage_cells(account_id: &T::AccountId) -> Result +where + T: Environment, +{ ::on_instance(|instance| { - instance.engine + instance + .engine .count_used_storage_cells(&scale::Encode::encode(&account_id)) .map_err(Into::into) }) } /// Sets the block timestamp for the next [`advance_block`] invocation. -pub fn set_block_timestamp(value: T::Timestamp) where T: Environment { +pub fn set_block_timestamp(value: T::Timestamp) +where + T: Environment, +{ ::on_instance(|instance| { instance.engine.set_block_timestamp(value); }) } /// Sets the block number for the next [`advance_block`] invocation. -pub fn set_block_number(value: T::BlockNumber) where T: Environment { +pub fn set_block_number(value: T::BlockNumber) +where + T: Environment, +{ ::on_instance(|instance| { instance.engine.set_block_number(value); }) @@ -231,10 +292,10 @@ pub fn set_block_number(value: T::BlockNumber) where T: Environment(f: F) -> Result<()> - where - T: Environment, - F: FnOnce(DefaultAccounts) -> Result<()>, - ::AccountId: From<[u8; 32]> +where + T: Environment, + F: FnOnce(DefaultAccounts) -> Result<()>, + ::AccountId: From<[u8; 32]>, { let default_accounts = default_accounts::(); ::on_instance(|instance| { @@ -248,11 +309,27 @@ pub fn run_test(f: F) -> Result<()> let substantial = 1_000_000; let some = 1_000; instance.engine.set_balance(encoded_alice, substantial); - instance.engine.set_balance(scale::Encode::encode(&default_accounts.bob), some); - instance.engine.set_balance(scale::Encode::encode(&default_accounts.charlie), some); - instance.engine.set_balance(scale::Encode::encode(&default_accounts.dave), 0); - instance.engine.set_balance(scale::Encode::encode(&default_accounts.eve), 0); - instance.engine.set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.bob), some); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.charlie), some); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.dave), 0); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.eve), 0); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.one), 0); + instance + .engine + .set_balance(scale::Encode::encode(&default_accounts.two), 0); }); f(default_accounts) } @@ -260,7 +337,9 @@ pub fn run_test(f: F) -> Result<()> /// Returns the default accounts for testing purposes: /// Alice, Bob, Charlie, Dave, Eve, Ferdie, One and Two. pub fn default_accounts() -> DefaultAccounts - where T: Environment, ::AccountId: From<[u8; 32]> +where + T: Environment, + ::AccountId: From<[u8; 32]>, { DefaultAccounts { alice: T::AccountId::from(sp_keyring::sr25519::Keyring::Alice.to_raw_public()), @@ -275,7 +354,10 @@ pub fn default_accounts() -> DefaultAccounts } /// The default accounts. -pub struct DefaultAccounts where T: Environment { +pub struct DefaultAccounts +where + T: Environment, +{ /// The predefined `ALICE` account holding substantial amounts of value. pub alice: T::AccountId, /// The predefined `BOB` account holding some amounts of value. @@ -297,7 +379,8 @@ pub struct DefaultAccounts where T: Environment { /// Returns the recorded emitted events in order. pub fn recorded_events() -> impl Iterator { ::on_instance(|instance| { - instance.engine + instance + .engine .get_emitted_events() .map(|evt: ink_engine::test_api::EmittedEvent| evt.into()) }) @@ -328,24 +411,24 @@ pub fn recorded_events() -> impl Iterator { pub fn assert_contract_termination( should_terminate: F, expected_beneficiary: T::AccountId, - expected_value_transferred_to_beneficiary: T::Balance -) - where - T: Environment, - F: FnMut() + UnwindSafe, - ::AccountId: Debug, - ::Balance: Debug + expected_value_transferred_to_beneficiary: T::Balance, +) where + T: Environment, + F: FnMut() + UnwindSafe, + ::AccountId: Debug, + ::Balance: Debug, { - let value_any = ::std::panic - ::catch_unwind(should_terminate) + let value_any = ::std::panic::catch_unwind(should_terminate) .expect_err("contract did not terminate"); - let encoded_input = value_any.downcast_ref::>().expect("panic object can not be cast"); - let (value_transferred, encoded_beneficiary): (T::Balance, Vec) = scale::Decode - ::decode(&mut &encoded_input[..]) - .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); - let beneficiary = - ::decode(&mut &encoded_beneficiary[..]) - .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); + let encoded_input = value_any + .downcast_ref::>() + .expect("panic object can not be cast"); + let (value_transferred, encoded_beneficiary): (T::Balance, Vec) = + scale::Decode::decode(&mut &encoded_input[..]) + .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); + let beneficiary = + ::decode(&mut &encoded_beneficiary[..]) + .unwrap_or_else(|err| panic!("input can not be decoded: {err}")); assert_eq!(value_transferred, expected_value_transferred_to_beneficiary); assert_eq!(beneficiary, expected_beneficiary); } @@ -354,10 +437,8 @@ pub fn assert_contract_termination( /// environment. #[macro_export] macro_rules! pay_with_call { - ($contract:ident.$message:ident($($params:expr),*), $amount:expr) => { - { + ($contract:ident . $message:ident ( $( $params:expr ),* ) , $amount:expr) => {{ $crate::test::transfer_in::($amount); $contract.$message($ ($params) ,*) - } - }; -} + }} +} \ No newline at end of file From 5efba024744ec36b86e1ce02e7642166f9f75d25 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Tue, 24 Oct 2023 09:27:53 -0300 Subject: [PATCH 08/18] Test comparing the default accounts in e2e and integration test. --- integration-tests/default-accounts/.gitignore | 9 ++ integration-tests/default-accounts/Cargo.toml | 26 ++++ integration-tests/default-accounts/lib.rs | 124 ++++++++++++++++++ 3 files changed, 159 insertions(+) create mode 100644 integration-tests/default-accounts/.gitignore create mode 100644 integration-tests/default-accounts/Cargo.toml create mode 100644 integration-tests/default-accounts/lib.rs diff --git a/integration-tests/default-accounts/.gitignore b/integration-tests/default-accounts/.gitignore new file mode 100644 index 00000000000..bf910de10af --- /dev/null +++ b/integration-tests/default-accounts/.gitignore @@ -0,0 +1,9 @@ +# Ignore build artifacts from the local tests sub-crate. +/target/ + +# Ignore backup files creates by cargo fmt. +**/*.rs.bk + +# Remove Cargo.lock when creating an executable, leave it for libraries +# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock +Cargo.lock \ No newline at end of file diff --git a/integration-tests/default-accounts/Cargo.toml b/integration-tests/default-accounts/Cargo.toml new file mode 100644 index 00000000000..3b0dee5319a --- /dev/null +++ b/integration-tests/default-accounts/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "default-accounts" +version = "4.1.0" +authors = ["Parity Technologies "] +edition = "2021" +publish = false + +[dependencies] +ink = { path = "../../crates/ink", default-features = false } + +scale = { package = "parity-scale-codec", version = "3", default-features = false, features = ["derive"] } +scale-info = { version = "2.5", default-features = false, features = ["derive"], optional = true } + +[dev-dependencies] +ink_e2e = { path = "../../crates/e2e" } + +[lib] +path = "lib.rs" + +[features] +default = ["std"] +std = [ + "ink/std", +] +ink-as-dependency = [] +e2e-tests = [] diff --git a/integration-tests/default-accounts/lib.rs b/integration-tests/default-accounts/lib.rs new file mode 100644 index 00000000000..dbd0d561d50 --- /dev/null +++ b/integration-tests/default-accounts/lib.rs @@ -0,0 +1,124 @@ +#![cfg_attr(not(feature = "std"), no_std, no_main)] + +#[ink::contract] +mod custom_default_accounts { + + #[ink(storage)] + pub struct CustomDefaultAccounts {} + + impl CustomDefaultAccounts { + /// Creates a new Template contract. + #[ink(constructor)] + pub fn new() -> Self { + Self {} + } + + #[ink(message)] + pub fn message(&self) {} + } + + impl Default for CustomDefaultAccounts { + fn default() -> Self { + Self::new() + } + } + + #[cfg(test)] + mod tests { + use super::*; + use ink::env::test::DefaultAccounts; + use ink_e2e; + + #[ink::test] + fn test_alice_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_alice_account_id = integration_test_accounts.alice; + + let e2e_alice_account_id: AccountId = + ink_e2e::AccountKeyring::Alice.to_raw_public().into(); + + assert_eq!(integration_alice_account_id, e2e_alice_account_id); + } + + #[ink::test] + fn test_bob_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_bob_account_id = integration_test_accounts.bob; + + let e2e_bob_account_id: AccountId = ink_e2e::AccountKeyring::Bob.to_raw_public().into(); + + assert_eq!(integration_bob_account_id, e2e_bob_account_id); + } + + #[ink::test] + fn test_charlie_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_charlie_account_id = integration_test_accounts.charlie; + + let e2e_charlie_account_id: AccountId = + ink_e2e::AccountKeyring::Charlie.to_raw_public().into(); + + assert_eq!(integration_charlie_account_id, e2e_charlie_account_id); + } + + #[ink::test] + fn test_dave_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_dave_account_id = integration_test_accounts.dave; + + let e2e_dave_account_id: AccountId = + ink_e2e::AccountKeyring::Dave.to_raw_public().into(); + + assert_eq!(integration_dave_account_id, e2e_dave_account_id); + } + + #[ink::test] + fn test_eve_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_eve_account_id = integration_test_accounts.eve; + + let e2e_eve_account_id: AccountId = ink_e2e::AccountKeyring::Eve.to_raw_public().into(); + + assert_eq!(integration_eve_account_id, e2e_eve_account_id); + } + + #[ink::test] + fn test_ferdie_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_ferdie_account_id = integration_test_accounts.ferdie; + + let e2e_ferdie_account_id: AccountId = + ink_e2e::AccountKeyring::Ferdie.to_raw_public().into(); + + assert_eq!(integration_ferdie_account_id, e2e_ferdie_account_id); + } + + #[ink::test] + fn test_one_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_one_account_id = integration_test_accounts.one; + + let e2e_one_account_id: AccountId = ink_e2e::AccountKeyring::One.to_raw_public().into(); + + assert_eq!(integration_one_account_id, e2e_one_account_id); + } + + #[ink::test] + fn test_two_account() { + let integration_test_accounts: DefaultAccounts = + ink::env::test::default_accounts::(); + let integration_two_account_id = integration_test_accounts.two; + + let e2e_two_account_id: AccountId = ink_e2e::AccountKeyring::Two.to_raw_public().into(); + + assert_eq!(integration_two_account_id, e2e_two_account_id); + } + } +} From e2276f5300f982fe517c4cf44f5a85fe3039d961 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Fri, 27 Oct 2023 15:49:24 -0300 Subject: [PATCH 09/18] Add changelog --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0aac63b02b0..8a4ffd8c0e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,8 +6,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## Changed +### Changed - Make `set_code_hash` generic - [#1906](https://github.com/paritytech/ink/pull/1906) +- Make the `default_accounts` in integration test and e2e the same addresses. - [#1955](https://github.com/paritytech/ink/pull/1955) ## Version 5.0.0-alpha From d396af5d87335923de580c298683c1973b164f47 Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Fri, 27 Oct 2023 17:25:58 -0300 Subject: [PATCH 10/18] Fix fmt --- crates/env/src/engine/off_chain/test_api.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index fdf43c21274..2ecb42ca72a 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -344,7 +344,9 @@ where DefaultAccounts { alice: T::AccountId::from(sp_keyring::sr25519::Keyring::Alice.to_raw_public()), bob: T::AccountId::from(sp_keyring::sr25519::Keyring::Bob.to_raw_public()), - charlie: T::AccountId::from(sp_keyring::sr25519::Keyring::Charlie.to_raw_public()), + charlie: T::AccountId::from( + sp_keyring::sr25519::Keyring::Charlie.to_raw_public(), + ), dave: T::AccountId::from(sp_keyring::sr25519::Keyring::Dave.to_raw_public()), eve: T::AccountId::from(sp_keyring::sr25519::Keyring::Eve.to_raw_public()), ferdie: T::AccountId::from(sp_keyring::sr25519::Keyring::Ferdie.to_raw_public()), @@ -441,4 +443,4 @@ macro_rules! pay_with_call { $crate::test::transfer_in::($amount); $contract.$message($ ($params) ,*) }} -} \ No newline at end of file +} From e4e0aa0db08b3c6ea0346c6b03d66573ed6008eb Mon Sep 17 00:00:00 2001 From: Brian Ramirez Date: Fri, 27 Oct 2023 17:28:57 -0300 Subject: [PATCH 11/18] Fix fmt in integration-test --- integration-tests/default-accounts/lib.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/integration-tests/default-accounts/lib.rs b/integration-tests/default-accounts/lib.rs index dbd0d561d50..fee11ddea33 100644 --- a/integration-tests/default-accounts/lib.rs +++ b/integration-tests/default-accounts/lib.rs @@ -47,7 +47,8 @@ mod custom_default_accounts { ink::env::test::default_accounts::(); let integration_bob_account_id = integration_test_accounts.bob; - let e2e_bob_account_id: AccountId = ink_e2e::AccountKeyring::Bob.to_raw_public().into(); + let e2e_bob_account_id: AccountId = + ink_e2e::AccountKeyring::Bob.to_raw_public().into(); assert_eq!(integration_bob_account_id, e2e_bob_account_id); } @@ -82,7 +83,8 @@ mod custom_default_accounts { ink::env::test::default_accounts::(); let integration_eve_account_id = integration_test_accounts.eve; - let e2e_eve_account_id: AccountId = ink_e2e::AccountKeyring::Eve.to_raw_public().into(); + let e2e_eve_account_id: AccountId = + ink_e2e::AccountKeyring::Eve.to_raw_public().into(); assert_eq!(integration_eve_account_id, e2e_eve_account_id); } @@ -105,7 +107,8 @@ mod custom_default_accounts { ink::env::test::default_accounts::(); let integration_one_account_id = integration_test_accounts.one; - let e2e_one_account_id: AccountId = ink_e2e::AccountKeyring::One.to_raw_public().into(); + let e2e_one_account_id: AccountId = + ink_e2e::AccountKeyring::One.to_raw_public().into(); assert_eq!(integration_one_account_id, e2e_one_account_id); } @@ -116,7 +119,8 @@ mod custom_default_accounts { ink::env::test::default_accounts::(); let integration_two_account_id = integration_test_accounts.two; - let e2e_two_account_id: AccountId = ink_e2e::AccountKeyring::Two.to_raw_public().into(); + let e2e_two_account_id: AccountId = + ink_e2e::AccountKeyring::Two.to_raw_public().into(); assert_eq!(integration_two_account_id, e2e_two_account_id); } From 46a50b6e32bd7b3e20a197973350296ca2ef650c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 13:41:39 -0300 Subject: [PATCH 12/18] Passed through rustfmt. --- crates/ink/codegen/src/generator/trait_def/trait_registry.rs | 4 +++- crates/ink/ir/src/ir/attrs.rs | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs index 6d6471e53e3..b0fe1a25bdb 100644 --- a/crates/ink/codegen/src/generator/trait_def/trait_registry.rs +++ b/crates/ink/codegen/src/generator/trait_def/trait_registry.rs @@ -21,7 +21,9 @@ use super::TraitDefinition; use crate::{ - generator::{self,}, + generator::{ + self, + }, traits::GenerateCode, EnforcedErrors, }; diff --git a/crates/ink/ir/src/ir/attrs.rs b/crates/ink/ir/src/ir/attrs.rs index 4cd8320f434..100efa06548 100644 --- a/crates/ink/ir/src/ir/attrs.rs +++ b/crates/ink/ir/src/ir/attrs.rs @@ -32,7 +32,9 @@ use syn::{ }; use crate::{ - ast::{self,}, + ast::{ + self, + }, error::ExtError as _, ir, ir::{ From 15e6a5f4f826e6d7b76be178610a04061c02f389 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 18:48:09 -0300 Subject: [PATCH 13/18] Updated test results. --- .../ui/contract/fail/constructor-input-non-codec.stderr | 8 +++++--- .../fail/constructor-return-result-non-codec-error.stderr | 1 + .../ui/contract/fail/constructor-self-receiver-03.stderr | 1 + .../tests/ui/contract/fail/message-input-non-codec.stderr | 8 +++++--- .../ui/contract/fail/message-returns-non-codec.stderr | 6 +++--- .../fail/packed_is_not_derived_automatically.stderr | 7 ++++--- .../ui/trait_def/fail/message_input_non_codec.stderr | 7 ++++--- .../ui/trait_def/fail/message_output_non_codec.stderr | 6 +++--- 8 files changed, 26 insertions(+), 18 deletions(-) diff --git a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr index 6889d1639f9..c88919a7f2e 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-input-non-codec.stderr @@ -6,6 +6,7 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` @@ -26,6 +27,7 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` @@ -41,14 +43,14 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonCodecType` to implement `Encode` note: required by a bound in `ExecutionInput::>::push_arg` --> $WORKSPACE/crates/env/src/call/execution_input.rs diff --git a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr index ba04fb8f656..a39e7acd6f7 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-return-result-non-codec-error.stderr @@ -22,6 +22,7 @@ error[E0277]: the trait bound `contract::Error: WrapperTypeDecode` is not satisf | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `contract::Error` to implement `ink::parity_scale_codec::Decode` diff --git a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr index 2f261fa67ca..ee2a3794ea4 100644 --- a/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr +++ b/crates/ink/tests/ui/contract/fail/constructor-self-receiver-03.stderr @@ -30,6 +30,7 @@ error[E0277]: the trait bound `&Contract: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `&Contract` to implement `ink::parity_scale_codec::Decode` diff --git a/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr b/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr index 3eff91fc43f..7b6e8089453 100644 --- a/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/message-input-non-codec.stderr @@ -6,6 +6,7 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` @@ -26,6 +27,7 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonCodecType` to implement `ink::parity_scale_codec::Decode` @@ -41,14 +43,14 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonCodecType` to implement `Encode` note: required by a bound in `ExecutionInput::>::push_arg` --> $WORKSPACE/crates/env/src/call/execution_input.rs diff --git a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr index 3474db6f08c..57118427c5f 100644 --- a/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr +++ b/crates/ink/tests/ui/contract/fail/message-returns-non-codec.stderr @@ -6,14 +6,14 @@ error[E0277]: the trait bound `NonCodecType: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonCodecType` to implement `Encode` note: required by a bound in `DispatchOutput` --> src/codegen/dispatch/type_check.rs diff --git a/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr b/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr index 4863fb334bc..8c057a82fb8 100644 --- a/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr +++ b/crates/ink/tests/ui/storage_item/fail/packed_is_not_derived_automatically.stderr @@ -6,6 +6,7 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonPacked` to implement `ink::parity_scale_codec::Decode` @@ -24,14 +25,14 @@ error[E0277]: the trait bound `NonPacked: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonPacked` to implement `Encode` = note: required for `NonPacked` to implement `Packed` note: required by a bound in `consume_packed` diff --git a/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr b/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr index 775914c95bc..a0a5dca8dfb 100644 --- a/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr +++ b/crates/ink/tests/ui/trait_def/fail/message_input_non_codec.stderr @@ -6,6 +6,7 @@ error[E0277]: the trait bound `NonCodec: WrapperTypeDecode` is not satisfied | = help: the following other types implement trait `WrapperTypeDecode`: Box + sp_core::Bytes Rc Arc = note: required for `NonCodec` to implement `ink::parity_scale_codec::Decode` @@ -29,14 +30,14 @@ error[E0277]: the trait bound `NonCodec: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonCodec` to implement `Encode` note: required by a bound in `ExecutionInput::>::push_arg` --> $WORKSPACE/crates/env/src/call/execution_input.rs diff --git a/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr b/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr index 983b1b3b880..e6ad591645c 100644 --- a/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr +++ b/crates/ink/tests/ui/trait_def/fail/message_output_non_codec.stderr @@ -6,14 +6,14 @@ error[E0277]: the trait bound `NonCodec: WrapperTypeEncode` is not satisfied | = help: the following other types implement trait `WrapperTypeEncode`: Box + bytes::bytes::Bytes Cow<'a, T> ink::parity_scale_codec::Ref<'a, T, U> + sp_core::Bytes Rc Arc Vec - String - &T - &mut T + and $N others = note: required for `NonCodec` to implement `Encode` note: required by a bound in `DispatchOutput` --> src/codegen/dispatch/type_check.rs From 3c76b3ba4c1e4eab8e7de2e4e315d0647aca3690 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 20:44:46 -0300 Subject: [PATCH 14/18] Update erc20 test to match new default account values. --- integration-tests/erc20/lib.rs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/integration-tests/erc20/lib.rs b/integration-tests/erc20/lib.rs index c04c7a254eb..c21cc74967b 100644 --- a/integration-tests/erc20/lib.rs +++ b/integration-tests/erc20/lib.rs @@ -273,6 +273,10 @@ mod erc20 { } } + fn alice() -> AccountId{ + ink::env::test::default_accounts::().alice + } + /// The default constructor does its job. #[ink::test] fn new_works() { @@ -286,7 +290,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); } @@ -301,7 +305,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); // Get the token total supply. @@ -318,7 +322,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); let accounts = @@ -349,14 +353,14 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); // Check the second transfer event relating to the actual trasfer. assert_transfer_event( &emitted_events[1], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x02; 32])), + Some(AccountId::from(accounts.alice)), + Some(AccountId::from(accounts.bob)), 10, ); } @@ -391,7 +395,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); } @@ -434,15 +438,15 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); // The second event `emitted_events[1]` is an Approve event that we skip // checking. assert_transfer_event( &emitted_events[2], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x05; 32])), + Some(AccountId::from(accounts.alice)), + Some(AccountId::from(accounts.eve)), 10, ); } From c387b040814f8a99cb21794801b068422d1b57b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 20:46:25 -0300 Subject: [PATCH 15/18] Updated erc721 test to use ferdie instead of frank. --- integration-tests/erc721/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration-tests/erc721/lib.rs b/integration-tests/erc721/lib.rs index 0bc5cddb034..527236314f1 100644 --- a/integration-tests/erc721/lib.rs +++ b/integration-tests/erc721/lib.rs @@ -578,7 +578,7 @@ mod erc721 { set_caller(accounts.eve); // Eve is not an approved operator by Alice. assert_eq!( - erc721.transfer_from(accounts.alice, accounts.frank, 1), + erc721.transfer_from(accounts.alice, accounts.ferdie, 1), Err(Error::NotApproved) ); // Alice owns 1 token. From 6d4a137a4c3c0b460f1cfab1cdf49925f2354913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 20:58:25 -0300 Subject: [PATCH 16/18] Updated and fixed tests for multisig. --- integration-tests/multisig/lib.rs | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/integration-tests/multisig/lib.rs b/integration-tests/multisig/lib.rs index f79fd16db77..a8e9ac42bfa 100755 --- a/integration-tests/multisig/lib.rs +++ b/integration-tests/multisig/lib.rs @@ -768,7 +768,7 @@ mod multisig { fn set_from_no_owner() { let accounts = default_accounts(); - set_caller(accounts.django); + set_caller(accounts.dave); } fn default_accounts() -> test::DefaultAccounts { @@ -782,6 +782,7 @@ mod multisig { let accounts = default_accounts(); let owners = vec![accounts.alice, accounts.bob, accounts.eve]; + println!("{:?}", owners); Multisig::new(2, owners) } @@ -802,7 +803,8 @@ mod multisig { #[ink::test] fn construction_works() { let accounts = default_accounts(); - let owners = [accounts.alice, accounts.bob, accounts.eve]; + let mut owners = [accounts.alice, accounts.bob, accounts.eve]; + owners.sort_unstable(); let contract = build_contract(); assert_eq!(contract.owners.len(), 3); @@ -812,8 +814,8 @@ mod multisig { assert!(contract.is_owner.contains(accounts.bob)); assert!(contract.is_owner.contains(accounts.eve)); assert!(!contract.is_owner.contains(accounts.charlie)); - assert!(!contract.is_owner.contains(accounts.django)); - assert!(!contract.is_owner.contains(accounts.frank)); + assert!(!contract.is_owner.contains(accounts.dave)); + assert!(!contract.is_owner.contains(accounts.ferdie)); assert_eq!(contract.transaction_list.transactions.len(), 0); } @@ -843,9 +845,9 @@ mod multisig { let mut contract = build_contract(); set_from_wallet(); let owners = contract.owners.len(); - contract.add_owner(accounts.frank); + contract.add_owner(accounts.ferdie); assert_eq!(contract.owners.len(), owners + 1); - assert!(contract.is_owner.contains(accounts.frank)); + assert!(contract.is_owner.contains(accounts.ferdie)); assert_eq!(test::recorded_events().count(), 1); } @@ -864,7 +866,7 @@ mod multisig { let accounts = default_accounts(); let mut contract = build_contract(); set_from_owner(); - contract.add_owner(accounts.frank); + contract.add_owner(accounts.ferdie); } #[ink::test] @@ -885,7 +887,7 @@ mod multisig { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); - contract.remove_owner(accounts.django); + contract.remove_owner(accounts.dave); } #[ink::test] @@ -903,10 +905,10 @@ mod multisig { let mut contract = build_contract(); set_from_wallet(); let owners = contract.owners.len(); - contract.replace_owner(accounts.alice, accounts.django); + contract.replace_owner(accounts.alice, accounts.dave); assert_eq!(contract.owners.len(), owners); assert!(!contract.is_owner.contains(accounts.alice)); - assert!(contract.is_owner.contains(accounts.django)); + assert!(contract.is_owner.contains(accounts.dave)); assert_eq!(test::recorded_events().count(), 2); } @@ -925,7 +927,7 @@ mod multisig { let accounts = default_accounts(); let mut contract = build_contract(); set_from_wallet(); - contract.replace_owner(accounts.django, accounts.frank); + contract.replace_owner(accounts.dave, accounts.ferdie); } #[ink::test] @@ -934,7 +936,7 @@ mod multisig { let accounts = default_accounts(); let mut contract = build_contract(); set_from_owner(); - contract.replace_owner(accounts.alice, accounts.django); + contract.replace_owner(accounts.alice, accounts.dave); } #[ink::test] @@ -1087,7 +1089,7 @@ mod multisig { fn revoke_transaction_no_owner_fail() { let mut contract = submit_transaction(); let accounts = default_accounts(); - set_caller(accounts.django); + set_caller(accounts.dave); contract.revoke_confirmation(0); } From a771d71c217feaab046c3fec4760e2c9717c9a7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Mon, 13 Nov 2023 21:02:18 -0300 Subject: [PATCH 17/18] Updated traut-erc20 test to match new default account values. --- integration-tests/trait-erc20/lib.rs | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/integration-tests/trait-erc20/lib.rs b/integration-tests/trait-erc20/lib.rs index 56c9c739751..4faf4a74006 100644 --- a/integration-tests/trait-erc20/lib.rs +++ b/integration-tests/trait-erc20/lib.rs @@ -333,6 +333,10 @@ mod erc20 { } } + fn alice() -> AccountId{ + ink::env::test::default_accounts::().alice + } + /// The default constructor does its job. #[ink::test] fn new_works() { @@ -350,7 +354,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); } @@ -366,7 +370,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); // Get the token total supply. @@ -384,7 +388,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(alice())), 100, ); let accounts = @@ -416,14 +420,14 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); // Check the second transfer event relating to the actual trasfer. assert_transfer_event( &emitted_events[1], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x02; 32])), + Some(AccountId::from(accounts.alice)), + Some(AccountId::from(accounts.bob)), 10, ); } @@ -456,7 +460,7 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); } @@ -498,15 +502,15 @@ mod erc20 { assert_transfer_event( &emitted_events[0], None, - Some(AccountId::from([0x01; 32])), + Some(AccountId::from(accounts.alice)), 100, ); // The second event `emitted_events[1]` is an Approve event that we skip // checking. assert_transfer_event( &emitted_events[2], - Some(AccountId::from([0x01; 32])), - Some(AccountId::from([0x05; 32])), + Some(AccountId::from(accounts.alice)), + Some(AccountId::from(accounts.eve)), 10, ); } From 24b8ca2ae2a53fb22172ee39f0b054f5930e574e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20M=2E=20Gonz=C3=A1lez?= Date: Tue, 21 Nov 2023 16:46:57 -0300 Subject: [PATCH 18/18] Set balances of default accounts to match those in E2E environment. --- crates/env/src/engine/off_chain/test_api.rs | 22 ++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/env/src/engine/off_chain/test_api.rs b/crates/env/src/engine/off_chain/test_api.rs index 2ecb42ca72a..0f86dbc3cbb 100644 --- a/crates/env/src/engine/off_chain/test_api.rs +++ b/crates/env/src/engine/off_chain/test_api.rs @@ -306,30 +306,30 @@ where instance.engine.set_callee(encoded_alice.clone()); // set up the funds for the default accounts - let substantial = 1_000_000; - let some = 1_000; + let substantial = 1_u128 << 60; instance.engine.set_balance(encoded_alice, substantial); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.bob), some); + .set_balance(scale::Encode::encode(&default_accounts.bob), substantial); + instance.engine.set_balance( + scale::Encode::encode(&default_accounts.charlie), + substantial, + ); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.charlie), some); + .set_balance(scale::Encode::encode(&default_accounts.dave), substantial); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.dave), 0); + .set_balance(scale::Encode::encode(&default_accounts.eve), substantial); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.eve), 0); + .set_balance(scale::Encode::encode(&default_accounts.ferdie), substantial); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.ferdie), 0); + .set_balance(scale::Encode::encode(&default_accounts.one), substantial); instance .engine - .set_balance(scale::Encode::encode(&default_accounts.one), 0); - instance - .engine - .set_balance(scale::Encode::encode(&default_accounts.two), 0); + .set_balance(scale::Encode::encode(&default_accounts.two), substantial); }); f(default_accounts) }