Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
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
2 changes: 1 addition & 1 deletion aleph-client/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion aleph-client/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"

Expand Down
131 changes: 88 additions & 43 deletions aleph-client/src/connections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,62 @@ 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;

const DEFAULT_RETRIES: u32 = 10;
const RETRY_WAIT_SECS: u64 = 1;

pub async fn create_connection(address: &str) -> Connection {
create_connection_with_retries(address, DEFAULT_RETRIES).await
}

async fn create_connection_with_retries(address: &str, mut retries: u32) -> Connection {
loop {
let client = Client::from_url(&address).await;
match (retries, client) {
(_, Ok(client)) => return client,
(0, Err(e)) => panic!("{:?}", e),
_ => {
sleep(Duration::from_secs(RETRY_WAIT_SECS));
retries -= 1;
}
}
}
}

pub trait AsConnection: Sync {
fn as_connection(&self) -> &Connection;
}

#[async_trait::async_trait]
pub trait ConnectionExt: AsConnection {
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 {
pub connection: Connection,
pub signer: KeyPair,
connection: Connection,
signer: KeyPair,
}

pub struct RootConnection {
pub connection: Connection,
pub root: KeyPair,
connection: Connection,
root: KeyPair,
}

#[async_trait::async_trait]
Expand Down Expand Up @@ -58,29 +101,27 @@ impl SudoCall for RootConnection {
}
}

