Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
2e22b79
dont use String for creating connections
krzysztofziobro Dec 27, 2022
20aafa6
do not wrap client
krzysztofziobro Dec 27, 2022
1f10b03
wip
krzysztofziobro Dec 28, 2022
2f5cda9
should work as old one
krzysztofziobro Dec 28, 2022
f5b769f
hide connection
krzysztofziobro Dec 28, 2022
44a4e9a
hide the rest
krzysztofziobro Dec 28, 2022
1472fd7
Don not hide clone
krzysztofziobro Dec 28, 2022
40225ca
Merge branch 'main' into A0-1613-improve-connection
krzysztofziobro Dec 29, 2022
168ce19
bump
krzysztofziobro Dec 29, 2022
0247e81
wip
krzysztofziobro Dec 30, 2022
4c1a6eb
wrap client
krzysztofziobro Dec 30, 2022
e41d124
rename client
krzysztofziobro Dec 30, 2022
7968aea
add Clone
krzysztofziobro Dec 30, 2022
9a979f6
Merge branch 'main' into A0-1613-improve-connection
krzysztofziobro Dec 30, 2022
50d7071
more general adder
krzysztofziobro Dec 30, 2022
dba9561
Add AsSigned
krzysztofziobro Dec 30, 2022
d700129
add impls for references
krzysztofziobro Dec 30, 2022
e45f361
wip
krzysztofziobro Jan 2, 2023
e6839b8
change TreasurySudoApi
krzysztofziobro Jan 2, 2023
8ec4625
Merge branch 'main' into A0-1613-improve-connection
krzysztofziobro Jan 2, 2023
3bf05d5
add methods to SignedConnectionApi
krzysztofziobro Jan 2, 2023
6b259b2
Merge branch 'A0-1613-improve-connection' of github.com:Cardinal-Cryp…
krzysztofziobro Jan 2, 2023
23d5a58
remove unnecessary casts
krzysztofziobro Jan 2, 2023
5600e11
Merge branch 'main' into A0-1613-improve-connection
krzysztofziobro Jan 2, 2023
b7ad771
review part 1
krzysztofziobro Jan 2, 2023
d156320
Merge branch 'A0-1613-improve-connection' of github.com:Cardinal-Cryp…
krzysztofziobro Jan 2, 2023
ef5625d
review part 2
krzysztofziobro Jan 2, 2023
af4d737
Make AsConnection visible only in crate
krzysztofziobro Jan 3, 2023
d15be1b
Merge branch 'main' into A0-1613-improve-connection
krzysztofziobro Jan 3, 2023
70db49a
Remove unnecessary dependencies on ConnectionApi
krzysztofziobro Jan 4, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
do not wrap client
  • Loading branch information
