Skip to content

Commit

Permalink
refactor(gcli): switch resolved API to gclient (#3687)
Browse files Browse the repository at this point in the history
  • Loading branch information
clearloop authored Feb 18, 2024
1 parent f643b99 commit 0148abe
Show file tree
Hide file tree
Showing 18 changed files with 143 additions and 130 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 1 addition & 2 deletions examples/messenger/src/bin/demo_messenger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,11 @@ pub struct Messager {
impl App for Messager {
async fn exec(&self) -> anyhow::Result<()> {
let lookup = gcli::lookup!();
let signer = self.signer().await?;

let Command::Upload(upload) = &self.command;
upload
.clone_with_code_overridden(lookup.opt)
.exec(signer)
.exec(self)
.await
.map_err(Into::into)
}
Expand Down
1 change: 1 addition & 0 deletions gcli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ repository.workspace = true

[dependencies]
gsdk.workspace = true
gclient.workspace = true
anyhow.workspace = true
async-trait.workspace = true
base64.workspace = true
Expand Down
8 changes: 5 additions & 3 deletions gcli/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ use crate::keystore;
use clap::Parser;
use color_eyre::{eyre::eyre, Result};
use env_logger::{Builder, Env};
use gsdk::{ext::sp_core, signer::Signer, Api};
use gclient::{ext::sp_core, GearApi};
use gsdk::{signer::Signer, Api};

/// Command line gear program application abstraction.
///
Expand Down Expand Up @@ -90,7 +91,7 @@ pub trait App: Parser + Sync {
async fn exec(&self) -> anyhow::Result<()>;

/// Get signer.
async fn signer(&self) -> anyhow::Result<Signer> {
async fn signer(&self) -> anyhow::Result<GearApi> {
let endpoint = self.endpoint().clone();
let timeout = self.timeout();
let passwd = self.passwd();
Expand All @@ -102,7 +103,8 @@ pub trait App: Parser + Sync {
keystore::keyring(passwd.as_deref())?
};

Ok((api, pair).into())
let signer: Signer = (api, pair).into();
Ok(signer.into())
}

/// Run application.
Expand Down
9 changes: 3 additions & 6 deletions gcli/src/cmd/claim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Command `claim`
use crate::{result::Result, utils::Hex};
use crate::{result::Result, utils::Hex, App};
use clap::Parser;
use gsdk::signer::Signer;

/// Claim value from mailbox.
#[derive(Clone, Debug, Parser)]
Expand All @@ -29,11 +28,9 @@ pub struct Claim {
}

impl Claim {
pub async fn exec(&self, signer: Signer) -> Result<()> {
pub async fn exec(&self, app: &impl App) -> Result<()> {
let message_id = self.message_id.to_hash()?.into();

signer.calls.claim_value(message_id).await?;

app.signer().await?.claim_value(message_id).await?;
Ok(())
}
}
16 changes: 6 additions & 10 deletions gcli/src/cmd/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! command `create`
use crate::{result::Result, utils::Hex};
use crate::{result::Result, utils::Hex, App};
use clap::Parser;
use gsdk::signer::Signer;

/// Deploy program to gear node
#[derive(Clone, Debug, Parser)]
Expand All @@ -44,26 +43,23 @@ pub struct Create {

impl Create {
/// Exec command submit
pub async fn exec(&self, signer: Signer) -> Result<()> {
pub async fn exec(&self, app: &impl App) -> Result<()> {
let code_id = self.code_id.to_hash()?.into();
let payload = self.init_payload.to_vec()?;
let signer = app.signer().await?;

let gas = if self.gas_limit == 0 {
// estimate gas
let gas_limit = if self.gas_limit == 0 {
signer
.rpc
.calculate_create_gas(None, code_id, payload.clone(), self.value, false, None)
.calculate_create_gas(None, code_id, payload.clone(), self.value, false)
.await?
.min_limit
} else {
self.gas_limit
};

// estimate gas
let gas_limit = signer.api().cmp_gas_limit(gas)?;

// create program
signer
.calls
.create_program(code_id, self.salt.to_vec()?, payload, gas_limit, self.value)
.await?;

Expand Down
56 changes: 27 additions & 29 deletions gcli/src/cmd/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,17 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! command `info`
use crate::result::{Error, Result};
use crate::{result::Result, App};
use clap::Parser;
use gsdk::{
use gclient::{
ext::{
sp_core::{crypto::Ss58Codec, sr25519::Pair, Pair as PairT},
sp_runtime::AccountId32,
},
metadata::runtime_types::{
gear_common::storage::primitives::Interval, gear_core::message::user::UserStoredMessage,
},
signer::Signer,
metadata::runtime_types::gear_common::storage::primitives::Interval,
GearApi,
};
use gear_core::message::UserStoredMessage;
use std::fmt;

#[derive(Clone, Debug, Parser)]
Expand Down Expand Up @@ -56,40 +55,36 @@ pub struct Info {

impl Info {
/// execute command transfer
pub async fn exec(&self, signer: Signer) -> Result<()> {
let mut address = self.address.clone().unwrap_or_else(|| signer.address());
pub async fn exec(&self, app: &impl App) -> Result<()> {
let signer = app.signer().await?;
let mut address = self
.address
.clone()
.unwrap_or_else(|| signer.account_id().to_ss58check());
if address.starts_with("//") {
address = Pair::from_string(&address, None)
.expect("Parse development address failed")
.public()
.to_ss58check()
}

let acc = AccountId32::from_ss58check(&address)?;
match self.action {
Action::Balance => Self::balance(signer, &address).await,
Action::Mailbox { count } => Self::mailbox(signer, &address, count).await,
Action::Balance => Self::balance(signer, acc).await,
Action::Mailbox { count } => Self::mailbox(signer, acc, count).await,
}
}

/// Get balance of address
pub async fn balance(signer: Signer, address: &str) -> Result<()> {
let info = signer.api().info(address).await?;

println!("{info:#?}");

pub async fn balance(signer: GearApi, acc: AccountId32) -> Result<()> {
let info = signer.free_balance(acc).await?;
println!("Free balance: {info:#?}");
Ok(())
}

/// Get mailbox of address
pub async fn mailbox(signer: Signer, address: &str, count: u32) -> Result<()> {
let mails = signer
.api()
.mailbox(
Some(AccountId32::from_ss58check(address).map_err(|_| Error::InvalidPublic)?),
count,
)
.await?;

pub async fn mailbox(signer: GearApi, acc: AccountId32, count: u32) -> Result<()> {
let mails = signer.get_mailbox_account_messages(acc, count).await?;
for t in mails.into_iter() {
println!("{:#?}", Mail::from(t));
}
Expand All @@ -115,20 +110,23 @@ impl From<(UserStoredMessage, Interval<u32>)> for Mail {
impl fmt::Debug for Mail {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Mail")
.field("id", &["0x", &hex::encode(self.message.id.0)].concat())
.field(
"id",
&["0x", &hex::encode(self.message.id().into_bytes())].concat(),
)
.field(
"source",
&["0x", &hex::encode(self.message.source.0)].concat(),
&["0x", &hex::encode(self.message.source().into_bytes())].concat(),
)
.field(
"destination",
&["0x", &hex::encode(self.message.destination.0)].concat(),
&["0x", &hex::encode(self.message.destination().into_bytes())].concat(),
)
.field(
"payload",
&["0x", &hex::encode(&self.message.payload.0)].concat(),
&["0x", &hex::encode(self.message.payload_bytes())].concat(),
)
.field("value", &self.message.value)
.field("value", &self.message.value())
.field("interval", &self.interval)
.finish()
}
Expand Down
2 changes: 1 addition & 1 deletion gcli/src/cmd/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! command `key`
use crate::{keystore::key::Key as KeyT, result::Result};
use clap::Parser;
use gsdk::ext::{
use gclient::ext::{
sp_core::{ecdsa, ed25519, sr25519, Pair},
sp_runtime::traits::IdentifyAccount,
};
Expand Down
14 changes: 7 additions & 7 deletions gcli/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,13 @@ impl Command {
Command::New(new) => new.exec().await?,
Command::Program(program) => program.exec(app).await?,
Command::Update(update) => update.exec().await?,
Command::Claim(claim) => claim.exec(app.signer().await?).await?,
Command::Create(create) => create.exec(app.signer().await?).await?,
Command::Info(info) => info.exec(app.signer().await?).await?,
Command::Send(send) => send.exec(app.signer().await?).await?,
Command::Upload(upload) => upload.exec(app.signer().await?).await?,
Command::Transfer(transfer) => transfer.exec(app.signer().await?).await?,
Command::Reply(reply) => reply.exec(app.signer().await?).await?,
Command::Claim(claim) => claim.exec(app).await?,
Command::Create(create) => create.exec(app).await?,
Command::Info(info) => info.exec(app).await?,
Command::Send(send) => send.exec(app).await?,
Command::Upload(upload) => upload.exec(app).await?,
Command::Transfer(transfer) => transfer.exec(app).await?,
Command::Reply(reply) => reply.exec(app).await?,
}

Ok(())
Expand Down
29 changes: 19 additions & 10 deletions gcli/src/cmd/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
//! Command `program`.
use crate::{meta::Meta, result::Result, App};
use clap::Parser;
use gsdk::{ext::sp_core::H256, Api};
use gclient::{ext::sp_core::H256, GearApi};
use std::{fs, path::PathBuf};

/// Read program state, etc.
Expand Down Expand Up @@ -83,13 +83,13 @@ impl Program {
args,
at,
} => {
let api = app.signer().await?.api().clone();
let api = app.signer().await?;
if let (Some(wasm), Some(method)) = (wasm, method) {
// read state from wasm.
Self::wasm_state(api, *pid, wasm.to_vec(), method, args.clone(), *at).await?;
Self::wasm_state(&api, *pid, wasm.to_vec(), method, args.clone(), *at).await?;
} else {
// read full state
Self::full_state(api, *pid, *at).await?;
Self::full_state(&api, *pid, *at).await?;
}
}
Program::Meta {
Expand All @@ -111,23 +111,32 @@ impl Program {
}

async fn wasm_state(
api: Api,
api: &GearApi,
pid: H256,
wasm: Vec<u8>,
method: &str,
args: Option<Vec<u8>>,
at: Option<H256>,
) -> Result<()> {
let state = api
.read_state_using_wasm(pid, Default::default(), method, wasm, args, at)
.read_state_bytes_using_wasm_at(
pid.0.into(),
Default::default(),
method,
wasm,
args,
at,
)
.await?;
println!("{state}");
println!("0x{}", hex::encode(state));
Ok(())
}

async fn full_state(api: Api, pid: H256, at: Option<H256>) -> Result<()> {
let state = api.read_state(pid, Default::default(), at).await?;
println!("{state}");
async fn full_state(api: &GearApi, pid: H256, at: Option<H256>) -> Result<()> {
let state = api
.read_state_bytes_at(pid.0.into(), Default::default(), at)
.await?;
println!("0x{}", hex::encode(state));
Ok(())
}

Expand Down
24 changes: 19 additions & 5 deletions gcli/src/cmd/reply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Command `reply`
use crate::{result::Result, utils::Hex};
use crate::{result::Result, utils::Hex, App};
use clap::Parser;
use gsdk::signer::Signer;

/// Sends a reply message.
///
Expand Down Expand Up @@ -49,15 +48,30 @@ pub struct Reply {
}

impl Reply {
pub async fn exec(&self, signer: Signer) -> Result<()> {
pub async fn exec(&self, app: &impl App) -> Result<()> {
let signer = app.signer().await?;
let reply_to_id = self.reply_to_id.to_hash()?;

let gas_limit = if self.gas_limit == 0 {
signer
.calculate_reply_gas(
None,
reply_to_id.into(),
self.payload.to_vec()?,
self.value,
false,
)
.await?
.min_limit
} else {
self.gas_limit
};

signer
.calls
.send_reply(
reply_to_id.into(),
self.payload.to_vec()?,
self.gas_limit,
gas_limit,
self.value,
)
.await?;
Expand Down
Loading

0 comments on commit 0148abe

Please sign in to comment.