Skip to content

Commit

Permalink
Remove some unused imports
Browse files Browse the repository at this point in the history
  • Loading branch information
mehcode committed May 11, 2022
1 parent d2ae0d4 commit 58438fb
Show file tree
Hide file tree
Showing 15 changed files with 88 additions and 70 deletions.
2 changes: 1 addition & 1 deletion sdk/rust/examples/transfer_hbar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async fn main() -> anyhow::Result<()> {

TransferTransaction::new()
.hbar_transfer(sender_id, -amount)
.hbar_transfer(receiver_id, amount)
.hbar_transfer(receiver_id, 2)
.execute(&client)
.await?;

Expand Down
22 changes: 13 additions & 9 deletions sdk/rust/src/account/account_balance_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@ pub type AccountBalanceQuery = Query<AccountBalanceQueryData>;

#[derive(Default, Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct AccountBalanceQueryData {
account_id: Option<AccountIdOrAlias>,
contract_id: Option<ContractIdOrEvmAddress>,
source: Option<AccountBalanceSource>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
enum AccountBalanceSource {
Account(AccountIdOrAlias),
Contract(ContractIdOrEvmAddress),
}

impl AccountBalanceQuery {
Expand All @@ -27,7 +32,7 @@ impl AccountBalanceQuery {
/// This is mutually exclusive with [`contract_id`](#method.contract_id).
///
pub fn account_id(&mut self, id: impl Into<AccountIdOrAlias>) -> &mut Self {
self.data.account_id = Some(id.into());
self.data.source = Some(AccountBalanceSource::Account(id.into()));
self
}

Expand All @@ -36,18 +41,17 @@ impl AccountBalanceQuery {
/// This is mutually exclusive with [`account_id`](#method.account_id).
///
pub fn contract_id(&mut self, id: ContractIdOrEvmAddress) -> &mut Self {
self.data.contract_id = Some(id.into());
self.data.source = Some(AccountBalanceSource::Contract(id.into()));
self
}
}

impl ToQueryProtobuf for AccountBalanceQueryData {
fn to_query_protobuf(&self, header: services::QueryHeader) -> services::Query {
let source = match (&self.account_id, &self.contract_id) {
(Some(id), _) => Some(BalanceSource::AccountId(id.to_protobuf())),
(_, Some(id)) => todo!(), // Some(BalanceSource::ContractId(id.to_protobuf())),
_ => None,
};
let source = self.source.as_ref().map(|source| match source {
AccountBalanceSource::Account(id) => BalanceSource::AccountId(id.to_protobuf()),
AccountBalanceSource::Contract(id) => BalanceSource::ContractId(id.to_protobuf()),
});

services::Query {
query: Some(services::query::Query::CryptogetAccountBalance(
Expand Down
9 changes: 3 additions & 6 deletions sdk/rust/src/account/account_id.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use std::fmt::{self, Debug};
use std::fmt::{Display, Formatter};
use std::fmt::{self, Debug, Display, Formatter};
use std::str::FromStr;

use hedera_proto::services;
Expand Down Expand Up @@ -70,17 +69,15 @@ impl FromStr for AccountId {
pub struct AccountAlias {
pub shard: u64,
pub realm: u64,

// TODO: Use hedera::PublicKey instead of Vec<u8>
pub alias: Vec<u8>,
pub alias: PublicKey,
}

impl ToProtobuf for AccountAlias {
type Protobuf = services::AccountId;

fn to_protobuf(&self) -> Self::Protobuf {
services::AccountId {
account: Some(services::account_id::Account::Alias(self.alias.clone())),
account: Some(services::account_id::Account::Alias(self.alias.as_bytes_raw().to_vec())),
realm_num: self.realm as i64,
shard_num: self.shard as i64,
}
Expand Down
2 changes: 1 addition & 1 deletion sdk/rust/src/client/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::atomic::{AtomicU64, AtomicUsize};
use std::sync::atomic::AtomicU64;
use std::sync::Arc;

use parking_lot::RwLock;
Expand Down
6 changes: 1 addition & 5 deletions sdk/rust/src/client/network.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::atomic::{AtomicI64, Ordering};
use std::time::Duration;

use hedera_proto::services::crypto_service_client::CryptoServiceClient;
use parking_lot::RwLock;
use rand::seq::index::IndexVec;
use rand::seq::IteratorRandom;
use rand::thread_rng;
use time::OffsetDateTime;
use tonic::transport::{Channel, Endpoint};

Expand Down
39 changes: 39 additions & 0 deletions sdk/rust/src/contract/contract_id.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
use hedera_proto::services;

use crate::ToProtobuf;

/// The unique identifier for a smart contract on Hedera.
#[derive(Debug, serde::Serialize, serde::Deserialize, Hash, PartialEq, Eq, Clone, Copy)]
#[repr(C)]
Expand All @@ -23,3 +27,38 @@ pub enum ContractIdOrEvmAddress {
ContractId(ContractId),
ContractEvmAddress(ContractEvmAddress),
}

impl ToProtobuf for ContractId {
type Protobuf = services::ContractId;

fn to_protobuf(&self) -> Self::Protobuf {
services::ContractId {
contract: Some(services::contract_id::Contract::ContractNum(self.num as i64)),
realm_num: self.realm as i64,
shard_num: self.shard as i64,
}
}
}

impl ToProtobuf for ContractEvmAddress {
type Protobuf = services::ContractId;

fn to_protobuf(&self) -> Self::Protobuf {
services::ContractId {
contract: Some(services::contract_id::Contract::EvmAddress(self.address.to_vec())),
realm_num: self.realm as i64,
shard_num: self.shard as i64,
}
}
}

impl ToProtobuf for ContractIdOrEvmAddress {
type Protobuf = services::ContractId;

fn to_protobuf(&self) -> Self::Protobuf {
match self {
Self::ContractId(id) => id.to_protobuf(),
Self::ContractEvmAddress(address) => address.to_protobuf(),
}
}
}
13 changes: 8 additions & 5 deletions sdk/rust/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::result::Result as StdResult;

use hedera_proto::services::ResponseCodeEnum;

use crate::AccountId;
use crate::{AccountId, TransactionId};

pub type Result<T> = StdResult<T, Error>;

Expand All @@ -23,8 +23,8 @@ pub enum Error {
/// Signals that a query or transaction has failed the pre-check.
// FIXME: Use hedera::Status (once available)
// TODO: Add transaction_id: Option<TransactionId>
#[error("transaction `_` failed pre-check with status `{status:?}`")]
PreCheckStatus { status: ResponseCodeEnum },
#[error("transaction `{}` failed pre-check with status `{status:?}`", .transaction_id.as_ref().map(|id| id.to_string()).as_deref().unwrap_or("_"))]
PreCheckStatus { status: ResponseCodeEnum, transaction_id: Option<TransactionId> },

#[error("failed to parse a key: {0}")]
KeyParse(BoxStdError),
Expand Down Expand Up @@ -58,7 +58,10 @@ impl Error {
Self::Signature(error.into())
}

pub(crate) fn pre_check(status: ResponseCodeEnum) -> Self {
Self::PreCheckStatus { status }
pub(crate) fn pre_check(
status: ResponseCodeEnum,
transaction_id: Option<TransactionId>,
) -> Self {
Self::PreCheckStatus { status, transaction_id }
}
}
12 changes: 3 additions & 9 deletions sdk/rust/src/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use backoff::backoff::Backoff;
use backoff::ExponentialBackoff;
use hedera_proto::services::ResponseCodeEnum;
use prost::Message;
use rand::seq::SliceRandom;
use rand::thread_rng;
use tokio::time::sleep;
use tonic::transport::Channel;
Expand Down Expand Up @@ -71,7 +70,6 @@ where

let mut backoff = ExponentialBackoff::default();
let mut last_error: Option<Error> = None;
let mut last_request: Option<(AccountId, E::Context)> = None;
let max_attempts = 10; // FIXME: from client

// TODO: cache requests to avoid signing a new request for every node in a delayed back-off
Expand Down Expand Up @@ -122,8 +120,6 @@ where
let (request, context) =
executable.make_request(client, &transaction_id, node_account_id).await?;

last_request = Some((node_account_id, context));

let response = match E::execute(channel, request).await {
Ok(response) => response.into_inner(),
Err(status) => {
Expand Down Expand Up @@ -153,8 +149,6 @@ where
// TODO: another function in the Execute trait to see if we need to
// retry yet again

let (node_account_id, context) = last_request.unwrap();

return E::make_response(
response,
context,
Expand All @@ -166,21 +160,21 @@ where
ResponseCodeEnum::Busy | ResponseCodeEnum::PlatformNotActive => {
// NOTE: this is a "busy" node
// try the next node in our allowed list, immediately
last_error = Some(Error::pre_check(status));
last_error = Some(Error::pre_check(status, transaction_id));
continue;
}

ResponseCodeEnum::TransactionExpired if explicit_transaction_id.is_none() => {
// the transaction that was generated has since expired
// re-generate the transaction ID and try again, immediately
last_error = Some(Error::pre_check(status, transaction_id));
transaction_id = client.generate_transaction_id();
last_error = Some(Error::pre_check(status));
continue;
}

_ => {
// any other pre-check is an error that the user needs to fix, fail immediately
return Err(Error::pre_check(status));
return Err(Error::pre_check(status, transaction_id));
}
},

Expand Down
3 changes: 1 addition & 2 deletions sdk/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ mod transaction_response;
mod transfer_transaction;

pub use account::{
AccountAlias, AccountBalance, AccountBalanceQuery, AccountId, AccountIdOrAlias, AccountInfo,
AccountInfoQuery,
AccountAlias, AccountBalance, AccountBalanceQuery, AccountId, AccountIdOrAlias, AccountInfo, AccountInfoQuery
};
pub use client::Client;
pub use contract::{ContractEvmAddress, ContractId, ContractIdOrEvmAddress};
Expand Down
2 changes: 0 additions & 2 deletions sdk/rust/src/protobuf/get.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::any::type_name;

/// Get an optional field from a protobuf object, returning an error if the field does not exist.
macro_rules! pb_getf {
($expr:expr, $field:ident) => {{
Expand Down
12 changes: 3 additions & 9 deletions sdk/rust/src/query/cost.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@ use async_trait::async_trait;
use hedera_proto::services;
use tonic::transport::Channel;

use crate::AccountId;
use crate::Client;
use crate::Query;

use crate::execute::execute;
use crate::execute::Execute;
use crate::execute::{execute, Execute};
use crate::query::execute::response_header;
use crate::query::QueryExecute;
use crate::query::ToQueryProtobuf;
use crate::TransactionId;
use crate::query::{QueryExecute, ToQueryProtobuf};
use crate::{AccountId, Client, Query, TransactionId};

pub(super) struct QueryCost<'a, D>(&'a Query<D>)
where
Expand Down
8 changes: 3 additions & 5 deletions sdk/rust/src/query/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@ use async_trait::async_trait;
use hedera_proto::services;
use tonic::transport::Channel;

use crate::{
execute::Execute, AccountId, Client, Error, FromProtobuf, Query, ToProtobuf, TransactionId,
};

use super::ToQueryProtobuf;
use crate::execute::Execute;
use crate::query::ToQueryProtobuf;
use crate::{AccountId, Client, Error, FromProtobuf, Query, TransactionId};

/// Describes a specific query that can be executed on the Hedera network.
#[async_trait]
Expand Down
9 changes: 4 additions & 5 deletions sdk/rust/src/query/payment_transaction.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
use async_trait::async_trait;
use hedera_proto::services::{self, crypto_service_client::CryptoServiceClient};
use hedera_proto::services::crypto_service_client::CryptoServiceClient;
use hedera_proto::services::{self};
use tonic::transport::Channel;

use crate::{
transaction::{ToTransactionDataProtobuf, TransactionExecute},
AccountId, ToProtobuf, Transaction, TransactionId,
};
use crate::transaction::{ToTransactionDataProtobuf, TransactionExecute};
use crate::{AccountId, ToProtobuf, Transaction, TransactionId};

pub(super) type PaymentTransaction = Transaction<PaymentTransactionData>;

Expand Down
16 changes: 7 additions & 9 deletions sdk/rust/src/transaction/execute.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
use std::sync::{
atomic::{AtomicU64, Ordering},
Arc,
};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use async_trait::async_trait;
use hedera_proto::services;
use prost::Message;
use tonic::{transport::Channel, Response, Status};
use tonic::transport::Channel;
use tonic::{Response, Status};

use crate::execute::Execute;
use crate::transaction::protobuf::ToTransactionDataProtobuf;
use crate::{
execute::Execute, AccountId, Client, Error, ToProtobuf, Transaction, TransactionHash,
TransactionId, TransactionResponse,
AccountId, Client, Error, ToProtobuf, Transaction, TransactionHash, TransactionId, TransactionResponse
};

use super::protobuf::ToTransactionDataProtobuf;

#[async_trait]
pub trait TransactionExecute {
fn default_max_transaction_fee() -> u64 {
Expand Down
3 changes: 1 addition & 2 deletions sdk/rust/src/transaction/mod.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use hedera_proto::services;
use time::Duration;

use crate::execute::execute;
use crate::{AccountId, Client, Signer, ToProtobuf, TransactionId, TransactionResponse};
use crate::{AccountId, Client, Signer, TransactionId, TransactionResponse};

mod execute;
mod protobuf;
Expand Down

0 comments on commit 58438fb

Please sign in to comment.