From 3d06de05f03e699d336bf04d1535bce4e82b3bee Mon Sep 17 00:00:00 2001 From: clearloop Date: Sun, 23 Jun 2024 20:16:47 +0800 Subject: [PATCH] chore(gsdk): introduce trait AsOption to simplify interfaces (#4022) --- gcli/src/app.rs | 4 ++-- gcli/tests/cmd/claim.rs | 8 ++----- gcli/tests/cmd/reply.rs | 2 +- gcli/tests/cmd/send.rs | 2 +- gcli/tests/cmd/transfer.rs | 2 +- gcli/tests/cmd/upload.rs | 2 +- gclient/src/api/mod.rs | 2 +- gsdk/src/api.rs | 11 ++++++---- gsdk/src/client.rs | 9 ++++---- gsdk/src/lib.rs | 1 + gsdk/src/utils.rs | 41 +++++++++++++++++++++++++++++++++++ gsdk/tests/backtrace.rs | 2 +- gsdk/tests/main.rs | 2 +- gsdk/tests/rpc.rs | 22 +++++++++---------- utils/crates-io/src/lib.rs | 11 +++++++--- utils/node-loader/src/main.rs | 2 +- 16 files changed, 85 insertions(+), 38 deletions(-) diff --git a/gcli/src/app.rs b/gcli/src/app.rs index 10820c49193..b425886ec26 100644 --- a/gcli/src/app.rs +++ b/gcli/src/app.rs @@ -111,7 +111,7 @@ pub trait App: Parser + Sync { async fn api(&self) -> anyhow::Result { 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) @@ -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())?; diff --git a/gcli/tests/cmd/claim.rs b/gcli/tests/cmd/claim.rs index 2a41d71f264..404f0a7411b 100644 --- a/gcli/tests/cmd/claim.rs +++ b/gcli/tests/cmd/claim.rs @@ -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 @@ -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) diff --git a/gcli/tests/cmd/reply.rs b/gcli/tests/cmd/reply.rs index 5610c5837d4..65ae0935024 100644 --- a/gcli/tests/cmd/reply.rs +++ b/gcli/tests/cmd/reply.rs @@ -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) diff --git a/gcli/tests/cmd/send.rs b/gcli/tests/cmd/send.rs index 815bdbd3da4..9ffff2ae260 100644 --- a/gcli/tests/cmd/send.rs +++ b/gcli/tests/cmd/send.rs @@ -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) diff --git a/gcli/tests/cmd/transfer.rs b/gcli/tests/cmd/transfer.rs index e03ac791289..f2d7ca1ef90 100644 --- a/gcli/tests/cmd/transfer.rs +++ b/gcli/tests/cmd/transfer.rs @@ -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 diff --git a/gcli/tests/cmd/upload.rs b/gcli/tests/cmd/upload.rs index b5a3d2e66ab..c4344d55d13 100644 --- a/gcli/tests/cmd/upload.rs +++ b/gcli/tests/cmd/upload.rs @@ -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(), diff --git a/gclient/src/api/mod.rs b/gclient/src/api/mod.rs index b6414c686fb..e66445247a5 100644 --- a/gclient/src/api/mod.rs +++ b/gclient/src/api/mod.rs @@ -52,7 +52,7 @@ impl GearApi { pub async fn init_with(address: WSAddress, suri: impl AsRef) -> Result { let mut suri = suri.as_ref().splitn(2, ':'); - Api::new(Some(&address.url())) + Api::new(address.url()) .await .and_then(|api| { Ok(Self( diff --git a/gsdk/src/api.rs b/gsdk/src/api.rs index b8d544ccd24..9d7c3c60ec6 100644 --- a/gsdk/src/api.rs +++ b/gsdk/src/api.rs @@ -17,8 +17,8 @@ // along with this program. If not, see . 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; @@ -37,7 +37,7 @@ pub struct Api { impl Api { /// Create new API client. - pub async fn new(url: Option<&str>) -> Result { + pub async fn new(url: impl AsOption) -> Result { Self::new_with_timeout(url, None).await } @@ -47,7 +47,10 @@ impl Api { } /// Create new API client with timeout. - pub async fn new_with_timeout(url: Option<&str>, timeout: Option) -> Result { + pub async fn new_with_timeout( + url: impl AsOption, + timeout: impl AsOption, + ) -> Result { let rpc = Rpc::new(url, timeout).await?; Ok(Self { diff --git a/gsdk/src/client.rs b/gsdk/src/client.rs index f31399c6e9f..d9748dc4f32 100644 --- a/gsdk/src/client.rs +++ b/gsdk/src/client.rs @@ -20,6 +20,7 @@ use crate::{ config::GearConfig, result::{Error, Result}, + utils::AsOption, }; use futures_util::{StreamExt, TryStreamExt}; use jsonrpsee::{ @@ -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) -> Result { + pub async fn new(url: impl AsOption, timeout: impl AsOption) -> Result { 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} ..."); @@ -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) -> Result { + pub async fn new(url: impl AsOption, timeout: impl AsOption) -> Result { let rpc = SubxtRpcClient::new(RpcClient::new(url, timeout).await?); let methods = LegacyRpcMethods::new(rpc.clone()); Ok(Self { rpc, methods }) diff --git a/gsdk/src/lib.rs b/gsdk/src/lib.rs index b8e32a68663..8c288559ebb 100644 --- a/gsdk/src/lib.rs +++ b/gsdk/src/lib.rs @@ -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; diff --git a/gsdk/src/utils.rs b/gsdk/src/utils.rs index 71cef3bcb76..bfcee5d84b3 100644 --- a/gsdk/src/utils.rs +++ b/gsdk/src/utils.rs @@ -107,3 +107,44 @@ pub(crate) fn storage_address_bytes( addr.append_entry_bytes(metadata, &mut bytes)?; Ok(bytes) } + +/// Interface for adapting optional values +pub trait AsOption { + fn as_option(&self) -> Option<&T>; +} + +impl AsOption for &str { + fn as_option(&self) -> Option<&str> { + Some(self) + } +} + +impl AsOption for Option<&str> { + fn as_option(&self) -> Option<&str> { + self.as_deref() + } +} + +impl AsOption for &String { + fn as_option(&self) -> Option<&str> { + Some(self.as_ref()) + } +} + +impl AsOption for String { + fn as_option(&self) -> Option<&str> { + Some(self) + } +} + +impl AsOption for u64 { + fn as_option(&self) -> Option<&u64> { + Some(self) + } +} + +impl AsOption for Option { + fn as_option(&self) -> Option<&u64> { + self.as_ref() + } +} diff --git a/gsdk/tests/backtrace.rs b/gsdk/tests/backtrace.rs index ed87f3a5efe..16bcfaae751 100644 --- a/gsdk/tests/backtrace.rs +++ b/gsdk/tests/backtrace.rs @@ -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(); diff --git a/gsdk/tests/main.rs b/gsdk/tests/main.rs index b97d56256d7..ca24dd7a05d 100644 --- a/gsdk/tests/main.rs +++ b/gsdk/tests/main.rs @@ -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: diff --git a/gsdk/tests/rpc.rs b/gsdk/tests/rpc.rs index 53e2990589b..711af261826 100644 --- a/gsdk/tests/rpc.rs +++ b/gsdk/tests/rpc.rs @@ -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( @@ -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(); @@ -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()) @@ -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 @@ -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( @@ -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?; @@ -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( @@ -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 @@ -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 @@ -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 @@ -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 { diff --git a/utils/crates-io/src/lib.rs b/utils/crates-io/src/lib.rs index 6c1ae231c22..75eecbccd67 100644 --- a/utils/crates-io/src/lib.rs +++ b/utils/crates-io/src/lib.rs @@ -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", @@ -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", diff --git a/utils/node-loader/src/main.rs b/utils/node-loader/src/main.rs index 3eac655e671..f63a6c075a9 100644 --- a/utils/node-loader/src/main.rs +++ b/utils/node-loader/src/main.rs @@ -37,7 +37,7 @@ async fn run(params: Params) -> Result<()> { /// /// Broadcast new events to receivers. async fn listen_events(tx: Sender>, 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 {