Skip to content

Commit

Permalink
feat(cosmos): dynamic gas price and gas limit (#1894)
Browse files Browse the repository at this point in the history
IBC and standard withdrawals for Cosmos now allow users to specify the gas price and gas limit for each transaction
---------

Signed-off-by: ozkanonur <work@onurozkan.dev>
  • Loading branch information
onur-ozkan authored Jul 5, 2023
1 parent e6bc207 commit 806ac63
Show file tree
Hide file tree
Showing 5 changed files with 93 additions and 21 deletions.
4 changes: 4 additions & 0 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1070,6 +1070,10 @@ pub enum WithdrawFee {
gas_limit: u64,
gas_price: u64,
},
CosmosGas {
gas_limit: u64,
gas_price: f64,
},
}

pub struct WithdrawSenderAddress<Address, Pubkey> {
Expand Down
3 changes: 2 additions & 1 deletion mm2src/coins/rpc_command/tendermint/ibc_withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use mm2_core::mm_ctx::MmArc;
use mm2_err_handle::prelude::MmError;
use mm2_number::BigDecimal;

use crate::{lp_coinfind_or_err, MmCoinEnum, WithdrawError, WithdrawResult};
use crate::{lp_coinfind_or_err, MmCoinEnum, WithdrawError, WithdrawFee, WithdrawResult};

#[derive(Clone, Deserialize)]
pub struct IBCWithdrawRequest {
Expand All @@ -15,6 +15,7 @@ pub struct IBCWithdrawRequest {
#[serde(default)]
pub(crate) max: bool,
pub(crate) memo: Option<String>,
pub(crate) fee: Option<WithdrawFee>,
}

pub async fn ibc_withdraw(ctx: MmArc, req: IBCWithdrawRequest) -> WithdrawResult {
Expand Down
56 changes: 42 additions & 14 deletions mm2src/coins/tendermint/tendermint_coin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::{big_decimal_from_sat_unsigned, BalanceError, BalanceFut, BigDecimal,
ValidateInstructionsErr, ValidateOtherPubKeyErr, ValidatePaymentFut, ValidatePaymentInput,
VerificationError, VerificationResult, WaitForHTLCTxSpendArgs, WatcherOps, WatcherReward,
WatcherRewardError, WatcherSearchForSwapTxSpendInput, WatcherValidatePaymentInput,
WatcherValidateTakerFeeInput, WithdrawError, WithdrawFut, WithdrawRequest};
WatcherValidateTakerFeeInput, WithdrawError, WithdrawFee, WithdrawFut, WithdrawRequest};
use async_std::prelude::FutureExt as AsyncStdFutureExt;
use async_trait::async_trait;
use bitcrypto::{dhash160, sha256};
Expand Down Expand Up @@ -582,8 +582,10 @@ impl TendermintCoin {
let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;
// >> END TX SIMULATION FOR FEE CALCULATION

let (_, gas_limit) = coin.gas_info_for_withdraw(&req.fee, IBC_GAS_LIMIT_DEFAULT);

let fee_amount_u64 = coin
.calculate_fee_amount_as_u64(msg_transfer.clone(), timeout_height, memo.clone())
.calculate_fee_amount_as_u64(msg_transfer.clone(), timeout_height, memo.clone(), req.fee)
.await?;
let fee_amount_dec = big_decimal_from_sat_unsigned(fee_amount_u64, coin.decimals());

Expand All @@ -592,7 +594,7 @@ impl TendermintCoin {
amount: fee_amount_u64.into(),
};

let fee = Fee::from_amount_and_gas(fee_amount, IBC_GAS_LIMIT_DEFAULT);
let fee = Fee::from_amount_and_gas(fee_amount, gas_limit);

let (amount_denom, total_amount) = if req.max {
if balance_denom < fee_amount_u64 {
Expand Down Expand Up @@ -654,7 +656,7 @@ impl TendermintCoin {
coin: coin.ticker.clone(),
amount: fee_amount_dec,
uamount: fee_amount_u64,
gas_limit: IBC_GAS_LIMIT_DEFAULT,
gas_limit,
})),
coin: coin.ticker.to_string(),
internal_id: hash.to_vec().into(),
Expand Down Expand Up @@ -876,6 +878,7 @@ impl TendermintCoin {
msg: Any,
timeout_height: u64,
memo: String,
withdraw_fee: Option<WithdrawFee>,
) -> MmResult<Fee, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_SIMULATE_TX_PATH).expect("valid path");

Expand Down Expand Up @@ -922,14 +925,16 @@ impl TendermintCoin {
))
})?;

let amount = ((gas.gas_used as f64 * 1.5) * self.gas_price()).ceil();
let (gas_price, gas_limit) = self.gas_info_for_withdraw(&withdraw_fee, GAS_LIMIT_DEFAULT);

let amount = ((gas.gas_used as f64 * 1.5) * gas_price).ceil();

let fee_amount = Coin {
denom: self.platform_denom().clone(),
amount: (amount as u64).into(),
};

