Skip to content

Commit

Permalink
api
Browse files Browse the repository at this point in the history
  • Loading branch information
scx1332 committed Mar 7, 2024
1 parent 0d01e45 commit f375646
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 57 deletions.
35 changes: 8 additions & 27 deletions crates/erc20_payment_lib/src/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,24 @@ pub struct GetBalanceResult {

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AllocationDetails {
pub customer: Address,
pub struct DepositDetails {
pub funder: Address,
pub spender: Address,
pub amount: String,
pub fee_amount: String,
pub amount_decimal: rust_decimal::Decimal,
pub fee_amount_decimal: rust_decimal::Decimal,
pub block_limit: u64,
pub valid_to: chrono::DateTime<chrono::Utc>,
pub current_block: u64,
pub current_block_datetime: Option<chrono::DateTime<chrono::Utc>>,
pub estimated_time_left: Option<i64>,
pub estimated_time_left_str: Option<String>,
}

pub async fn get_allocation_details(
web3: Arc<Web3RpcPool>,
allocation_id: U256,
lock_contract_address: Address,
block_number: Option<u64>,
) -> Result<AllocationDetails, PaymentError> {
) -> Result<DepositDetails, PaymentError> {
let block_number = if let Some(block_number) = block_number {
log::debug!("Checking balance for block number {}", block_number);
block_number
Expand Down Expand Up @@ -75,23 +73,17 @@ pub async fn get_allocation_details(
}
let amount_u256 = U256::from(&res.0[(2 * 32)..(3 * 32)]);
let fee_amount_u256 = U256::from(&res.0[(3 * 32)..(4 * 32)]);

let block_no = U256::from(&res.0[(4 * 32)..(5 * 32)]);
if block_no > U256::from(u32::MAX) {
return Err(err_custom_create!("Block number too big: {}", block_no));
}
Ok(AllocationDetails {
customer: Address::from_slice(&res.0[12..32]),

Ok(DepositDetails {
funder: Address::from_slice(&res.0[12..32]),
spender: Address::from_slice(&res.0[(32 + 12)..(2 * 32)]),
amount: amount_u256.to_string(),
fee_amount: fee_amount_u256.to_string(),
block_limit: block_no.as_u64(),
current_block: block_number,
amount_decimal: amount_u256.to_eth().map_err(err_from!())?,
fee_amount_decimal: fee_amount_u256.to_eth().map_err(err_from!())?,
current_block_datetime: None,
estimated_time_left: None,
estimated_time_left_str: None,
valid_to: Default::default(),
})
}

Expand Down Expand Up @@ -197,17 +189,6 @@ pub async fn get_latest_block_info(web3: Arc<Web3RpcPool>) -> Result<Web3BlockIn
})
}

pub fn average_block_time(web3: &Web3RpcPool) -> Option<u32> {
if web3.chain_id == 1 || web3.chain_id == 5 || web3.chain_id == 17000 {
Some(12)
} else if web3.chain_id == 137 || web3.chain_id == 80001 {
Some(2)
} else if web3.chain_id == 987789 {
Some(5)
} else {
None
}
}

pub(crate) async fn get_transaction_count(
address: Address,
Expand Down
59 changes: 29 additions & 30 deletions crates/erc20_payment_lib/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::account_balance::{test_balance_loop, BalanceOptions2};
use crate::config::AdditionalOptions;
use crate::contracts::CreateAllocationArgs;
use crate::eth::{
average_block_time, get_eth_addr_from_secret, get_latest_block_info, AllocationDetails,
get_eth_addr_from_secret, get_latest_block_info, DepositDetails,
};
use crate::sender::service_loop;
use crate::utils::{DecimalConvExt, StringConvExt, U256ConvExt};
Expand Down Expand Up @@ -666,6 +666,26 @@ impl PaymentRuntime {
.await
}

pub async fn deposit_details(
&self,
chain_name: String,
allocation_id: U256,
lock_contract_address: Address,
) -> Result<DepositDetails, PaymentError> {
let chain_cfg = self
.config
.chain
.get(&chain_name)
.ok_or(err_custom_create!(
"Chain {} not found in config file",
chain_name
))?;

let web3 = self.setup.get_provider(chain_cfg.chain_id)?;

allocation_details(web3, allocation_id, lock_contract_address).await
}

pub async fn get_token_balance(
&self,
chain_name: String,
Expand Down Expand Up @@ -1086,7 +1106,7 @@ pub async fn allocation_details(
web3: Arc<Web3RpcPool>,
allocation_id: U256,
lock_contract_address: Address,
) -> Result<AllocationDetails, PaymentError> {
) -> Result<DepositDetails, PaymentError> {
let block_info = get_latest_block_info(web3.clone()).await?;

let mut result = crate::eth::get_allocation_details(
Expand All @@ -1097,33 +1117,10 @@ pub async fn allocation_details(
)
.await?;
result.current_block_datetime = Some(block_info.block_date);
if result.spender.is_zero() && result.customer.is_zero() {
if result.spender.is_zero() && result.funder.is_zero() {
return Ok(result);
}
if let Some(average_block_time) = average_block_time(&web3) {
result.estimated_time_left = Some(
(result.block_limit as i64 - result.current_block as i64) * average_block_time as i64,
);
} else {
log::info!("Unknown chain id: {} for estimation", web3.chain_id);
}
if let Some(estimated_time_left) = result.estimated_time_left {
if estimated_time_left <= 0 {
result.estimated_time_left_str = Some(format!(
"{} ago",
humantime::format_duration(std::time::Duration::from_secs(
estimated_time_left.unsigned_abs()
))
));
} else {
result.estimated_time_left_str = Some(format!(
"in {} ",
humantime::format_duration(std::time::Duration::from_secs(
estimated_time_left.unsigned_abs()
))
));
}
}

Ok(result)
}

Expand Down Expand Up @@ -1160,14 +1157,16 @@ pub async fn cancel_allocation(
opt.allocation_id
));
}
if allocation_details.customer != from {
if allocation_details.funder != from {
log::error!("You are not the owner of allocation {}", opt.allocation_id);
return Err(err_custom_create!(
"You are not the owner of allocation {}",
opt.allocation_id
));
}
if let Some(est_time_left) = allocation_details.estimated_time_left {
//TODO: check if allocation is not expired
/*
if let Some(est_time_left) = allocation_details.valid_to {
if est_time_left > 10 {
log::error!(
"Allocation {} is not ready to be cancelled. Estimated time left: {}",
Expand All @@ -1180,7 +1179,7 @@ pub async fn cancel_allocation(
est_time_left
));
}
}
}*/
}

let mut db_transaction = conn.begin().await.map_err(err_from!())?;
Expand Down

0 comments on commit f375646

Please sign in to comment.