Skip to content

Commit

Permalink
fix sleep time bug (#35)
Browse files Browse the repository at this point in the history
* fix get_latest

* add version print

* update version

* add version

* add log

* check availability

* print settigs to log

* fix get_latest_withdrawal_timestamp filter

* add x version header
  • Loading branch information
kbizikav authored Nov 14, 2024
1 parent 43c5fe6 commit 78a6889
Show file tree
Hide file tree
Showing 14 changed files with 108 additions and 53 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "mining-cli"
version = "1.1.6"
version = "1.1.7"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down
28 changes: 13 additions & 15 deletions src/external_api/contracts/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ use intmax2_zkp::{
};
use log::info;

use crate::{external_api::contracts::utils::get_latest_block_number, utils::retry::with_retry};
use crate::{
external_api::contracts::utils::{get_block, get_latest_block_number},
utils::retry::with_retry,
};

use super::{
error::BlockchainError,
Expand Down Expand Up @@ -159,7 +162,6 @@ pub async fn get_latest_deposit_timestamp(sender: Address) -> Result<Option<u64>
let int1 = get_int1_contract().await?;

let mut to_block = get_latest_block_number().await?;
let mut latest_event_block_number = None;
let int1_deployed_block = crate::utils::config::Settings::load()
.unwrap()
.blockchain
Expand All @@ -180,17 +182,15 @@ pub async fn get_latest_deposit_timestamp(sender: Address) -> Result<Option<u64>
.into_iter()
.map(|(_, meta)| meta.block_number.as_u64())
.max();
if max_block_number.is_some() {
latest_event_block_number = max_block_number;
break;
if let Some(max_block_number) = max_block_number {
let block = get_block(max_block_number).await?;
return Ok(Some(block.unwrap().timestamp.as_u64()));
}
to_block = to_block.saturating_sub(EVENT_BLOCK_RANGE);
if to_block < int1_deployed_block {
break;
return Ok(None);
}
}

Ok(latest_event_block_number)
}

pub async fn get_latest_withdrawal_timestamp(
Expand All @@ -200,7 +200,6 @@ pub async fn get_latest_withdrawal_timestamp(
let int1 = get_int1_contract().await?;

let mut to_block = get_latest_block_number().await?;
let mut latest_event_block_number = None;
let int1_deployed_block = crate::utils::config::Settings::load()
.unwrap()
.blockchain
Expand All @@ -211,7 +210,7 @@ pub async fn get_latest_withdrawal_timestamp(
.from_block(to_block.saturating_sub(EVENT_BLOCK_RANGE))
.to_block(to_block)
.address(int1.address().into())
.topic2(recipient)
.topic1(recipient)
.query_with_meta()
.await
})
Expand All @@ -221,16 +220,15 @@ pub async fn get_latest_withdrawal_timestamp(
.into_iter()
.map(|(_, meta)| meta.block_number.as_u64())
.max();
if max_block_number.is_some() {
latest_event_block_number = max_block_number;
break;
if let Some(max_block_number) = max_block_number {
let block = get_block(max_block_number).await?;
return Ok(Some(block.unwrap().timestamp.as_u64()));
}
to_block = to_block.saturating_sub(EVENT_BLOCK_RANGE);
if to_block < int1_deployed_block {
break;
return Ok(None);
}
}
Ok(latest_event_block_number)
}

#[cfg(test)]
Expand Down
18 changes: 12 additions & 6 deletions src/external_api/intmax/availability.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use log::info;
use serde::{Deserialize, Serialize};

use crate::utils::{config::Settings, retry::with_retry};
use crate::{
external_api::intmax::header::VersionHeader as _,
utils::{config::Settings, retry::with_retry},
};

use super::error::{IntmaxError, IntmaxErrorResponse};

Expand All @@ -24,11 +27,14 @@ pub async fn get_availability() -> Result<AvaliabilityServerSuccessResponse, Int
let version = env!("CARGO_PKG_VERSION");
let settings = Settings::load().unwrap();
let response = with_retry(|| async {
reqwest::get(format!(
"{}?version={}",
settings.api.availability_server_url, version,
))
.await
reqwest::Client::new()
.get(format!(
"{}?version={}",
settings.api.availability_server_url, version,
))
.with_version_header()
.send()
.await
})
.await
.map_err(|_| IntmaxError::NetworkError("failed to request availability server".to_string()))?;
Expand Down
18 changes: 12 additions & 6 deletions src/external_api/intmax/circulation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use ethers::types::Address;
use log::info;
use serde::{Deserialize, Serialize};

use crate::utils::{config::Settings, retry::with_retry};
use crate::{
external_api::intmax::header::VersionHeader as _,
utils::{config::Settings, retry::with_retry},
};

use super::error::{IntmaxError, IntmaxErrorResponse};

Expand All @@ -23,11 +26,14 @@ pub async fn get_circulation(address: Address) -> Result<CirculationSuccessRespo
info!("Getting circulation for address {:?}", address);
let settings = Settings::load().unwrap();
let response = with_retry(|| async {
reqwest::get(format!(
"{}/addresses/{:?}/exclusion",
settings.api.circulation_server_url, address,
))
.await
reqwest::Client::new()
.get(format!(
"{}/addresses/{:?}/exclusion",
settings.api.circulation_server_url, address,
))
.with_version_header()
.send()
.await
})
.await
.map_err(|_| IntmaxError::NetworkError("failed to request circulation server".to_string()))?;
Expand Down
19 changes: 13 additions & 6 deletions src/external_api/intmax/gas_estimation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use log::info;
use serde::{Deserialize, Serialize};

use crate::utils::{config::Settings, retry::with_retry};
use crate::{
external_api::intmax::header::VersionHeader as _,
utils::{config::Settings, retry::with_retry},
};

use super::error::{IntmaxError, IntmaxErrorResponse};

Expand All @@ -22,11 +25,15 @@ enum GasPriceResponse {
pub async fn get_gas_estimation() -> Result<GasPriceSuccessResponse, IntmaxError> {
info!("Getting gas price");
let settings = Settings::load().unwrap();
let response = with_retry(|| async { reqwest::get(settings.api.gas_server_url.clone()).await })
.await
.map_err(|_| {
IntmaxError::NetworkError("failed to request circulation server".to_string())
})?;
let response = with_retry(|| async {
reqwest::Client::new()
.get(settings.api.gas_server_url.clone())
.with_version_header()
.send()
.await
})
.await
.map_err(|_| IntmaxError::NetworkError("failed to request circulation server".to_string()))?;
let response_json: GasPriceResponse = response.json().await.map_err(|e| {
IntmaxError::SerializeError(format!("failed to parse response: {}", e.to_string()))
})?;
Expand Down
13 changes: 9 additions & 4 deletions src/external_api/intmax/gnark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ use plonky2::{
};
use serde::{Deserialize, Serialize};

use crate::utils::{
config::Settings,
retry::with_retry,
time::{sleep_for, sleep_until},
use crate::{
external_api::intmax::header::VersionHeader as _,
utils::{
config::Settings,
retry::with_retry,
time::{sleep_for, sleep_until},
},
};

use super::error::{IntmaxError, IntmaxErrorResponse};
Expand Down Expand Up @@ -88,6 +91,7 @@ pub async fn gnark_start_prove(
reqwest::Client::new()
.post(format!("{}/start-proof", base_url))
.json(&input)
.with_version_header()
.send()
.await
})
Expand All @@ -110,6 +114,7 @@ pub async fn gnark_get_proof(
let response = with_retry(|| async {
reqwest::Client::new()
.get(format!("{}/get-proof?jobId={}", base_url, job_id))
.with_version_header()
.send()
.await
})
Expand Down
11 changes: 11 additions & 0 deletions src/external_api/intmax/header.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
use reqwest::RequestBuilder;

pub trait VersionHeader {
fn with_version_header(self) -> Self;
}

impl VersionHeader for RequestBuilder {
fn with_version_header(self) -> Self {
self.header("X-Version", env!("CARGO_PKG_VERSION"))
}
}
1 change: 1 addition & 0 deletions src/external_api/intmax/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ pub mod error;
pub mod gas_estimation;
pub mod gnark;
pub mod withdrawal;
pub mod header;
18 changes: 14 additions & 4 deletions src/external_api/intmax/withdrawal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use serde_json::Value;
use std::str::FromStr;

use crate::{
external_api::contracts::int1::{get_int1_contract_with_signer, int_1},
external_api::{
contracts::int1::{get_int1_contract_with_signer, int_1},
intmax::header::VersionHeader as _,
},
utils::{
config::Settings,
network::{get_network, Network},
Expand Down Expand Up @@ -70,6 +73,7 @@ async fn start_withdrawal(
reqwest::Client::new()
.post(url.clone())
.json(&input)
.with_version_header()
.send()
.await
})
Expand Down Expand Up @@ -98,9 +102,15 @@ async fn query_withdrawal(withdrawal_id: &str) -> Result<QueryWithdrawalSuccess,
"{}/{}/proof-status",
settings.api.withdrawal_server_url, withdrawal_id
);
let response = with_retry(|| async { reqwest::Client::new().get(url.clone()).send().await })
.await
.map_err(|_| IntmaxError::NetworkError("failed to query withdrawal server".to_string()))?;
let response = with_retry(|| async {
reqwest::Client::new()
.get(url.clone())
.with_version_header()
.send()
.await
})
.await
.map_err(|_| IntmaxError::NetworkError("failed to query withdrawal server".to_string()))?;
let response: Value = response.json().await.map_err(|e| {
IntmaxError::SerializeError(format!(
"failed to parse response as json: {}",
Expand Down
8 changes: 7 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ async fn main() {
}

async fn set_up(is_interactive: bool) -> anyhow::Result<()> {
let version = env!("CARGO_PKG_VERSION");
println!("Mining CLI {}", version);
if is_interactive {
// select network if in interactive mode
let network = select_network()?;
Expand All @@ -79,7 +81,11 @@ async fn set_up(is_interactive: bool) -> anyhow::Result<()> {
create_config_files()?;

// check loading test
Settings::load()?;
let settings = Settings::load()?;
log::info!(
"Settings loaded: {}",
serde_json::to_string_pretty(&settings)?
);

check_avaliability().await?;
Ok(())
Expand Down
7 changes: 6 additions & 1 deletion src/services/mining/deterministic_sleep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,14 @@ pub async fn sleep_before_withdrawal(deposit_address: Address) -> anyhow::Result
}

async fn sleep_if_needed(target_time: u64, is_deposit: bool) {
log::info!(
"sleep_if_needed: target_time: {}, is_deposit: {}",
target_time,
is_deposit
);
let now = chrono::Utc::now().timestamp() as u64;
if now >= target_time {
info!("No need to sleep");
info!("No need to sleep: now={}, target_time={}", now, target_time);
return; // no need to sleep
}
let sleep_from_now = target_time - now;
Expand Down
4 changes: 2 additions & 2 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ pub async fn mining_loop(
mining_unit: U256,
mining_times: u64,
) -> anyhow::Result<()> {
check_avaliability().await?;
let key = Key::new(withdrawal_private_key, 0);
print_log(format!(
"Processing mining for deposit address {:?}",
Expand All @@ -44,6 +43,7 @@ pub async fn mining_loop(
)
.await?;
loop {
check_avaliability().await?;
let assets_status = state.sync_and_fetch_assets(&key).await?;
let is_qualified = !get_circulation(key.deposit_address).await?.is_excluded;
let will_deposit = assets_status.effective_deposit_times() < mining_times as usize
Expand Down Expand Up @@ -90,10 +90,10 @@ pub async fn mining_loop(
}

pub async fn exit_loop(state: &mut State, withdrawal_private_key: H256) -> anyhow::Result<()> {
check_avaliability().await?;
let key = Key::new(withdrawal_private_key, 0);
print_log(format!("Exit for deposit address{:?}", key.deposit_address));
loop {
check_avaliability().await?;
let assets_status = state.sync_and_fetch_assets(&key).await?;
if assets_status.pending_indices.is_empty()
&& assets_status.rejected_indices.is_empty()
Expand Down
Loading

0 comments on commit 78a6889

Please sign in to comment.