Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions mm2src/coins/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5902,6 +5902,27 @@ impl EthCoin {
},
}
}

/// Estimated trade fee for the provided gas limit
pub async fn estimate_trade_fee(&self, gas_limit: U256, stage: FeeApproxStage) -> TradePreimageResult<TradeFee> {
let pay_for_gas_option = self
.get_swap_pay_for_gas_option(self.get_swap_gas_fee_policy().await.map_mm_err()?)
.await
.map_mm_err()?;
let pay_for_gas_option = increase_gas_price_by_stage(pay_for_gas_option, &stage);
let total_fee = calc_total_fee(gas_limit, &pay_for_gas_option).map_mm_err()?;
let amount = u256_to_big_decimal(total_fee, ETH_DECIMALS).map_mm_err()?;
let fee_coin = match &self.coin_type {
EthCoinType::Eth => &self.ticker,
EthCoinType::Erc20 { platform, .. } => platform,
EthCoinType::Nft { .. } => return MmError::err(TradePreimageError::NftProtocolNotSupported),
};
Ok(TradeFee {
coin: fee_coin.into(),
amount: amount.into(),
paid_from_trading_vol: false,
})
}
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/eth/eth_swap_v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ fn check_decoded_length(decoded: &[Token], expected_len: usize) -> Result<(), Pr
}