Ok(Fee::from_amount_and_gas(fee_amount, GAS_LIMIT_DEFAULT))
Ok(Fee::from_amount_and_gas(fee_amount, gas_limit))
}

#[allow(deprecated)]
Expand All @@ -938,6 +943,7 @@ impl TendermintCoin {
msg: Any,
timeout_height: u64,
memo: String,
withdraw_fee: Option<WithdrawFee>,
) -> MmResult<u64, TendermintCoinRpcError> {
let path = AbciPath::from_str(ABCI_SIMULATE_TX_PATH).expect("valid path");

Expand Down Expand Up @@ -984,7 +990,9 @@ impl TendermintCoin {
))
})?;

Ok(((gas.gas_used as f64 * 1.5) * self.gas_price()).ceil() as u64)
let (gas_price, _) = self.gas_info_for_withdraw(&withdraw_fee, 0);

Ok(((gas.gas_used as f64 * 1.5) * gas_price).ceil() as u64)
}

pub(super) async fn my_account_info(&self) -> MmResult<BaseAccount, TendermintCoinRpcError> {
Expand Down Expand Up @@ -1222,7 +1230,8 @@ impl TendermintCoin {
coin.calculate_fee(
create_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.to_owned()
TX_DEFAULT_MEMO.to_owned(),
None
)
.await
);
Expand Down Expand Up @@ -1276,7 +1285,7 @@ impl TendermintCoin {
let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;

let fee = try_tx_s!(
coin.calculate_fee(tx_payload.clone(), timeout_height, TX_DEFAULT_MEMO.to_owned())
coin.calculate_fee(tx_payload.clone(), timeout_height, TX_DEFAULT_MEMO.to_owned(), None)
.await
);

Expand Down Expand Up @@ -1518,6 +1527,7 @@ impl TendermintCoin {
create_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.to_owned(),
None,
)
.await?;

Expand Down Expand Up @@ -1562,7 +1572,7 @@ impl TendermintCoin {
.map_err(|e| MmError::new(TradePreimageError::InternalError(e.to_string())))?;

let fee_uamount = self
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, TX_DEFAULT_MEMO.to_owned())
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, TX_DEFAULT_MEMO.to_owned(), None)
.await?;
let fee_amount = big_decimal_from_sat_unsigned(fee_uamount, decimals);

Expand Down Expand Up @@ -1726,6 +1736,17 @@ impl TendermintCoin {
unexpected_state => MmError::err(SearchForSwapTxSpendErr::UnexpectedHtlcState(unexpected_state)),
}
}

pub(crate) fn gas_info_for_withdraw(
&self,
withdraw_fee: &Option<WithdrawFee>,
fallback_gas_limit: u64,
) -> (f64, u64) {
match withdraw_fee {
Some(WithdrawFee::CosmosGas { gas_price, gas_limit }) => (*gas_price, *gas_limit),
_ => (self.gas_price(), fallback_gas_limit),
}
}
}

fn clients_from_urls(rpc_urls: &[String]) -> MmResult<Vec<HttpClient>, TendermintInitErrorKind> {
Expand Down Expand Up @@ -1858,8 +1879,10 @@ impl MmCoin for TendermintCoin {
let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;
// >> END TX SIMULATION FOR FEE CALCULATION

let (_, gas_limit) = coin.gas_info_for_withdraw(&req.fee, GAS_LIMIT_DEFAULT);

let fee_amount_u64 = coin
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, memo.clone())
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, memo.clone(), req.fee)
.await?;
let fee_amount_dec = big_decimal_from_sat_unsigned(fee_amount_u64, coin.decimals());

Expand All @@ -1868,7 +1891,7 @@ impl MmCoin for TendermintCoin {
amount: fee_amount_u64.into(),
};

let fee = Fee::from_amount_and_gas(fee_amount, GAS_LIMIT_DEFAULT);
let fee = Fee::from_amount_and_gas(fee_amount, gas_limit);

