Skip to content

Commit

Permalink
Problem: there is a lot of clippy errors in rust (#183)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomas-nguy authored Jan 11, 2023
1 parent 155515c commit a3f05a4
Show file tree
Hide file tree
Showing 37 changed files with 214 additions and 235 deletions.
3 changes: 1 addition & 2 deletions orchestrator/cosmos_gravity/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,7 @@ pub async fn ethereum_vote_height_messages<CS: CosmosSigner>(
};
let msg = Msg::new("/gravity.v1.MsgEthereumHeightVote", msg);

let mut msgs = Vec::new();
msgs.push(msg);
let msgs = vec![msg];

msgs
}
Expand Down
6 changes: 3 additions & 3 deletions orchestrator/cosmos_gravity/src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ impl FromStr for PrivateKey {
}
}

impl Into<InnerPrivateKey> for PrivateKey {
fn into(self) -> InnerPrivateKey {
self.0
impl From<PrivateKey> for InnerPrivateKey {
fn from(val: PrivateKey) -> Self {
val.0
}
}

Expand Down
17 changes: 11 additions & 6 deletions orchestrator/cosmos_gravity/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,15 +102,20 @@ pub async fn get_latest_batch(
client: &mut GravityQueryClient<Channel>,
contract: EthAddress,
) -> Result<TransactionBatch, GravityError> {
debug!("ask latest batch for contract {:?}", format_eth_address(contract));
debug!(
"ask latest batch for contract {:?}",
format_eth_address(contract)
);
let request = client
.last_batch_tx(LastBatchTxRequest { token_contract: format_eth_address(contract)})
.last_batch_tx(LastBatchTxRequest {
token_contract: format_eth_address(contract),
})
.await?;
return match request.into_inner().batch {
match request.into_inner().batch {
Some(b) => TransactionBatch::from_proto(b),
None => {
Err(GravityError::CosmosGrpcError(CosmosGrpcError::BadResponse(String::from("no batch found"))))
},
None => Err(GravityError::CosmosGrpcError(CosmosGrpcError::BadResponse(
String::from("no batch found"),
))),
}
}

Expand Down
13 changes: 10 additions & 3 deletions orchestrator/cosmos_gravity/src/send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub const TIMEOUT: Duration = Duration::from_secs(60);

/// Send a transaction updating the eth address for the sending
/// Cosmos address. The sending Cosmos address should be a validator
#[allow(clippy::too_many_arguments)]
pub async fn update_gravity_delegate_addresses<S: Signer + 'static, CS: CosmosSigner>(
contact: &Contact,
delegate_eth_address: EthAddress,
Expand Down Expand Up @@ -86,6 +87,7 @@ pub async fn update_gravity_delegate_addresses<S: Signer + 'static, CS: CosmosSi

/// Sends tokens from Cosmos to Ethereum. These tokens will not be sent immediately instead
/// they will require some time to be included in a batch
#[allow(clippy::too_many_arguments)]
pub async fn send_to_eth<CS: CosmosSigner>(
cosmos_key: CS,
cosmos_granter: Option<String>,
Expand Down Expand Up @@ -186,11 +188,15 @@ pub async fn send_messages<CS: CosmosSigner>(

// multiply the estimated gas by the configured gas adjustment
let estimated_gas_limit: f64 = (gas.gas_used as f64) * gas_adjustment;
args.fee.gas_limit = cmp::max(estimated_gas_limit as u64, gas_limit * messages.len() as u64);
args.fee.gas_limit = cmp::max(
estimated_gas_limit as u64,
gas_limit * messages.len() as u64,
);

// compute the fee as fee=ceil(gas_limit * gas_price)
let fee_amount = (args.fee.gas_limit as u128).checked_mul(gas_price.0 as u128)
.ok_or_else( || GravityError::OverflowError("fee amount".to_string()))?;
let fee_amount = (args.fee.gas_limit as u128)
.checked_mul(gas_price.0 as u128)
.ok_or_else(|| GravityError::OverflowError("fee amount".to_string()))?;
let fee_amount = Coin {
denom: gas_price.1,
amount: fee_amount.into(),
Expand All @@ -208,6 +214,7 @@ pub async fn send_messages<CS: CosmosSigner>(
Ok(contact.wait_for_tx(response, TIMEOUT).await?)
}

#[allow(clippy::too_many_arguments)]
pub async fn send_main_loop<CS: CosmosSigner>(
contact: &Contact,
cosmos_key: CS,
Expand Down
6 changes: 2 additions & 4 deletions orchestrator/ethereum_gravity/src/deploy_erc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ pub async fn deploy_erc20<S: Signer + 'static>(
let gas_as_f64 = downcast_to_f64(gas);
if gas_as_f64.is_none() {
return Err(GravityError::GravityContractError(format!(
"Gas estimate too large to downcast to f64: {}",
gas
"Gas estimate too large to downcast to f64: {gas}"
)));
}
let gas = (gas_as_f64.unwrap() * gas_multiplier) as u128;
Expand All @@ -54,8 +53,7 @@ pub async fn deploy_erc20<S: Signer + 'static>(
// additionally we are mirroring only waiting for 1 confirmation by leaving that as default
let pending_tx = pending_tx.interval(Duration::from_secs(1));
let potential_error = GravityError::GravityContractError(format!(
"Did not receive transaction receipt when deploying ERC-20 {}: {}",
erc20_symbol,
"Did not receive transaction receipt when deploying ERC-20 {erc20_symbol}: {}",
format_eth_hash(tx_hash)
));

Expand Down
3 changes: 1 addition & 2 deletions orchestrator/ethereum_gravity/src/erc20_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ pub async fn approve_erc20_transfers<S: Signer + 'static>(
// additionally we are mirroring only waiting for 1 confirmation by leaving that as default
let pending_tx = pending_tx.interval(Duration::from_secs(1));
let potential_error = GravityError::GravityContractError(format!(
"Did not receive transaction receipt when approving ERC-20 {}: {}",
erc20, tx_hash
"Did not receive transaction receipt when approving ERC-20 {erc20}: {tx_hash}"
));

if let Some(timeout) = timeout_option {
Expand Down
51 changes: 18 additions & 33 deletions orchestrator/ethereum_gravity/src/logic_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ pub fn build_send_logic_call_contract_call<S: Signer + 'static>(
Ok(contract_call)
}

#[derive(Clone)]
#[derive(Clone, Default)]
pub struct LogicCallSkips {
skip_map: HashMap<Vec<u8>, HashMap<u64, LogicCallSkipState>>,
}
Expand All @@ -218,30 +218,19 @@ pub struct LogicCallSkipState {
}

impl LogicCallSkips {
pub fn new() -> Self {
LogicCallSkips {
skip_map: HashMap::new(),
}
}

pub fn skips_left(&self, call: &LogicCall) -> u32 {
let id_skips = self.skip_map.get(&call.invalidation_id);
if id_skips.is_some() {
let skip_state = id_skips.unwrap().get(&call.invalidation_nonce);
if skip_state.is_some() {
return skip_state.unwrap().skips_left;
if let Some(id_skips) = self.skip_map.get(&call.invalidation_id) {
if let Some(skip_state) = id_skips.get(&call.invalidation_nonce) {
return skip_state.skips_left;
}
}

0
}

pub fn permanently_skipped(&self, call: &LogicCall) -> bool {
let id_skips = self.skip_map.get(&call.invalidation_id);
if id_skips.is_some() {
let skip_state = id_skips.unwrap().get(&call.invalidation_nonce);
if skip_state.is_some() {
return skip_state.unwrap().permanently_skipped;
if let Some(id_skips) = self.skip_map.get(&call.invalidation_id) {
if let Some(skip_state) = id_skips.get(&call.invalidation_nonce) {
return skip_state.permanently_skipped;
}
}

Expand All @@ -264,20 +253,8 @@ impl LogicCallSkips {
permanently_skipped: permanently_skip,
};

let id_skips = self.skip_map.get_mut(&call.invalidation_id);
if id_skips.is_none() {
// first time we've seen this invalidation id, start at 2 skips
let new_id_skips = HashMap::from([(call.invalidation_nonce, new_skip_state)]);
self.skip_map
.insert(call.invalidation_id.clone(), new_id_skips);
} else {
let id_skips = id_skips.unwrap();
let skip_state = id_skips.get_mut(&call.invalidation_nonce);
if skip_state.is_none() {
// first time we've seen this invalidation id and nonce combo, start at 2 skips
id_skips.insert(call.invalidation_nonce.clone(), new_skip_state);
} else {
let mut skip_state = skip_state.unwrap();
if let Some(id_skips) = self.skip_map.get_mut(&call.invalidation_id) {
if let Some(skip_state) = id_skips.get_mut(&call.invalidation_nonce) {
if !skip_state.permanently_skipped {
if skip_state.skips_left == 0 {
// exponential backoff: double the number of skips and reset the skip counter
Expand All @@ -288,7 +265,15 @@ impl LogicCallSkips {
skip_state.skips_left -= 1;
}
}
} else {
// first time we've seen this invalidation id and nonce combo, start at 2 skips
id_skips.insert(call.invalidation_nonce, new_skip_state);
}
} else {
// first time we've seen this invalidation id, start at 2 skips
let new_id_skips = HashMap::from([(call.invalidation_nonce, new_skip_state)]);
self.skip_map
.insert(call.invalidation_id.clone(), new_id_skips);
}
}

Expand Down Expand Up @@ -352,7 +337,7 @@ fn test_logic_call_skips() {
invalidation_nonce: 1,
};

let mut skips = LogicCallSkips::new();
let mut skips = LogicCallSkips::default();

assert_eq!(skips.skips_left(&logic_call_1_nonce_1), 0);
assert_eq!(skips.skips_left(&logic_call_1_nonce_2), 0);
Expand Down
3 changes: 1 addition & 2 deletions orchestrator/ethereum_gravity/src/send_to_cosmos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ pub async fn send_to_cosmos<S: Signer + 'static>(
// additionally we are mirroring only waiting for 1 confirmation by leaving that as default
let pending_tx = pending_tx.interval(Duration::from_secs(1));
let potential_error = GravityError::GravityContractError(format!(
"Did not receive transaction receipt when sending to Cosmos: {}",
tx_hash
"Did not receive transaction receipt when sending to Cosmos: {tx_hash}"
));

if let Some(timeout) = wait_timeout {
Expand Down
39 changes: 17 additions & 22 deletions orchestrator/ethereum_gravity/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::types::EthClient;
use deep_space::error::CosmosGrpcError;
use ethers::middleware::gas_oracle::Etherscan;
use ethers::prelude::gas_oracle::GasOracle;
use ethers::prelude::*;
Expand All @@ -8,9 +9,8 @@ use gravity_proto::gravity::query_client::QueryClient as GravityQueryClient;
use gravity_utils::error::GravityError;
use gravity_utils::ethereum::{downcast_to_u64, hex_str_to_bytes, vec_u8_to_fixed_32};
use gravity_utils::types::{decode_gravity_error, GravityContractError};
use tonic::transport::Channel;
use std::result::Result;
use deep_space::error::CosmosGrpcError;
use tonic::transport::Channel;

/// Gets the latest validator set nonce
pub async fn get_valset_nonce<S: Signer + 'static>(
Expand Down Expand Up @@ -120,7 +120,7 @@ pub async fn get_event_nonce<S: Signer + 'static>(
pub async fn get_gravity_id<S: Signer + 'static>(
gravity_contract_address: EthAddress,
eth_client: EthClient<S>,
mut cosmos_client: GravityQueryClient<Channel>
mut cosmos_client: GravityQueryClient<Channel>,
) -> Result<String, GravityError> {
let contract_call = Gravity::new(gravity_contract_address, eth_client.clone())
.state_gravity_id()
Expand Down Expand Up @@ -149,28 +149,25 @@ pub async fn get_gravity_id<S: Signer + 'static>(
if gravity_id != contract_id_value {
error!("Contract gravity id does not match with the chain gravity id");
return Err(GravityError::GravityContractError(format!(
"Gravity contract id {} does not match with chain gravity id {}",
gravity_id,
contract_id_value,
)))
"Gravity contract id {gravity_id} does not match with chain gravity id {contract_id_value}"
)));
}

info!("Gravity contract id {} match with chain gravity id {}", gravity_id, contract_id_value);
info!(
"Gravity contract id {gravity_id} match with chain gravity id {contract_id_value}"
);
Ok(params.gravity_id)
}
None => Err(GravityError::CosmosGrpcError(CosmosGrpcError::BadResponse(
format!("Cannot get params from the chain"))))
"Cannot get params from the chain".to_string(),
))),
}

},
}
Err(err) => Err(GravityError::GravityContractError(format!(
"Received invalid utf8 when getting gravity id {:?}: {}",
&gravity_id, err
))),
}



}

/// If ETHERSCAN_API_KEY env var is set, we'll call out to Etherscan for a gas estimate.
Expand All @@ -196,8 +193,7 @@ pub async fn get_chain<S: Signer + 'static>(

if chain_id.is_none() {
return Err(GravityError::EthereumBadDataError(format!(
"Chain ID is larger than u64 max: {}",
chain_id_result
"Chain ID is larger than u64 max: {chain_id_result}"
)));
}

Expand Down Expand Up @@ -231,11 +227,10 @@ impl GasCost {
// returns a bool indicating whether or not this error means we should permanently
// skip this logic call
pub fn handle_contract_error<S: Signer + 'static>(gravity_error: GravityError) -> bool {
let error_string = format!("LogicCall error: {:?}", gravity_error);
let gravity_contract_error = extract_gravity_contract_error::<S>(gravity_error);
let error_string = format!("LogicCall error: {gravity_error:?}");

if gravity_contract_error.is_some() {
match gravity_contract_error.unwrap() {
if let Some(gravity_contract_error) = extract_gravity_contract_error::<S>(gravity_error) {
match gravity_contract_error {
GravityContractError::InvalidLogicCallNonce(nonce_error) => {
info!(
"LogicCall already processed, skipping until observed on chain: {}",
Expand All @@ -252,11 +247,11 @@ pub fn handle_contract_error<S: Signer + 'static>(gravity_error: GravityError) -
}
// TODO(bolten): implement other cases if necessary
_ => {
error!("Unspecified gravity contract error: {}", error_string)
error!("Unspecified gravity contract error: {error_string}")
}
}
} else {
error!("Non-gravity contract error: {}", error_string);
error!("Non-gravity contract error: {error_string}");
}

false
Expand Down
15 changes: 7 additions & 8 deletions orchestrator/gorc/src/commands/cosmos_to_eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ pub fn one_atom() -> f64 {
pub fn print_atom(input: Uint256) -> String {
let float: f64 = input.to_string().parse().unwrap();
let res = float / one_atom();
format!("{}", res)
format!("{res}")
}

pub fn print_eth(input: Uint256) -> String {
let float: f64 = input.to_string().parse().unwrap();
let res = float / one_eth();
format!("{}", res)
format!("{res}")
}

impl Runnable for CosmosToEthCmd {
Expand All @@ -62,7 +62,7 @@ impl Runnable for CosmosToEthCmd {
let cosmos_address = cosmos_key.to_address(cosmos_prefix).unwrap();
let cosmos_grpc = config.cosmos.grpc.trim();
let cosmos_granter = config.cosmos.granter.clone();
println!("Sending from Cosmos address {}", cosmos_address);
println!("Sending from Cosmos address {cosmos_address}");
abscissa_tokio::run_with_actix(&APP, async {
let connections = create_rpc_connections(
cosmos_prefix.to_string(),
Expand All @@ -86,8 +86,7 @@ impl Runnable for CosmosToEthCmd {
),
Err(_e) => {
println!(
"Asset {} has no ERC20 representation, you may need to deploy an ERC20 for it!",
gravity_denom
"Asset {gravity_denom} has no ERC20 representation, you may need to deploy an ERC20 for it!"
);
exit(1);
}
Expand Down Expand Up @@ -117,13 +116,13 @@ impl Runnable for CosmosToEthCmd {
}
}

println!("Cosmos balances {:?}", balances);
println!("Cosmos balances {balances:?}");

let times = self.args.get(4).expect("times is required");
let times = times.parse::<usize>().expect("cannot parse times");

match found {
None => panic!("You don't have any {} tokens!", gravity_denom),
None => panic!("You don't have any {gravity_denom} tokens!"),
Some(found) => {
if amount.amount.clone() * times.into() >= found.amount && times == 1 {
if is_cosmos_originated {
Expand Down Expand Up @@ -165,7 +164,7 @@ impl Runnable for CosmosToEthCmd {
successful_sends += 1;
println!("Send to Eth txid {}", tx_id.txhash);
}
Err(e) => println!("Failed to send tokens! {:?}", e),
Err(e) => println!("Failed to send tokens! {e:?}"),
}
}

Expand Down
Loading

0 comments on commit a3f05a4

Please sign in to comment.