diff --git a/aleph-client/Cargo.lock b/aleph-client/Cargo.lock index 33dfcb4bbf..e39596ee91 100644 --- a/aleph-client/Cargo.lock +++ b/aleph-client/Cargo.lock @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aleph_client" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "async-trait", diff --git a/aleph-client/Cargo.toml b/aleph-client/Cargo.toml index e37a066193..3b61da710f 100644 --- a/aleph-client/Cargo.toml +++ b/aleph-client/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "aleph_client" # TODO bump major version when API stablize -version = "2.5.0" +version = "2.6.0" edition = "2021" license = "Apache 2.0" diff --git a/aleph-client/src/connections.rs b/aleph-client/src/connections.rs index 5b12262349..9011949403 100644 --- a/aleph-client/src/connections.rs +++ b/aleph-client/src/connections.rs @@ -12,21 +12,72 @@ use subxt::{ SubstrateConfig, }; -use crate::{api, sp_weights::weight_v2::Weight, BlockHash, Call, Client, KeyPair, TxStatus}; +use crate::{ + api, sp_weights::weight_v2::Weight, AccountId, BlockHash, Call, KeyPair, SubxtClient, TxStatus, +}; #[derive(Clone)] pub struct Connection { - pub client: Client, + client: SubxtClient, } pub struct SignedConnection { - pub connection: Connection, - pub signer: KeyPair, + connection: Connection, + signer: KeyPair, } +#[derive(Clone)] pub struct RootConnection { - pub connection: Connection, - pub root: KeyPair, + connection: SignedConnection, +} + +pub(crate) trait AsConnection { + fn as_connection(&self) -> &Connection; +} + +pub(crate) trait AsSigned { + fn as_signed(&self) -> &SignedConnection; +} + +#[async_trait::async_trait] +pub trait ConnectionApi: Sync { + async fn get_storage_entry( + &self, + addrs: &StaticStorageAddress, + at: Option, + ) -> T::Target; + + async fn get_storage_entry_maybe< + T: DecodeWithMetadata + Sync, + Defaultable: Sync, + Iterable: Sync, + >( + &self, + addrs: &StaticStorageAddress, + at: Option, + ) -> Option; + + async fn rpc_call(&self, func_name: String, params: RpcParams) -> anyhow::Result; +} + +#[async_trait::async_trait] +pub trait SignedConnectionApi: ConnectionApi { + async fn send_tx( + &self, + tx: Call, + status: TxStatus, + ) -> anyhow::Result; + + async fn send_tx_with_params( + &self, + tx: Call, + params: BaseExtrinsicParamsBuilder, + status: TxStatus, + ) -> anyhow::Result; + + fn account_id(&self) -> &AccountId; + fn signer(&self) -> &KeyPair; + async fn try_as_root(&self) -> anyhow::Result; } #[async_trait::async_trait] @@ -58,29 +109,42 @@ impl SudoCall for RootConnection { } } -impl Connection { - const DEFAULT_RETRIES: u32 = 10; - const RETRY_WAIT_SECS: u64 = 1; +impl Clone for SignedConnection { + fn clone(&self) -> Self { + SignedConnection { + connection: self.connection.clone(), + signer: KeyPair::new(self.signer.signer().clone()), + } + } +} - pub async fn new(address: String) -> Self { - Self::new_with_retries(address, Self::DEFAULT_RETRIES).await +impl AsConnection for Connection { + fn as_connection(&self) -> &Connection { + self } +} - pub async fn new_with_retries(address: String, mut retries: u32) -> Self { - loop { - let client = Client::from_url(&address).await; - match (retries, client) { - (_, Ok(client)) => return Self { client }, - (0, Err(e)) => panic!("{:?}", e), - _ => { - sleep(Duration::from_secs(Self::RETRY_WAIT_SECS)); - retries -= 1; - } - } - } +impl AsConnection for S { + fn as_connection(&self) -> &Connection { + &self.as_signed().connection } +} + +impl AsSigned for SignedConnection { + fn as_signed(&self) -> &SignedConnection { + self + } +} + +impl AsSigned for RootConnection { + fn as_signed(&self) -> &SignedConnection { + &self.connection + } +} - pub async fn get_storage_entry( +#[async_trait::async_trait] +impl ConnectionApi for C { + async fn get_storage_entry( &self, addrs: &StaticStorageAddress, at: Option, @@ -90,41 +154,40 @@ impl Connection { .expect("There should be a value") } - pub async fn get_storage_entry_maybe( + async fn get_storage_entry_maybe< + T: DecodeWithMetadata + Sync, + Defaultable: Sync, + Iterable: Sync, + >( &self, addrs: &StaticStorageAddress, at: Option, ) -> Option { info!(target: "aleph-client", "accessing storage at {}::{} at block {:?}", addrs.pallet_name(), addrs.entry_name(), at); - self.client + self.as_connection() + .as_client() .storage() .fetch(addrs, at) .await .expect("Should access storage") } - pub async fn rpc_call( - &self, - func_name: String, - params: RpcParams, - ) -> anyhow::Result { + async fn rpc_call(&self, func_name: String, params: RpcParams) -> anyhow::Result { info!(target: "aleph-client", "submitting rpc call `{}`, with params {:?}", func_name, params); - let bytes: Bytes = self.client.rpc().request(&func_name, params).await?; + let bytes: Bytes = self + .as_connection() + .as_client() + .rpc() + .request(&func_name, params) + .await?; Ok(R::decode(&mut bytes.as_ref())?) } } -impl SignedConnection { - pub async fn new(address: String, signer: KeyPair) -> Self { - Self::from_connection(Connection::new(address).await, signer) - } - - pub fn from_connection(connection: Connection, signer: KeyPair) -> Self { - Self { connection, signer } - } - - pub async fn send_tx( +#[async_trait::async_trait] +impl SignedConnectionApi for S { + async fn send_tx( &self, tx: Call, status: TxStatus, @@ -133,7 +196,7 @@ impl SignedConnection { .await } - pub async fn send_tx_with_params( + async fn send_tx_with_params( &self, tx: Call, params: BaseExtrinsicParamsBuilder, @@ -144,10 +207,10 @@ impl SignedConnection { } let progress = self - .connection - .client + .as_connection() + .as_client() .tx() - .sign_and_submit_then_watch(&tx, &self.signer, params) + .sign_and_submit_then_watch(&tx, self.as_signed().signer(), params) .await .map_err(|e| anyhow!("Failed to submit transaction: {:?}", e))?; @@ -161,10 +224,60 @@ impl SignedConnection { Ok(hash) } + + fn account_id(&self) -> &AccountId { + self.as_signed().signer().account_id() + } + + fn signer(&self) -> &KeyPair { + &self.as_signed().signer + } + + async fn try_as_root(&self) -> anyhow::Result { + let temp = self.as_signed().clone(); + RootConnection::try_from_connection(temp.connection, temp.signer).await + } +} + +impl Connection { + const DEFAULT_RETRIES: u32 = 10; + const RETRY_WAIT_SECS: u64 = 1; + + pub async fn new(address: &str) -> Connection { + Self::new_with_retries(address, Self::DEFAULT_RETRIES).await + } + + async fn new_with_retries(address: &str, mut retries: u32) -> Connection { + loop { + let client = SubxtClient::from_url(&address).await; + match (retries, client) { + (_, Ok(client)) => return Connection { client }, + (0, Err(e)) => panic!("{:?}", e), + _ => { + sleep(Duration::from_secs(Self::RETRY_WAIT_SECS)); + retries -= 1; + } + } + } + } + + pub(crate) fn as_client(&self) -> &SubxtClient { + &self.client + } +} + +impl SignedConnection { + pub async fn new(address: &str, signer: KeyPair) -> Self { + Self::from_connection(Connection::new(address).await, signer) + } + + pub fn from_connection(connection: Connection, signer: KeyPair) -> Self { + Self { connection, signer } + } } impl RootConnection { - pub async fn new(address: String, root: KeyPair) -> anyhow::Result { + pub async fn new(address: &str, root: KeyPair) -> anyhow::Result { RootConnection::try_from_connection(Connection::new(address).await, root).await } @@ -174,7 +287,12 @@ impl RootConnection { ) -> anyhow::Result { let root_address = api::storage().sudo().key(); - let root = match connection.client.storage().fetch(&root_address, None).await { + let root = match connection + .as_client() + .storage() + .fetch(&root_address, None) + .await + { Ok(Some(account)) => account, _ => return Err(anyhow!("Could not read sudo key from chain")), }; @@ -188,15 +306,7 @@ impl RootConnection { } Ok(Self { - connection, - root: signer, + connection: SignedConnection { connection, signer }, }) } - - pub fn as_signed(&self) -> SignedConnection { - SignedConnection { - connection: self.connection.clone(), - signer: KeyPair::new(self.root.signer().clone()), - } - } } diff --git a/aleph-client/src/contract/mod.rs b/aleph-client/src/contract/mod.rs index d40c662050..ddff119754 100644 --- a/aleph-client/src/contract/mod.rs +++ b/aleph-client/src/contract/mod.rs @@ -54,7 +54,7 @@ use crate::{ contract_transcode::Value, pallets::contract::{ContractCallArgs, ContractRpc, ContractsUserApi}, sp_weights::weight_v2::Weight, - AccountId, Connection, SignedConnection, TxStatus, + AccountId, ConnectionApi, SignedConnectionApi, TxStatus, }; /// Represents a contract instantiated on the chain. @@ -80,21 +80,25 @@ impl ContractInstance { } /// Reads the value of a read-only, 0-argument call via RPC. - pub async fn contract_read0>( + pub async fn contract_read0< + T: TryFrom, + C: ConnectionApi, + >( &self, - conn: &Connection, + conn: &C, message: &str, ) -> Result { - self.contract_read::(conn, message, &[]).await + self.contract_read::(conn, message, &[]).await } /// Reads the value of a read-only call via RPC. pub async fn contract_read< S: AsRef + Debug, T: TryFrom, + C: ConnectionApi, >( &self, - conn: &Connection, + conn: &C, message: &str, args: &[S], ) -> Result { @@ -119,35 +123,40 @@ impl ContractInstance { } /// Executes a 0-argument contract call. - pub async fn contract_exec0(&self, conn: &SignedConnection, message: &str) -> Result<()> { - self.contract_exec::(conn, message, &[]).await + pub async fn contract_exec0( + &self, + conn: &C, + message: &str, + ) -> Result<()> { + self.contract_exec::(conn, message, &[]).await } /// Executes a contract call. - pub async fn contract_exec + Debug>( + pub async fn contract_exec + Debug>( &self, - conn: &SignedConnection, + conn: &C, message: &str, args: &[S], ) -> Result<()> { - self.contract_exec_value(conn, message, args, 0).await + self.contract_exec_value::(conn, message, args, 0) + .await } /// Executes a 0-argument contract call sending the given amount of value with it. - pub async fn contract_exec_value0( + pub async fn contract_exec_value0( &self, - conn: &SignedConnection, + conn: &C, message: &str, value: u128, ) -> Result<()> { - self.contract_exec_value::(conn, message, &[], value) + self.contract_exec_value::(conn, message, &[], value) .await } /// Executes a contract call sending the given amount of value with it. - pub async fn contract_exec_value + Debug>( + pub async fn contract_exec_value + Debug>( &self, - conn: &SignedConnection, + conn: &C, message: &str, args: &[S], value: u128, diff --git a/aleph-client/src/lib.rs b/aleph-client/src/lib.rs index f6ccaceeec..4dbdf8cfc1 100644 --- a/aleph-client/src/lib.rs +++ b/aleph-client/src/lib.rs @@ -30,10 +30,13 @@ pub type AlephKeyPair = ed25519::Pair; pub type RawKeyPair = sr25519::Pair; pub type KeyPair = PairSigner; pub type AccountId = subxt::ext::sp_core::crypto::AccountId32; -pub type Client = OnlineClient; pub type BlockHash = H256; -pub use connections::{Connection, RootConnection, SignedConnection, SudoCall}; +pub(crate) type SubxtClient = OnlineClient; + +pub use connections::{ + Connection, ConnectionApi, RootConnection, SignedConnection, SignedConnectionApi, SudoCall, +}; #[derive(Copy, Clone)] pub enum TxStatus { diff --git a/aleph-client/src/pallets/aleph.rs b/aleph-client/src/pallets/aleph.rs index 5e7ece9824..3f0c8530b5 100644 --- a/aleph-client/src/pallets/aleph.rs +++ b/aleph-client/src/pallets/aleph.rs @@ -10,7 +10,7 @@ use crate::{ pallet_aleph::pallet::Call::schedule_finality_version_change, AccountId, AlephKeyPair, BlockHash, Call::Aleph, - Connection, Pair, RootConnection, SudoCall, TxStatus, + ConnectionApi, Pair, RootConnection, SudoCall, TxStatus, }; #[async_trait::async_trait] @@ -68,7 +68,7 @@ impl AlephSudoApi for RootConnection { } #[async_trait::async_trait] -impl AlephRpc for Connection { +impl AlephRpc for C { async fn emergency_finalize( &self, number: BlockNumber, diff --git a/aleph-client/src/pallets/author.rs b/aleph-client/src/pallets/author.rs index 6edae050b0..56bc511782 100644 --- a/aleph-client/src/pallets/author.rs +++ b/aleph-client/src/pallets/author.rs @@ -1,6 +1,6 @@ use codec::Decode; -use crate::{aleph_runtime::SessionKeys, Connection}; +use crate::{aleph_runtime::SessionKeys, connections::AsConnection}; #[async_trait::async_trait] pub trait AuthorRpc { @@ -8,10 +8,9 @@ pub trait AuthorRpc { } #[async_trait::async_trait] -impl AuthorRpc for Connection { +impl AuthorRpc for C { async fn author_rotate_keys(&self) -> anyhow::Result { - let bytes = self.client.rpc().rotate_keys().await?; - + let bytes = self.as_connection().as_client().rpc().rotate_keys().await?; SessionKeys::decode(&mut bytes.0.as_slice()).map_err(|e| e.into()) } } diff --git a/aleph-client/src/pallets/balances.rs b/aleph-client/src/pallets/balances.rs index 166cf56271..e4d44e6f6b 100644 --- a/aleph-client/src/pallets/balances.rs +++ b/aleph-client/src/pallets/balances.rs @@ -7,7 +7,7 @@ use crate::{ pallets::utility::UtilityApi, AccountId, BlockHash, Call::Balances, - Connection, SignedConnection, TxStatus, + ConnectionApi, SignedConnectionApi, TxStatus, }; #[async_trait::async_trait] @@ -53,7 +53,7 @@ pub trait BalanceUserBatchExtApi { } #[async_trait::async_trait] -impl BalanceApi for Connection { +impl BalanceApi for C { async fn locks_for_account( &self, account: AccountId, @@ -86,7 +86,7 @@ impl BalanceApi for Connection { } #[async_trait::async_trait] -impl BalanceUserApi for SignedConnection { +impl BalanceUserApi for S { async fn transfer( &self, dest: AccountId, @@ -116,7 +116,7 @@ impl BalanceUserApi for SignedConnection { } #[async_trait::async_trait] -impl BalanceUserBatchExtApi for SignedConnection { +impl BalanceUserBatchExtApi for S { async fn batch_transfer( &self, dests: &[AccountId], diff --git a/aleph-client/src/pallets/contract.rs b/aleph-client/src/pallets/contract.rs index 8ea602df63..1eb7fd807e 100644 --- a/aleph-client/src/pallets/contract.rs +++ b/aleph-client/src/pallets/contract.rs @@ -5,7 +5,7 @@ use subxt::{ext::sp_core::Bytes, rpc_params}; use crate::{ api, pallet_contracts::wasm::OwnerInfo, sp_weights::weight_v2::Weight, AccountId, BlockHash, - Connection, SignedConnection, TxStatus, + ConnectionApi, SignedConnectionApi, TxStatus, }; #[derive(Encode)] @@ -82,7 +82,7 @@ pub trait ContractRpc { } #[async_trait::async_trait] -impl ContractsApi for Connection { +impl ContractsApi for C { async fn get_owner_info( &self, code_hash: BlockHash, @@ -95,7 +95,7 @@ impl ContractsApi for Connection { } #[async_trait::async_trait] -impl ContractsUserApi for SignedConnection { +impl ContractsUserApi for S { async fn upload_code( &self, code: Vec, @@ -179,7 +179,7 @@ impl ContractsUserApi for SignedConnection { } #[async_trait::async_trait] -impl ContractRpc for Connection { +impl ContractRpc for C { async fn call_and_get( &self, args: ContractCallArgs, diff --git a/aleph-client/src/pallets/elections.rs b/aleph-client/src/pallets/elections.rs index b29789f084..5c04534657 100644 --- a/aleph-client/src/pallets/elections.rs +++ b/aleph-client/src/pallets/elections.rs @@ -6,13 +6,14 @@ use crate::{ pallet_elections::pallet::Call::set_ban_config, primitives::{BanReason, CommitteeSeats, EraValidators}, }, + connections::AsConnection, pallet_elections::pallet::Call::{ ban_from_committee, change_validators, set_elections_openness, }, primitives::{BanConfig, BanInfo, ElectionOpenness}, AccountId, BlockHash, Call::Elections, - Connection, RootConnection, SudoCall, TxStatus, + ConnectionApi, RootConnection, SudoCall, TxStatus, }; #[async_trait::async_trait] @@ -78,7 +79,7 @@ pub trait ElectionsSudoApi { } #[async_trait::async_trait] -impl ElectionsApi for Connection { +impl ElectionsApi for C { async fn get_ban_config(&self, at: Option) -> BanConfig { let addrs = api::storage().elections().ban_config(); @@ -166,8 +167,11 @@ impl ElectionsApi for Connection { async fn get_session_period(&self) -> anyhow::Result { let addrs = api::constants().elections().session_period(); - - self.client.constants().at(&addrs).map_err(|e| e.into()) + self.as_connection() + .as_client() + .constants() + .at(&addrs) + .map_err(|e| e.into()) } } diff --git a/aleph-client/src/pallets/fee.rs b/aleph-client/src/pallets/fee.rs index 1b7e595ec8..330b8239c0 100644 --- a/aleph-client/src/pallets/fee.rs +++ b/aleph-client/src/pallets/fee.rs @@ -1,4 +1,4 @@ -use crate::{api, BlockHash, Connection}; +use crate::{api, BlockHash, ConnectionApi}; pub type FeeMultiplier = u128; @@ -8,7 +8,7 @@ pub trait TransactionPaymentApi { } #[async_trait::async_trait] -impl TransactionPaymentApi for Connection { +impl TransactionPaymentApi for C { async fn get_next_fee_multiplier(&self, at: Option) -> FeeMultiplier { let addrs = api::storage().transaction_payment().next_fee_multiplier(); diff --git a/aleph-client/src/pallets/multisig.rs b/aleph-client/src/pallets/multisig.rs index a91241135c..e92bdbe122 100644 --- a/aleph-client/src/pallets/multisig.rs +++ b/aleph-client/src/pallets/multisig.rs @@ -1,8 +1,8 @@ use primitives::{Balance, BlockNumber}; use crate::{ - api, api::runtime_types, sp_weights::weight_v2::Weight, AccountId, BlockHash, SignedConnection, - TxStatus, + api, api::runtime_types, sp_weights::weight_v2::Weight, AccountId, BlockHash, + SignedConnectionApi, TxStatus, }; pub type CallHash = [u8; 32]; @@ -32,7 +32,7 @@ pub trait MultisigUserApi { } #[async_trait::async_trait] -impl MultisigUserApi for SignedConnection { +impl MultisigUserApi for S { async fn approve_as_multi( &self, threshold: u16, diff --git a/aleph-client/src/pallets/session.rs b/aleph-client/src/pallets/session.rs index c5393e2a49..d9176ada4a 100644 --- a/aleph-client/src/pallets/session.rs +++ b/aleph-client/src/pallets/session.rs @@ -1,8 +1,8 @@ use primitives::SessionIndex; use crate::{ - api, api::runtime_types::aleph_runtime::SessionKeys, AccountId, BlockHash, Connection, - SignedConnection, TxStatus, + api, api::runtime_types::aleph_runtime::SessionKeys, AccountId, BlockHash, ConnectionApi, + SignedConnectionApi, TxStatus, }; #[async_trait::async_trait] @@ -22,7 +22,7 @@ pub trait SessionUserApi { } #[async_trait::async_trait] -impl SessionApi for Connection { +impl SessionApi for C { async fn get_next_session_keys( &self, account: AccountId, @@ -49,7 +49,7 @@ impl SessionApi for Connection { } #[async_trait::async_trait] -impl SessionUserApi for SignedConnection { +impl SessionUserApi for S { async fn set_keys(&self, new_keys: SessionKeys, status: TxStatus) -> anyhow::Result { let tx = api::tx().session().set_keys(new_keys, vec![]); diff --git a/aleph-client/src/pallets/staking.rs b/aleph-client/src/pallets/staking.rs index 7d10ec7201..cae30b052c 100644 --- a/aleph-client/src/pallets/staking.rs +++ b/aleph-client/src/pallets/staking.rs @@ -9,6 +9,7 @@ use subxt::{ use crate::{ api, + connections::AsConnection, pallet_staking::{ pallet::pallet::{ Call::{bond, force_new_era, nominate, set_staking_configs}, @@ -22,7 +23,7 @@ use crate::{ sp_arithmetic::per_things::Perbill, AccountId, BlockHash, Call::{Staking, Sudo}, - Connection, RootConnection, SignedConnection, SudoCall, TxStatus, + ConnectionApi, RootConnection, SignedConnectionApi, SudoCall, TxStatus, }; #[async_trait::async_trait] @@ -123,7 +124,7 @@ pub trait StakingRawApi { } #[async_trait::async_trait] -impl StakingApi for Connection { +impl StakingApi for C { async fn get_active_era(&self, at: Option) -> EraIndex { let addrs = api::storage().staking().active_era(); @@ -183,13 +184,16 @@ impl StakingApi for Connection { async fn get_session_per_era(&self) -> anyhow::Result { let addrs = api::constants().staking().sessions_per_era(); - - self.client.constants().at(&addrs).map_err(|e| e.into()) + self.as_connection() + .as_client() + .constants() + .at(&addrs) + .map_err(|e| e.into()) } } #[async_trait::async_trait] -impl StakingUserApi for SignedConnection { +impl StakingUserApi for S { async fn bond( &self, initial_stake: Balance, @@ -295,7 +299,7 @@ impl StakingSudoApi for RootConnection { } #[async_trait::async_trait] -impl StakingRawApi for Connection { +impl StakingRawApi for C { async fn get_stakers_storage_keys( &self, era: EraIndex, @@ -304,7 +308,8 @@ impl StakingRawApi for Connection { let key_addrs = api::storage().staking().eras_stakers_root(); let mut key = key_addrs.to_root_bytes(); StorageMapKey::new(era, StorageHasher::Twox64Concat).to_bytes(&mut key); - self.client + self.as_connection() + .as_client() .storage() .fetch_keys(&key, 10, None, at) .await @@ -356,7 +361,7 @@ impl StakingApiExt for RootConnection { }) .collect(); - self.as_signed().batch_call(calls, status).await + self.batch_call(calls, status).await } async fn batch_nominate( @@ -377,6 +382,6 @@ impl StakingApiExt for RootConnection { }) .collect(); - self.as_signed().batch_call(calls, status).await + self.batch_call(calls, status).await } } diff --git a/aleph-client/src/pallets/system.rs b/aleph-client/src/pallets/system.rs index 102d3bf095..5c2bb270b4 100644 --- a/aleph-client/src/pallets/system.rs +++ b/aleph-client/src/pallets/system.rs @@ -7,7 +7,7 @@ use crate::{ sp_arithmetic::per_things::Perbill, AccountId, BlockHash, Call::System, - Connection, RootConnection, SudoCall, TxStatus, + ConnectionApi, RootConnection, SudoCall, TxStatus, }; #[async_trait::async_trait] @@ -47,7 +47,7 @@ impl SystemSudoApi for RootConnection { } #[async_trait::async_trait] -impl SystemApi for Connection { +impl SystemApi for C { async fn get_free_balance(&self, account: AccountId, at: Option) -> Balance { let addrs = api::storage().system().account(&account); diff --git a/aleph-client/src/pallets/treasury.rs b/aleph-client/src/pallets/treasury.rs index 1b1bb3773a..8e4deace36 100644 --- a/aleph-client/src/pallets/treasury.rs +++ b/aleph-client/src/pallets/treasury.rs @@ -5,11 +5,12 @@ use subxt::ext::sp_runtime::MultiAddress; use crate::{ api, + connections::AsConnection, pallet_treasury::pallet::Call::{approve_proposal, reject_proposal}, pallets::{elections::ElectionsApi, staking::StakingApi}, AccountId, BlockHash, Call::Treasury, - Connection, RootConnection, SignedConnection, SudoCall, TxStatus, + ConnectionApi, RootConnection, SignedConnectionApi, SudoCall, TxStatus, }; #[async_trait::async_trait] @@ -43,7 +44,7 @@ pub trait TreasurySudoApi { } #[async_trait::async_trait] -impl TreasuryApi for Connection { +impl TreasuryApi for C { async fn treasury_account(&self) -> AccountId { PalletId(*b"a0/trsry").into_account_truncating() } @@ -62,7 +63,7 @@ impl TreasuryApi for Connection { } #[async_trait::async_trait] -impl TreasuryUserApi for SignedConnection { +impl TreasuryUserApi for S { async fn propose_spend( &self, amount: Balance, @@ -105,11 +106,10 @@ impl TreasurySudoApi for RootConnection { } #[async_trait::async_trait] -impl TreasureApiExt for Connection { +impl TreasureApiExt for C { async fn possible_treasury_payout(&self) -> anyhow::Result { let session_period = self.get_session_period().await?; let sessions_per_era = self.get_session_per_era().await?; - let millisecs_per_era = MILLISECS_PER_BLOCK * session_period as u64 * sessions_per_era as u64; Ok(primitives::staking::era_payout(millisecs_per_era).1) diff --git a/aleph-client/src/pallets/utility.rs b/aleph-client/src/pallets/utility.rs index 9374b8480e..884325508c 100644 --- a/aleph-client/src/pallets/utility.rs +++ b/aleph-client/src/pallets/utility.rs @@ -1,4 +1,4 @@ -use crate::{api, BlockHash, Call, SignedConnection, TxStatus}; +use crate::{api, BlockHash, Call, SignedConnectionApi, TxStatus}; #[async_trait::async_trait] pub trait UtilityApi { @@ -6,7 +6,7 @@ pub trait UtilityApi { } #[async_trait::async_trait] -impl UtilityApi for SignedConnection { +impl UtilityApi for S { async fn batch_call(&self, calls: Vec, status: TxStatus) -> anyhow::Result { let tx = api::tx().utility().batch(calls); diff --git a/aleph-client/src/pallets/vesting.rs b/aleph-client/src/pallets/vesting.rs index 567c35202d..c6faa1d7a7 100644 --- a/aleph-client/src/pallets/vesting.rs +++ b/aleph-client/src/pallets/vesting.rs @@ -1,8 +1,8 @@ use subxt::ext::sp_runtime::MultiAddress; use crate::{ - api, pallet_vesting::vesting_info::VestingInfo, AccountId, BlockHash, Connection, - SignedConnection, TxStatus, + api, pallet_vesting::vesting_info::VestingInfo, AccountId, BlockHash, ConnectionApi, + SignedConnectionApi, TxStatus, }; #[async_trait::async_trait] @@ -33,7 +33,7 @@ pub trait VestingUserApi { } #[async_trait::async_trait] -impl VestingApi for Connection { +impl VestingApi for C { async fn get_vesting( &self, who: AccountId, @@ -46,7 +46,7 @@ impl VestingApi for Connection { } #[async_trait::async_trait] -impl VestingUserApi for SignedConnection { +impl VestingUserApi for S { async fn vest(&self, status: TxStatus) -> anyhow::Result { let tx = api::tx().vesting().vest(); diff --git a/aleph-client/src/utility.rs b/aleph-client/src/utility.rs index bdb195a1dc..e02b1e2cb8 100644 --- a/aleph-client/src/utility.rs +++ b/aleph-client/src/utility.rs @@ -2,8 +2,9 @@ use log::info; use primitives::{BlockNumber, EraIndex, SessionIndex}; use crate::{ + connections::AsConnection, pallets::{elections::ElectionsApi, staking::StakingApi}, - BlockHash, Connection, + BlockHash, }; #[async_trait::async_trait] @@ -16,6 +17,10 @@ pub trait BlocksApi { async fn get_best_block(&self) -> anyhow::Result>; async fn get_finalized_block_hash(&self) -> anyhow::Result; async fn get_block_number(&self, block: BlockHash) -> anyhow::Result>; + async fn get_block_number_opt( + &self, + block: Option, + ) -> anyhow::Result>; } #[async_trait::async_trait] @@ -23,22 +28,8 @@ pub trait SessionEraApi { async fn get_active_era_for_session(&self, session: SessionIndex) -> anyhow::Result; } -impl Connection { - async fn get_block_number_inner( - &self, - block: Option, - ) -> anyhow::Result> { - self.client - .rpc() - .header(block) - .await - .map(|maybe_header| maybe_header.map(|header| header.number)) - .map_err(|e| e.into()) - } -} - #[async_trait::async_trait] -impl BlocksApi for Connection { +impl BlocksApi for C { async fn first_block_of_session( &self, session: SessionIndex, @@ -51,7 +42,8 @@ impl BlocksApi for Connection { async fn get_block_hash(&self, block: BlockNumber) -> anyhow::Result> { info!(target: "aleph-client", "querying block hash for number #{}", block); - self.client + self.as_connection() + .as_client() .rpc() .block_hash(Some(block.into())) .await @@ -59,24 +51,38 @@ impl BlocksApi for Connection { } async fn get_best_block(&self) -> anyhow::Result> { - self.get_block_number_inner(None).await + self.get_block_number_opt(None).await } async fn get_finalized_block_hash(&self) -> anyhow::Result { - self.client + self.as_connection() + .as_client() .rpc() .finalized_head() .await .map_err(|e| e.into()) } + async fn get_block_number_opt( + &self, + block: Option, + ) -> anyhow::Result> { + self.as_connection() + .as_client() + .rpc() + .header(block) + .await + .map(|maybe_header| maybe_header.map(|header| header.number)) + .map_err(|e| e.into()) + } + async fn get_block_number(&self, block: BlockHash) -> anyhow::Result> { - self.get_block_number_inner(Some(block)).await + self.get_block_number_opt(Some(block)).await } } #[async_trait::async_trait] -impl SessionEraApi for Connection { +impl SessionEraApi for C { async fn get_active_era_for_session(&self, session: SessionIndex) -> anyhow::Result { let block = self.first_block_of_session(session).await?; Ok(self.get_active_era(block).await) diff --git a/aleph-client/src/waiting.rs b/aleph-client/src/waiting.rs index 74d7cc5ca9..e06fdd09d2 100644 --- a/aleph-client/src/waiting.rs +++ b/aleph-client/src/waiting.rs @@ -6,8 +6,8 @@ use subxt::events::StaticEvent; use crate::{ aleph_zero, api::session::events::NewSession, + connections::AsConnection, pallets::{session::SessionApi, staking::StakingApi}, - Connection, }; pub enum BlockStatus { @@ -34,17 +34,19 @@ pub trait WaitingExt { } #[async_trait::async_trait] -impl AlephWaiting for Connection { +impl AlephWaiting for C { async fn wait_for_block bool + Send>(&self, predicate: P, status: BlockStatus) { let mut block_sub = match status { BlockStatus::Best => self - .client + .as_connection() + .as_client() .blocks() .subscribe_best() .await .expect("Failed to subscribe to the best block stream!"), BlockStatus::Finalized => self - .client + .as_connection() + .as_client() .blocks() .subscribe_finalized() .await @@ -65,13 +67,15 @@ impl AlephWaiting for Connection { ) -> T { let mut block_sub = match status { BlockStatus::Best => self - .client + .as_connection() + .as_client() .blocks() .subscribe_best() .await .expect("Failed to subscribe to the best block stream!"), BlockStatus::Finalized => self - .client + .as_connection() + .as_client() .blocks() .subscribe_finalized() .await @@ -102,7 +106,8 @@ impl AlephWaiting for Connection { async fn wait_for_era(&self, era: EraIndex, status: BlockStatus) { let addrs = aleph_zero::api::constants().staking().sessions_per_era(); let sessions_per_era = self - .client + .as_connection() + .as_client() .constants() .at(&addrs) .expect("Failed to obtain sessions_per_era const!"); @@ -121,7 +126,7 @@ impl AlephWaiting for Connection { } #[async_trait::async_trait] -impl WaitingExt for Connection { +impl WaitingExt for C { async fn wait_for_n_sessions(&self, n: SessionIndex, status: BlockStatus) { let current_session = self.get_session(None).await; diff --git a/benches/payout-stakers/Cargo.lock b/benches/payout-stakers/Cargo.lock index 2749a90e7b..b7108bb045 100644 --- a/benches/payout-stakers/Cargo.lock +++ b/benches/payout-stakers/Cargo.lock @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aleph_client" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "async-trait", diff --git a/benches/payout-stakers/src/main.rs b/benches/payout-stakers/src/main.rs index 81aef363a4..ba9a3ab003 100644 --- a/benches/payout-stakers/src/main.rs +++ b/benches/payout-stakers/src/main.rs @@ -7,7 +7,8 @@ use aleph_client::{ staking::{StakingApi, StakingApiExt, StakingUserApi}, }, waiting::{BlockStatus, WaitingExt}, - AccountId, Connection, KeyPair, RootConnection, SignedConnection, TxStatus, + AccountId, ConnectionApi, KeyPair, RootConnection, SignedConnection, SignedConnectionApi, + TxStatus, }; use clap::{ArgGroup, Parser}; use futures::future::join_all; @@ -69,7 +70,7 @@ async fn main() -> anyhow::Result<()> { let sudoer = get_sudoer_keypair(root_seed_file); - let connection = RootConnection::new(address.clone(), sudoer).await.unwrap(); + let connection = RootConnection::new(&address, sudoer).await.unwrap(); let validators = match validators_seed_file { Some(validators_seed_file) => { @@ -109,7 +110,7 @@ async fn main() -> anyhow::Result<()> { wait_for_successive_eras( &address, - &connection.connection, + &connection, validators_and_nominator_stashes, ERAS_TO_WAIT, ) @@ -151,7 +152,7 @@ async fn setup_test_validators_and_nominator_stashes( for (validator_index, validator) in validators.into_iter().enumerate() { let (nominator_controller_accounts, nominator_stash_accounts) = generate_nominator_accounts_with_minimal_bond( - &connection.as_signed(), + connection, validator_index as u32, validators_len as u32, ) @@ -180,9 +181,9 @@ pub fn derive_user_account_from_numeric_seed(seed: u32) -> KeyPair { } /// For a given number of eras, in each era check whether stash balances of a validator are locked. -async fn wait_for_successive_eras( +async fn wait_for_successive_eras( address: &str, - connection: &Connection, + connection: &C, validators_and_nominator_stashes: Vec<(KeyPair, Vec)>, eras_to_wait: u32, ) -> anyhow::Result<()> { @@ -198,11 +199,8 @@ async fn wait_for_successive_eras( current_era - 1 ); for (validator, nominators_stashes) in validators_and_nominator_stashes.iter() { - let validator_connection = SignedConnection::new( - address.to_string(), - KeyPair::new(validator.signer().clone()), - ) - .await; + let validator_connection = + SignedConnection::new(address, KeyPair::new(validator.signer().clone())).await; let validator_account = validator.account_id().clone(); info!("Doing payout_stakers for validator {}", validator_account); payout_stakers_and_assert_locked_balance( @@ -269,7 +267,7 @@ async fn bond_validators_funds_and_choose_controllers( for (controller, validator) in controllers.into_iter().zip(validators) { let validator_address = address.to_string(); handles.push(tokio::spawn(async move { - let connection = SignedConnection::new(validator_address, validator).await; + let connection = SignedConnection::new(&validator_address, validator).await; let controller_account_id = controller.account_id().clone(); connection .bond(MIN_VALIDATOR_BOND, controller_account_id, TxStatus::InBlock) @@ -290,7 +288,7 @@ async fn send_validate_txs(address: &str, controllers: Vec) { let prc = rng.gen::() % 100; handles.push(tokio::spawn(async move { let connection = - SignedConnection::new(node_address, KeyPair::new(controller.signer().clone())) + SignedConnection::new(&node_address, KeyPair::new(controller.signer().clone())) .await; connection.validate(prc, TxStatus::InBlock).await.unwrap(); })); @@ -301,8 +299,8 @@ async fn send_validate_txs(address: &str, controllers: Vec) { /// For a specific validator given by index, generates a predetermined number of nominator accounts. /// Nominator accounts are produced as (controller, stash) tuples with initial endowments. -async fn generate_nominator_accounts_with_minimal_bond( - connection: &SignedConnection, +async fn generate_nominator_accounts_with_minimal_bond( + connection: &S, validator_number: u32, validators_count: u32, ) -> (Vec, Vec) { @@ -343,7 +341,6 @@ async fn payout_stakers_and_assert_locked_balance( era: EraIndex, ) { let locked_stash_balances_before_payout = stash_connection - .connection .locks(accounts_to_check_balance, None) .await; stash_connection @@ -351,7 +348,6 @@ async fn payout_stakers_and_assert_locked_balance( .await .unwrap(); let locked_stash_balances_after_payout = stash_connection - .connection .locks(accounts_to_check_balance, None) .await; locked_stash_balances_before_payout.iter() diff --git a/bin/cliain/Cargo.lock b/bin/cliain/Cargo.lock index 346655da73..4dd2246534 100644 --- a/bin/cliain/Cargo.lock +++ b/bin/cliain/Cargo.lock @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aleph_client" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "async-trait", diff --git a/bin/cliain/src/contracts.rs b/bin/cliain/src/contracts.rs index 412c6009b5..301968a502 100644 --- a/bin/cliain/src/contracts.rs +++ b/bin/cliain/src/contracts.rs @@ -9,7 +9,7 @@ use aleph_client::{ pallets::contract::{ContractsApi, ContractsUserApi}, sp_weights::weight_v2::Weight, waiting::{AlephWaiting, BlockStatus}, - AccountId, Connection, SignedConnection, TxStatus, + AccountId, Connection, SignedConnection, SignedConnectionApi, TxStatus, }; use codec::{Compact, Decode}; use contract_metadata::ContractMetadata; @@ -45,7 +45,7 @@ pub async fn upload_code( let wasm = fs::read(wasm_path).expect("WASM artifact not found"); debug!(target: "contracts", "Found WASM contract code {:?}", wasm); - let connection = signed_connection.connection.clone(); + let connection = signed_connection.clone(); let event_handler = tokio::spawn(async move { connection .wait_for_event( @@ -94,8 +94,8 @@ pub async fn instantiate( debug!("Encoded constructor data {:?}", data); - let connection = signed_connection.connection.clone(); - let signer_id = signed_connection.signer.account_id().clone(); + let connection = signed_connection.clone(); + let signer_id = signed_connection.account_id().clone(); let event_handler = tokio::spawn(async move { connection @@ -153,9 +153,9 @@ pub async fn instantiate_with_code( debug!("Encoded constructor data {:?}", data); - let signer_id = signed_connection.signer.account_id().clone(); - let connection_0 = signed_connection.connection.clone(); - let connection_1 = signed_connection.connection.clone(); + let signer_id = signed_connection.account_id().clone(); + let connection_0 = signed_connection.clone(); + let connection_1 = signed_connection.clone(); let event_handler_0 = tokio::spawn(async move { connection_0 @@ -253,7 +253,7 @@ pub async fn remove_code( ) -> anyhow::Result { let ContractRemoveCode { code_hash } = command; - let connection = signed_connection.connection.clone(); + let connection = signed_connection.clone(); let event_handler = tokio::spawn(async move { connection diff --git a/bin/cliain/src/keys.rs b/bin/cliain/src/keys.rs index 7cd1827ebc..ae341fccbd 100644 --- a/bin/cliain/src/keys.rs +++ b/bin/cliain/src/keys.rs @@ -18,7 +18,6 @@ pub async fn prepare_keys( controller_account_id: AccountId, ) -> anyhow::Result<()> { connection - .as_signed() .bond( MIN_VALIDATOR_BOND, controller_account_id, @@ -26,11 +25,8 @@ pub async fn prepare_keys( ) .await .unwrap(); - let new_keys = connection.connection.author_rotate_keys().await?; - let _ = connection - .as_signed() - .set_keys(new_keys, TxStatus::Finalized) - .await?; + let new_keys = connection.author_rotate_keys().await?; + connection.set_keys(new_keys, TxStatus::Finalized).await?; Ok(()) } diff --git a/bin/cliain/src/lib.rs b/bin/cliain/src/lib.rs index 0c49fdc0b5..f246fd341b 100644 --- a/bin/cliain/src/lib.rs +++ b/bin/cliain/src/lib.rs @@ -45,23 +45,16 @@ impl ConnectionConfig { } pub async fn get_connection(&self) -> Connection { - Connection::new(self.node_endpoint.clone()).await + Connection::new(&self.node_endpoint).await } pub async fn get_signed_connection(&self) -> SignedConnection { - SignedConnection::new( - self.node_endpoint.clone(), - keypair_from_string(&self.signer_seed), - ) - .await + SignedConnection::new(&self.node_endpoint, keypair_from_string(&self.signer_seed)).await } pub async fn get_root_connection(&self) -> RootConnection { - RootConnection::new( - self.node_endpoint.clone(), - keypair_from_string(&self.signer_seed), - ) - .await - .expect("signer should be root") + RootConnection::new(&self.node_endpoint, keypair_from_string(&self.signer_seed)) + .await + .expect("signer should be root") } } diff --git a/bin/cliain/src/treasury.rs b/bin/cliain/src/treasury.rs index 4843b1b10b..f62f463cc9 100644 --- a/bin/cliain/src/treasury.rs +++ b/bin/cliain/src/treasury.rs @@ -18,16 +18,14 @@ pub async fn propose(connection: SignedConnection, amount_in_tokens: u64, benefi /// Delegates to `aleph_client::approve_treasury_proposal`. pub async fn approve(connection: RootConnection, proposal_id: u32) { - connection - .approve(proposal_id, TxStatus::Finalized) + TreasurySudoApi::approve(&connection, proposal_id, TxStatus::Finalized) .await .unwrap(); } /// Delegates to `aleph_client::reject_treasury_proposal`. pub async fn reject(connection: RootConnection, proposal_id: u32) { - connection - .reject(proposal_id, TxStatus::Finalized) + TreasurySudoApi::reject(&connection, proposal_id, TxStatus::Finalized) .await .unwrap(); } diff --git a/e2e-tests/Cargo.lock b/e2e-tests/Cargo.lock index 91ed27a6a8..24029e5fcb 100644 --- a/e2e-tests/Cargo.lock +++ b/e2e-tests/Cargo.lock @@ -78,7 +78,7 @@ dependencies = [ [[package]] name = "aleph_client" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "async-trait", diff --git a/e2e-tests/src/ban.rs b/e2e-tests/src/ban.rs index 8d54b229d0..e0a92c662f 100644 --- a/e2e-tests/src/ban.rs +++ b/e2e-tests/src/ban.rs @@ -4,7 +4,7 @@ use aleph_client::{ primitives::{BanConfig, BanInfo, CommitteeSeats, EraValidators}, utility::BlocksApi, waiting::{AlephWaiting, BlockStatus, WaitingExt}, - AccountId, Connection, RootConnection, TxStatus, + AccountId, RootConnection, TxStatus, }; use codec::Encode; use log::info; @@ -47,10 +47,7 @@ pub async fn setup_test( ) .await?; - root_connection - .connection - .wait_for_n_eras(2, BlockStatus::Best) - .await; + root_connection.wait_for_n_eras(2, BlockStatus::Best).await; Ok(( root_connection, @@ -71,8 +68,8 @@ pub fn check_validators( era_validators } -pub async fn check_ban_config( - connection: &Connection, +pub async fn check_ban_config( + connection: &C, expected_minimal_expected_performance: Perbill, expected_session_count_threshold: SessionCount, expected_clean_session_counter_delay: SessionCount, @@ -95,8 +92,8 @@ pub async fn check_ban_config( ban_config } -pub async fn check_underperformed_validator_session_count( - connection: &Connection, +pub async fn check_underperformed_validator_session_count( + connection: &C, validator: &AccountId, expected_session_count: SessionCount, ) -> SessionCount { @@ -113,8 +110,8 @@ pub async fn check_underperformed_validator_session_count( underperformed_validator_session_count } -pub async fn check_underperformed_validator_reason( - connection: &Connection, +pub async fn check_underperformed_validator_reason( + connection: &C, validator: &AccountId, expected_info: Option<&BanInfo>, ) -> Option { @@ -126,8 +123,8 @@ pub async fn check_underperformed_validator_reason( validator_ban_info } -pub async fn check_ban_info_for_validator( - connection: &Connection, +pub async fn check_ban_info_for_validator( + connection: &C, validator: &AccountId, expected_info: Option<&BanInfo>, ) -> Option { @@ -140,8 +137,8 @@ pub async fn check_ban_info_for_validator( validator_ban_info } -pub async fn check_ban_event( - connection: &Connection, +pub async fn check_ban_event( + connection: &C, expected_banned_validators: &[(AccountId, BanInfo)], ) -> anyhow::Result { let event = connection @@ -177,8 +174,8 @@ pub fn get_members_for_session( /// Checks whether underperformed counts for validators change predictably. Assumes: (a) that the /// sessions checked are in the past, (b) that all the checked validators are underperforming in /// those sessions (e.g. due to a prohibitively high performance threshold). -pub async fn check_underperformed_count_for_sessions( - connection: &Connection, +pub async fn check_underperformed_count_for_sessions( + connection: &C, reserved_validators: &[AccountId], non_reserved_validators: &[AccountId], seats: &CommitteeSeats, diff --git a/e2e-tests/src/config.rs b/e2e-tests/src/config.rs index 3352ea35f1..d2a53c2c00 100644 --- a/e2e-tests/src/config.rs +++ b/e2e-tests/src/config.rs @@ -79,9 +79,7 @@ impl Config { pub async fn create_root_connection(&self) -> RootConnection { let sudo_keypair = get_sudo_key(self); - RootConnection::new(self.node.clone(), sudo_keypair) - .await - .unwrap() + RootConnection::new(&self.node, sudo_keypair).await.unwrap() } /// Get a `SignedConnection` where the signer is the first validator. @@ -89,7 +87,7 @@ impl Config { let node = &self.node; let mut accounts = get_validators_keys(self); let sender = accounts.remove(0); - SignedConnection::new(node.clone(), sender).await + SignedConnection::new(node, sender).await } } diff --git a/e2e-tests/src/elections.rs b/e2e-tests/src/elections.rs index 72c42f2545..5640b5ae28 100644 --- a/e2e-tests/src/elections.rs +++ b/e2e-tests/src/elections.rs @@ -4,13 +4,13 @@ use aleph_client::{ pallets::session::SessionApi, primitives::{CommitteeSeats, EraValidators}, utility::BlocksApi, - AccountId, Connection, + AccountId, }; use log::debug; use primitives::SessionIndex; -pub async fn get_and_test_members_for_session( - connection: &Connection, +pub async fn get_and_test_members_for_session( + connection: &C, seats: CommitteeSeats, era_validators: &EraValidators, session: SessionIndex, diff --git a/e2e-tests/src/rewards.rs b/e2e-tests/src/rewards.rs index d081a4272e..3e49b81538 100644 --- a/e2e-tests/src/rewards.rs +++ b/e2e-tests/src/rewards.rs @@ -33,8 +33,8 @@ type RewardPoint = u32; /// Changes session_keys used by a given `controller` to some `zero`/invalid value, /// making it impossible to create new legal blocks. -pub async fn set_invalid_keys_for_validator( - controller_connection: &SignedConnection, +pub async fn set_invalid_keys_for_validator( + controller_connection: &S, ) -> anyhow::Result<()> { let zero_session_keys = [0; 64].to_vec().into(); @@ -44,7 +44,6 @@ pub async fn set_invalid_keys_for_validator( .await .unwrap(); controller_connection - .connection .wait_for_n_sessions(2, BlockStatus::Best) .await; @@ -52,13 +51,10 @@ pub async fn set_invalid_keys_for_validator( } /// Rotates session_keys of a given `controller`, making it able to rejoin the `consensus`. -pub(super) async fn reset_validator_keys( - controller_connection: &SignedConnection, +pub(super) async fn reset_validator_keys( + controller_connection: &S, ) -> anyhow::Result<()> { - let validator_keys = controller_connection - .connection - .author_rotate_keys() - .await?; + let validator_keys = controller_connection.author_rotate_keys().await?; controller_connection .set_keys(validator_keys, TxStatus::InBlock) .await @@ -66,21 +62,19 @@ pub(super) async fn reset_validator_keys( // wait until our node is forced to use new keys, i.e. current session + 2 controller_connection - .connection .wait_for_n_sessions(2, BlockStatus::Best) .await; Ok(()) } -pub async fn download_exposure( - connection: &SignedConnection, +pub async fn download_exposure( + connection: &S, era: EraIndex, account_id: &AccountId, beginning_of_session_block_hash: BlockHash, ) -> Balance { let exposure = connection - .connection .get_exposure(era, account_id, Some(beginning_of_session_block_hash)) .await; info!( @@ -130,14 +124,13 @@ fn check_rewards( Ok(()) } -async fn get_node_performance( - connection: &SignedConnection, +async fn get_node_performance( + connection: &S, account_id: &AccountId, before_end_of_session_block_hash: BlockHash, blocks_to_produce_per_session: u32, ) -> f64 { let block_count = connection - .connection .get_validator_block_count(account_id.clone(), Some(before_end_of_session_block_hash)) .await .unwrap_or_default(); @@ -159,8 +152,8 @@ async fn get_node_performance( lenient_performance } -pub async fn check_points( - connection: &SignedConnection, +pub async fn check_points( + connection: &S, session: SessionIndex, era: EraIndex, members: impl IntoIterator, @@ -168,7 +161,7 @@ pub async fn check_points( members_per_session: u32, max_relative_difference: f64, ) -> anyhow::Result<()> { - let session_period = connection.connection.get_session_period().await?; + let session_period = connection.get_session_period().await?; info!("Era: {} | session: {}.", era, session); @@ -176,22 +169,15 @@ pub async fn check_points( let end_of_session_block = beginning_of_session_block + session_period; info!("Waiting for block: {}.", end_of_session_block); connection - .connection .wait_for_block(|n| n >= end_of_session_block, BlockStatus::Finalized) .await; let beginning_of_session_block_hash = connection - .connection .get_block_hash(beginning_of_session_block) .await?; - let end_of_session_block_hash = connection - .connection - .get_block_hash(end_of_session_block) - .await?; - let before_end_of_session_block_hash = connection - .connection - .get_block_hash(end_of_session_block - 1) - .await?; + let end_of_session_block_hash = connection.get_block_hash(end_of_session_block).await?; + let before_end_of_session_block_hash = + connection.get_block_hash(end_of_session_block - 1).await?; info!( "End-of-session block hash: {:?}.", end_of_session_block_hash @@ -207,7 +193,6 @@ pub async fn check_points( // get points stored by the Staking pallet let validator_reward_points_current_era = connection - .connection .get_era_reward_points(era, end_of_session_block_hash) .await .unwrap_or_default() @@ -215,7 +200,6 @@ pub async fn check_points( let validator_reward_points_previous_session = HashMap::::from_iter( connection - .connection .get_era_reward_points(era, beginning_of_session_block_hash) .await .unwrap_or_default() @@ -286,10 +270,7 @@ pub async fn setup_validators( ) -> anyhow::Result<(EraValidators, CommitteeSeats, SessionIndex)> { let root_connection = config.create_root_connection().await; // we need to wait for at least era 1 since some of the storage items are not available at era 0 - root_connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; + root_connection.wait_for_n_eras(1, BlockStatus::Best).await; let seats = COMMITTEE_SEATS; let members_seats = seats.reserved_seats + seats.non_reserved_seats; @@ -309,18 +290,13 @@ pub async fn setup_validators( let reserved_members = &members[0..reserved_size]; let non_reserved_members = &members[reserved_size..]; - let session = root_connection.connection.get_session(None).await; - let network_validators = root_connection - .connection - .get_current_era_validators(None) - .await; + let session = root_connection.get_session(None).await; + let network_validators = root_connection.get_current_era_validators(None).await; let first_block_in_session = root_connection - .connection .first_block_of_session(session) .await? .ok_or(anyhow!("First block of session {} is None!", session))?; let network_seats = root_connection - .connection .get_committee_seats(Some(first_block_in_session)) .await; @@ -344,18 +320,11 @@ pub async fn setup_validators( ) .await?; - root_connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; - let session = root_connection.connection.get_session(None).await; + root_connection.wait_for_n_eras(1, BlockStatus::Best).await; + let session = root_connection.get_session(None).await; - let first_block_in_session = root_connection - .connection - .first_block_of_session(session) - .await?; + let first_block_in_session = root_connection.first_block_of_session(session).await?; let network_validators = root_connection - .connection .get_current_era_validators(first_block_in_session) .await; let reserved: HashSet<_> = era_validators.reserved.iter().cloned().collect(); @@ -363,7 +332,6 @@ pub async fn setup_validators( let non_reserved: HashSet<_> = era_validators.non_reserved.iter().cloned().collect(); let network_non_reserved: HashSet<_> = network_validators.non_reserved.into_iter().collect(); let network_seats = root_connection - .connection .get_committee_seats(first_block_in_session) .await; @@ -390,7 +358,6 @@ pub async fn validators_bond_extra_stakes(config: &Config, additional_stakes: &[ // funds to cover fees root_connection - .as_signed() .batch_transfer(&controller_accounts, TOKEN, TxStatus::Finalized) .await .unwrap(); @@ -401,11 +368,10 @@ pub async fn validators_bond_extra_stakes(config: &Config, additional_stakes: &[ // Additional TOKEN to cover fees root_connection - .as_signed() .transfer(validator_id, *additional_stake + TOKEN, TxStatus::Finalized) .await .unwrap(); - let stash_connection = SignedConnection::new(node.clone(), account_keys.validator).await; + let stash_connection = SignedConnection::new(node, account_keys.validator).await; stash_connection .bond_extra_stake(*additional_stake, TxStatus::Finalized) .await diff --git a/e2e-tests/src/test/adder.rs b/e2e-tests/src/test/adder.rs index 3b32450795..1deeea6285 100644 --- a/e2e-tests/src/test/adder.rs +++ b/e2e-tests/src/test/adder.rs @@ -1,6 +1,8 @@ use std::str::FromStr; -use aleph_client::{contract::ContractInstance, AccountId, Connection, SignedConnection}; +use aleph_client::{ + contract::ContractInstance, AccountId, Connection, ConnectionApi, SignedConnectionApi, +}; use anyhow::{Context, Result}; use assert2::assert; @@ -20,15 +22,20 @@ pub async fn adder() -> Result<()> { let increment = 10; let before = contract.get(&conn).await?; - contract.add(&account.sign(&conn), increment).await?; + let raw_connection = Connection::new(&config.node).await; + contract + .add(&account.sign(&raw_connection), increment) + .await?; let after = contract.get(&conn).await?; assert!(after == before + increment); let new_name = "test"; - contract.set_name(&account.sign(&conn), None).await?; + contract + .set_name(&account.sign(&raw_connection), None) + .await?; assert!(contract.get_name(&conn).await?.is_none()); contract - .set_name(&account.sign(&conn), Some(new_name)) + .set_name(&account.sign(&raw_connection), Some(new_name)) .await?; assert!(contract.get_name(&conn).await? == Some(new_name.to_string())); @@ -65,17 +72,21 @@ impl AdderInstance { Ok(Self { contract }) } - pub async fn get(&self, conn: &Connection) -> Result { + pub async fn get(&self, conn: &C) -> Result { self.contract.contract_read0(conn, "get").await } - pub async fn add(&self, conn: &SignedConnection, value: u32) -> Result<()> { + pub async fn add(&self, conn: &S, value: u32) -> Result<()> { self.contract .contract_exec(conn, "add", &[value.to_string()]) .await } - pub async fn set_name(&self, conn: &SignedConnection, name: Option<&str>) -> Result<()> { + pub async fn set_name( + &self, + conn: &S, + name: Option<&str>, + ) -> Result<()> { let name = name.map_or_else( || "None".to_string(), |name| { @@ -88,8 +99,8 @@ impl AdderInstance { self.contract.contract_exec(conn, "set_name", &[name]).await } - pub async fn get_name(&self, conn: &Connection) -> Result> { + pub async fn get_name(&self, conn: &C) -> Result> { let res: Option = self.contract.contract_read0(conn, "get_name").await?; - Ok(res.map(|name| name.replace("\0", ""))) + Ok(res.map(|name| name.replace('\0', ""))) } } diff --git a/e2e-tests/src/test/ban.rs b/e2e-tests/src/test/ban.rs index b1ddebd621..56e0b08eb1 100644 --- a/e2e-tests/src/test/ban.rs +++ b/e2e-tests/src/test/ban.rs @@ -48,7 +48,7 @@ async fn disable_validator(validator_address: &str, validator_seed: u32) -> anyh // This connection has to be set up with the controller key. let connection_to_disable = - SignedConnection::new(validator_address.to_string(), controller_key_to_disable).await; + SignedConnection::new(validator_address, controller_key_to_disable).await; set_invalid_keys_for_validator(&connection_to_disable).await } @@ -57,11 +57,7 @@ async fn signed_connection_for_disabled_controller() -> SignedConnection { let validator_seed = get_validator_seed(VALIDATOR_TO_DISABLE_OVERALL_INDEX); let stash_controller = NodeKeys::from(validator_seed); let controller_key_to_disable = stash_controller.controller; - SignedConnection::new( - NODE_TO_DISABLE_ADDRESS.to_string(), - controller_key_to_disable, - ) - .await + SignedConnection::new(NODE_TO_DISABLE_ADDRESS, controller_key_to_disable).await } /// Runs a chain, sets up a committee and validators. Sets an incorrect key for one of the @@ -79,14 +75,11 @@ pub async fn ban_automatic() -> anyhow::Result<()> { check_validators( &reserved_validators, &non_reserved_validators, - root_connection - .connection - .get_current_era_validators(None) - .await, + root_connection.get_current_era_validators(None).await, ); check_ban_config( - &root_connection.connection, + &root_connection, DEFAULT_BAN_MINIMAL_EXPECTED_PERFORMANCE, DEFAULT_BAN_SESSION_COUNT_THRESHOLD, DEFAULT_CLEAN_SESSION_COUNTER_DELAY, @@ -98,37 +91,25 @@ pub async fn ban_automatic() -> anyhow::Result<()> { info!("Validator to disable: {}", validator_to_disable); - check_underperformed_validator_session_count( - &root_connection.connection, - validator_to_disable, - 0, - ) - .await; - check_underperformed_validator_reason(&root_connection.connection, validator_to_disable, None) - .await; + check_underperformed_validator_session_count(&root_connection, validator_to_disable, 0).await; + check_underperformed_validator_reason(&root_connection, validator_to_disable, None).await; disable_validator(NODE_TO_DISABLE_ADDRESS, VALIDATOR_TO_DISABLE_OVERALL_INDEX).await?; root_connection - .connection .wait_for_n_sessions(SESSIONS_TO_MEET_BAN_THRESHOLD, BlockStatus::Best) .await; // The session count for underperforming validators is reset to 0 immediately on reaching the // threshold. - check_underperformed_validator_session_count( - &root_connection.connection, - validator_to_disable, - 0, - ) - .await; + check_underperformed_validator_session_count(&root_connection, validator_to_disable, 0).await; let reason = BanReason::InsufficientUptime(DEFAULT_BAN_SESSION_COUNT_THRESHOLD); - let start = root_connection.connection.get_current_era(None).await + 1; + let start = root_connection.get_current_era(None).await + 1; let expected_ban_info = BanInfo { reason, start }; check_underperformed_validator_reason( - &root_connection.connection, + &root_connection, validator_to_disable, Some(&expected_ban_info), ) @@ -138,16 +119,13 @@ pub async fn ban_automatic() -> anyhow::Result<()> { &non_reserved_validators[(VALIDATOR_TO_DISABLE_NON_RESERVED_INDEX + 1) as usize..]; let expected_banned_validators = vec![(validator_to_disable.clone(), expected_ban_info)]; - check_ban_event(&root_connection.connection, &expected_banned_validators).await?; + check_ban_event(&root_connection, &expected_banned_validators).await?; // Check current validators. check_validators( &reserved_validators, expected_non_reserved, - root_connection - .connection - .get_current_era_validators(None) - .await, + root_connection.get_current_era_validators(None).await, ); Ok(()) @@ -166,14 +144,11 @@ pub async fn ban_manual() -> anyhow::Result<()> { check_validators( &reserved_validators, &non_reserved_validators, - root_connection - .connection - .get_current_era_validators(None) - .await, + root_connection.get_current_era_validators(None).await, ); check_ban_config( - &root_connection.connection, + &root_connection, DEFAULT_BAN_MINIMAL_EXPECTED_PERFORMANCE, DEFAULT_BAN_SESSION_COUNT_THRESHOLD, DEFAULT_CLEAN_SESSION_COUNTER_DELAY, @@ -185,14 +160,9 @@ pub async fn ban_manual() -> anyhow::Result<()> { info!("Validator to manually ban: {}", validator_to_manually_ban); - check_underperformed_validator_session_count( - &root_connection.connection, - validator_to_manually_ban, - 0, - ) - .await; - check_ban_info_for_validator(&root_connection.connection, validator_to_manually_ban, None) + check_underperformed_validator_session_count(&root_connection, validator_to_manually_ban, 0) .await; + check_ban_info_for_validator(&root_connection, validator_to_manually_ban, None).await; let bounded_reason = BoundedVec(MANUAL_BAN_REASON.as_bytes().to_vec()); @@ -205,10 +175,10 @@ pub async fn ban_manual() -> anyhow::Result<()> { .await?; let reason = BanReason::OtherReason(bounded_reason); - let start = root_connection.connection.get_current_era(None).await + 1; + let start = root_connection.get_current_era(None).await + 1; let expected_ban_info = BanInfo { reason, start }; check_ban_info_for_validator( - &root_connection.connection, + &root_connection, validator_to_manually_ban, Some(&expected_ban_info), ) @@ -216,7 +186,7 @@ pub async fn ban_manual() -> anyhow::Result<()> { let expected_banned_validators = vec![(validator_to_manually_ban.clone(), expected_ban_info)]; - check_ban_event(&root_connection.connection, &expected_banned_validators).await?; + check_ban_event(&root_connection, &expected_banned_validators).await?; let expected_non_reserved: Vec<_> = non_reserved_validators .clone() @@ -228,10 +198,7 @@ pub async fn ban_manual() -> anyhow::Result<()> { check_validators( &reserved_validators, &expected_non_reserved, - root_connection - .connection - .get_current_era_validators(None) - .await, + root_connection.get_current_era_validators(None).await, ); Ok(()) @@ -257,12 +224,10 @@ pub async fn clearing_session_count() -> anyhow::Result<()> { disable_validator(NODE_TO_DISABLE_ADDRESS, VALIDATOR_TO_DISABLE_OVERALL_INDEX).await?; root_connection - .connection .wait_for_n_sessions(5, BlockStatus::Best) .await; let underperformed_validator_session_count = root_connection - .connection .get_underperformed_validator_session_count(validator_to_disable.clone(), None) .await .unwrap_or_default(); @@ -270,12 +235,8 @@ pub async fn clearing_session_count() -> anyhow::Result<()> { // it only has to be ge than 0 and should be cleared before reaching values larger than 3. assert!(underperformed_validator_session_count <= 2); - let next_era_reserved_validators = root_connection - .connection - .get_next_era_reserved_validators(None) - .await; + let next_era_reserved_validators = root_connection.get_next_era_reserved_validators(None).await; let next_era_non_reserved_validators = root_connection - .connection .get_next_era_non_reserved_validators(None) .await; @@ -328,14 +289,12 @@ pub async fn permissionless_ban() -> anyhow::Result<()> { .ban_from_committee(validator_to_ban.clone(), vec![], TxStatus::InBlock) .await?; root_connection - .connection .wait_for_n_eras(2, BlockStatus::Finalized) .await; let without_banned = HashSet::<_>::from_iter(non_reserved_without_banned); let non_reserved = HashSet::<_>::from_iter( root_connection - .connection .get_current_era_validators(None) .await .non_reserved, @@ -346,13 +305,11 @@ pub async fn permissionless_ban() -> anyhow::Result<()> { // validate again signed_connection.validate(0, TxStatus::InBlock).await?; root_connection - .connection .wait_for_n_eras(2, BlockStatus::Finalized) .await; let expected_non_reserved = HashSet::<_>::from_iter(non_reserved_validators); let non_reserved = HashSet::<_>::from_iter( root_connection - .connection .get_current_era_validators(None) .await .non_reserved, @@ -376,14 +333,11 @@ pub async fn ban_threshold() -> anyhow::Result<()> { check_validators( &reserved_validators, &non_reserved_validators, - root_connection - .connection - .get_current_era_validators(None) - .await, + root_connection.get_current_era_validators(None).await, ); check_ban_config( - &root_connection.connection, + &root_connection, DEFAULT_BAN_MINIMAL_EXPECTED_PERFORMANCE, DEFAULT_BAN_SESSION_COUNT_THRESHOLD, DEFAULT_CLEAN_SESSION_COUNTER_DELAY, @@ -401,16 +355,15 @@ pub async fn ban_threshold() -> anyhow::Result<()> { ) .await?; - let ban_config_change_session = root_connection.connection.get_session(None).await; + let ban_config_change_session = root_connection.get_session(None).await; let check_start_session = ban_config_change_session + 1; let check_end_session = check_start_session + SESSIONS_TO_CHECK - 1; root_connection - .connection .wait_for_n_sessions(SESSIONS_TO_CHECK, BlockStatus::Finalized) .await; check_underperformed_count_for_sessions( - &root_connection.connection, + &root_connection, &reserved_validators, &non_reserved_validators, &seats, diff --git a/e2e-tests/src/test/electing_validators.rs b/e2e-tests/src/test/electing_validators.rs index b099bde3b6..59bdfc65b7 100644 --- a/e2e-tests/src/test/electing_validators.rs +++ b/e2e-tests/src/test/electing_validators.rs @@ -8,7 +8,7 @@ use aleph_client::{ }, primitives::CommitteeSeats, waiting::{BlockStatus, WaitingExt}, - AccountId, Connection, KeyPair, Pair, SignedConnection, TxStatus, + AccountId, ConnectionApi, KeyPair, Pair, SignedConnection, TxStatus, }; use log::info; use primitives::EraIndex; @@ -21,8 +21,8 @@ use crate::{ /// Verify that `pallet_staking::ErasStakers` contains all target validators. /// /// We have to do it by comparing keys in storage trie. -async fn assert_validators_are_elected_stakers( - connection: &Connection, +async fn assert_validators_are_elected_stakers( + connection: &C, current_era: EraIndex, expected_validators_as_keys: Vec>, ) -> anyhow::Result<()> { @@ -61,8 +61,8 @@ fn min_num_sessions_to_see_all_non_reserved_validators( /// Verify that all target validators are included `pallet_session::Validators` across a few /// consecutive sessions. -async fn assert_validators_are_used_as_authorities( - connection: &Connection, +async fn assert_validators_are_used_as_authorities( + connection: &C, expected_authorities: &BTreeSet, min_num_sessions: u32, ) { @@ -87,7 +87,7 @@ async fn assert_validators_are_used_as_authorities( ); } -async fn assert_enough_validators(connection: &Connection, min_validator_count: u32) { +async fn assert_enough_validators(connection: &C, min_validator_count: u32) { let current_validator_count = connection.get_validators(None).await.len() as u32; assert!( current_validator_count >= min_validator_count, @@ -127,7 +127,7 @@ fn assert_enough_validators_left_after_chilling( async fn chill_validators(node: &str, chilling: Vec) { for validator in chilling.into_iter() { info!("Chilling validator {:?}", validator.signer().public()); - let connection = SignedConnection::new(node.to_string(), validator).await; + let connection = SignedConnection::new(node, validator).await; connection.chill(TxStatus::InBlock).await.unwrap(); } } @@ -160,10 +160,7 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { const NON_RESERVED_SEATS_DEFAULT: u32 = 3; // `MinimumValidatorCount` from `pallet_staking`, set in chain spec. - let min_validator_count = root_connection - .connection - .get_minimum_validator_count(None) - .await; + let min_validator_count = root_connection.get_minimum_validator_count(None).await; let reserved_seats = match config.test_case_params.reserved_seats { Some(seats) => seats, @@ -178,11 +175,11 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { const RESERVED_TO_CHILL_COUNT: u32 = 1; const NON_RESERVED_TO_CHILL_COUNT: u32 = 1; - assert_enough_validators(&root_connection.connection, min_validator_count).await; + assert_enough_validators(&root_connection, min_validator_count).await; let desired_validator_count = reserved_seats + non_reserved_seats; let accounts = setup_accounts(desired_validator_count); - prepare_validators(&root_connection.as_signed(), node, &accounts).await?; + prepare_validators(&root_connection, node, &accounts).await?; info!("New validators are set up"); let reserved_validators = accounts.get_stash_accounts()[..reserved_seats as usize].to_vec(); @@ -228,19 +225,15 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { info!("Changed validators to a new set"); // We need any signed connection. - let connection = root_connection.as_signed(); - connection - .connection - .wait_for_n_eras(2, BlockStatus::Best) - .await; - let current_era = connection.connection.get_current_era(None).await; + let connection = root_connection; + connection.wait_for_n_eras(2, BlockStatus::Best).await; + let current_era = connection.get_current_era(None).await; info!("New validators are in force (era: {})", current_era); assert_validators_are_elected_stakers( - &connection.connection, + &connection, current_era, connection - .connection .get_stakers_storage_keys_from_accounts( current_era, accounts.get_stash_accounts(), @@ -257,7 +250,7 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { min_num_sessions_to_see_all_non_reserved_validators(non_reserved_count, non_reserved_seats); assert_validators_are_used_as_authorities( - &connection.connection, + &connection, &BTreeSet::from_iter(accounts.get_stash_accounts().clone().into_iter()), min_num_sessions, ) @@ -265,11 +258,8 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { chill_validators(node, vec![chilling_reserved, chilling_non_reserved]).await; - connection - .connection - .wait_for_n_eras(2, BlockStatus::Best) - .await; - let current_era = connection.connection.get_current_era(None).await; + connection.wait_for_n_eras(2, BlockStatus::Best).await; + let current_era = connection.get_current_era(None).await; info!( "Subset of validators should be in force (era: {})", current_era @@ -280,10 +270,9 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { left_stashes.remove(0); assert_validators_are_elected_stakers( - &connection.connection, + &connection, current_era, connection - .connection .get_stakers_storage_keys_from_accounts(current_era, &left_stashes, None) .await .into_iter() @@ -292,7 +281,7 @@ pub async fn authorities_are_staking() -> anyhow::Result<()> { ) .await?; assert_validators_are_used_as_authorities( - &connection.connection, + &connection, &BTreeSet::from_iter(left_stashes.into_iter()), min_num_sessions, ) diff --git a/e2e-tests/src/test/era_payout.rs b/e2e-tests/src/test/era_payout.rs index d2576d1584..a822f716bf 100644 --- a/e2e-tests/src/test/era_payout.rs +++ b/e2e-tests/src/test/era_payout.rs @@ -1,7 +1,7 @@ use aleph_client::{ pallets::staking::{StakingApi, StakingSudoApi}, waiting::{AlephWaiting, BlockStatus, WaitingExt}, - Connection, TxStatus, + TxStatus, }; use primitives::{ staking::era_payout, Balance, EraIndex, DEFAULT_SESSIONS_PER_ERA, DEFAULT_SESSION_PERIOD, @@ -32,7 +32,7 @@ fn payout_within_two_block_delta(expected_payout: Balance, payout: Balance) { ); } -async fn wait_to_second_era(connection: &Connection) -> EraIndex { +async fn wait_to_second_era(connection: &C) -> EraIndex { let active_era = connection.get_active_era(None).await; if active_era < 2 { connection.wait_for_n_eras(2, BlockStatus::Best).await; @@ -42,30 +42,22 @@ async fn wait_to_second_era(connection: &Connection) -> EraIndex { async fn force_era_payout(config: &Config) -> anyhow::Result<()> { let root_connection = config.create_root_connection().await; - let active_era = wait_to_second_era(&root_connection.connection).await; - root_connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; + let active_era = wait_to_second_era(&root_connection).await; + root_connection.wait_for_n_eras(1, BlockStatus::Best).await; let active_era = active_era + 1; let starting_session = active_era * DEFAULT_SESSIONS_PER_ERA; root_connection - .connection .wait_for_session(starting_session + 1, BlockStatus::Best) .await; // new era will start in the session `starting_session + 3` root_connection.force_new_era(TxStatus::InBlock).await?; root_connection - .connection .wait_for_session(starting_session + 3, BlockStatus::Best) .await; - let payout = root_connection - .connection - .get_payout_for_era(active_era, None) - .await; + let payout = root_connection.get_payout_for_era(active_era, None).await; let expected_payout = era_payout((3 * DEFAULT_SESSION_PERIOD) as u64 * MILLISECS_PER_BLOCK).0; payout_within_two_block_delta(expected_payout, payout); @@ -76,9 +68,8 @@ async fn force_era_payout(config: &Config) -> anyhow::Result<()> { async fn normal_era_payout(config: &Config) -> anyhow::Result<()> { let root_connection = config.create_root_connection().await; - let active_era = wait_to_second_era(&root_connection.connection).await; + let active_era = wait_to_second_era(&root_connection).await; let payout = root_connection - .connection .get_payout_for_era(active_era - 1, None) .await; let expected_payout = era_payout( diff --git a/e2e-tests/src/test/era_validators.rs b/e2e-tests/src/test/era_validators.rs index 4eee186fb9..c3b20d8195 100644 --- a/e2e-tests/src/test/era_validators.rs +++ b/e2e-tests/src/test/era_validators.rs @@ -3,7 +3,7 @@ use aleph_client::{ primitives::CommitteeSeats, utility::BlocksApi, waiting::{AlephWaiting, BlockStatus, WaitingExt}, - AccountId, Connection, KeyPair, TxStatus, + AccountId, KeyPair, TxStatus, }; use anyhow::anyhow; @@ -40,16 +40,16 @@ fn get_new_non_reserved_validators(config: &Config) -> Vec { .collect() } -async fn get_current_and_next_era_reserved_validators( - connection: &Connection, +async fn get_current_and_next_era_reserved_validators( + connection: &C, ) -> (Vec, Vec) { let stored_reserved = connection.get_next_era_reserved_validators(None).await; let current_reserved = connection.get_current_era_validators(None).await.reserved; (current_reserved, stored_reserved) } -async fn get_current_and_next_era_non_reserved_validators( - connection: &Connection, +async fn get_current_and_next_era_non_reserved_validators( + connection: &C, ) -> (Vec, Vec) { let stored_non_reserved = connection.get_next_era_non_reserved_validators(None).await; let current_non_reserved = connection @@ -90,7 +90,6 @@ pub async fn era_validators() -> anyhow::Result<()> { ) .await?; root_connection - .connection .wait_for_n_eras(1, BlockStatus::Finalized) .await; @@ -107,13 +106,12 @@ pub async fn era_validators() -> anyhow::Result<()> { .await?; root_connection - .connection .wait_for_session(1, BlockStatus::Finalized) .await; let (eras_reserved, stored_reserved) = - get_current_and_next_era_reserved_validators(&connection.connection).await; + get_current_and_next_era_reserved_validators(&connection).await; let (eras_non_reserved, stored_non_reserved) = - get_current_and_next_era_non_reserved_validators(&connection.connection).await; + get_current_and_next_era_non_reserved_validators(&connection).await; assert_eq!( stored_reserved, new_reserved_validators, @@ -133,15 +131,12 @@ pub async fn era_validators() -> anyhow::Result<()> { "Non-reserved validators set has been updated too early." ); - connection - .connection - .wait_for_n_eras(1, BlockStatus::Finalized) - .await; + connection.wait_for_n_eras(1, BlockStatus::Finalized).await; let (eras_reserved, stored_reserved) = - get_current_and_next_era_reserved_validators(&connection.connection).await; + get_current_and_next_era_reserved_validators(&connection).await; let (eras_non_reserved, stored_non_reserved) = - get_current_and_next_era_non_reserved_validators(&connection.connection).await; + get_current_and_next_era_non_reserved_validators(&connection).await; assert_eq!( stored_reserved, new_reserved_validators, @@ -162,12 +157,10 @@ pub async fn era_validators() -> anyhow::Result<()> { ); let block_number = connection - .connection .get_best_block() .await? .ok_or(anyhow!("Failed to retrieve best block number!"))?; connection - .connection .wait_for_block(|n| n >= block_number, BlockStatus::Finalized) .await; diff --git a/e2e-tests/src/test/fee.rs b/e2e-tests/src/test/fee.rs index 3fcf1a4132..8bafab4b93 100644 --- a/e2e-tests/src/test/fee.rs +++ b/e2e-tests/src/test/fee.rs @@ -2,7 +2,7 @@ use aleph_client::{ api::transaction_payment::events::TransactionFeePaid, pallets::{balances::BalanceUserApi, fee::TransactionPaymentApi, system::SystemSudoApi}, waiting::{AlephWaiting, BlockStatus}, - AccountId, RootConnection, SignedConnection, TxStatus, + AccountId, RootConnection, SignedConnection, SignedConnectionApi, TxStatus, }; use log::info; use primitives::Balance; @@ -105,10 +105,10 @@ pub async fn current_fees( tip: Option, transfer_value: Balance, ) -> (Balance, u128) { - let actual_multiplier = connection.connection.get_next_fee_multiplier(None).await; + let actual_multiplier = connection.get_next_fee_multiplier(None).await; - let waiting_connection = connection.connection.clone(); - let signer = connection.signer.account_id().clone(); + let waiting_connection = connection.clone(); + let signer = connection.account_id().clone(); let event_handle = tokio::spawn(async move { waiting_connection .wait_for_event( diff --git a/e2e-tests/src/test/finalization.rs b/e2e-tests/src/test/finalization.rs index 3d53c3a562..ab01b8d032 100644 --- a/e2e-tests/src/test/finalization.rs +++ b/e2e-tests/src/test/finalization.rs @@ -11,16 +11,15 @@ pub async fn finalization() -> anyhow::Result<()> { let config = setup_test(); let connection = config.create_root_connection().await; - let finalized = connection.connection.get_finalized_block_hash().await?; + let finalized = connection.get_finalized_block_hash().await?; let finalized_number = connection - .connection .get_block_number(finalized) .await? .ok_or(anyhow!( "Failed to retrieve block number for hash {finalized:?}" ))?; + connection - .connection .wait_for_block(|n| n > finalized_number, BlockStatus::Finalized) .await; diff --git a/e2e-tests/src/test/helpers.rs b/e2e-tests/src/test/helpers.rs index a235fde8fe..4ebe74a377 100644 --- a/e2e-tests/src/test/helpers.rs +++ b/e2e-tests/src/test/helpers.rs @@ -2,7 +2,7 @@ use std::ops::Deref; use aleph_client::{ pallets::balances::BalanceUserApi, AccountId, Connection, KeyPair, Pair, SignedConnection, - TxStatus, + SignedConnectionApi, TxStatus, }; use anyhow::Result; use primitives::Balance; @@ -55,7 +55,11 @@ pub fn random_account() -> KeyPairWrapper { } /// Transfer `amount` from `from` to `to` -pub async fn transfer(conn: &SignedConnection, to: &KeyPair, amount: Balance) -> Result<()> { +pub async fn transfer( + conn: &S, + to: &KeyPair, + amount: Balance, +) -> Result<()> { conn.transfer(to.signer().public().into(), amount, TxStatus::InBlock) .await .map(|_| ()) @@ -69,12 +73,12 @@ pub fn alephs(basic_unit_amount: Balance) -> Balance { /// Prepares a `(conn, authority, account)` triple with some money in `account` for fees. pub async fn basic_test_context( config: &Config, -) -> Result<(Connection, KeyPairWrapper, KeyPairWrapper)> { +) -> Result<(SignedConnection, KeyPairWrapper, KeyPairWrapper)> { let conn = config.get_first_signed_connection().await; let authority = KeyPairWrapper(aleph_client::keypair_from_string(&config.sudo_seed)); let account = random_account(); transfer(&conn, &account, alephs(100)).await?; - Ok((conn.connection, authority, account)) + Ok((conn.clone(), authority, account)) } diff --git a/e2e-tests/src/test/rewards.rs b/e2e-tests/src/test/rewards.rs index fd4652ef57..cd7d225718 100644 --- a/e2e-tests/src/test/rewards.rs +++ b/e2e-tests/src/test/rewards.rs @@ -1,12 +1,13 @@ use aleph_client::{ pallets::{ + elections::ElectionsApi, session::SessionApi, staking::{StakingApi, StakingSudoApi}, }, primitives::{CommitteeSeats, EraValidators}, - utility::SessionEraApi, + utility::{BlocksApi, SessionEraApi}, waiting::{AlephWaiting, BlockStatus, WaitingExt}, - AccountId, SignedConnection, TxStatus, + AccountId, SignedConnection, SignedConnectionApi, TxStatus, }; use log::info; use primitives::{staking::MIN_VALIDATOR_BOND, EraIndex, SessionIndex}; @@ -32,11 +33,8 @@ pub async fn points_basic() -> anyhow::Result<()> { let connection = config.get_first_signed_connection().await; - connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; - let end_session = connection.connection.get_session(None).await; + connection.wait_for_n_eras(1, BlockStatus::Best).await; + let end_session = connection.get_session(None).await; let members_per_session = committee_size.reserved_seats + committee_size.non_reserved_seats; info!( @@ -45,12 +43,9 @@ pub async fn points_basic() -> anyhow::Result<()> { ); for session in start_session..end_session { - let era = connection - .connection - .get_active_era_for_session(session) - .await?; + let era = connection.get_active_era_for_session(session).await?; let (members_active, members_bench) = get_and_test_members_for_session( - &connection.connection, + &connection, committee_size.clone(), &era_validators, session, @@ -92,12 +87,9 @@ pub async fn points_stake_change() -> anyhow::Result<()> { .await; let connection = config.get_first_signed_connection().await; - let start_session = connection.connection.get_session(None).await; - connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; - let end_session = connection.connection.get_session(None).await; + let start_session = connection.get_session(None).await; + connection.wait_for_n_eras(1, BlockStatus::Best).await; + let end_session = connection.get_session(None).await; let members_per_session = committee_size.reserved_seats + committee_size.non_reserved_seats; info!( @@ -106,12 +98,9 @@ pub async fn points_stake_change() -> anyhow::Result<()> { ); for session in start_session..end_session { - let era = connection - .connection - .get_active_era_for_session(session) - .await?; + let era = connection.get_active_era_for_session(session).await?; let (members_active, members_bench) = get_and_test_members_for_session( - &connection.connection, + &connection, committee_size.clone(), &era_validators, session, @@ -142,18 +131,15 @@ pub async fn disable_node() -> anyhow::Result<()> { let root_connection = config.create_root_connection().await; let controller_connection = - SignedConnection::new(config.node.clone(), config.node_keys().controller).await; + SignedConnection::new(&config.node, config.node_keys().controller).await; // this should `disable` this node by setting invalid session_keys set_invalid_keys_for_validator(&controller_connection).await?; // this should `re-enable` this node, i.e. by means of the `rotate keys` procedure reset_validator_keys(&controller_connection).await?; - root_connection - .connection - .wait_for_n_eras(1, BlockStatus::Best) - .await; - let end_session = root_connection.connection.get_session(None).await; + root_connection.wait_for_n_eras(1, BlockStatus::Best).await; + let end_session = root_connection.get_session(None).await; let members_per_session = committee_size.reserved_seats + committee_size.non_reserved_seats; info!( @@ -162,12 +148,9 @@ pub async fn disable_node() -> anyhow::Result<()> { ); for session in start_session..end_session { - let era = root_connection - .connection - .get_active_era_for_session(session) - .await?; + let era = root_connection.get_active_era_for_session(session).await?; let (members_active, members_bench) = get_and_test_members_for_session( - &controller_connection.connection, + &controller_connection, committee_size.clone(), &era_validators, session, @@ -200,20 +183,16 @@ pub async fn force_new_era() -> anyhow::Result<()> { let connection = config.get_first_signed_connection().await; let root_connection = config.create_root_connection().await; - let start_era = connection - .connection - .get_active_era_for_session(start_session) - .await?; + let start_era = connection.get_active_era_for_session(start_session).await?; info!("Start | era: {}, session: {}", start_era, start_session); root_connection.force_new_era(TxStatus::Finalized).await?; connection - .connection .wait_for_session(start_session + 2, BlockStatus::Finalized) .await; - let active_era = connection.connection.get_active_era(None).await; - let current_session = connection.connection.get_session(None).await; + let active_era = connection.get_active_era(None).await; + let current_session = connection.get_session(None).await; info!( "After ForceNewEra | era: {}, session: {}", active_era, current_session @@ -245,10 +224,7 @@ pub async fn change_stake_and_force_new_era() -> anyhow::Result<()> { let connection = config.get_first_signed_connection().await; let root_connection = config.create_root_connection().await; - let start_era = connection - .connection - .get_active_era_for_session(start_session) - .await?; + let start_era = connection.get_active_era_for_session(start_session).await?; info!("Start | era: {}, session: {}", start_era, start_session); validators_bond_extra_stakes( @@ -264,13 +240,12 @@ pub async fn change_stake_and_force_new_era() -> anyhow::Result<()> { .await; root_connection.force_new_era(TxStatus::Finalized).await?; - let start_session = root_connection.connection.get_session(None).await; + let start_session = root_connection.get_session(None).await; connection - .connection .wait_for_session(start_session + 2, BlockStatus::Finalized) .await; - let active_era = connection.connection.get_active_era(None).await; - let current_session = connection.connection.get_session(None).await; + let active_era = connection.get_active_era(None).await; + let current_session = connection.get_session(None).await; info!( "After ForceNewEra | era: {}, session: {}", active_era, current_session @@ -288,8 +263,10 @@ pub async fn change_stake_and_force_new_era() -> anyhow::Result<()> { Ok(()) } -async fn check_points_after_force_new_era( - connection: &SignedConnection, +async fn check_points_after_force_new_era< + S: SignedConnectionApi + BlocksApi + ElectionsApi + AlephWaiting + StakingApi, +>( + connection: &S, start_session: SessionIndex, start_era: EraIndex, era_validators: &EraValidators, @@ -311,7 +288,7 @@ async fn check_points_after_force_new_era( ); let (members_active, members_bench) = get_and_test_members_for_session( - &connection.connection, + connection, seats.clone(), era_validators, session_to_check, diff --git a/e2e-tests/src/test/staking.rs b/e2e-tests/src/test/staking.rs index 766c0a1971..757638a69a 100644 --- a/e2e-tests/src/test/staking.rs +++ b/e2e-tests/src/test/staking.rs @@ -11,7 +11,7 @@ use aleph_client::{ primitives::CommitteeSeats, sp_core::bounded::bounded_vec::BoundedVec, waiting::{BlockStatus, WaitingExt}, - AccountId, KeyPair, Pair, SignedConnection, TxStatus, + AccountId, KeyPair, Pair, SignedConnection, SignedConnectionApi, TxStatus, }; use log::info; use primitives::{ @@ -63,7 +63,7 @@ pub async fn staking_era_payouts() -> anyhow::Result<()> { .into_iter() .zip(validator_accounts) { - let connection = SignedConnection::new(node.clone(), nominator).await; + let connection = SignedConnection::new(node, nominator).await; let nominee_account_id = AccountId::from(nominee.signer().public()); connection .nominate(nominee_account_id, TxStatus::InBlock) @@ -72,11 +72,8 @@ pub async fn staking_era_payouts() -> anyhow::Result<()> { // All the above calls influence the next era, so we need to wait that it passes. // this test can be speeded up by forcing new era twice, and waiting 4 sessions in total instead of almost 10 sessions - connection - .connection - .wait_for_n_eras(2, BlockStatus::Finalized) - .await; - let current_era = connection.connection.get_current_era(None).await; + connection.wait_for_n_eras(2, BlockStatus::Finalized).await; + let current_era = connection.get_current_era(None).await; info!( "Era {} started, claiming rewards for era {}", current_era, @@ -86,7 +83,7 @@ pub async fn staking_era_payouts() -> anyhow::Result<()> { let (_, validator_accounts) = get_validator_stashes_key_pairs(config); for key_pair in validator_accounts { let stash_account = AccountId::from(key_pair.signer().public()); - let stash_connection = SignedConnection::new(node.to_string(), key_pair).await; + let stash_connection = SignedConnection::new(node, key_pair).await; payout_stakers_and_assert_locked_balance( &stash_connection, &[stash_account.clone()], @@ -137,13 +134,11 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { .await?; root_connection - .connection .wait_for_n_sessions(2, BlockStatus::Best) .await; // to cover tx fees as we need a bit more than VALIDATOR_STAKE root_connection - .as_signed() .transfer( stash_account.clone(), MIN_VALIDATOR_BOND + TOKEN, @@ -152,12 +147,10 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { .await?; // to cover txs fees root_connection - .as_signed() .transfer(controller_account.clone(), TOKEN, TxStatus::InBlock) .await?; - let stash_connection = - SignedConnection::new(node.to_string(), KeyPair::new(stash.signer().clone())).await; + let stash_connection = SignedConnection::new(node, KeyPair::new(stash.signer().clone())).await; stash_connection .bond( @@ -168,7 +161,6 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { .await?; let bonded_controller_account = root_connection - .connection .get_bonded(stash_account.clone(), None) .await .expect("should be bonded to smth"); @@ -178,9 +170,9 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { &stash_account, &controller_account, &bonded_controller_account ); - let validator_keys = root_connection.connection.author_rotate_keys().await?; + let validator_keys = root_connection.author_rotate_keys().await?; let controller_connection = - SignedConnection::new(node.to_string(), KeyPair::new(controller.signer().clone())).await; + SignedConnection::new(node, KeyPair::new(controller.signer().clone())).await; controller_connection .set_keys(validator_keys, TxStatus::InBlock) .await?; @@ -188,7 +180,6 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { .validate(10, TxStatus::InBlock) .await?; let ledger = controller_connection - .connection .get_ledger(controller_account, None) .await; assert_eq!( @@ -217,14 +208,10 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { ) .await?; root_connection - .connection .wait_for_n_sessions(2, BlockStatus::Best) .await; - root_connection - .connection - .wait_for_n_eras(2, BlockStatus::Best) - .await; - let current_era = root_connection.connection.get_current_era(None).await; + root_connection.wait_for_n_eras(2, BlockStatus::Best).await; + let current_era = root_connection.get_current_era(None).await; info!( "Era {} started, claiming rewards for era {}", current_era, @@ -245,8 +232,7 @@ pub async fn staking_new_validator() -> anyhow::Result<()> { pub async fn multi_bond(node: &str, bonders: &[KeyPair], stake: Balance) { for bonder in bonders { let controller_account = account_from_keypair(bonder.signer()); - let connection = - SignedConnection::new(node.to_string(), KeyPair::new(bonder.signer().clone())).await; + let connection = SignedConnection::new(node, KeyPair::new(bonder.signer().clone())).await; connection .bond(stake, controller_account, TxStatus::InBlock) .await @@ -254,14 +240,13 @@ pub async fn multi_bond(node: &str, bonders: &[KeyPair], stake: Balance) { } } -async fn payout_stakers_and_assert_locked_balance( - stash_connection: &SignedConnection, +async fn payout_stakers_and_assert_locked_balance( + stash_connection: &S, accounts_to_check_balance: &[AccountId], stash_account: &AccountId, era: BlockNumber, ) { let locked_stash_balances_before_payout = stash_connection - .connection .locks(accounts_to_check_balance, None) .await; stash_connection @@ -269,7 +254,6 @@ async fn payout_stakers_and_assert_locked_balance( .await .unwrap(); let locked_stash_balances_after_payout = stash_connection - .connection .locks(accounts_to_check_balance, None) .await; locked_stash_balances_before_payout.iter() diff --git a/e2e-tests/src/test/transfer.rs b/e2e-tests/src/test/transfer.rs index 8cd33daa3c..c0c29a04a8 100644 --- a/e2e-tests/src/test/transfer.rs +++ b/e2e-tests/src/test/transfer.rs @@ -11,10 +11,7 @@ pub async fn token_transfer() -> anyhow::Result<()> { let config = setup_test(); let (connection, to) = setup_for_transfer(config).await; - let balance_before = connection - .connection - .get_free_balance(to.clone(), None) - .await; + let balance_before = connection.get_free_balance(to.clone(), None).await; info!("[+] Account {} balance before tx: {}", to, balance_before); let transfer_value = 1000; @@ -22,10 +19,7 @@ pub async fn token_transfer() -> anyhow::Result<()> { .transfer(to.clone(), transfer_value, TxStatus::Finalized) .await?; - let balance_after = connection - .connection - .get_free_balance(to.clone(), None) - .await; + let balance_after = connection.get_free_balance(to.clone(), None).await; info!("[+] Account {} balance after tx: {}", to, balance_after); assert_eq!( diff --git a/e2e-tests/src/test/treasury.rs b/e2e-tests/src/test/treasury.rs index 940d0779af..2ab69a80a6 100644 --- a/e2e-tests/src/test/treasury.rs +++ b/e2e-tests/src/test/treasury.rs @@ -7,7 +7,7 @@ use aleph_client::{ treasury::{TreasureApiExt, TreasuryApi, TreasuryUserApi}, }, waiting::{AlephWaiting, BlockStatus}, - Connection, KeyPair, RootConnection, SignedConnection, TxStatus, + ConnectionApi, KeyPair, RootConnection, SignedConnection, TxStatus, }; use log::info; use primitives::Balance; @@ -20,7 +20,7 @@ use crate::{ /// Returns current treasury free funds and total issuance. /// /// Takes two storage reads. -async fn balance_info(connection: &Connection) -> (Balance, Balance) { +async fn balance_info(connection: &C) -> (Balance, Balance) { let treasury_balance = connection .get_free_balance(connection.treasury_account().await, None) .await; @@ -39,11 +39,11 @@ pub async fn channeling_fee_and_tip() -> anyhow::Result<()> { let (transfer_amount, tip) = (1_000u128, 10_000u128); let (connection, to) = setup_for_transfer(config).await; - let (treasury_balance_before, issuance_before) = balance_info(&connection.connection).await; - let possible_treasury_gain_from_staking = - connection.connection.possible_treasury_payout().await?; + let (treasury_balance_before, issuance_before) = balance_info(&connection).await; + let possible_treasury_gain_from_staking = connection.possible_treasury_payout().await?; + let (fee, _) = current_fees(&connection, to, Some(tip), transfer_amount).await; - let (treasury_balance_after, issuance_after) = balance_info(&connection.connection).await; + let (treasury_balance_after, issuance_after) = balance_info(&connection).await; check_issuance( possible_treasury_gain_from_staking, @@ -107,24 +107,16 @@ pub async fn treasury_access() -> anyhow::Result<()> { let config = setup_test(); let proposer = KeyPair::new(get_validators_raw_keys(config)[0].clone()); let beneficiary = account_from_keypair(proposer.signer()); - let connection = SignedConnection::new(config.node.clone(), proposer).await; + let connection = SignedConnection::new(&config.node, proposer).await; - let proposals_counter_before = connection - .connection - .proposals_count(None) - .await - .unwrap_or_default(); + let proposals_counter_before = connection.proposals_count(None).await.unwrap_or_default(); connection .propose_spend(10, beneficiary.clone(), TxStatus::InBlock) .await?; connection .propose_spend(100, beneficiary.clone(), TxStatus::InBlock) .await?; - let proposals_counter_after = connection - .connection - .proposals_count(None) - .await - .unwrap_or_default(); + let proposals_counter_after = connection.proposals_count(None).await.unwrap_or_default(); assert_eq!( proposals_counter_before + 2, @@ -141,18 +133,15 @@ pub async fn treasury_access() -> anyhow::Result<()> { } async fn approve_treasury_proposal(connection: &RootConnection, id: u32) -> anyhow::Result<()> { - connection - .as_signed() - .approve(id, TxStatus::Finalized) - .await?; - let approvals = connection.connection.approvals(None).await; + connection.approve(id, TxStatus::Finalized).await?; + let approvals = connection.approvals(None).await; assert!(approvals.contains(&id)); Ok(()) } async fn reject_treasury_proposal(connection: &RootConnection, id: u32) -> anyhow::Result<()> { - let handle_connection = connection.connection.clone(); + let handle_connection = connection.clone(); let handle = tokio::spawn(async move { handle_connection .wait_for_event( @@ -161,10 +150,7 @@ async fn reject_treasury_proposal(connection: &RootConnection, id: u32) -> anyho ) .await; }); - connection - .as_signed() - .reject(id, TxStatus::Finalized) - .await?; + connection.reject(id, TxStatus::Finalized).await?; handle.await?; Ok(()) diff --git a/e2e-tests/src/test/validators_change.rs b/e2e-tests/src/test/validators_change.rs index f906f980f1..187142c3da 100644 --- a/e2e-tests/src/test/validators_change.rs +++ b/e2e-tests/src/test/validators_change.rs @@ -18,18 +18,9 @@ pub async fn change_validators() -> anyhow::Result<()> { let accounts = get_validators_keys(config); let connection = config.create_root_connection().await; - let reserved_before = connection - .connection - .get_next_era_reserved_validators(None) - .await; - let non_reserved_before = connection - .connection - .get_next_era_non_reserved_validators(None) - .await; - let committee_size_before = connection - .connection - .get_next_era_committee_seats(None) - .await; + let reserved_before = connection.get_next_era_reserved_validators(None).await; + let non_reserved_before = connection.get_next_era_non_reserved_validators(None).await; + let committee_size_before = connection.get_next_era_committee_seats(None).await; info!( "[+] state before tx: reserved: {:#?}, non_reserved: {:#?}, committee_size: {:#?}", @@ -52,7 +43,7 @@ pub async fn change_validators() -> anyhow::Result<()> { ) .await?; - connection.connection.wait_for_event(|e: &ChangeValidators| { + connection.wait_for_event(|e: &ChangeValidators| { info!("[+] NewValidatorsEvent: reserved: {:#?}, non_reserved: {:#?}, committee_size: {:#?}", e.0, e.1, e.2); e.0 == new_validators[0..2] @@ -64,18 +55,9 @@ pub async fn change_validators() -> anyhow::Result<()> { } }, BlockStatus::Best).await; - let reserved_after = connection - .connection - .get_next_era_reserved_validators(None) - .await; - let non_reserved_after = connection - .connection - .get_next_era_non_reserved_validators(None) - .await; - let committee_size_after = connection - .connection - .get_next_era_committee_seats(None) - .await; + let reserved_after = connection.get_next_era_reserved_validators(None).await; + let non_reserved_after = connection.get_next_era_non_reserved_validators(None).await; + let committee_size_after = connection.get_next_era_committee_seats(None).await; info!( "[+] state before tx: reserved: {:#?}, non_reserved: {:#?}, committee_size: {:#?}", @@ -91,13 +73,12 @@ pub async fn change_validators() -> anyhow::Result<()> { }, committee_size_after ); + let block_number = connection - .connection .get_best_block() .await? .ok_or(anyhow!("Failed to retrieve best block!"))?; connection - .connection .wait_for_block(|n| n >= block_number, BlockStatus::Finalized) .await; diff --git a/e2e-tests/src/test/validators_rotate.rs b/e2e-tests/src/test/validators_rotate.rs index f206865a20..8e55cc67b4 100644 --- a/e2e-tests/src/test/validators_rotate.rs +++ b/e2e-tests/src/test/validators_rotate.rs @@ -41,12 +41,10 @@ pub async fn validators_rotate() -> anyhow::Result<()> { ) .await?; root_connection - .connection .wait_for_n_eras(2, BlockStatus::Finalized) .await; - let current_session = root_connection.connection.get_session(None).await; + let current_session = root_connection.get_session(None).await; root_connection - .connection .wait_for_n_sessions(TEST_LENGTH, BlockStatus::Finalized) .await; @@ -54,13 +52,7 @@ pub async fn validators_rotate() -> anyhow::Result<()> { for session in current_session..current_session + TEST_LENGTH { let elected = connection - .connection - .get_validators( - connection - .connection - .first_block_of_session(session) - .await?, - ) + .get_validators(connection.first_block_of_session(session).await?) .await; let non_reserved = get_members_subset_for_session( @@ -108,12 +100,10 @@ pub async fn validators_rotate() -> anyhow::Result<()> { assert!(max_elected - min_elected <= 1); let block_number = connection - .connection .get_best_block() .await? .ok_or(anyhow!("Failed to retrieve best block number!"))?; connection - .connection .wait_for_block(|n| n >= block_number, BlockStatus::Finalized) .await; diff --git a/e2e-tests/src/test/version_upgrade.rs b/e2e-tests/src/test/version_upgrade.rs index 8d0846e78e..6bce869b1a 100644 --- a/e2e-tests/src/test/version_upgrade.rs +++ b/e2e-tests/src/test/version_upgrade.rs @@ -22,7 +22,7 @@ pub async fn schedule_version_change() -> anyhow::Result<()> { let connection = config.create_root_connection().await; let test_case_params = config.test_case_params.clone(); - let current_session = connection.connection.get_session(None).await; + let current_session = connection.get_session(None).await; let version_for_upgrade = test_case_params .upgrade_to_version .unwrap_or(UPGRADE_TO_VERSION); @@ -41,17 +41,14 @@ pub async fn schedule_version_change() -> anyhow::Result<()> { ) .await?; connection - .connection .wait_for_session(session_after_upgrade + 1, BlockStatus::Finalized) .await; let block_number = connection - .connection .get_best_block() .await? .ok_or(anyhow!("Failed to retrieve best block number!"))?; connection - .connection .wait_for_block(|n| n >= block_number, BlockStatus::Finalized) .await; @@ -67,7 +64,7 @@ pub async fn schedule_doomed_version_change_and_verify_finalization_stopped() -> let connection = config.create_root_connection().await; let test_case_params = config.test_case_params.clone(); - let current_session = connection.connection.get_session(None).await; + let current_session = connection.get_session(None).await; let version_for_upgrade = test_case_params .upgrade_to_version .unwrap_or(UPGRADE_TO_VERSION); @@ -86,14 +83,12 @@ pub async fn schedule_doomed_version_change_and_verify_finalization_stopped() -> ) .await?; connection - .connection .wait_for_session(session_after_upgrade + 1, BlockStatus::Best) .await; - let last_finalized_block = - session_for_upgrade * connection.connection.get_session_period().await? - 1; + let last_finalized_block = session_for_upgrade * connection.get_session_period().await? - 1; - let connection = connection.connection; + let connection = connection; let finalized_block_head = connection.get_finalized_block_hash().await?; let finalized_block = connection.get_block_number(finalized_block_head).await?; diff --git a/e2e-tests/src/transfer.rs b/e2e-tests/src/transfer.rs index e9d19ee18c..b12364a8e7 100644 --- a/e2e-tests/src/transfer.rs +++ b/e2e-tests/src/transfer.rs @@ -9,7 +9,7 @@ async fn setup(config: &Config) -> (Connection, KeyPair, AccountId) { KeyPair::new(accounts[1].clone()), ); let to = AccountId::from(to.signer().public()); - (Connection::new(config.node.clone()).await, from, to) + (Connection::new(&config.node).await, from, to) } pub async fn setup_for_transfer(config: &Config) -> (SignedConnection, AccountId) { diff --git a/e2e-tests/src/validators.rs b/e2e-tests/src/validators.rs index 31833885b2..850dbad40f 100644 --- a/e2e-tests/src/validators.rs +++ b/e2e-tests/src/validators.rs @@ -5,7 +5,8 @@ use aleph_client::{ staking::StakingUserApi, }, primitives::EraValidators, - raw_keypair_from_string, AccountId, KeyPair, RawKeyPair, SignedConnection, TxStatus, + raw_keypair_from_string, AccountId, KeyPair, RawKeyPair, SignedConnection, SignedConnectionApi, + TxStatus, }; use futures::future::join_all; use primitives::{staking::MIN_VALIDATOR_BOND, TOKEN}; @@ -103,8 +104,8 @@ pub fn setup_accounts(desired_validator_count: u32) -> Accounts { /// Endow validators (stashes and controllers), bond and rotate keys. /// /// Signer of `connection` should have enough balance to endow new accounts. -pub async fn prepare_validators( - connection: &SignedConnection, +pub async fn prepare_validators( + connection: &S, node: &str, accounts: &Accounts, ) -> anyhow::Result<()> { @@ -127,7 +128,7 @@ pub async fn prepare_validators( .iter() .zip(accounts.get_controller_accounts().iter()) { - let connection = SignedConnection::new(node.to_string(), KeyPair::new(stash.clone())).await; + let connection = SignedConnection::new(node, KeyPair::new(stash.clone())).await; let contr = controller.clone(); handles.push(tokio::spawn(async move { connection @@ -138,9 +139,8 @@ pub async fn prepare_validators( } for controller in accounts.controller_raw_keys.iter() { - let keys = connection.connection.author_rotate_keys().await?; - let connection = - SignedConnection::new(node.to_string(), KeyPair::new(controller.clone())).await; + let keys = connection.author_rotate_keys().await?; + let connection = SignedConnection::new(node, KeyPair::new(controller.clone())).await; handles.push(tokio::spawn(async move { connection .set_keys(keys, TxStatus::Finalized) diff --git a/flooder/Cargo.lock b/flooder/Cargo.lock index fef7c2c125..d1b9af837e 100644 --- a/flooder/Cargo.lock +++ b/flooder/Cargo.lock @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aleph_client" -version = "2.5.0" +version = "2.6.0" dependencies = [ "anyhow", "async-trait", diff --git a/flooder/src/main.rs b/flooder/src/main.rs index f9c1b8c9c5..2a44a9c913 100644 --- a/flooder/src/main.rs +++ b/flooder/src/main.rs @@ -2,7 +2,7 @@ use std::time::Duration; use aleph_client::{ account_from_keypair, pallets::balances::BalanceUserApi, raw_keypair_from_string, AccountId, - KeyPair, SignedConnection, TxStatus, + KeyPair, SignedConnection, SignedConnectionApi, TxStatus, }; use clap::Parser; use config::Config; @@ -72,7 +72,7 @@ async fn initialize_n_accounts String>( for i in 0..n { let seed = i.to_string(); let signer = KeyPair::new(raw_keypair_from_string(&("//".to_string() + &seed))); - connections.push(SignedConnection::new(node(i), signer).await); + connections.push(SignedConnection::new(&node(i), signer).await); } if skip { @@ -81,7 +81,7 @@ async fn initialize_n_accounts String>( for conn in connections.iter() { connection .transfer( - conn.signer.account_id().clone(), + conn.account_id().clone(), account_balance, TxStatus::Submitted, ) @@ -90,11 +90,7 @@ async fn initialize_n_accounts String>( } connection - .transfer( - connection.signer.account_id().clone(), - 1, - TxStatus::Finalized, - ) + .transfer(connection.account_id().clone(), 1, TxStatus::Finalized) .await .unwrap(); @@ -138,7 +134,7 @@ async fn main() -> anyhow::Result<()> { .unwrap(), }; let main_connection = - SignedConnection::new(config.nodes[0].to_string(), KeyPair::new(account.clone())).await; + SignedConnection::new(&config.nodes[0], KeyPair::new(account.clone())).await; let nodes = config.nodes.clone();