Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance enable with tokens methods #1762

Merged
merged 14 commits into from
May 2, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
26 changes: 15 additions & 11 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use ethereum_types::{Address, H160, H256, U256};
use ethkey::{public_to_address, KeyPair, Public, Signature};
use ethkey::{sign, verify_address};
use futures::compat::Future01CompatExt;
use futures::future::{join_all, select_ok, Either, FutureExt, TryFutureExt};
use futures::future::{join_all, select_ok, try_join_all, Either, FutureExt, TryFutureExt};
use futures01::Future;
use http::StatusCode;
use mm2_core::mm_ctx::{MmArc, MmWeak};
Expand Down Expand Up @@ -3430,19 +3430,23 @@ impl EthCoin {
}

pub async fn get_tokens_balance_list(&self) -> Result<HashMap<String, CoinBalance>, MmError<BalanceError>> {
let coin = self.clone();
let mut token_balances = HashMap::new();
for (token_ticker, info) in self.get_erc_tokens_infos().iter() {
let balance_as_u256 = coin.get_token_balance_by_address(info.token_address).await?;
let balance_as_big_decimal = u256_to_big_decimal(balance_as_u256, info.decimals)?;
let balance = CoinBalance {
spendable: balance_as_big_decimal,
unspendable: BigDecimal::from(0),
let selfi = self.clone();
let mut requests = Vec::new();
for (token_ticker, info) in self.get_erc_tokens_infos() {
let coin = selfi.clone();
rozhkovdmitrii marked this conversation as resolved.
Show resolved Hide resolved
let fut = async move {
let balance_as_u256 = coin.get_token_balance_by_address(info.token_address).await?;
let balance_as_big_decimal = u256_to_big_decimal(balance_as_u256, info.decimals)?;
let balance = CoinBalance {
rozhkovdmitrii marked this conversation as resolved.
Show resolved Hide resolved
spendable: balance_as_big_decimal,
unspendable: BigDecimal::from(0),
};
Ok::<_, MmError<BalanceError>>((token_ticker.clone(), balance))
rozhkovdmitrii marked this conversation as resolved.
Show resolved Hide resolved
};
token_balances.insert(token_ticker.clone(), balance);
requests.push(fut);
}

Ok(token_balances)
try_join_all(requests).await.map(|res| res.into_iter().collect())
}

async fn get_token_balance_by_address(&self, token_address: Address) -> Result<U256, MmError<BalanceError>> {
Expand Down
3 changes: 1 addition & 2 deletions mm2src/coins/solana.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,10 +320,9 @@ impl SolanaCoin {
Ok((hash, fees))
}

pub async fn my_balance_spl(&self, infos: &SplTokenInfo) -> Result<CoinBalance, MmError<BalanceError>> {
pub async fn my_balance_spl(&self, infos: SplTokenInfo) -> Result<CoinBalance, MmError<BalanceError>> {
let token_accounts = async_blocking({
let coin = self.clone();
rozhkovdmitrii marked this conversation as resolved.
Show resolved Hide resolved
let infos = infos.clone();
move || {
coin.rpc().get_token_accounts_by_owner(
&coin.key_pair.pubkey(),
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/solana/spl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ impl SplToken {
let coin = self.clone();
let fut = async move {
coin.platform_coin
.my_balance_spl(&SplTokenInfo {
.my_balance_spl(SplTokenInfo {
token_contract_address: coin.conf.token_contract_address,
decimals: coin.conf.decimals,
})
Expand Down
24 changes: 16 additions & 8 deletions mm2src/coins/tendermint/tendermint_coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ use cosmrs::tx::{self, Fee, Msg, Raw, SignDoc, SignerInfo};
use cosmrs::{AccountId, Any, Coin, Denom, ErrorReport};
use crypto::{privkey::key_pair_from_secret, Secp256k1Secret, StandardHDPathToCoin};
use derive_more::Display;
use futures::future::try_join_all;
use futures::lock::Mutex as AsyncMutex;
use futures::{FutureExt, TryFutureExt};
use futures01::Future;
Expand Down Expand Up @@ -422,17 +423,24 @@ impl TendermintCommons for TendermintCoin {
let platform_balance = big_decimal_from_sat_unsigned(platform_balance_denom, self.decimals);
let ibc_assets_info = self.tokens_info.lock().clone();

let mut result = AllBalancesResult {
platform_balance,
tokens_balances: HashMap::new(),
};
let mut requests = Vec::new();
for (ticker, info) in ibc_assets_info {
let balance_denom = self.balance_for_denom(info.denom.to_string()).await?;
let balance_decimal = big_decimal_from_sat_unsigned(balance_denom, info.decimals);
result.tokens_balances.insert(ticker, balance_decimal);
let fut = async move {
let balance_denom = self
.balance_for_denom(info.denom.to_string())
.await
.map_err(|e| e.into_inner())?;
let balance_decimal = big_decimal_from_sat_unsigned(balance_denom, info.decimals);
Ok::<_, TendermintCoinRpcError>((ticker.clone(), balance_decimal))
};
requests.push(fut);
}
let tokens_balances = try_join_all(requests).await?.into_iter().collect();

Ok(result)
Ok(AllBalancesResult {
platform_balance,
tokens_balances,
})
}

#[inline(always)]
Expand Down
43 changes: 25 additions & 18 deletions mm2src/coins_activation/src/bch_with_tokens_activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use coins::utxo::UtxoCommonOps;
use coins::{CoinBalance, CoinProtocol, MarketCoinOps, MmCoin, PrivKeyBuildPolicy, PrivKeyPolicyNotAllowed,
UnexpectedDerivationMethod};
use common::executor::{AbortSettings, SpawnAbortable};
use common::true_f;
use common::Future01CompatExt;
use crypto::CryptoCtxError;
use mm2_core::mm_ctx::MmArc;
Expand Down Expand Up @@ -119,6 +120,8 @@ pub struct BchWithTokensActivationRequest {
#[serde(flatten)]
platform_request: BchActivationRequest,
slp_tokens_requests: Vec<TokenActivationRequest<SlpActivationRequest>>,
#[serde(default = "true_f")]
pub get_balances: bool,
}

impl TxHistory for BchWithTokensActivationRequest {
Expand Down Expand Up @@ -244,6 +247,7 @@ impl PlatformWithTokensActivationOps for BchCoin {

async fn get_activation_result(
&self,
activation_request: &Self::ActivationRequest,
) -> Result<BchWithTokensActivationResult, MmError<BchWithTokensActivationError>> {
let my_address = self.as_ref().derivation_method.single_addr_or_err()?;
let my_slp_address = self
Expand All @@ -254,34 +258,37 @@ impl PlatformWithTokensActivationOps for BchCoin {

let current_block = self.as_ref().rpc_client.get_block_count().compat().await?;

let bch_unspents = self.bch_unspents_for_display(my_address).await?;
let bch_balance = bch_unspents.platform_balance(self.decimals());

let mut token_balances = HashMap::new();
for (token_ticker, info) in self.get_slp_tokens_infos().iter() {
let token_balance = bch_unspents.slp_token_balance(&info.token_id, info.decimals);
token_balances.insert(token_ticker.clone(), token_balance);
}

let mut result = BchWithTokensActivationResult {
current_block,
bch_addresses_infos: HashMap::new(),
slp_addresses_infos: HashMap::new(),
};

result
.bch_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
if activation_request.get_balances {
let bch_unspents = self.bch_unspents_for_display(my_address).await?;
let bch_balance = bch_unspents.platform_balance(self.decimals());

let mut token_balances = HashMap::new();
for (token_ticker, info) in self.get_slp_tokens_infos().iter() {
let token_balance = bch_unspents.slp_token_balance(&info.token_id, info.decimals);
token_balances.insert(token_ticker.clone(), token_balance);
}

result
.bch_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: self.my_public_key()?.to_string(),
balances: bch_balance,
});

result.slp_addresses_infos.insert(my_slp_address, CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: self.my_public_key()?.to_string(),
balances: bch_balance,
balances: token_balances,
});
}

result.slp_addresses_infos.insert(my_slp_address, CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: self.my_public_key()?.to_string(),
balances: token_balances,
});
Ok(result)
}

Expand Down
58 changes: 33 additions & 25 deletions mm2src/coins_activation/src/eth_with_token_activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use coins::{eth::{v2_activation::{eth_coin_from_conf_and_request_v2, Erc20Protoc
Erc20TokenInfo, EthCoin, EthCoinType},
my_tx_history_v2::TxHistoryStorage,
CoinBalance, CoinProtocol, MarketCoinOps, MmCoin};
use common::true_f;
use common::Future01CompatExt;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
Expand Down Expand Up @@ -122,6 +123,8 @@ pub struct EthWithTokensActivationRequest {
#[serde(flatten)]
platform_request: EthActivationV2Request,
erc20_tokens_requests: Vec<TokenActivationRequest<Erc20TokenActivationRequest>>,
#[serde(default = "true_f")]
pub get_balances: bool,
}

impl TxHistory for EthWithTokensActivationRequest {
Expand Down Expand Up @@ -198,7 +201,10 @@ impl PlatformWithTokensActivationOps for EthCoin {
})]
}

async fn get_activation_result(&self) -> Result<EthWithTokensActivationResult, MmError<EthActivationV2Error>> {
async fn get_activation_result(
&self,
activation_request: &Self::ActivationRequest,
) -> Result<EthWithTokensActivationResult, MmError<EthActivationV2Error>> {
let my_address = self.my_address()?;
let pubkey = self.get_public_key()?;

Expand All @@ -208,37 +214,39 @@ impl PlatformWithTokensActivationOps for EthCoin {
.await
.map_err(EthActivationV2Error::InternalError)?;

let eth_balance = self
.my_balance()
.compat()
.await
.map_err(|e| EthActivationV2Error::CouldNotFetchBalance(e.to_string()))?;
let token_balances = self
.get_tokens_balance_list()
.await
.map_err(|e| EthActivationV2Error::CouldNotFetchBalance(e.to_string()))?;

let mut result = EthWithTokensActivationResult {
current_block,
eth_addresses_infos: HashMap::new(),
erc20_addresses_infos: HashMap::new(),
};

result
.eth_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: pubkey.clone(),
balances: eth_balance,
});
if activation_request.get_balances {
let eth_balance = self
.my_balance()
.compat()
.await
.map_err(|e| EthActivationV2Error::CouldNotFetchBalance(e.to_string()))?;
let token_balances = self
.get_tokens_balance_list()
.await
.map_err(|e| EthActivationV2Error::CouldNotFetchBalance(e.to_string()))?;

result
.eth_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: pubkey.clone(),
balances: eth_balance,
});

result
.erc20_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey,
balances: token_balances,
});
result
.erc20_addresses_infos
.insert(my_address.to_string(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey,
balances: token_balances,
});
}

Ok(result)
}
Expand Down
7 changes: 5 additions & 2 deletions mm2src/coins_activation/src/platform_coin_with_tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,10 @@ pub trait PlatformWithTokensActivationOps: Into<MmCoinEnum> {
&self,
) -> Vec<Box<dyn TokenAsMmCoinInitializer<PlatformCoin = Self, ActivationRequest = Self::ActivationRequest>>>;

async fn get_activation_result(&self) -> Result<Self::ActivationResult, MmError<Self::ActivationError>>;
async fn get_activation_result(
&self,
activation_request: &Self::ActivationRequest,
) -> Result<Self::ActivationResult, MmError<Self::ActivationError>>;

fn start_history_background_fetching(
&self,
Expand Down Expand Up @@ -311,7 +314,7 @@ where
mm_tokens.extend(tokens);
}

let activation_result = platform_coin.get_activation_result().await?;
let activation_result = platform_coin.get_activation_result(&req.request).await?;
log::info!("{} current block {}", req.ticker, activation_result.current_block());

if req.request.tx_history() {
Expand Down
59 changes: 37 additions & 22 deletions mm2src/coins_activation/src/solana_with_tokens_activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ use coins::solana::solana_coin_with_policy;
use coins::solana::spl::{SplProtocolConf, SplTokenCreationError};
use coins::{BalanceError, CoinBalance, CoinProtocol, MarketCoinOps, PrivKeyBuildPolicy, SolanaActivationParams,
SolanaCoin, SplToken};
use common::true_f;
use common::Future01CompatExt;
use crypto::CryptoCtxError;
use futures::future::try_join_all;
use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::*;
use mm2_number::BigDecimal;
Expand Down Expand Up @@ -79,6 +81,8 @@ pub struct SolanaWithTokensActivationRequest {
#[serde(flatten)]
platform_request: SolanaActivationParams,
spl_tokens_requests: Vec<TokenActivationRequest<SplActivationRequest>>,
#[serde(default = "true_f")]
pub get_balances: bool,
}

impl TxHistory for SolanaWithTokensActivationRequest {
Expand Down Expand Up @@ -205,42 +209,53 @@ impl PlatformWithTokensActivationOps for SolanaCoin {
})]
}

async fn get_activation_result(&self) -> Result<Self::ActivationResult, MmError<Self::ActivationError>> {
async fn get_activation_result(
&self,
activation_request: &Self::ActivationRequest,
) -> Result<Self::ActivationResult, MmError<Self::ActivationError>> {
let my_address = self.my_address()?;

let current_block = self
.current_block()
.compat()
.await
.map_to_mm(Self::ActivationError::Internal)?;
let solana_balance = self
.my_balance()
.compat()
.await
.map_err(|e| Self::ActivationError::GetBalanceError(e.into_inner()))?;
let mut token_balances = HashMap::new();
let token_infos = self.get_spl_tokens_infos();
for (token_ticker, info) in token_infos.into_iter() {
let balance = self.my_balance_spl(&info.clone()).await?;
token_balances.insert(token_ticker.to_owned(), balance);
}

let mut result = SolanaWithTokensActivationResult {
current_block,
solana_addresses_infos: HashMap::new(),
spl_addresses_infos: HashMap::new(),
};
result
.solana_addresses_infos
.insert(my_address.clone(), CoinAddressInfo {

if activation_request.get_balances {
let solana_balance = self
.my_balance()
.compat()
.await
.map_err(|e| Self::ActivationError::GetBalanceError(e.into_inner()))?;

let (token_tickers, requests): (Vec<_>, Vec<_>) = self
.get_spl_tokens_infos()
.into_iter()
.map(|(ticker, info)| (ticker, self.my_balance_spl(info)))
.unzip();
let token_balances = token_tickers.into_iter().zip(try_join_all(requests).await?).collect();

result
.solana_addresses_infos
.insert(my_address.clone(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: my_address.clone(),
balances: solana_balance,
});

result.spl_addresses_infos.insert(my_address.clone(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: my_address.clone(),
balances: solana_balance,
pubkey: my_address,
balances: token_balances,
});
}

result.spl_addresses_infos.insert(my_address.clone(), CoinAddressInfo {
derivation_method: DerivationMethod::Iguana,
pubkey: my_address,
balances: token_balances,
});
Ok(result)
}

Expand Down
Loading