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

[r2r] enhanced logging in spv and rpc_client mods #1594

Merged
merged 14 commits into from
Jan 13, 2023
20 changes: 14 additions & 6 deletions mm2src/coins/utxo/rpc_clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1960,7 +1960,12 @@ impl ElectrumClient {
.block_headers_storage()
.get_block_height_by_hash(blockhash.into())
.await?
.ok_or_else(|| GetTxHeightError::HeightNotFound("Transaction block header is not found in storage".into()))?
.ok_or_else(|| {
GetTxHeightError::HeightNotFound(format!(
"Transaction block header is not found in storage for {}",
self.0.coin_ticker
))
})?
.try_into()?)
}

Expand All @@ -1978,16 +1983,19 @@ impl ElectrumClient {
}
}
}
Err(GetTxHeightError::HeightNotFound(
"Couldn't find height through electrum!".into(),
))
Err(GetTxHeightError::HeightNotFound(format!(
"Couldn't find height through electrum for {}",
self.coin_ticker
)))
}

async fn block_header_from_storage(&self, height: u64) -> Result<BlockHeader, MmError<GetBlockHeaderError>> {
self.block_headers_storage()
.get_block_header(height)
.await?
.ok_or_else(|| GetBlockHeaderError::Internal("Header not in storage!".into()).into())
.ok_or_else(|| {
GetBlockHeaderError::Internal(format!("Header not found in storage for {}", self.coin_ticker)).into()
})
}

