Skip to content

Commit

Permalink
fix: remove early panics
Browse files Browse the repository at this point in the history
  • Loading branch information
willyrgf committed May 27, 2023
1 parent 915e5c5 commit 7d1c66b
Show file tree
Hide file tree
Showing 10 changed files with 98 additions and 123 deletions.
33 changes: 9 additions & 24 deletions src/allowance/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,26 @@ async fn run(args: &ArgMatches) -> Result<(), anyhow::Error> {
let config = Config::global();
let mut table = table!(["Exchange", "Asset", "Balance", "Allowance"]);

let network = helpers::get_network(args).unwrap_or_else(|e| {
tracing::error!(error = %e);
panic!()
});
let wallet = helpers::get_wallet(args).unwrap_or_else(|e| {
tracing::error!(error = %e);
panic!()
});
let network = helpers::get_network(args)?;
let wallet = helpers::get_wallet(args)?;

for exchange in network.get_exchanges().into_iter() {
let assets_list = config.assets.hashmap().values().flat_map(|asset_config| {
asset_config.new_assets_list().unwrap_or_else(|e| {
tracing::error!(error = %e);
panic!()
})
});

futures::future::join_all(assets_list.map(|asset| async move {
let balance_of = asset.balance_of(wallet.address()).await;
let decimals = asset.decimals().await.unwrap();
let assets_list = config.assets.assets_by_network(network)?;

for asset in assets_list.into_iter() {
let balance_of = asset.balance_of(wallet.address()).await?;
let decimals = asset.decimals().await?;
let allowance = asset
.allowance(wallet.address(), exchange.as_router_address().unwrap())
.await;
(asset, balance_of, decimals, allowance, exchange)
}))
.await
.into_iter()
.for_each(|(asset, balance_of, decimals, allowance, exchange)| {

table.add_row(row![
exchange.name,
asset.name(),
utils::blockchain::display_amount_to_float(balance_of, decimals),
utils::blockchain::display_amount_to_float(allowance, decimals),
]);
});
}
}

table.printstd();
Expand Down
14 changes: 12 additions & 2 deletions src/asset/config.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::Asset;
use crate::config::Config;
use crate::config::{network::Network, Config};
use anyhow::Context;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
Expand Down Expand Up @@ -32,7 +32,7 @@ pub struct AssetConfig {
}

impl AssetConfig {
pub fn new_assets_list(&self) -> Result<Vec<Asset>, anyhow::Error> {
pub fn assets_list_by_network(&self) -> Result<Vec<Asset>, anyhow::Error> {
self.networks
.hashmap()
.values()
Expand All @@ -58,6 +58,16 @@ impl AssetsConfig {
self.0.get(key)
}

//TODO: use this function to get assets of the current network
pub fn assets_by_network(&self, network: &Network) -> Result<Vec<Asset>, anyhow::Error> {
let assets_config = self
.0
.values()
.filter(|&a| a.networks.get(network.name()).is_ok());

assets_config.map(|ac| Asset::new(ac, network)).collect()
}

//TODO: use this function to get assets of the current network
pub fn find_by_name_and_network(
&self,
Expand Down
23 changes: 14 additions & 9 deletions src/asset/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,20 +128,25 @@ impl Asset {
.map_err(|e| anyhow::anyhow!("failed to fetch gas_price, got: {:?}", e))
}

pub async fn balance_of(&self, account: H160) -> U256 {
pub async fn balance_of(&self, account: H160) -> Result<U256, anyhow::Error> {
let contract = &self.contract();
let result = contract.query("balanceOf", (account,), None, Options::default(), None);
let result_balance: U256 = result.await.unwrap();
result_balance
contract
.query("balanceOf", (account,), None, Options::default(), None)
.await
.map_err(|e| anyhow::anyhow!("failed to fetch balance, got: {:?}", e))
}

pub fn build_path_for_coin(&self, coin_address: H160) -> Vec<H160> {
vec![coin_address, self.as_address().unwrap()]
}

pub async fn balance_of_quoted_in(&self, wallet: &Wallet, quoted: &Asset) -> U256 {
pub async fn balance_of_quoted_in(
&self,
wallet: &Wallet,
quoted: &Asset,
) -> Result<U256, anyhow::Error> {
let account = wallet.address();
let base_balance = self.balance_of(account).await;
let base_balance = self.balance_of(account).await?;
let exchange = self
.get_network()
.get_exchange_by_liquidity(self, quoted, base_balance)
Expand All @@ -155,17 +160,17 @@ impl Asset {
});

if self.name() == quoted.name() {
return base_balance;
return Ok(base_balance);
}

let assets_path = exchange.build_route_for(self, quoted).await;

exchange
Ok(exchange
.get_amounts_out(base_balance, assets_path)
.await
.last()
.unwrap()
.into()
.into())
}

pub fn exist_max_tx_amount(&self) -> bool {
Expand Down
93 changes: 28 additions & 65 deletions src/balances/mod.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use crate::cmd::helpers;
use crate::config::Config;
use crate::utils::scalar::BigDecimal;
use crate::{cmd::helpers, utils};
use clap::ArgMatches;
use prettytable::{row, table};
use web3::types::U256;

pub mod cmd;

#[tracing::instrument(name = "run balances")]
async fn run(args: &ArgMatches) {
async fn run(args: &ArgMatches) -> Result<(), anyhow::Error> {
let config = Config::global();
let wallet = helpers::get_wallet(args).unwrap_or_else(|e| {
tracing::error!(error = %e);
panic!()
});
let wallet = helpers::get_wallet(args)?;
let hide_zero = helpers::get_hide_zero(args);

let mut table = table!([
Expand All @@ -24,74 +20,41 @@ async fn run(args: &ArgMatches) {
"Decimals"
]);

futures::future::join_all(
config
.networks
.hashmap()
.values()
.map(|network| async move {
let balance_of = match network
.get_web3_client_rpc()
.eth()
.balance(wallet.address(), None)
.await
{
Ok(n) => n,
Err(_) => U256::default(),
};
(
network.name(),
network.symbol(),
balance_of,
network.coin_decimals(),
)
}),
)
.await
.into_iter()
.for_each(|(network_name, symbol, balance_of, decimals)| {
let balance_of_bd = BigDecimal::from_unsigned_u256(&balance_of, decimals.into());
let balance_of_f64 = balance_of_bd.with_scale(decimals.into()).to_f64().unwrap();
let networks = config.networks.hashmap().values();

for network in networks.clone() {
let network_name = network.name();
let symbol = network.symbol();
let decimals = network.coin_decimals();
let balance_of = network.balance_coin(wallet).await?;
if !(hide_zero && balance_of == U256::from(0_i32)) {
table.add_row(row![
network_name,
symbol,
balance_of_f64,
utils::blockchain::display_amount_to_float(balance_of, decimals),
balance_of,
decimals
]);
}
});

futures::future::join_all(
config
.assets
.hashmap()
.values()
.flat_map(|asset_config| asset_config.new_assets_list().unwrap())
.map(|asset| async move {
let balance_of = asset.balance_of(wallet.address()).await;
let decimals = asset.decimals().await.unwrap();
(asset, balance_of, decimals)
}),
)
.await
.into_iter()
.for_each(|(asset, balance_of, decimals)| {
let balance_of_bd = BigDecimal::from_unsigned_u256(&balance_of, decimals.into());
let balance_of_f64 = balance_of_bd.with_scale(decimals.into()).to_f64().unwrap();

if !(hide_zero && balance_of == U256::from(0_i32)) {
table.add_row(row![
asset.network_id(),
asset.name(),
balance_of_f64,
balance_of,
decimals
]);
}

for network in networks.clone() {
let assets_list = config.assets.assets_by_network(network)?;
for asset in assets_list.into_iter() {
let balance_of = asset.balance_of(wallet.address()).await?;
let decimals = asset.decimals().await?;
if !(hide_zero && balance_of == U256::from(0_i32)) {
table.add_row(row![
asset.network_id(),
asset.name(),
utils::blockchain::display_amount_to_float(balance_of, decimals),
balance_of,
decimals
]);
}
}
});
}

table.printstd();
Ok(())
}
12 changes: 6 additions & 6 deletions src/config/exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl Exchange {
Ok(a) => a,
Err(e) => {
tracing::error!(
"get_amounts_out(): result err: {:?}, return zeroed value",
"get_amounts_out(): error return zeroed value, result err: {:?},",
e
);
vec![zero]
Expand Down Expand Up @@ -259,7 +259,7 @@ impl Exchange {
from_wallet: &Wallet,
input_asset: &Asset,
output_asset: &Asset,
) -> U256 {
) -> Result<U256, anyhow::Error> {
let asset_path = self
.build_route_for(input_asset, output_asset)
.await
Expand All @@ -273,8 +273,8 @@ impl Exchange {
.collect::<Vec<_>>(),
);

let output_asset_decimals = output_asset.decimals().await.unwrap();
let amount_in = input_asset.balance_of(from_wallet.address()).await;
let output_asset_decimals = output_asset.decimals().await?;
let amount_in = input_asset.balance_of(from_wallet.address()).await?;

let amount_out: U256 = self
.get_amounts_out(amount_in, asset_path.clone())
Expand All @@ -299,7 +299,7 @@ impl Exchange {
)
.await
{
Ok(gas) => gas,
Ok(gas) => Ok(gas),
Err(e) => {
tracing::error!(
"swap_cost() estimate_gas(): error: {}, input_asset: {:?}, amount_in: {:?}, amount_out: {:?} amount_min_out_slippage: {:?}",
Expand All @@ -309,7 +309,7 @@ impl Exchange {
amount_out,
amount_min_out_slippage
);
panic!();
Err(anyhow::anyhow!(e))
}
}
}
Expand Down
12 changes: 11 additions & 1 deletion src/config/network.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use web3::{
signing::Key,
transports::{Http, WebSocket},
types::U256,
Web3,
};

use super::{exchange::Exchange, Config};
use super::{exchange::Exchange, wallet::Wallet, Config};
use crate::{asset::Asset, utils::scalar::BigDecimal};

#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
Expand Down Expand Up @@ -89,6 +90,15 @@ impl Network {
.collect()
}

pub async fn balance_coin(&self, wallet: &Wallet) -> Result<U256, anyhow::Error> {
Ok(self
.get_web3_client_rpc()
.eth()
.balance(wallet.address(), None)
.await
.map_err(|e| anyhow::anyhow!("error fetch balance from network: {:?}", e))?)
}

pub async fn get_exchange_by_liquidity(
&self,
input_asset: &Asset,
Expand Down
4 changes: 2 additions & 2 deletions src/rebalancer/cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ async fn wrapped_cmd_info(args: &ArgMatches) -> Result<(), anyhow::Error> {
};

if let Some(input_asset) = input_asset {
let amount_in = input_asset.balance_of(from_wallet.address()).await;
let amount_in = input_asset.balance_of(from_wallet.address()).await?;
let parking_asset_exchange = input_asset
.get_network()
.get_exchange_by_liquidity(&input_asset, &parking_asset, amount_in)
Expand All @@ -287,7 +287,7 @@ async fn wrapped_cmd_info(args: &ArgMatches) -> Result<(), anyhow::Error> {
let gas_price = client.clone().eth().gas_price().await.unwrap();
let swap_cost = parking_asset_exchange
.estimate_swap_cost(from_wallet, &input_asset, &parking_asset)
.await;
.await?;

let total_ops = U256::from(asset_rebalances.len());

Expand Down
Loading

0 comments on commit 7d1c66b

Please sign in to comment.