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

enhancement(utxo): improve trade and withdraw fee calculations #2083

Open
wants to merge 20 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 15 commits
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
4 changes: 4 additions & 0 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5216,6 +5216,7 @@ impl MmCoin for EthCoin {
coin: fee_coin.into(),
amount: try_s!(u256_to_big_decimal(fee, ETH_DECIMALS)).into(),
paid_from_trading_vol: false,
tx_size: None,
})
}),
)
Expand Down Expand Up @@ -5273,6 +5274,7 @@ impl MmCoin for EthCoin {
coin: fee_coin.into(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
})
}

Expand All @@ -5292,6 +5294,7 @@ impl MmCoin for EthCoin {
coin: fee_coin.into(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
})
};
Box::new(fut.boxed().compat())
Expand Down Expand Up @@ -5341,6 +5344,7 @@ impl MmCoin for EthCoin {
coin: fee_coin.into(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
})
}

Expand Down
4 changes: 4 additions & 0 deletions mm2src/coins/eth/eth_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ fn get_sender_trade_preimage() {
coin: "ETH".to_owned(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
}
}

Expand Down Expand Up @@ -395,6 +396,7 @@ fn get_erc20_sender_trade_preimage() {
coin: "ETH".to_owned(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
}
}

Expand Down Expand Up @@ -468,6 +470,7 @@ fn get_receiver_trade_preimage() {
coin: "ETH".to_owned(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
};

let actual = coin
Expand All @@ -492,6 +495,7 @@ fn test_get_fee_to_send_taker_fee() {
coin: "ETH".to_owned(),
amount: amount.into(),
paid_from_trading_vol: false,
tx_size: None,
};

let dex_fee_amount = u256_to_big_decimal(DEX_FEE_AMOUNT.into(), 18).expect("!u256_to_big_decimal");
Expand Down
3 changes: 3 additions & 0 deletions mm2src/coins/lightning.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1341,6 +1341,7 @@ impl MmCoin for LightningCoin {
coin: self.ticker().to_owned(),
amount: Default::default(),
paid_from_trading_vol: false,
tx_size: None,
})
}

Expand All @@ -1350,6 +1351,7 @@ impl MmCoin for LightningCoin {
coin: self.ticker().to_owned(),
amount: Default::default(),
paid_from_trading_vol: false,
tx_size: None,
}))
}

Expand All @@ -1363,6 +1365,7 @@ impl MmCoin for LightningCoin {
coin: self.ticker().to_owned(),
amount: Default::default(),
paid_from_trading_vol: false,
tx_size: None,
})
}

Expand Down
19 changes: 19 additions & 0 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1913,15 +1913,33 @@ pub trait MarketCoinOps {
fn is_trezor(&self) -> bool;
}

