Skip to content

Commit

Permalink
chore(gsdk): introduce trait AsOption to simplify interfaces (#4022)
Browse files Browse the repository at this point in the history
  • Loading branch information
clearloop authored Jun 23, 2024
1 parent 05e97f7 commit 3d06de0
Show file tree
Hide file tree
Showing 16 changed files with 85 additions and 38 deletions.
4 changes: 2 additions & 2 deletions gcli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ pub trait App: Parser + Sync {
async fn api(&self) -> anyhow::Result<GearApi> {
let endpoint = self.endpoint().clone();
let timeout = self.timeout();
Api::new_with_timeout(endpoint.as_deref(), Some(timeout))
Api::new_with_timeout(endpoint.as_deref(), timeout)
.await
.map(Into::into)
.map_err(Into::into)
Expand All @@ -123,7 +123,7 @@ pub trait App: Parser + Sync {
let timeout = self.timeout();
let passwd = self.passwd();

let api = Api::new_with_timeout(endpoint.as_deref(), Some(timeout)).await?;
let api = Api::new_with_timeout(endpoint.as_deref(), timeout).await?;
let pair = Keyring::load(gring::cmd::Command::store()?)?
.primary()?
.decrypt(passwd.clone().and_then(|p| hex::decode(p).ok()).as_deref())?;
Expand Down
8 changes: 2 additions & 6 deletions gcli/tests/cmd/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,7 @@ async fn test_command_claim_works() -> Result<()> {
let node = common::dev()?;

// Get balance of the testing address
let signer = Api::new(Some(&node.ws()))
.await?
.signer("//Alice//stash", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice//stash", None)?;
(
signer.api().get_balance(ADDRESS).await.unwrap_or(0),
signer
Expand All @@ -53,9 +51,7 @@ async fn test_command_claim_works() -> Result<()> {
let node = common::create_messager().await?;

// Check the mailbox of the testing account
let signer = Api::new(Some(&node.ws()))
.await?
.signer("//Alice//stash", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice//stash", None)?;
let mailbox = signer
.api()
.mailbox(Some(common::alice_account_id()), 10)
Expand Down
2 changes: 1 addition & 1 deletion gcli/tests/cmd/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn test_command_reply_works() -> Result<()> {
let node = common::create_messager().await?;

// Get balance of the testing address
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;
let mailbox = signer
.api()
.mailbox(Some(common::alice_account_id()), 10)
Expand Down
2 changes: 1 addition & 1 deletion gcli/tests/cmd/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async fn test_command_send_works() -> Result<()> {
let node = common::create_messager().await?;

// Get balance of the testing address
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;
let mailbox = signer
.api()
.mailbox(Some(common::alice_account_id()), 10)
Expand Down
2 changes: 1 addition & 1 deletion gcli/tests/cmd/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async fn test_command_transfer_works() -> Result<()> {
let node = common::dev()?;

// Get balance of the testing address
let signer = Api::new(Some(&node.ws())).await?.signer(SURI, None)?;
let signer = Api::new(node.ws()).await?.signer(SURI, None)?;
let before = signer.api().get_balance(ADDRESS).await.unwrap_or(0);

// Run command transfer
Expand Down
2 changes: 1 addition & 1 deletion gcli/tests/cmd/upload.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use gsdk::Api;
#[tokio::test]
async fn test_command_upload_works() -> Result<()> {
let node = common::dev()?;
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;
let code_id = CodeId::generate(demo_new_meta::WASM_BINARY);
assert!(
signer.api().code_storage(code_id).await.is_err(),
Expand Down
2 changes: 1 addition & 1 deletion gclient/src/api/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl GearApi {
pub async fn init_with(address: WSAddress, suri: impl AsRef<str>) -> Result<Self> {
let mut suri = suri.as_ref().splitn(2, ':');

Api::new(Some(&address.url()))
Api::new(address.url())
.await
.and_then(|api| {
Ok(Self(
Expand Down
11 changes: 7 additions & 4 deletions gsdk/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use crate::{
client::Rpc, config::GearConfig, metadata::Event, signer::Signer, Blocks, Events, Result,
TxInBlock,
client::Rpc, config::GearConfig, metadata::Event, signer::Signer, AsOption, Blocks, Events,
Result, TxInBlock,
};
use core::ops::{Deref, DerefMut};
use std::result::Result as StdResult;
Expand All @@ -37,7 +37,7 @@ pub struct Api {

impl Api {
/// Create new API client.
pub async fn new(url: Option<&str>) -> Result<Self> {
pub async fn new(url: impl AsOption<str>) -> Result<Self> {
Self::new_with_timeout(url, None).await
}

Expand All @@ -47,7 +47,10 @@ impl Api {
}

/// Create new API client with timeout.
pub async fn new_with_timeout(url: Option<&str>, timeout: Option<u64>) -> Result<Self> {
pub async fn new_with_timeout(
url: impl AsOption<str>,
timeout: impl AsOption<u64>,
) -> Result<Self> {
let rpc = Rpc::new(url, timeout).await?;

Ok(Self {
Expand Down
9 changes: 5 additions & 4 deletions gsdk/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use crate::{
config::GearConfig,
result::{Error, Result},
utils::AsOption,
};
use futures_util::{StreamExt, TryStreamExt};
use jsonrpsee::{
Expand Down Expand Up @@ -65,10 +66,10 @@ pub enum RpcClient {

impl RpcClient {
/// Create RPC client from url and timeout.
pub async fn new(url: Option<&str>, timeout: Option<u64>) -> Result<Self> {
pub async fn new(url: impl AsOption<str>, timeout: impl AsOption<u64>) -> Result<Self> {
let (url, timeout) = (
url.unwrap_or(DEFAULT_GEAR_ENDPOINT),
timeout.unwrap_or(DEFAULT_TIMEOUT),
url.as_option().unwrap_or(DEFAULT_GEAR_ENDPOINT),
*timeout.as_option().unwrap_or(&DEFAULT_TIMEOUT),
);

log::info!("Connecting to {url} ...");
Expand Down Expand Up @@ -167,7 +168,7 @@ pub struct Rpc {

impl Rpc {
/// Create RPC client from url and timeout.
pub async fn new(url: Option<&str>, timeout: Option<u64>) -> Result<Self> {
pub async fn new(url: impl AsOption<str>, timeout: impl AsOption<u64>) -> Result<Self> {
let rpc = SubxtRpcClient::new(RpcClient::new(url, timeout).await?);
let methods = LegacyRpcMethods::new(rpc.clone());
Ok(Self { rpc, methods })
Expand Down
1 change: 1 addition & 0 deletions gsdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub use crate::{
result::{Error, Result},
signer::PairSigner,
subscription::{Blocks, Events},
utils::AsOption,
};
pub use gear_core::gas::GasInfo;
pub use subxt::dynamic::Value;
Expand Down
41 changes: 41 additions & 0 deletions gsdk/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,44 @@ pub(crate) fn storage_address_bytes<Address: StorageAddress>(
addr.append_entry_bytes(metadata, &mut bytes)?;
Ok(bytes)
}

/// Interface for adapting optional values
pub trait AsOption<T: ?Sized> {
fn as_option(&self) -> Option<&T>;
}

impl AsOption<str> for &str {
fn as_option(&self) -> Option<&str> {
Some(self)
}
}

impl AsOption<str> for Option<&str> {
fn as_option(&self) -> Option<&str> {
self.as_deref()
}
}

impl AsOption<str> for &String {
fn as_option(&self) -> Option<&str> {
Some(self.as_ref())
}
}

impl AsOption<str> for String {
fn as_option(&self) -> Option<&str> {
Some(self)
}
}

impl AsOption<u64> for u64 {
fn as_option(&self) -> Option<&u64> {
Some(self)
}
}

impl AsOption<u64> for Option<u64> {
fn as_option(&self) -> Option<&u64> {
self.as_ref()
}
}
2 changes: 1 addition & 1 deletion gsdk/tests/backtrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ mod utils;
#[tokio::test]
async fn transfer_backtrace() -> Result<()> {
let node = dev_node();
let api = Api::new(Some(&node.ws())).await?;
let api = Api::new(node.ws()).await?;
let signer = Signer::new(api, "//Alice", None)?;
let alice: [u8; 32] = *alice_account_id().as_ref();

Expand Down
2 changes: 1 addition & 1 deletion gsdk/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use gsdk::Api;

#[tokio::test]
async fn timeout() {
let error = Api::new_with_timeout(None, Some(0)).await.err();
let error = Api::new_with_timeout(None, 0).await.err();
// NOTE:
//
// There are two kinds of timeout error provided by subxt:
Expand Down
22 changes: 11 additions & 11 deletions gsdk/tests/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ mod utils;
#[tokio::test]
async fn pallet_errors_formatting() -> Result<()> {
let node = dev_node();
let api = Api::new(Some(&node.ws())).await?;
let api = Api::new(node.ws()).await?;

let err = api
.calculate_upload_gas(
Expand Down Expand Up @@ -65,7 +65,7 @@ async fn pallet_errors_formatting() -> Result<()> {
#[tokio::test]
async fn test_calculate_upload_gas() -> Result<()> {
let node = dev_node();
let api = Api::new(Some(&node.ws())).await?;
let api = Api::new(node.ws()).await?;

let alice: [u8; 32] = *alice_account_id().as_ref();

Expand All @@ -87,7 +87,7 @@ async fn test_calculate_create_gas() -> Result<()> {
let node = dev_node();

// 1. upload code.
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;
signer
.calls
.upload_code(demo_messenger::WASM_BINARY.to_vec())
Expand Down Expand Up @@ -116,7 +116,7 @@ async fn test_calculate_handle_gas() -> Result<()> {
let pid = ProgramId::generate_from_user(CodeId::generate(demo_messenger::WASM_BINARY), &salt);

// 1. upload program.
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;

signer
.calls
Expand Down Expand Up @@ -160,7 +160,7 @@ async fn test_calculate_reply_gas() -> Result<()> {
let payload = demo_waiter::Command::SendUpTo(alice, 10);

// 1. upload program.
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;
signer
.calls
.upload_program(
Expand Down Expand Up @@ -242,7 +242,7 @@ async fn test_runtime_wasm_blob_version() -> Result<()> {
assert_ne!(git_commit_hash, "unknown");

let node = dev_node();
let api = Api::new(Some(&node.ws())).await?;
let api = Api::new(node.ws()).await?;
let mut finalized_blocks = api.subscribe_finalized_blocks().await?;

let wasm_blob_version_1 = api.runtime_wasm_blob_version(None).await?;
Expand All @@ -267,7 +267,7 @@ async fn test_runtime_wasm_blob_version() -> Result<()> {

#[tokio::test]
async fn test_runtime_wasm_blob_version_history() -> Result<()> {
let api = Api::new(Some("wss://archive-rpc.vara.network:443")).await?;
let api = Api::new("wss://archive-rpc.vara.network:443").await?;

{
let no_method_block_hash = sp_core::H256::from_str(
Expand Down Expand Up @@ -303,7 +303,7 @@ async fn test_original_code_storage() -> Result<()> {
let salt = vec![];
let pid = ProgramId::generate_from_user(CodeId::generate(demo_messenger::WASM_BINARY), &salt);

let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;

signer
.calls
Expand Down Expand Up @@ -359,7 +359,7 @@ async fn test_calculate_reply_for_handle() -> Result<()> {
let pid = ProgramId::generate_from_user(CodeId::generate(demo_new_meta::WASM_BINARY), &salt);

// 1. upload program.
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;

signer
.calls
Expand Down Expand Up @@ -418,7 +418,7 @@ async fn test_calculate_reply_for_handle_does_not_change_state() -> Result<()> {
let pid = ProgramId::generate_from_user(CodeId::generate(demo_vec::WASM_BINARY), &salt);

// 1. upload program.
let signer = Api::new(Some(&node.ws())).await?.signer("//Alice", None)?;
let signer = Api::new(node.ws()).await?.signer("//Alice", None)?;

signer
.calls
Expand Down Expand Up @@ -488,7 +488,7 @@ async fn query_program_counters(
use parity_scale_codec::Decode;
use subxt::dynamic::Value;

let signer = Api::new(Some(uri)).await?.signer("//Alice", None)?;
let signer = Api::new(uri).await?.signer("//Alice", None)?;

let client_block = signer.api().blocks();
let (block_hash, block_number) = match block_hash {
Expand Down
11 changes: 8 additions & 3 deletions utils/crates-io/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,9 @@ pub const SAFE_DEPENDENCIES: [&str; 15] = [

/// Required packages with local dependencies.
///
/// NOTE: DO NOT change the order of this array.
/// NOTE: Each package in this array could possibly depend
/// on the previous one, please be cautious about changing
/// the order.
pub const STACKED_DEPENDENCIES: [&str; 13] = [
"gcore",
"gmeta",
Expand All @@ -68,10 +70,13 @@ pub const STACKED_DEPENDENCIES: [&str; 13] = [

/// Packages need to be published.
///
/// NOTE: DO NOT change the order of this array.
pub const PACKAGES: [&str; 7] = [
/// NOTE: Each package in this array could possibly depend
/// on the previous one, please be cautious about changing
/// the order.
pub const PACKAGES: [&str; 8] = [
"gring",
"gear-wasm-builder",
"cargo-gbuild",
"gstd",
"gtest",
"gsdk",
Expand Down
2 changes: 1 addition & 1 deletion utils/node-loader/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn run(params: Params) -> Result<()> {
///
/// Broadcast new events to receivers.
async fn listen_events(tx: Sender<subxt::events::Events<GearConfig>>, node: String) -> Result<()> {
let api = gsdk::Api::new(Some(&node)).await?;
let api = gsdk::Api::new(node).await?;
let mut event_listener = api.subscribe_finalized_blocks().await?;

while let Some(events) = event_listener.next_events().await {
Expand Down

0 comments on commit 3d06de0

Please sign in to comment.