impl Connection {
const DEFAULT_RETRIES: u32 = 10;
const RETRY_WAIT_SECS: u64 = 1;
impl AsConnection for Connection {
fn as_connection(&self) -> &Connection {
self
}
}

pub async fn new(address: String) -> Self {
Self::new_with_retries(address, Self::DEFAULT_RETRIES).await
impl AsConnection for SignedConnection {
fn as_connection(&self) -> &Connection {
&self.connection
}
}

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 RootConnection {
fn as_connection(&self) -> &Connection {
&self.connection
}
}

pub async fn get_storage_entry<T: DecodeWithMetadata, Defaultable, Iterable>(
#[async_trait::async_trait]
impl<C: AsConnection> ConnectionExt for C {
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,40 +131,48 @@ 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
self.as_connection()
.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
.as_connection()
.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 async fn new(address: &str, signer: KeyPair) -> Self {
Self::from_connection(create_connection(address).await, signer)
}

pub fn from_connection(connection: Connection, signer: KeyPair) -> Self {
Self { connection, signer }
}

pub fn account_id(&self) -> &subxt::ext::sp_runtime::AccountId32 {
self.signer.account_id()
}

pub async fn send_tx<Call: TxPayload>(
&self,
tx: Call,
Expand All @@ -144,7 +193,6 @@ impl SignedConnection {
}
let progress = self
.connection
.client
.tx()
.sign_and_submit_then_watch(&tx, &self.signer, params)
.await?;
Expand All @@ -162,17 +210,14 @@ impl SignedConnection {
}

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

pub async fn try_from_connection(
connection: Connection,
signer: KeyPair,
) -> anyhow::Result<Self> {
pub async fn try_from_connection(connection: Client, signer: KeyPair) -> 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
12 changes: 8 additions & 4 deletions aleph-client/src/contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ use serde_json::{from_reader, from_value};
use crate::{
pallets::contract::{ContractCallArgs, ContractRpc, ContractsUserApi},
sp_weights::weight_v2::Weight,
AccountId, Connection, SignedConnection, TxStatus,
AccountId, ConnectionExt, SignedConnection, TxStatus,
};

/// Represents a contract instantiated on the chain.
Expand Down Expand Up @@ -96,14 +96,18 @@ impl ContractInstance {
}

/// Reads the value of a read-only, 0-argument call via RPC.
pub async fn contract_read0<T: Decode>(&self, conn: &Connection, message: &str) -> Result<T> {
pub async fn contract_read0<T: Decode, C: ConnectionExt>(
&self,
conn: &C,
message: &str,
) -> Result<T> {
self.contract_read(conn, message, &[]).await
}

/// Reads the value of a read-only call via RPC.
pub async fn contract_read<T: Decode>(
pub async fn contract_read<T: Decode, C: ConnectionExt>(
&self,
conn: &Connection,
conn: &C,
message: &str,
args: &[&str],
) -> Result<T> {
Expand Down
5 changes: 4 additions & 1 deletion aleph-client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ 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::{
create_connection, AsConnection, Connection, ConnectionExt, RootConnection, SignedConnection,
SudoCall,
};

#[derive(Copy, Clone)]
pub enum TxStatus {
Expand Down
4 changes: 2 additions & 2 deletions aleph-client/src/pallets/aleph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::{
pallet_aleph::pallet::Call::schedule_finality_version_change,
AccountId, AlephKeyPair, BlockHash,
Call::Aleph,
Connection, Pair, RootConnection, SudoCall, TxStatus,
ConnectionExt, Pair, RootConnection, SudoCall, TxStatus,
};

#[async_trait::async_trait]
Expand Down Expand Up @@ -68,7 +68,7 @@ impl AlephSudoApi for RootConnection {
}

#[async_trait::async_trait]
impl AlephRpc for Connection {
impl<C: ConnectionExt> AlephRpc for C {
async fn emergency_finalize(
&self,
number: BlockNumber,
Expand Down
7 changes: 3 additions & 4 deletions aleph-client/src/pallets/author.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
use codec::Decode;

use crate::{aleph_runtime::SessionKeys, Connection};
use crate::{aleph_runtime::SessionKeys, ConnectionExt};

#[async_trait::async_trait]
pub trait AuthorRpc {
async fn author_rotate_keys(&self) -> anyhow::Result<SessionKeys>;
}

#[async_trait::async_trait]
impl AuthorRpc for Connection {
impl<C: ConnectionExt> AuthorRpc for C {
async fn author_rotate_keys(&self) -> anyhow::Result<SessionKeys> {
let bytes = self.client.rpc().rotate_keys().await?;

let bytes = self.as_connection().rpc().rotate_keys().await?;
SessionKeys::decode(&mut bytes.0.as_slice()).map_err(|e| e.into())
}
}
4 changes: 2 additions & 2 deletions aleph-client/src/pallets/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
pallets::utility::UtilityApi,
AccountId, BlockHash,
Call::Balances,
Connection, SignedConnection, TxStatus,
ConnectionExt, SignedConnection, TxStatus,
};

#[async_trait::async_trait]
Expand Down Expand Up @@ -53,7 +53,7 @@ pub trait BalanceUserBatchExtApi {
}

#[async_trait::async_trait]
impl BalanceApi for Connection {
impl<C: ConnectionExt> BalanceApi for C {
async fn locks_for_account(
&self,
account: AccountId,
Expand Down
6 changes: 3 additions & 3 deletions aleph-client/src/pallets/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use subxt::{

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

#[derive(Encode)]
Expand Down Expand Up @@ -82,7 +82,7 @@ pub trait ContractRpc {
}

#[async_trait::async_trait]
impl ContractsApi for Connection {
impl<C: ConnectionExt> ContractsApi for C {
async fn get_owner_info(
&self,
code_hash: BlockHash,
Expand Down Expand Up @@ -182,7 +182,7 @@ impl ContractsUserApi for SignedConnection {
}

#[async_trait::async_trait]
impl ContractRpc for Connection {
impl<C: ConnectionExt> ContractRpc for C {
async fn call_and_get<T: Decode>(&self, args: ContractCallArgs) -> anyhow::Result<T> {
let params = rpc_params!["ContractsApi_call", Bytes(args.encode())];

Expand Down
10 changes: 6 additions & 4 deletions aleph-client/src/pallets/elections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::{
primitives::{BanConfig, BanInfo, ElectionOpenness},
AccountId, BlockHash,
Call::Elections,
Connection, RootConnection, SudoCall, TxStatus,
ConnectionExt, RootConnection, SudoCall, TxStatus,
};

#[async_trait::async_trait]
Expand Down Expand Up @@ -78,7 +78,7 @@ pub trait ElectionsSudoApi {
}

#[async_trait::async_trait]
impl ElectionsApi for Connection {
impl<C: ConnectionExt> ElectionsApi for C {
async fn get_ban_config(&self, at: Option<BlockHash>) -> BanConfig {
let addrs = api::storage().elections().ban_config();

Expand Down Expand Up @@ -166,8 +166,10 @@ impl ElectionsApi for Connection {

async fn get_session_period(&self) -> anyhow::Result<u32> {
let addrs = api::constants().elections().session_period();

self.client.constants().at(&addrs).map_err(|e| e.into())
self.as_connection()
.constants()
.at(&addrs)
.map_err(|e| e.into())
}
}

Expand Down
4 changes: 2 additions & 2 deletions 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, BlockHash, ConnectionExt};

pub type FeeMultiplier = u128;

Expand All @@ -8,7 +8,7 @@ pub trait TransactionPaymentApi {
}

#[async_trait::async_trait]
impl TransactionPaymentApi for Connection {
impl<C: ConnectionExt> TransactionPaymentApi for C {
async fn get_next_fee_multiplier(&self, at: Option<BlockHash>) -> FeeMultiplier {
let addrs = api::storage().transaction_payment().next_fee_multiplier();

Expand Down
Loading