let (amount_denom, total_amount) = if req.max {
if balance_denom < fee_amount_u64 {
Expand Down Expand Up @@ -1914,6 +1937,7 @@ impl MmCoin for TendermintCoin {
.map_to_mm(|e| WithdrawError::InternalError(e.to_string()))?;

let hash = sha256(&tx_bytes);

Ok(TransactionDetails {
tx_hash: hex::encode_upper(hash.as_slice()),
tx_hex: tx_bytes.into(),
Expand All @@ -1929,7 +1953,7 @@ impl MmCoin for TendermintCoin {
coin: coin.ticker.clone(),
amount: fee_amount_dec,
uamount: fee_amount_u64,
gas_limit: GAS_LIMIT_DEFAULT,
gas_limit,
})),
coin: coin.ticker.to_string(),
internal_id: hash.to_vec().into(),
Expand Down Expand Up @@ -2325,7 +2349,8 @@ impl SwapOps for TendermintCoin {
coin.calculate_fee(
claim_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.to_owned()
TX_DEFAULT_MEMO.to_owned(),
None
)
.await
);
Expand Down Expand Up @@ -2378,6 +2403,7 @@ impl SwapOps for TendermintCoin {
claim_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.into(),
None
)
.await
);
Expand Down Expand Up @@ -2788,6 +2814,7 @@ pub mod tendermint_coin_tests {
create_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.to_owned(),
None,
)
.await
.unwrap()
Expand Down Expand Up @@ -2832,6 +2859,7 @@ pub mod tendermint_coin_tests {
claim_htlc_tx.msg_payload.clone(),
timeout_height,
TX_DEFAULT_MEMO.to_owned(),
None,
)
.await
.unwrap()
Expand Down
16 changes: 10 additions & 6 deletions mm2src/coins/tendermint/tendermint_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,10 @@ impl TendermintToken {

let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;

let (_, gas_limit) = platform.gas_info_for_withdraw(&req.fee, IBC_GAS_LIMIT_DEFAULT);

let fee_amount_u64 = platform
.calculate_fee_amount_as_u64(msg_transfer.clone(), timeout_height, memo.clone())
.calculate_fee_amount_as_u64(msg_transfer.clone(), timeout_height, memo.clone(), req.fee)
.await?;

let fee_amount_dec = big_decimal_from_sat_unsigned(fee_amount_u64, platform.decimals());
Expand All @@ -194,7 +196,7 @@ impl TendermintToken {
amount: fee_amount_u64.into(),
};

let fee = Fee::from_amount_and_gas(fee_amount, IBC_GAS_LIMIT_DEFAULT);
let fee = Fee::from_amount_and_gas(fee_amount, gas_limit);

let account_info = platform.my_account_info().await?;
let tx_raw = platform
Expand All @@ -221,7 +223,7 @@ impl TendermintToken {
coin: platform.ticker().to_string(),
amount: fee_amount_dec,
uamount: fee_amount_u64,
gas_limit: IBC_GAS_LIMIT_DEFAULT,
gas_limit,
})),
coin: token.ticker.clone(),
internal_id: hash.to_vec().into(),
Expand Down Expand Up @@ -649,8 +651,10 @@ impl MmCoin for TendermintToken {

let timeout_height = current_block + TIMEOUT_HEIGHT_DELTA;

let (_, gas_limit) = platform.gas_info_for_withdraw(&req.fee, GAS_LIMIT_DEFAULT);

let fee_amount_u64 = platform
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, memo.clone())
.calculate_fee_amount_as_u64(msg_send.clone(), timeout_height, memo.clone(), req.fee)
.await?;

let fee_amount_dec = big_decimal_from_sat_unsigned(fee_amount_u64, platform.decimals());
Expand All @@ -668,7 +672,7 @@ impl MmCoin for TendermintToken {
amount: fee_amount_u64.into(),
};

let fee = Fee::from_amount_and_gas(fee_amount, GAS_LIMIT_DEFAULT);
let fee = Fee::from_amount_and_gas(fee_amount, gas_limit);

let account_info = platform.my_account_info().await?;
let tx_raw = platform
Expand All @@ -695,7 +699,7 @@ impl MmCoin for TendermintToken {
coin: platform.ticker().to_string(),
amount: fee_amount_dec,
uamount: fee_amount_u64,
gas_limit: GAS_LIMIT_DEFAULT,
gas_limit,
})),
coin: token.ticker.clone(),
internal_id: hash.to_vec().into(),
Expand Down
35 changes: 35 additions & 0 deletions mm2src/mm2_main/tests/mm2_tests/tendermint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,41 @@ fn test_tendermint_withdraw() {
println!("Send raw tx {}", json::to_string(&send_raw_tx).unwrap());
}

#[test]
fn test_custom_gas_limit_on_tendermint_withdraw() {
let coins = json!([atom_testnet_conf()]);

let conf = Mm2TestConf::seednode(ATOM_TEST_WITHDRAW_SEED, &coins);
let mm = MarketMakerIt::start(conf.conf, conf.rpc_password, None).unwrap();

let activation_res = block_on(enable_tendermint(
&mm,
ATOM_TICKER,
&[],
ATOM_TENDERMINT_RPC_URLS,
false,
));
println!("Activation {}", json::to_string(&activation_res).unwrap());

let request = block_on(mm.rpc(&json!({
"userpass": mm.userpass,
"method": "withdraw",
"coin": ATOM_TICKER,
"to": "cosmos1svaw0aqc4584x825ju7ua03g5xtxwd0ahl86hz",
"amount": "0.1",
"fee": {
"type": "CosmosGas",
"gas_limit": 150000,
"gas_price": 0.1
}
})))
.unwrap();
assert_eq!(request.0, common::StatusCode::OK, "'withdraw' failed: {}", request.1);
let tx_details: TransactionDetails = json::from_str(&request.1).unwrap();

assert_eq!(tx_details.fee_details["gas_limit"], 150000);
}

#[test]
fn test_tendermint_ibc_withdraw() {
const IBC_SOURCE_CHANNEL: &str = "channel-81";
Expand Down

0 comments on commit 806ac63

Please sign in to comment.