impl EthCoin {
async fn handle_allowance(
pub async fn handle_allowance(
&self,
swap_contract: Address,
payment_amount: U256,
Expand Down
2 changes: 1 addition & 1 deletion mm2src/coins/eth/eth_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ fn display_u256_with_point() {
}

#[test]
fn test_wei_from_big_decimal() {
fn test_u256_from_big_decimal() {
let amount = "0.000001".parse().unwrap();
let wei = u256_from_big_decimal(&amount, 18).unwrap();
let expected_wei: U256 = 1000000000000u64.into();
Expand Down
7 changes: 7 additions & 0 deletions mm2src/coins/eth/eth_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ pub(crate) mod nonce_sequencer {
}
}

#[macro_export]
macro_rules! is_eth_platform_coin {
($coin: expr) => {
matches!($coin.coin_type, EthCoinType::Eth)
};
}

pub(crate) fn get_function_input_data(decoded: &[Token], func: &Function, index: usize) -> Result<Token, String> {
decoded.get(index).cloned().ok_or(format!(
"Missing input in function {}: No input found at index {}",
Expand Down
14 changes: 7 additions & 7 deletions mm2src/coins/lp_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -496,13 +496,13 @@ pub enum GasPriceRpcParam {
#[derive(Clone, Debug, Deserialize)]
pub struct SignEthTransactionParams {
/// Eth transfer value
value: Option<BigDecimal>,
pub value: Option<BigDecimal>,
/// Eth to address
to: Option<String>,
pub to: Option<String>,
/// Eth contract data
data: Option<String>,
pub data: Option<String>,
/// Eth gas use limit
gas_limit: U256,
pub gas_limit: U256,
/// Optional gas price or fee per gas params
pub pay_for_gas: Option<GasPriceRpcParam>,
}
Expand All @@ -517,9 +517,9 @@ pub enum SignRawTransactionEnum {
/// sign_raw_transaction RPC request
#[derive(Clone, Debug, Deserialize)]
pub struct SignRawTransactionRequest {
coin: String,
pub coin: String,
#[serde(flatten)]
tx: SignRawTransactionEnum,
pub tx: SignRawTransactionEnum,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -4276,7 +4276,7 @@ impl DexFee {
}

/// Calculates the total spend amount, considering both the fee and burn amounts.
pub fn total_spend_amount(&self) -> MmNumber {
pub fn total_amount(&self) -> MmNumber {
match self {
DexFee::NoFee => 0.into(),
DexFee::Standard(t) => t.clone(),
Expand Down
5 changes: 2 additions & 3 deletions mm2src/coins/utxo/utxo_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5314,7 +5314,7 @@ where
T: UtxoCommonOps + GetUtxoListOps + SwapOps,
{
let taker_htlc_key_pair = coin.derive_htlc_key_pair(args.swap_unique_data);
let total_amount = &args.dex_fee.total_spend_amount().to_decimal() + &args.premium_amount + &args.trading_amount;
let total_amount = &args.dex_fee.total_amount().to_decimal() + &args.premium_amount + &args.trading_amount;

let SwapPaymentOutputsResult {
payment_address,
Expand Down Expand Up @@ -5406,8 +5406,7 @@ where
T: UtxoCommonOps + SwapOps,
{
let maker_htlc_key_pair = coin.derive_htlc_key_pair(args.swap_unique_data);
let total_expected_amount =
&args.dex_fee.total_spend_amount().to_decimal() + &args.premium_amount + &args.trading_amount;
let total_expected_amount = &args.dex_fee.total_amount().to_decimal() + &args.premium_amount + &args.trading_amount;

let expected_amount_sat = sat_from_big_decimal(&total_expected_amount, coin.as_ref().decimals).map_mm_err()?;

Expand Down
2 changes: 1 addition & 1 deletion mm2src/common/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1313,7 +1313,7 @@ macro_rules! push_if_some {
macro_rules! def_with_opt_param {
($var: ident, $var_type: ty) => {
$crate::paste! {
pub fn [<with_ $var>](&mut self, $var: Option<$var_type>) -> &mut Self {
pub fn [<with_ $var>](mut self, $var: Option<$var_type>) -> Self {
self.$var = $var;
self
}
Expand Down
10 changes: 8 additions & 2 deletions mm2src/mm2_main/src/database.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// The module responsible to work with SQLite database
///
//! The module responsible to work with SQLite database

pub mod my_lr_swaps;
pub mod my_orders;
pub mod my_swaps;
pub mod stats_nodes;
Expand Down Expand Up @@ -137,6 +138,10 @@ async fn migration_14(ctx: &MmArc) -> Vec<(&'static str, Vec<SqlValue>)> {
fix_maker_and_taker_pubkeys_in_stats_db(ctx).await
}

fn migration_15() -> Vec<(&'static str, Vec<SqlValue>)> {
db_common::sqlite::execute_batch(my_lr_swaps::LR_SWAP_MIGRATION)
}

async fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option<Vec<(&'static str, Vec<SqlValue>)>> {
match current_migration {
1 => Some(migration_1(ctx).await),
Expand All @@ -153,6 +158,7 @@ async fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option
12 => Some(migration_12()),
13 => Some(migration_13()),
14 => Some(migration_14(ctx).await),
15 => Some(migration_15()),
_ => None,
}
}
Expand Down
63 changes: 63 additions & 0 deletions mm2src/mm2_main/src/database/my_lr_swaps.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//! This module contains code to store swaps with LR data in the my_swaps table in MM2 SQLite DB.

#![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29

use db_common::sqlite::rusqlite::{Result as SqlResult, ToSql};
use mm2_core::mm_ctx::MmArc;

/// Adds new fields required for aggregated swaps with liquidity routing
pub const LR_SWAP_MIGRATION: &[&str] = &[
"ALTER TABLE my_swaps ADD COLUMN lr_swap_0 TEXT;",
"ALTER TABLE my_swaps ADD COLUMN sell_buy_req TEXT;",
"ALTER TABLE my_swaps ADD COLUMN lr_swap_1 TEXT;",
];

const INSERT_LR_SWAP: &str = r#"INSERT INTO my_swaps (
my_coin,
other_coin,
uuid,
started_at,
swap_type,
maker_volume,
taker_volume,
swap_version,
lr_swap_0,
sell_buy_req,
lr_swap_1
) VALUES (
:my_coin,
:other_coin,
:uuid,
:started_at,
:swap_type,
:maker_volume,
:taker_volume,
:swap_version,
:lr_swap_0,
:sell_buy_req,
:lr_swap_1
);"#;

pub(crate) fn insert_new_lr_swap(ctx: &MmArc, params: &[(&str, &dyn ToSql)]) -> SqlResult<()> {
let conn = ctx.sqlite_connection();
conn.execute(INSERT_LR_SWAP, params).map(|_| ())
}

/// The SQL query selecting swap with LR required to re-initialize the swap e.g., on restart.
/// NOTE: the 'taker_volume' db field is used as source_volume and the 'maker_volume' db field is used as destination_volume
pub(crate) const SELECT_LR_SWAP_BY_UUID: &str = r#"SELECT
my_coin,
other_coin,
uuid,
started_at,
is_finished,
events_json,
swap_version,
taker_volume,
maker_volume,
lr_swap_0,
sell_buy_req,
lr_swap_1
FROM my_swaps
WHERE uuid = :uuid;
"#;
3 changes: 2 additions & 1 deletion mm2src/mm2_main/src/database/my_swaps.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! This module contains code to work with my_swaps table in MM2 SQLite DB

#![allow(deprecated)] // TODO: remove this once rusqlite is >= 0.29

/// This module contains code to work with my_swaps table in MM2 SQLite DB
use crate::lp_swap::{MyRecentSwapsUuids, MySwapsFilter, SavedSwap, SavedSwapIo};
use common::log::debug;
use common::PagingOptions;
Expand Down
33 changes: 26 additions & 7 deletions mm2src/mm2_main/src/lp_swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,12 @@ mod my_swaps_storage;
mod pubkey_banning;
mod recreate_swap_data;
mod saved_swap;
mod swap_lock;
pub(crate) mod swap_lock;
#[path = "lp_swap/komodefi.swap_v2.pb.rs"]
#[rustfmt::skip]
mod swap_v2_pb;
pub(crate) mod swap_events;
mod swap_v2_common;
pub(crate) mod swap_v2_common;
pub(crate) mod swap_v2_rpcs;
pub(crate) mod swap_watcher;
pub(crate) mod taker_restart;
Expand All @@ -122,9 +122,12 @@ pub mod taker_swap_v2;
mod trade_preimage;

#[cfg(target_arch = "wasm32")]
mod swap_wasm_db;
pub(crate) mod swap_wasm_db;

pub use check_balance::{check_other_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult};
pub use check_balance::check_my_coin_balance_for_swap;
pub use check_balance::{
check_other_coin_balance_for_swap, CheckBalanceError, CheckBalanceResult, TakerFeeAdditionalInfo,
};
use crypto::secret_hash_algo::SecretHashAlgo;
use crypto::CryptoCtx;
use keys::{KeyPair, SECP_SIGN, SECP_VERIFY};
Expand All @@ -144,7 +147,9 @@ use swap_v2_common::{
get_unfinished_swaps_uuids, swap_kickstart_handler_for_maker, swap_kickstart_handler_for_taker, ActiveSwapV2Info,
};
use swap_v2_pb::*;
use swap_v2_rpcs::{get_maker_swap_data_for_rpc, get_swap_type, get_taker_swap_data_for_rpc};
use swap_v2_rpcs::{
get_agg_taker_swap_data_for_rpc, get_maker_swap_data_for_rpc, get_swap_type, get_taker_swap_data_for_rpc,
};
pub use swap_watcher::{
process_watcher_msg, watcher_topic, TakerSwapWatcherData, MAKER_PAYMENT_SPEND_FOUND_LOG,
MAKER_PAYMENT_SPEND_SENT_LOG, TAKER_PAYMENT_REFUND_SENT_LOG, TAKER_SWAP_ENTRY_TIMEOUT_SEC, WATCHER_PREFIX,
Expand All @@ -166,6 +171,7 @@ pub const TX_HELPER_PREFIX: TopicPrefix = "txhlp";
pub(crate) const LEGACY_SWAP_TYPE: u8 = 0;
pub(crate) const MAKER_SWAP_V2_TYPE: u8 = 1;
pub(crate) const TAKER_SWAP_V2_TYPE: u8 = 2;
pub(crate) const AGG_TAKER_SWAP_TYPE: u8 = 3;

pub(crate) const TAKER_FEE_VALIDATION_ATTEMPTS: usize = 6;
pub(crate) const TAKER_FEE_VALIDATION_RETRY_DELAY_SECS: f64 = 10.;
Expand Down Expand Up @@ -547,7 +553,7 @@ struct LockedAmountInfo {
locked_amount: LockedAmount,
}

struct SwapsContext {
pub(crate) struct SwapsContext {
running_swaps: Mutex<HashMap<Uuid, Arc<dyn AtomicSwap>>>,
active_swaps_v2_infos: Mutex<HashMap<Uuid, ActiveSwapV2Info>>,
banned_pubkeys: Mutex<TimedMap<H256Json, BanReason>>,
Expand All @@ -561,7 +567,7 @@ struct SwapsContext {

impl SwapsContext {
/// Obtains a reference to this crate context, creating it if necessary.
fn from_ctx(ctx: &MmArc) -> Result<Arc<SwapsContext>, String> {
pub(crate) fn from_ctx(ctx: &MmArc) -> Result<Arc<SwapsContext>, String> {
Ok(try_s!(from_ctx(&ctx.swaps_ctx, move || {
Ok(SwapsContext {
running_swaps: Mutex::new(HashMap::new()),
Expand Down Expand Up @@ -1136,6 +1142,12 @@ pub async fn my_swap_status(ctx: MmArc, req: Json) -> Result<Response<Vec<u8>>,
let res = try_s!(json::to_vec(&res_js));
Ok(try_s!(Response::builder().body(res)))
},
Some(AGG_TAKER_SWAP_TYPE) => {
let swap_data = try_s!(get_agg_taker_swap_data_for_rpc(&ctx, &uuid).await);
let res_js = json!({ "result": swap_data });
let res = try_s!(json::to_vec(&res_js));
Ok(try_s!(Response::builder().body(res)))
},
Some(unsupported_type) => ERR!("Got unsupported swap type from DB: {}", unsupported_type),
None => ERR!("No swap with uuid {}", uuid),
}
Expand Down Expand Up @@ -1334,6 +1346,13 @@ pub async fn my_recent_swaps_rpc(ctx: MmArc, req: Json) -> Result<Response<Vec<u
},
Err(e) => error!("Error loading a swap with the uuid '{}': {}", uuid, e),
},
AGG_TAKER_SWAP_TYPE => match get_agg_taker_swap_data_for_rpc(&ctx, uuid).await {
Ok(data) => {
let swap_json = try_s!(json::to_value(data));
swaps.push(swap_json);
},
Err(e) => error!("Error loading a swap with the uuid '{}': {}", uuid, e),
},
unknown_type => error!("Swap with the uuid '{}' has unknown type {}", uuid, unknown_type),
}
}
Expand Down
2 changes: 1 addition & 1 deletion mm2src/mm2_main/src/lp_swap/check_balance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ pub struct TakerFeeAdditionalInfo {
pub fee_to_send_dex_fee: TradeFee,
}

#[derive(Debug, Display, Serialize, SerializeErrorType)]
#[derive(Clone, Debug, Display, Serialize, SerializeErrorType)]
#[serde(tag = "error_type", content = "error_data")]
pub enum CheckBalanceError {
#[display(
Expand Down
Loading
Loading