krzysztofziobro committed Dec 27, 2022
commit 20aafa6f13aaa319014772c1fd6427868e35b0ab
66 changes: 45 additions & 21 deletions aleph-client/src/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,34 @@ use subxt::{

use crate::{api, sp_weights::weight_v2::Weight, BlockHash, Call, Client, KeyPair, TxStatus};

#[derive(Clone)]
pub struct Connection {
pub client: Client,
pub type Connection = Client;

#[async_trait::async_trait]
pub trait ConnectionExt {
const DEFAULT_RETRIES: u32;
const RETRY_WAIT_SECS: u64;

async fn new(address: &str) -> Self;

async fn new_with_retries(address: &str, mut retries: u32) -> Self;

async fn get_storage_entry<T: DecodeWithMetadata + Sync, Defaultable: Sync, Iterable: Sync>(
&self,
addrs: &StaticStorageAddress<T, Yes, Defaultable, Iterable>,
at: Option<BlockHash>,
) -> T::Target;

async fn get_storage_entry_maybe<
T: DecodeWithMetadata + Sync,
Defaultable: Sync,
Iterable: Sync,
>(
&self,
addrs: &StaticStorageAddress<T, Yes, Defaultable, Iterable>,
at: Option<BlockHash>,
) -> Option<T::Target>;

async fn rpc_call<R: Decode>(&self, func_name: String, params: RpcParams) -> anyhow::Result<R>;
}

pub struct SignedConnection {
Expand Down Expand Up @@ -58,19 +83,20 @@ impl SudoCall for RootConnection {
}
}

impl Connection {
#[async_trait::async_trait]
impl ConnectionExt for Connection {
const DEFAULT_RETRIES: u32 = 10;
const RETRY_WAIT_SECS: u64 = 1;

pub async fn new(address: &str) -> Self {
async fn new(address: &str) -> Self {
Self::new_with_retries(address, Self::DEFAULT_RETRIES).await
}

pub async fn new_with_retries(address: &str, mut retries: u32) -> Self {
async fn new_with_retries(address: &str, mut retries: u32) -> Self {
loop {
let client = Client::from_url(&address).await;
match (retries, client) {
(_, Ok(client)) => return Self { client },
(_, Ok(client)) => return client,
(0, Err(e)) => panic!("{:?}", e),
_ => {
sleep(Duration::from_secs(Self::RETRY_WAIT_SECS));
Expand All @@ -80,7 +106,7 @@ impl Connection {
}
}

pub async fn get_storage_entry<T: DecodeWithMetadata, Defaultable, Iterable>(
async fn get_storage_entry<T: DecodeWithMetadata + Sync, Defaultable: Sync, Iterable: Sync>(
&self,
addrs: &StaticStorageAddress<T, Yes, Defaultable, Iterable>,
at: Option<BlockHash>,
Expand All @@ -90,34 +116,33 @@ impl Connection {
.expect("There should be a value")
}

pub async fn get_storage_entry_maybe<T: DecodeWithMetadata, Defaultable, Iterable>(
async fn get_storage_entry_maybe<
T: DecodeWithMetadata + Sync,
Defaultable: Sync,
Iterable: Sync,
>(
&self,
addrs: &StaticStorageAddress<T, Yes, Defaultable, Iterable>,
at: Option<BlockHash>,
) -> Option<T::Target> {
info!(target: "aleph-client", "accessing storage at {}::{} at block {:?}", addrs.pallet_name(), addrs.entry_name(), at);
self.client
.storage()
self.storage()
.fetch(addrs, at)
.await
.expect("Should access storage")
}

pub async fn rpc_call<R: Decode>(
&self,
func_name: String,
params: RpcParams,
) -> anyhow::Result<R> {
async fn rpc_call<R: Decode>(&self, func_name: String, params: RpcParams) -> anyhow::Result<R> {
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.rpc().request(&func_name, params).await?;

Ok(R::decode(&mut bytes.as_ref())?)
}
}

impl SignedConnection {
pub async fn new(address: &str, signer: KeyPair) -> Self {
Self::from_connection(Connection::new(address).await, signer)
Self::from_connection(ConnectionExt::new(address).await, signer)
}

pub fn from_connection(connection: Connection, signer: KeyPair) -> Self {
Expand All @@ -144,7 +169,6 @@ impl SignedConnection {
}
let progress = self
.connection
.client
.tx()
.sign_and_submit_then_watch(&tx, &self.signer, params)
.await?;
Expand All @@ -163,7 +187,7 @@ impl SignedConnection {

impl RootConnection {
pub async fn new(address: &str, root: KeyPair) -> anyhow::Result<Self> {
RootConnection::try_from_connection(Connection::new(address).await, root).await
RootConnection::try_from_connection(ConnectionExt::new(address).await, root).await
}

pub async fn try_from_connection(
Expand All @@ -172,7 +196,7 @@ impl RootConnection {
) -> anyhow::Result<Self> {
let root_address = api::storage().sudo().key();

let root = match connection.client.storage().fetch(&root_address, None).await {
let root = match connection.storage().fetch(&root_address, None).await {
Ok(Some(account)) => account,
_ => return Err(anyhow!("Could not read sudo key from chain")),
};
Expand Down
2 changes: 1 addition & 1 deletion aleph-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub type AccountId = subxt::ext::sp_core::crypto::AccountId32;
pub type Client = OnlineClient<AlephConfig>;
pub type BlockHash = H256;

pub use connections::{Connection, RootConnection, SignedConnection, SudoCall};
pub use connections::{Connection, ConnectionExt, RootConnection, SignedConnection, SudoCall};

#[derive(Copy, Clone)]
pub enum TxStatus {
Expand Down
1 change: 1 addition & 0 deletions aleph-client/src/pallets/aleph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use crate::{
pallet_aleph::pallet::Call::set_emergency_finalizer, primitives::app::Public,
sp_core::ed25519::Public as EdPublic,
},
connections::ConnectionExt,
pallet_aleph::pallet::Call::schedule_finality_version_change,
AccountId, AlephKeyPair, BlockHash,
Call::Aleph,
Expand Down
2 changes: 1 addition & 1 deletion aleph-client/src/pallets/author.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub trait AuthorRpc {
#[async_trait::async_trait]
impl AuthorRpc for Connection {
async fn author_rotate_keys(&self) -> SessionKeys {
let bytes = self.client.rpc().rotate_keys().await.unwrap();
let bytes = self.rpc().rotate_keys().await.unwrap();

SessionKeys::decode(&mut bytes.0.as_slice()).unwrap()
}
Expand Down
1 change: 1 addition & 0 deletions aleph-client/src/pallets/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use subxt::{ext::sp_runtime::MultiAddress, tx::PolkadotExtrinsicParamsBuilder};

use crate::{
aleph_zero::{self, api, api::runtime_types::pallet_balances::BalanceLock},
connections::ConnectionExt,
pallet_balances::pallet::Call::transfer,
pallets::utility::UtilityApi,
AccountId, BlockHash,
Expand Down
4 changes: 2 additions & 2 deletions aleph-client/src/pallets/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use subxt::{
};

use crate::{
api, pallet_contracts::wasm::OwnerInfo, sp_weights::weight_v2::Weight, AccountId, BlockHash,
Connection, SignedConnection, TxStatus,
api, connections::ConnectionExt, pallet_contracts::wasm::OwnerInfo,
sp_weights::weight_v2::Weight, AccountId, BlockHash, Connection, SignedConnection, TxStatus,
};

#[derive(Encode)]
Expand Down
3 changes: 2 additions & 1 deletion aleph-client/src/pallets/elections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::{
pallet_elections::pallet::Call::set_ban_config,
primitives::{BanReason, CommitteeSeats, EraValidators},
},
connections::ConnectionExt,
pallet_elections::pallet::Call::{
ban_from_committee, change_validators, set_elections_openness,
},
Expand Down Expand Up @@ -167,7 +168,7 @@ impl ElectionsApi for Connection {
async fn get_session_period(&self) -> u32 {
let addrs = api::constants().elections().session_period();

self.client.constants().at(&addrs).unwrap()
self.constants().at(&addrs).unwrap()
}
}

Expand Down
2 changes: 1 addition & 1 deletion aleph-client/src/pallets/fee.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{api, BlockHash, Connection};
use crate::{api, connections::ConnectionExt, BlockHash, Connection};

pub type FeeMultiplier = u128;

Expand Down
4 changes: 2 additions & 2 deletions aleph-client/src/pallets/session.rs
Original file line number Diff line number Diff line change
@@ -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, connections::ConnectionExt, AccountId,
BlockHash, Connection, SignedConnection, TxStatus,
};

#[async_trait::async_trait]
Expand Down
9 changes: 3 additions & 6 deletions aleph-client/src/pallets/staking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use subxt::{

use crate::{
api,
connections::ConnectionExt,
pallet_staking::{
pallet::pallet::{
Call::{bond, force_new_era, nominate, set_staking_configs},
Expand Down Expand Up @@ -184,7 +185,7 @@ impl StakingApi for Connection {
async fn get_session_per_era(&self) -> u32 {
let addrs = api::constants().staking().sessions_per_era();

self.client.constants().at(&addrs).unwrap()
self.constants().at(&addrs).unwrap()
}
}

Expand Down Expand Up @@ -304,11 +305,7 @@ 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
.storage()
.fetch_keys(&key, 10, None, at)
.await
.unwrap()
self.storage().fetch_keys(&key, 10, None, at).await.unwrap()
}

async fn get_stakers_storage_keys_from_accounts(
Expand Down
1 change: 1 addition & 0 deletions aleph-client/src/pallets/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use subxt::ext::sp_runtime::Perbill as SPerbill;

use crate::{
api,
connections::ConnectionExt,
frame_system::pallet::Call::{fill_block, set_code},
sp_arithmetic::per_things::Perbill,
AccountId, BlockHash,
Expand Down
1 change: 1 addition & 0 deletions aleph-client/src/pallets/treasury.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use subxt::ext::sp_runtime::MultiAddress;

use crate::{
api,
connections::ConnectionExt,
pallet_treasury::pallet::Call::{approve_proposal, reject_proposal},
pallets::{elections::ElectionsApi, staking::StakingApi},
AccountId, BlockHash,
Expand Down
4 changes: 2 additions & 2 deletions aleph-client/src/pallets/vesting.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use subxt::ext::sp_runtime::MultiAddress;

use crate::{
api, pallet_vesting::vesting_info::VestingInfo, AccountId, BlockHash, Connection,
SignedConnection, TxStatus,
api, connections::ConnectionExt, pallet_vesting::vesting_info::VestingInfo, AccountId,
BlockHash, Connection, SignedConnection, TxStatus,
};

#[async_trait::async_trait]
Expand Down
19 changes: 4 additions & 15 deletions aleph-client/src/utility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,30 +31,19 @@ impl BlocksApi for Connection {

async fn get_block_hash(&self, block: BlockNumber) -> Option<BlockHash> {
info!(target: "aleph-client", "querying block hash for number #{}", block);
self.client
.rpc()
.block_hash(Some(block.into()))
.await
.unwrap()
self.rpc().block_hash(Some(block.into())).await.unwrap()
}

async fn get_best_block(&self) -> BlockNumber {
self.client
.rpc()
.header(None)
.await
.unwrap()
.unwrap()
.number
self.rpc().header(None).await.unwrap().unwrap().number
}

async fn get_finalized_block_hash(&self) -> BlockHash {
self.client.rpc().finalized_head().await.unwrap()
self.rpc().finalized_head().await.unwrap()
}

async fn get_block_number(&self, block: BlockHash) -> Option<BlockNumber> {
self.client
.rpc()
self.rpc()
.header(Some(block))
.await
.unwrap()
Expand Down
10 changes: 5 additions & 5 deletions aleph-client/src/waiting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ pub trait WaitingExt {
impl AlephWaiting for Connection {
async fn wait_for_block<P: Fn(u32) -> bool + Send>(&self, predicate: P, status: BlockStatus) {
let mut block_sub = match status {
BlockStatus::Best => self.client.blocks().subscribe_best().await.unwrap(),
BlockStatus::Finalized => self.client.blocks().subscribe_finalized().await.unwrap(),
BlockStatus::Best => self.blocks().subscribe_best().await.unwrap(),
BlockStatus::Finalized => self.blocks().subscribe_finalized().await.unwrap(),
};

while let Some(Ok(block)) = block_sub.next().await {
Expand All @@ -54,8 +54,8 @@ impl AlephWaiting for Connection {
status: BlockStatus,
) -> T {
let mut block_sub = match status {
BlockStatus::Best => self.client.blocks().subscribe_best().await.unwrap(),
BlockStatus::Finalized => self.client.blocks().subscribe_finalized().await.unwrap(),
BlockStatus::Best => self.blocks().subscribe_best().await.unwrap(),
BlockStatus::Finalized => self.blocks().subscribe_finalized().await.unwrap(),
};

info!(target: "aleph-client", "waiting for event {}.{}", T::PALLET, T::EVENT);
Expand All @@ -81,7 +81,7 @@ 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.constants().at(&addrs).unwrap();
let sessions_per_era = self.constants().at(&addrs).unwrap();
let first_session_in_era = era * sessions_per_era;

self.wait_for_session(first_session_in_era, status).await;
Expand Down
6 changes: 4 additions & 2 deletions bin/cliain/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ mod validators;
mod version_upgrade;
mod vesting;

use aleph_client::{keypair_from_string, Connection, RootConnection, SignedConnection};
use aleph_client::{
keypair_from_string, Connection, ConnectionExt, RootConnection, SignedConnection,
};
pub use commands::Command;
pub use contracts::{
call, instantiate, instantiate_with_code, owner_info, remove_code, upload_code,
Expand Down Expand Up @@ -45,7 +47,7 @@ impl ConnectionConfig {
}

pub async fn get_connection(&self) -> Connection {
Connection::new(&self.node_endpoint).await
ConnectionExt::new(&self.node_endpoint).await
}

pub async fn get_signed_connection(&self) -> SignedConnection {
Expand Down
4 changes: 2 additions & 2 deletions e2e-tests/src/transfer.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use aleph_client::{AccountId, Connection, KeyPair, Pair, SignedConnection};
use aleph_client::{AccountId, Connection, ConnectionExt, KeyPair, Pair, SignedConnection};

use crate::{accounts::get_validators_raw_keys, config::Config};

Expand All @@ -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).await, from, to)
(ConnectionExt::new(&config.node).await, from, to)
}

pub async fn setup_for_transfer(config: &Config) -> (SignedConnection, AccountId) {
Expand Down