/// Priority levels for UTXO fee estimation for withdrawal.
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub enum UtxoFeePriority {
/// Low priority: Estimated confirmation within approximately 3 blocks.
Low,
/// Normal priority: Estimated confirmation within approximately 2 blocks.
Normal,
/// High priority: Estimated confirmation within approximately 1 block.
High,
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum WithdrawFee {
/// encapsulates the fixed fee amount for a withdrawal transaction, regardless of transaction size.
UtxoFixed {
amount: BigDecimal,
},
/// encapsulates the fee amount for a withdrawal transaction calculated based on the transaction size in kilobytes.
UtxoPerKbyte {
amount: BigDecimal,
},
/// encapsulates the priority of a withdrawal transaction, indicating the desired fee
/// level for transaction processing.
UtxoPriority {
priority: UtxoFeePriority,
},
Comment on lines +1970 to +1974
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is how I envision the GUI implementation of this part.

We present the user with the three levels of fees and let them make a choice. The GUI would potentially make three separate withdrawal requests, each using a different priority level. This would generate three different raw transaction hexes, each associated with a different fee and expected confirmation time.

Once the user selects the fee they prefer, the corresponding transaction hex would be used.

What are your thoughts on this approach? Would it be feasible to make some changes that simplifies the process for the GUI to handle this with a single request?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, here's mine view.

The api receives a priority withdrawal request from the gui, the api generates fee for the available priorities(currently 3) and send the response (each fee with it's tx hex) and finally, gui can render this three options for user to pick a choice.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The api receives a priority withdrawal request from the gui, the api generates fee for the available priorities(currently 3) and send the response (each fee with it's tx hex) and finally, gui can render this three options for user to pick a choice.

This is how I see it as well, but it might be too complicated as we would probably need to return 3 TransactionDetails objects in the response which is different from the current withdraw response.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI for eth I also added priority levels for tx fees:
For withdrawals user can add a new WithdrawFee option and set explicit fee per gas.
For swaps there is an rpc to set the desired level of low/medium/priority for the whole swap (so the API will by itself query the current fee value before each swap step).
There is also an rpc for GUI to query fees for all supported 3 levels (to show fe values to the user so he could select desired level). Initially user should start a loop in the API which periodically calculates priority fees, so the query rpc just immediately returns the recent estimated fee values.

Maybe we could do this similar both for utxo and eth.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Some explanation why a there is loop in API to obtain fees. This is how other eth wallet apps do it: API does fee estimations getting data from the eth provider. The GUI subscribes to the fee updates from API so it can in realtime notify the user about changes)

EthGas {
/// in gwei
gas_price: BigDecimal,
Expand Down Expand Up @@ -2242,6 +2260,7 @@ pub struct TradeFee {
pub coin: String,
pub amount: MmNumber,
pub paid_from_trading_vol: bool,
pub tx_size: Option<u64>,
}

/// A type alias for a HashMap where the key is a String representing the coin/token ticker,
Expand Down
43 changes: 25 additions & 18 deletions mm2src/coins/qrc20.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ use crate::utxo::tx_cache::{UtxoVerboseCacheOps, UtxoVerboseCacheShared};
use crate::utxo::utxo_builder::{UtxoCoinBuildError, UtxoCoinBuildResult, UtxoCoinBuilder, UtxoCoinBuilderCommonOps,
UtxoFieldsWithGlobalHDBuilder, UtxoFieldsWithHardwareWalletBuilder,
UtxoFieldsWithIguanaSecretBuilder};
use crate::utxo::utxo_common::{self, big_decimal_from_sat, check_all_utxo_inputs_signed_by_pub, UtxoTxBuilder};
use crate::utxo::{qtum, ActualTxFee, AdditionalTxData, AddrFromStrError, BroadcastTxErr, FeePolicy, GenerateTxError,
GetUtxoListOps, HistoryUtxoTx, HistoryUtxoTxMap, MatureUnspentList, RecentlySpentOutPointsGuard,
UnsupportedAddr, UtxoActivationParams, UtxoAddressFormat, UtxoCoinFields, UtxoCommonOps,
UtxoFromLegacyReqErr, UtxoTx, UtxoTxBroadcastOps, UtxoTxGenerationOps, VerboseTransactionFrom,
UTXO_LOCK};
use crate::utxo::utxo_common::{self, big_decimal_from_sat, check_all_utxo_inputs_signed_by_pub,
PreImageTradeFeeResult, UtxoTxBuilder};
use crate::utxo::{qtum, AdditionalTxData, AddrFromStrError, BroadcastTxErr, FeePolicy, GenerateTxError,
GetUtxoListOps, HistoryUtxoTx, HistoryUtxoTxMap, HtlcSpendFeeResult, MatureUnspentList,
RecentlySpentOutPointsGuard, UnsupportedAddr, UtxoActivationParams, UtxoAddressFormat,
UtxoCoinFields, UtxoCommonOps, UtxoFromLegacyReqErr, UtxoTx, UtxoTxBroadcastOps,
UtxoTxGenerationOps, VerboseTransactionFrom, UTXO_LOCK};
use crate::{BalanceError, BalanceFut, CheckIfMyPaymentSentArgs, CoinBalance, CoinFutSpawner, ConfirmPaymentInput,
DexFee, FeeApproxStage, FoundSwapTxSpend, HistorySyncState, IguanaPrivKey, MakerSwapTakerCoin,
MarketCoinOps, MmCoin, MmCoinEnum, NegotiateSwapContractAddrErr, PaymentInstructionArgs,
Expand Down Expand Up @@ -492,9 +493,7 @@ impl Qrc20Coin {
/// `gas_fee` should be calculated by: gas_limit * gas_price * (count of contract calls),
/// or should be sum of gas fee of all contract calls.
pub async fn get_qrc20_tx_fee(&self, gas_fee: u64) -> Result<u64, String> {
match try_s!(self.get_tx_fee().await) {
ActualTxFee::Dynamic(amount) | ActualTxFee::FixedPerKb(amount) => Ok(amount + gas_fee),
}
Ok(try_s!(self.get_tx_fee_per_kb().await) + gas_fee)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want to add a fee rate (rate per kb) to the gas fee?
Is the gas fee here a rate as well (per kb)?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

assuming that gas_fee represents the gas costs and self.get_tx_fee_per_kb() represents the per-kb costs associated with the tx size

}

/// Generate and send a transaction with the specified UTXO outputs.
Expand Down Expand Up @@ -587,7 +586,7 @@ impl Qrc20Coin {
&self,
contract_outputs: Vec<ContractCallOutput>,
stage: &FeeApproxStage,
) -> TradePreimageResult<BigDecimal> {
) -> TradePreimageResult<PreImageTradeFeeResult> {
let decimals = self.as_ref().decimals;
let mut gas_fee = 0;
let mut outputs = Vec::with_capacity(contract_outputs.len());
Expand All @@ -600,7 +599,10 @@ impl Qrc20Coin {
UtxoCommonOps::preimage_trade_fee_required_to_send_outputs(self, outputs, fee_policy, Some(gas_fee), stage)
.await?;
let gas_fee = big_decimal_from_sat(gas_fee as i64, decimals);
Ok(miner_fee + gas_fee)
Ok(PreImageTradeFeeResult {
tx_size: miner_fee.tx_size,
fee: miner_fee.fee + gas_fee,
})
}
}

Expand All @@ -617,7 +619,7 @@ impl UtxoTxBroadcastOps for Qrc20Coin {
#[cfg_attr(test, mockable)]
impl UtxoTxGenerationOps for Qrc20Coin {
/// Get only QTUM transaction fee.
async fn get_tx_fee(&self) -> UtxoRpcResult<ActualTxFee> { utxo_common::get_tx_fee(&self.utxo).await }
async fn get_tx_fee_per_kb(&self) -> UtxoRpcResult<u64> { utxo_common::get_tx_fee_per_kb(&self.utxo).await }

async fn calc_interest_if_required(
&self,
Expand Down Expand Up @@ -658,7 +660,7 @@ impl GetUtxoListOps for Qrc20Coin {
#[async_trait]
#[cfg_attr(test, mockable)]
impl UtxoCommonOps for Qrc20Coin {
async fn get_htlc_spend_fee(&self, tx_size: u64, stage: &FeeApproxStage) -> UtxoRpcResult<u64> {
async fn get_htlc_spend_fee(&self, tx_size: u64, stage: &FeeApproxStage) -> UtxoRpcResult<HtlcSpendFeeResult> {
utxo_common::get_htlc_spend_fee(self, tx_size, stage).await
}

Expand Down Expand Up @@ -723,7 +725,7 @@ impl UtxoCommonOps for Qrc20Coin {
fee_policy: FeePolicy,
gas_fee: Option<u64>,
stage: &FeeApproxStage,
) -> TradePreimageResult<BigDecimal> {
) -> TradePreimageResult<PreImageTradeFeeResult> {
utxo_common::preimage_trade_fee_required_to_send_outputs(
self,
self.platform_ticker(),
Expand Down Expand Up @@ -1357,6 +1359,7 @@ impl MmCoin for Qrc20Coin {
coin: selfi.platform.clone(),
amount: big_decimal_from_sat(fee as i64, selfi.utxo.decimals).into(),
paid_from_trading_vol: false,
tx_size: None,
})
};
Box::new(fut.boxed().compat())
Expand Down Expand Up @@ -1404,11 +1407,12 @@ impl MmCoin for Qrc20Coin {
.await?
};

let total_fee = erc20_payment_fee + sender_refund_fee;
borngraced marked this conversation as resolved.
Show resolved Hide resolved
let qrc20_payment_fee = erc20_payment_fee.fee + sender_refund_fee.fee;
Ok(TradeFee {
coin: self.platform.clone(),
amount: total_fee.into(),
amount: qrc20_payment_fee.into(),
paid_from_trading_vol: false,
tx_size: sender_refund_fee.tx_size,
})
}

Expand All @@ -1429,10 +1433,12 @@ impl MmCoin for Qrc20Coin {
let total_fee = selfi
.preimage_trade_fee_required_to_send_outputs(vec![output], &stage)
.await?;

Ok(TradeFee {
coin: selfi.platform.clone(),
amount: total_fee.into(),
amount: total_fee.fee.into(),
paid_from_trading_vol: false,
tx_size: total_fee.tx_size,
})
};
Box::new(fut.boxed().compat())
Expand All @@ -1456,8 +1462,9 @@ impl MmCoin for Qrc20Coin {

Ok(TradeFee {
coin: self.platform.clone(),
amount: total_fee.into(),
amount: total_fee.fee.into(),
paid_from_trading_vol: false,
tx_size: total_fee.tx_size,
})
}

Expand Down
Loading
Loading