async fn block_header_from_storage_or_rpc(&self, height: u64) -> Result<BlockHeader, MmError<GetBlockHeaderError>> {
Expand Down Expand Up @@ -2030,7 +2038,7 @@ impl ElectrumClient {
.blockchain_transaction_get_merkle(tx.hash().reversed().into(), height)
.compat()
.await
.map_to_mm(|e| SPVError::UnableToGetMerkle(e.to_string()))?;
.map_to_mm(|e| SPVError::UnableToGetMerkle(format!("{e:?} for {}", self.coin_ticker)))?;
shamardy marked this conversation as resolved.
Show resolved Hide resolved

let header = self.block_header_from_storage(height).await?;

Expand Down
14 changes: 10 additions & 4 deletions mm2src/mm2_bitcoin/spv_validation/src/helpers_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ pub enum SPVError {
InsufficientWork,
#[display(fmt = "Couldn't calculate the required difficulty for the block: {}", _0)]
DifficultyCalculationError(NextBlockBitsError),
#[display(fmt = "Header {} in chain does not correctly reference parent header", _0)]
InvalidChain(u64),
#[display(fmt = "Header {height} in chain does not correctly reference parent header, coin: {coin}")]
InvalidChain { coin: String, height: u64 },
#[display(fmt = "When validating a `BitcoinHeader`, the `hash` field is not the digest of the raw header")]
WrongDigest,
#[display(
Expand Down Expand Up @@ -357,7 +357,10 @@ pub async fn validate_headers(
if previous_height == 0 {
// previous_header is genesis header in this case, checking that the first header hash is the same as the genesis header hash is enough
if header.hash() != previous_hash {
return Err(SPVError::InvalidChain(previous_height + 1));
return Err(SPVError::InvalidChain {
coin: coin.to_string(),
height: previous_height + 1,
});
}
previous_height += 1;
continue;
Expand All @@ -367,7 +370,10 @@ pub async fn validate_headers(
return Err(SPVError::UnexpectedDifficultyChange);
}
if !validate_header_prev_hash(&header.previous_header_hash, &previous_hash) {
return Err(SPVError::InvalidChain(previous_height + 1));
return Err(SPVError::InvalidChain {
coin: coin.to_string(),
height: previous_height + 1,
});
}
if let Some(algorithm) = &params.difficulty_algorithm {
if !params.constant_difficulty
Expand Down
46 changes: 29 additions & 17 deletions mm2src/mm2_main/src/lp_ordermatch/simple_market_maker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -430,12 +430,12 @@ async fn checks_order_prerequisites(
}

async fn prepare_order(
rates: RateInfos,
rates: &RateInfos,
cfg: &SimpleCoinMarketMakerCfg,
key_trade_pair: &str,
ctx: &MmArc,
) -> OrderPreparationResult {
checks_order_prerequisites(&rates, cfg, key_trade_pair).await?;
checks_order_prerequisites(rates, cfg, key_trade_pair).await?;
let base_coin = lp_coinfind(ctx, cfg.base.as_str())
.await?
.ok_or_else(|| MmError::new(OrderProcessingError::AssetNotEnabled))?;
Expand All @@ -446,7 +446,7 @@ async fn prepare_order(

debug!("balance for {} is {}", cfg.base, base_balance);

let mut calculated_price = rates.price * cfg.spread.clone();
let mut calculated_price = &rates.price * &cfg.spread;
debug!("calculated price is: {}", calculated_price);
if cfg.check_last_bidirectional_trade_thresh_hold.unwrap_or(false) {
calculated_price = vwap_calculator(calculated_price.clone(), ctx, cfg).await?;
Expand Down Expand Up @@ -495,7 +495,7 @@ async fn prepare_order(
}

async fn update_single_order(
rates: RateInfos,
rates: &RateInfos,
cfg: SimpleCoinMarketMakerCfg,
uuid: Uuid,
key_trade_pair: String,
Expand All @@ -505,7 +505,7 @@ async fn update_single_order(

let req = MakerOrderUpdateReq {
uuid,
new_price: Some(calculated_price),
new_price: Some(calculated_price.clone()),
max: is_max.into(),
volume_delta: None,
min_volume: min_vol,
Expand All @@ -518,7 +518,11 @@ async fn update_single_order(
let resp = update_maker_order(ctx, req)
.await
.map_to_mm(OrderProcessingError::OrderUpdateError)?;
info!("Successfully update order for {} - uuid: {}", key_trade_pair, resp.uuid);
info!(
"Successfully update order for {key_trade_pair} - uuid: {} - rate: ({:.4} {key_trade_pair})",
resp.uuid,
calculated_price.to_decimal()
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
);
Ok(true)
}

Expand All @@ -528,14 +532,14 @@ async fn execute_update_order(
cloned_infos: (MmArc, RateInfos, TradingPair, SimpleCoinMarketMakerCfg),
) -> bool {
let (ctx, rates, key_trade_pair, cfg) = cloned_infos;
match update_single_order(rates, cfg, uuid, key_trade_pair.as_combination(), &ctx).await {
match update_single_order(&rates, cfg.clone(), uuid, key_trade_pair.as_combination(), &ctx).await {
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
Ok(resp) => resp,
Err(err) => {
let pair = key_trade_pair.as_combination();
error!(
"Order with uuid: {} for {} cannot be updated - {}",
"Order with uuid: {} for {pair} cannot be updated - rate: ({:.} {pair}) - err: {err:?}",
order.uuid,
key_trade_pair.as_combination(),
err
rates.price.to_decimal(),
);
cancel_single_order(&ctx, order.uuid).await;
false
Expand All @@ -544,7 +548,7 @@ async fn execute_update_order(
}

async fn create_single_order(
rates: RateInfos,
rates: &RateInfos,
cfg: SimpleCoinMarketMakerCfg,
key_trade_pair: String,
ctx: MmArc,
Expand All @@ -554,7 +558,7 @@ async fn create_single_order(
let req = SetPriceReq {
base: cfg.base.clone(),
rel: cfg.rel.clone(),
price: calculated_price,
price: calculated_price.clone(),
max: is_max,
volume,
min_volume: min_vol,
Expand All @@ -569,7 +573,11 @@ async fn create_single_order(
let resp = create_maker_order(&ctx, req)
.await
.map_to_mm(OrderProcessingError::OrderUpdateError)?;
info!("Successfully placed order for {} - uuid: {}", key_trade_pair, resp.uuid);
info!(
"Successfully placed order for {key_trade_pair} - uuid: {} - rate: ({:.4} {key_trade_pair})",
resp.uuid,
calculated_price.to_decimal()
);
Ok(true)
}

Expand All @@ -579,10 +587,14 @@ async fn execute_create_single_order(
key_trade_pair: String,
ctx: &MmArc,
) -> bool {
match create_single_order(rates, cfg, key_trade_pair.clone(), ctx.clone()).await {
match create_single_order(&rates, cfg, key_trade_pair.clone(), ctx.clone()).await {
Ok(resp) => resp,
Err(err) => {
error!("{} - order cannot be created for: {}", err, key_trade_pair);
error!(
"{} - order cannot be created for: {key_trade_pair} - rate: ({:.4} {key_trade_pair})",
err,
sergeyboyko0791 marked this conversation as resolved.
Show resolved Hide resolved
rates.price.to_decimal()
);
false
},
}
Expand All @@ -601,12 +613,12 @@ async fn process_bot_logic(ctx: &MmArc) {
};
let rates_registry = match fetch_price_tickers(price_url.as_str()).await {
Ok(model) => {
info!("price successfully fetched");
info!("price successfully fetched from {price_url}");
model
},
Err(err) => {
let nb_orders = cancel_pending_orders(ctx, &cfg).await;
error!("error during fetching price: {:?} - cancel {} orders", err, nb_orders);
error!("error fetching price: {:?} - cancel {} orders", err, nb_orders);
return;
},
};
Expand Down