Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions mm2src/coins/coin_balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,8 @@ pub trait HDWalletBalanceOps: HDWalletCoinOps {
// Derive HD addresses and split addresses and their derivation paths into two collections.
let (addresses, der_paths): (Vec<_>, Vec<_>) = self
.derive_addresses(hd_account, address_ids)
.await?
.await
.map_mm_err()?
.into_iter()
.map(|hd_address| (hd_address.address(), hd_address.derivation_path().clone()))
.unzip();
Expand Down Expand Up @@ -428,11 +429,12 @@ pub mod common_impl {
HDCoinAddress<Coin>: fmt::Display,
{
let gap_limit = hd_wallet.gap_limit();
let mut addresses = coin.all_known_addresses_balances(hd_account).await?;
let mut addresses = coin.all_known_addresses_balances(hd_account).await.map_mm_err()?;
if scan_new_addresses {
addresses.extend(
coin.scan_for_new_addresses(hd_wallet, hd_account, address_scanner, gap_limit)
.await?,
.await
.map_mm_err()?,
);
}

Expand Down Expand Up @@ -474,7 +476,7 @@ pub mod common_impl {
HDCoinHDAccount<Coin>: HDAccountStorageOps,
{
let mut accounts = hd_wallet.get_accounts_mut().await;
let address_scanner = coin.produce_hd_address_scanner().await?;
let address_scanner = coin.produce_hd_address_scanner().await.map_mm_err()?;

let mut result = HDWalletBalance {
accounts: Vec::with_capacity(accounts.len() + 1),
Expand All @@ -489,8 +491,9 @@ pub mod common_impl {
);

// Create new HD account.
let mut new_account =
create_new_account(coin, hd_wallet, xpub_extractor, Some(path_to_address.account_id)).await?;
let mut new_account = create_new_account(coin, hd_wallet, xpub_extractor, Some(path_to_address.account_id))
.await
.map_mm_err()?;
let scan_new_addresses = matches!(
params.scan_policy,
EnableCoinScanPolicy::ScanIfNewWallet | EnableCoinScanPolicy::Scan
Expand Down Expand Up @@ -576,7 +579,10 @@ pub mod common_impl {
let mut new_addresses = Vec::with_capacity(to_generate);
let mut addresses_to_request = Vec::with_capacity(to_generate);
for _ in 0..to_generate {
let hd_address = coin.generate_new_address(hd_wallet, hd_account, chain).await?;
let hd_address = coin
.generate_new_address(hd_wallet, hd_account, chain)
.await
.map_mm_err()?;

new_addresses.push(HDAddressBalance {
address: hd_address.address().display_address(),
Expand All @@ -589,7 +595,8 @@ pub mod common_impl {

let to_extend = coin
.known_addresses_balances(addresses_to_request)
.await?
.await
.map_mm_err()?
.into_iter()
// The balances are guaranteed to be in the same order as they were requests.
.zip(new_addresses)
Expand Down
335 changes: 203 additions & 132 deletions mm2src/coins/eth.rs

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions mm2src/coins/eth/eth_balance_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{eth::{u256_to_big_decimal, Erc20TokenDetails},
hd_wallet::AddrToString,
BalanceError, CoinWithDerivationMethod};
use common::{executor::Timer, log, Future01CompatExt};
use mm2_err_handle::prelude::MmError;
use mm2_err_handle::prelude::*;
use mm2_event_stream::{Broadcaster, Event, EventStreamer, NoDataIn, StreamHandlerInput, StreamerId};
use mm2_number::BigDecimal;

Expand Down Expand Up @@ -133,7 +133,7 @@ async fn fetch_balance(
let balance_as_big_decimal = u256_to_big_decimal(balance_as_u256, decimals).map_err(|e| BalanceFetchError {
ticker: token_ticker.clone(),
address: address.addr_to_string(),
error: e.into(),
error: e.map(BalanceError::from),
})?;

Ok(BalanceData {
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/eth/eth_hd_wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ impl HDWalletBalanceOps for EthCoin {
async fn known_address_balance(&self, address: &Address) -> BalanceResult<Self::BalanceObject> {
let balance = self
.address_balance(*address)
.and_then(move |result| Ok(u256_to_big_decimal(result, self.decimals())?))
.and_then(move |result| u256_to_big_decimal(result, self.decimals()).map_mm_err())
.compat()
.await?;

Expand Down
6 changes: 3 additions & 3 deletions mm2src/coins/eth/eth_swap_v2/eth_maker_swap_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use ethereum_types::{Address, Public, U256};
use ethkey::public_to_address;
use futures::compat::Future01CompatExt;
use mm2_err_handle::mm_error::MmError;
use mm2_err_handle::prelude::MapToMmResult;
use mm2_err_handle::prelude::{MapToMmResult, MmResultExt};
use std::convert::TryInto;
use web3::types::TransactionId;

Expand Down Expand Up @@ -137,10 +137,10 @@ impl EthCoin {
))
})?;
let maker_address = public_to_address(args.maker_pub);
validate_from_to_addresses(tx_from_rpc, maker_address, maker_swap_v2_contract)?;
validate_from_to_addresses(tx_from_rpc, maker_address, maker_swap_v2_contract).map_mm_err()?;

let validation_args = {
let amount = wei_from_big_decimal(&args.amount, self.decimals)?;
let amount = wei_from_big_decimal(&args.amount, self.decimals).map_mm_err()?;
MakerValidationArgs {
swap_id,
amount,
Expand Down
9 changes: 5 additions & 4 deletions mm2src/coins/eth/eth_swap_v2/eth_taker_swap_v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use ethcore_transaction::Action;
use ethereum_types::{Address, Public, U256};
use ethkey::public_to_address;
use futures::compat::Future01CompatExt;
use mm2_err_handle::prelude::{MapToMmResult, MmError, MmResult};
use mm2_err_handle::prelude::{MapToMmResult, MmError, MmResult, MmResultExt};
use std::convert::TryInto;
use web3::types::{BlockNumber, TransactionId};

Expand Down Expand Up @@ -166,11 +166,12 @@ impl EthCoin {
))
})?;
let taker_address = public_to_address(args.taker_pub);
validate_from_to_addresses(tx_from_rpc, taker_address, taker_swap_v2_contract)?;
validate_from_to_addresses(tx_from_rpc, taker_address, taker_swap_v2_contract).map_mm_err()?;

let validation_args = {
let dex_fee = wei_from_big_decimal(&args.dex_fee.fee_amount().into(), self.decimals)?;
let payment_amount = wei_from_big_decimal(&(args.trading_amount + args.premium_amount), self.decimals)?;
let dex_fee = wei_from_big_decimal(&args.dex_fee.fee_amount().into(), self.decimals).map_mm_err()?;
let payment_amount =
wei_from_big_decimal(&(args.trading_amount + args.premium_amount), self.decimals).map_mm_err()?;
TakerValidationArgs {
swap_id,
amount: payment_amount,
Expand Down
66 changes: 39 additions & 27 deletions mm2src/coins/eth/eth_withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use kdf_walletconnect::{WalletConnectCtx, WalletConnectOps};
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::map_mm_error::MapMmError;
use mm2_err_handle::mm_error::MmResult;
use mm2_err_handle::prelude::{MapToMmResult, MmError, OrMmError};
use mm2_err_handle::prelude::{MapToMmResult, MmError, MmResultExt, OrMmError};
use std::ops::Deref;
use std::sync::Arc;
#[cfg(target_arch = "wasm32")]
Expand Down Expand Up @@ -59,8 +59,8 @@ where
async fn get_from_address(&self, req: &WithdrawRequest) -> Result<H160, MmError<WithdrawError>> {
let coin = self.coin();
match req.from {
Some(_) => Ok(coin.get_withdraw_sender_address(req).await?.address),
None => Ok(coin.derivation_method.single_addr_or_err().await?),
Some(_) => Ok(coin.get_withdraw_sender_address(req).await.map_mm_err()?.address),
None => Ok(coin.derivation_method.single_addr_or_err().await.map_mm_err()?),
}
}

Expand All @@ -77,7 +77,8 @@ where
let derivation_path = self.get_from_derivation_path(from)?;
let raw_priv_key = coin
.priv_key_policy
.hd_wallet_derived_priv_key_or_err(&derivation_path)?;
.hd_wallet_derived_priv_key_or_err(&derivation_path)
.map_mm_err()?;
KeyPair::from_secret_slice(raw_priv_key.as_slice())
.map_to_mm(|e| WithdrawError::InternalError(e.to_string()))
},
Expand All @@ -93,11 +94,17 @@ where
#[allow(clippy::result_large_err)]
fn get_from_derivation_path(&self, from: &HDAddressSelector) -> Result<DerivationPath, MmError<WithdrawError>> {
let coin = self.coin();
let path_to_coin = &coin.deref().derivation_method.hd_wallet_or_err()?.derivation_path;
let path_to_coin = &coin
.deref()
.derivation_method
.hd_wallet_or_err()
.map_mm_err()?
.derivation_path;
let path_to_address = from
.to_address_path(path_to_coin.coin_type())
.mm_err(|err| WithdrawError::UnexpectedFromAddress(err.to_string()))?;
let derivation_path = path_to_address.to_derivation_path(path_to_coin)?;
.mm_err(|err| WithdrawError::UnexpectedFromAddress(err.to_string()))
.map_mm_err()?;
let derivation_path = path_to_address.to_derivation_path(path_to_coin).map_mm_err()?;
Ok(derivation_path)
}

Expand All @@ -113,7 +120,8 @@ where
let default_hd_address = &coin
.deref()
.derivation_method
.hd_wallet_or_err()?
.hd_wallet_or_err()
.map_mm_err()?
.get_enabled_address()
.await
.ok_or_else(|| WithdrawError::InternalError("no enabled address".to_owned()))?;
Expand Down Expand Up @@ -187,7 +195,8 @@ where

let signed_tx = coin
.wait_for_tx_appears_on_rpc(tx_hash, wait_rpc_timeout, check_every)
.await?;
.await
.map_mm_err()?;
let tx_hex = signed_tx
.map(|signed_tx| BytesJson::from(rlp::encode(&signed_tx).to_vec()))
// Return an empty `tx_hex` if the transaction is still not appeared on the RPC node.
Expand Down Expand Up @@ -216,13 +225,13 @@ where

self.on_generating_transaction()?;

let my_balance = coin.address_balance(my_address).compat().await?;
let my_balance_dec = u256_to_big_decimal(my_balance, coin.decimals)?;
let my_balance = coin.address_balance(my_address).compat().await.map_mm_err()?;
let my_balance_dec = u256_to_big_decimal(my_balance, coin.decimals).map_mm_err()?;

let (mut wei_amount, dec_amount) = if req.max {
(my_balance, my_balance_dec.clone())
} else {
let wei_amount = wei_from_big_decimal(&req.amount, coin.decimals)?;
let wei_amount = wei_from_big_decimal(&req.amount, coin.decimals).map_mm_err()?;
(wei_amount, req.amount.clone())
};
if wei_amount > my_balance {
Expand All @@ -241,7 +250,7 @@ where
},
EthCoinType::Nft { .. } => return MmError::err(WithdrawError::NftProtocolNotSupported),
};
let eth_value_dec = u256_to_big_decimal(eth_value, coin.decimals)?;
let eth_value_dec = u256_to_big_decimal(eth_value, coin.decimals).map_mm_err()?;

let (gas, pay_for_gas_option) = get_eth_gas_details_from_withdraw_fee(
coin,
Expand All @@ -252,9 +261,10 @@ where
call_addr,
false,
)
.await?;
let total_fee = calc_total_fee(gas, &pay_for_gas_option)?;
let total_fee_dec = u256_to_big_decimal(total_fee, coin.decimals)?;
.await
.map_mm_err()?;
let total_fee = calc_total_fee(gas, &pay_for_gas_option).map_mm_err()?;
let total_fee_dec = u256_to_big_decimal(total_fee, coin.decimals).map_mm_err()?;

if req.max && coin.coin_type == EthCoinType::Eth {
if eth_value < total_fee || wei_amount < total_fee {
Expand Down Expand Up @@ -362,14 +372,14 @@ where
let tx_hash_bytes = BytesJson::from(tx_hash.0.to_vec());
let tx_hash_str = format!("{:02x}", tx_hash_bytes);

let amount_decimal = u256_to_big_decimal(wei_amount, coin.decimals)?;
let amount_decimal = u256_to_big_decimal(wei_amount, coin.decimals).map_mm_err()?;
let mut spent_by_me = amount_decimal.clone();
let received_by_me = if to_addr == my_address {
amount_decimal.clone()
} else {
0.into()
};
let fee_details = EthTxFeeDetails::new(gas, pay_for_gas_option, fee_coin)?;
let fee_details = EthTxFeeDetails::new(gas, pay_for_gas_option, fee_coin).map_mm_err()?;
if coin.coin_type == EthCoinType::Eth {
spent_by_me += &fee_details.total_fee;
}
Expand Down Expand Up @@ -408,15 +418,15 @@ impl EthWithdraw for InitEthWithdraw {
fn request(&self) -> &WithdrawRequest { &self.req }

fn on_generating_transaction(&self) -> Result<(), MmError<WithdrawError>> {
Ok(self
.task_handle
.update_in_progress_status(WithdrawInProgressStatus::GeneratingTransaction)?)
self.task_handle
.update_in_progress_status(WithdrawInProgressStatus::GeneratingTransaction)
.map_mm_err()
}

fn on_finishing(&self) -> Result<(), MmError<WithdrawError>> {
Ok(self
.task_handle
.update_in_progress_status(WithdrawInProgressStatus::Finishing)?)
self.task_handle
.update_in_progress_status(WithdrawInProgressStatus::Finishing)
.map_mm_err()
}

async fn sign_tx_with_trezor(
Expand All @@ -425,7 +435,7 @@ impl EthWithdraw for InitEthWithdraw {
unsigned_tx: &TransactionWrapper,
) -> Result<SignedEthTx, MmError<WithdrawError>> {
let coin = self.coin();
let crypto_ctx = CryptoCtx::from_ctx(&self.ctx)?;
let crypto_ctx = CryptoCtx::from_ctx(&self.ctx).map_mm_err()?;
let hw_ctx = crypto_ctx
.hw_ctx()
.or_mm_err(|| WithdrawError::HwError(HwRpcError::NoTrezorDeviceAvailable))?;
Expand All @@ -437,7 +447,7 @@ impl EthWithdraw for InitEthWithdraw {
};
let sign_processor = TrezorRpcTaskProcessor::new(self.task_handle.clone(), trezor_statuses);
let sign_processor = Arc::new(sign_processor);
let mut trezor_session = hw_ctx.trezor(sign_processor).await?;
let mut trezor_session = hw_ctx.trezor(sign_processor).await.map_mm_err()?;
let chain_id = match coin.chain_spec {
ChainSpec::Evm { chain_id } => chain_id,
// Todo: Add support for Tron signing with Trezor
Expand All @@ -449,7 +459,9 @@ impl EthWithdraw for InitEthWithdraw {
};
let unverified_tx = trezor_session
.sign_eth_tx(derivation_path, unsigned_tx, chain_id)
.await?;
.await
.map_mm_err()?;

Ok(SignedEthTx::new(unverified_tx).map_to_mm(|err| WithdrawError::InternalError(err.to_string()))?)
}
}
Expand Down
3 changes: 2 additions & 1 deletion mm2src/coins/eth/fee_estimation/eip1559/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use crate::eth::web3_transport::FeeHistoryResult;
use crate::eth::{wei_from_gwei_decimal, wei_to_gwei_decimal, EthCoin, Web3RpcError, Web3RpcResult};
use mm2_err_handle::mm_error::MmError;
use mm2_err_handle::or_mm_error::OrMmError;
use mm2_err_handle::prelude::MmResultExt;
use mm2_number::BigDecimal;

use ethereum_types::U256;
Expand Down Expand Up @@ -101,7 +102,7 @@ impl FeePerGasSimpleEstimator {

Ok(FeePerGasLevel {
max_priority_fee_per_gas,
max_fee_per_gas: wei_from_gwei_decimal(&max_fee_per_gas_dec)?,
max_fee_per_gas: wei_from_gwei_decimal(&max_fee_per_gas_dec).map_mm_err()?,
// TODO: Consider adding default wait times if applicable (and mark them as uncertain).
min_wait_time: None,
max_wait_time: None,
Expand Down
6 changes: 3 additions & 3 deletions mm2src/coins/eth/nft_swap_v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use ethcore_transaction::Action;
use ethereum_types::U256;
use ethkey::public_to_address;
use futures::compat::Future01CompatExt;
use mm2_err_handle::prelude::{MapToMmResult, MmError, MmResult};
use mm2_err_handle::prelude::{MapToMmResult, MmError, MmResult, MmResultExt};
use mm2_number::BigDecimal;
use num_traits::Signed;
use web3::types::TransactionId;
Expand Down Expand Up @@ -89,7 +89,7 @@ impl EthCoin {
args.maker_payment_tx.tx_hash()
))
})?;
validate_from_to_addresses(tx_from_rpc, maker_address, *token_address)?;
validate_from_to_addresses(tx_from_rpc, maker_address, *token_address).map_mm_err()?;

let (decoded, bytes_index) = get_decoded_tx_data_and_bytes_index(contract_type, &tx_from_rpc.input.0)?;

Expand All @@ -116,7 +116,7 @@ impl EthCoin {
maker_secret_hash: args.maker_secret_hash.to_vec(),
time_lock: U256::from(args.time_lock),
};
decode_and_validate_htlc_params(decoded, bytes_index, htlc_params)?;
decode_and_validate_htlc_params(decoded, bytes_index, htlc_params).map_mm_err()?;
},
EthCoinType::Eth | EthCoinType::Erc20 { .. } => {
return MmError::err(ValidatePaymentError::InternalError(
Expand Down
Loading
Loading