Skip to content

Commit

Permalink
r
Browse files Browse the repository at this point in the history
  • Loading branch information
scx1332 committed Oct 23, 2023
1 parent a8f368b commit d5f68fb
Show file tree
Hide file tree
Showing 13 changed files with 141 additions and 99 deletions.
16 changes: 16 additions & 0 deletions crates/erc20_payment_lib/src/db/ops/chain_tx_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16) R
Ok(res)
}

pub async fn get_chain_txs_by_chain_id(
conn: &SqlitePool,
chain_id: i64,
limit: Option<i64>,
) -> Result<Vec<ChainTxDao>, sqlx::Error> {
let limit = limit.unwrap_or(i64::MAX);
let rows = sqlx::query_as::<_, ChainTxDao>(
r"SELECT * FROM chain_tx WHERE chain_id = $1 ORDER by id DESC LIMIT $2",
)
.bind(chain_id)
.bind(limit)
.fetch_all(conn)
.await?;
Ok(rows)
}

pub async fn get_chain_tx(conn: &SqlitePool, id: i64) -> Result<ChainTxDao, sqlx::Error> {
let row = sqlx::query_as::<_, ChainTxDao>(r"SELECT * FROM chain_tx WHERE id = $1")
.bind(id)
Expand Down
61 changes: 25 additions & 36 deletions crates/erc20_payment_lib/src/sender/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ use crate::transaction::find_receipt;
use crate::transaction::send_transaction;
use crate::transaction::sign_transaction_with_callback;
use crate::utils::{
datetime_from_u256_timestamp, get_env_bool_value, rust_dec_to_u256, u256_to_gwei,
u256_to_rust_dec,
datetime_from_u256_timestamp, get_env_bool_value, rust_dec_to_u256, u256_to_gwei, U256Ext,
};

#[derive(Debug)]
Expand Down Expand Up @@ -202,8 +201,8 @@ pub async fn process_transaction(

if new_target_gas_u256 * 11 < max_fee_per_gas * 10 {
log::warn!("Eco mode activated. Sending transaction with lower base fee. Blockchain base fee: {} Gwei, Tx base fee: {} Gwei",
u256_to_rust_dec(blockchain_gas_price, Some(9)).map_err(err_from!())?,
u256_to_rust_dec(new_target_gas_u256, Some(9)).map_err(err_from!())?,
blockchain_gas_price.to_gwei().map_err(err_from!())?,
new_target_gas_u256.to_gwei().map_err(err_from!())?,
);

web3_tx_dao.max_fee_per_gas = new_target_gas_u256.to_string();
Expand Down Expand Up @@ -243,8 +242,8 @@ pub async fn process_transaction(
msg,
chain_id,
from_addr,
u256_to_rust_dec(gas_balance, Some(18)).map_err(err_from!())?,
u256_to_rust_dec(expected_gas_balance, Some(18)).map_err(err_from!())?
gas_balance.to_eth().map_err(err_from!())?,
expected_gas_balance.to_eth().map_err(err_from!())?
);
}
}
Expand Down Expand Up @@ -282,29 +281,24 @@ pub async fn process_transaction(
if gas_balance < res {
log::warn!(
"Gas balance too low for gas {} - vs needed: {}",
u256_to_rust_dec(gas_balance, Some(18)).map_err(err_from!())?,
u256_to_rust_dec(res, Some(18)).map_err(err_from!())?
gas_balance.to_eth().map_err(err_from!())?,
res.to_eth().map_err(err_from!())?
);
send_driver_event(
&event_sender,
DriverEventContent::TransactionStuck(TransactionStuckReason::NoGas(
NoGasDetails {
tx: web3_tx_dao.clone(),
gas_balance: Some(
u256_to_rust_dec(gas_balance, Some(18))
.map_err(err_from!())?,
),
gas_needed: Some(
u256_to_rust_dec(res, Some(18)).map_err(err_from!())?,
),
gas_balance: Some(gas_balance.to_eth().map_err(err_from!())?),
gas_needed: Some(res.to_eth().map_err(err_from!())?),
},
)),
)
.await;
return Err(err_custom_create!(
"Gas balance too low for gas {} - vs needed: {}",
u256_to_rust_dec(gas_balance, Some(18)).map_err(err_from!())?,
u256_to_rust_dec(res, Some(18)).map_err(err_from!())?
gas_balance.to_eth().map_err(err_from!())?,
res.to_eth().map_err(err_from!())?
));
}
}
Expand Down Expand Up @@ -458,13 +452,11 @@ pub async fn process_transaction(
if let Some(base_fee_per_gas_u256) = block.base_fee_per_gas {
if effective_gas_price > base_fee_per_gas_u256 {
let base_fee_per_gas =
u256_to_rust_dec(base_fee_per_gas_u256, Some(9))
.unwrap_or_default();
let effective_priority_fee = u256_to_rust_dec(
effective_gas_price - base_fee_per_gas_u256,
Some(9),
)
.unwrap_or_default();
base_fee_per_gas_u256.to_gwei().unwrap_or_default();
let effective_priority_fee = (effective_gas_price
- base_fee_per_gas_u256)
.to_gwei()
.unwrap_or_default();
log::info!(
"Effective priority fee: {}",
effective_priority_fee
Expand Down Expand Up @@ -650,7 +642,7 @@ pub async fn process_transaction(
log::warn!(
"Replacement priority fee is bumped by 10% from {} to {}",
tx_pr_fee,
u256_to_rust_dec(replacement_priority_fee, Some(9)).map_err(err_from!())?
replacement_priority_fee.to_gwei().map_err(err_from!())?
);
send_replacement_tx = true;
} else {
Expand Down Expand Up @@ -755,17 +747,14 @@ pub async fn process_transaction(
if let Ok(Some(block)) =
web3.eth().block(BlockId::Number(BlockNumber::Latest)).await
{
let block_base_fee_per_gas_gwei = u256_to_rust_dec(
block.base_fee_per_gas.unwrap_or(U256::zero()),
Some(9),
)
.map_err(err_from!())?;
let tx_max_fee_per_gas_gwei = u256_to_rust_dec(
U256::from_dec_str(&web3_tx_dao.max_fee_per_gas)
.map_err(err_from!())?,
Some(9),
)
.map_err(err_from!())?;
let block_base_fee_per_gas_gwei = block
.base_fee_per_gas
.unwrap_or_default()
.to_gwei()
.map_err(err_from!())?;

let tx_max_fee_per_gas_gwei =
web3_tx_dao.max_fee_per_gas.to_gwei().map_err(err_from!())?;
let assumed_min_priority_fee_gwei = if web3_tx_dao.chain_id == 137 {
const POLYGON_MIN_PRIORITY_FEE_FOR_GAS_PRICE_CHECK: u32 = 30;
Decimal::from(POLYGON_MIN_PRIORITY_FEE_FOR_GAS_PRICE_CHECK)
Expand Down
33 changes: 31 additions & 2 deletions crates/erc20_payment_lib/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ pub fn rust_dec_to_u256(
Ok(U256::from(u128))
}

pub fn u256_to_rust_dec(
fn u256_to_rust_dec(
amount: U256,
decimals: Option<u32>,
) -> Result<rust_decimal::Decimal, ConversionError> {
Expand All @@ -140,7 +140,36 @@ pub fn u256_to_gwei(amount: U256) -> Result<Decimal, ConversionError> {
u256_to_rust_dec(amount, Some(9))
}

pub fn u256_to_eth(amount: U256) -> Result<Decimal, ConversionError> {
pub trait U256Ext {
fn to_gwei(&self) -> Result<Decimal, ConversionError>;
fn to_eth(&self) -> Result<Decimal, ConversionError>;
}
impl U256Ext for U256 {
fn to_gwei(&self) -> Result<Decimal, ConversionError> {
u256_to_gwei(*self)
}
fn to_eth(&self) -> Result<Decimal, ConversionError> {
u256_to_eth(*self)
}
}
impl U256Ext for String {
fn to_gwei(&self) -> Result<Decimal, ConversionError> {
U256::from_dec_str(self)
.map_err(|err| {
ConversionError::from(format!("Invalid string when converting: {err:?}"))
})?
.to_gwei()
}
fn to_eth(&self) -> Result<Decimal, ConversionError> {
U256::from_dec_str(self)
.map_err(|err| {
ConversionError::from(format!("Invalid string when converting: {err:?}"))
})?
.to_eth()
}
}

fn u256_to_eth(amount: U256) -> Result<Decimal, ConversionError> {
u256_to_rust_dec(amount, Some(18))
}

Expand Down
6 changes: 3 additions & 3 deletions crates/erc20_payment_lib_extra/src/account_balance.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use erc20_payment_lib::error::PaymentError;
use erc20_payment_lib::eth::get_balance;
use erc20_payment_lib::setup::PaymentSetup;
use erc20_payment_lib::utils::u256_to_rust_dec;
use erc20_payment_lib::utils::U256Ext;
use erc20_payment_lib::{config, err_custom_create};
use futures_util::{stream, StreamExt};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -124,10 +124,10 @@ pub async fn account_balance(
log::debug!("{:#x} token: {:?}", job, token_balance);
let gas_balance_decimal = balance
.gas_balance
.map(|v| u256_to_rust_dec(v, None).unwrap_or_default().to_string());
.map(|v| v.to_eth().unwrap_or_default().to_string());
let token_balance_decimal = balance
.token_balance
.map(|v| u256_to_rust_dec(v, None).unwrap_or_default().to_string());
.map(|v| v.to_eth().unwrap_or_default().to_string());
let gas_balance_human = gas_balance_decimal.clone().map(|v| {
format!(
"{:.03} {}",
Expand Down
6 changes: 3 additions & 3 deletions crates/erc20_payment_lib_test/src/durabily2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use erc20_payment_lib::misc::load_private_keys;
use erc20_payment_lib::runtime::DriverEventContent::*;
use erc20_payment_lib::runtime::{DriverEvent, PaymentRuntime};
use erc20_payment_lib::signer::PrivateKeySigner;
use erc20_payment_lib::utils::u256_to_rust_dec;
use erc20_payment_lib::utils::U256Ext;
use erc20_payment_lib_extra::{generate_test_payments, GenerateOptions};
use std::env;
use std::path::Path;
Expand Down Expand Up @@ -151,12 +151,12 @@ pub async fn test_durability2(generate_count: u64, gen_interval_secs: f64, trans
{
// *** RESULT CHECK ***
let (fee_paid_events, fee_paid_events_approve) = receiver_loop.await.unwrap();
log::info!("fee paid from events: {}", u256_to_rust_dec(fee_paid_events, None).unwrap());
log::info!("fee paid from events: {}", fee_paid_events.to_eth().unwrap());

let transfer_stats = get_transfer_stats(&conn, chain_id, None).await.unwrap();
let stats_all = transfer_stats.per_sender.iter().next().unwrap().1.all.clone();
let fee_paid_stats = stats_all.fee_paid;
log::info!("fee paid from stats: {}", u256_to_rust_dec(fee_paid_stats, None).unwrap());
log::info!("fee paid from stats: {}", fee_paid_stats.to_eth().unwrap());

assert_eq!(fee_paid_events, fee_paid_stats);

Expand Down
6 changes: 3 additions & 3 deletions crates/erc20_payment_lib_test/src/multi_erc20_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use erc20_payment_lib::misc::load_private_keys;
use erc20_payment_lib::runtime::DriverEventContent::*;
use erc20_payment_lib::runtime::{DriverEvent, PaymentRuntime};
use erc20_payment_lib::signer::PrivateKeySigner;
use erc20_payment_lib::utils::u256_to_rust_dec;
use erc20_payment_lib::utils::U256Ext;
use erc20_payment_lib_extra::{generate_test_payments, GenerateOptions};
use std::env;
use std::path::Path;
Expand Down Expand Up @@ -152,12 +152,12 @@ pub async fn test_durability(generate_count: u64, gen_interval_secs: f64, transf
{
// *** RESULT CHECK ***
let (fee_paid_events, fee_paid_events_approve) = receiver_loop.await.unwrap();
log::info!("fee paid from events: {}", u256_to_rust_dec(fee_paid_events, None).unwrap());
log::info!("fee paid from events: {}", fee_paid_events.to_eth().unwrap());

let transfer_stats = get_transfer_stats(&conn, chain_id, None).await.unwrap();
let stats_all = transfer_stats.per_sender.iter().next().unwrap().1.all.clone();
let fee_paid_stats = stats_all.fee_paid;
log::info!("fee paid from stats: {}", u256_to_rust_dec(fee_paid_stats, None).unwrap());
log::info!("fee paid from stats: {}", fee_paid_stats.to_eth().unwrap());

assert_eq!(fee_paid_events, fee_paid_stats);

Expand Down
6 changes: 2 additions & 4 deletions crates/web3_test_proxy_client/src/list_txs.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{get_calls, JSONRPCResult};
use erc20_payment_lib::utils::u256_to_rust_dec;
use erc20_payment_lib::utils::U256Ext;
use web3::types::U256;

/// List transactions captured by web3 proxy in human readable format
Expand Down Expand Up @@ -71,9 +71,7 @@ pub async fn list_transactions_human(proxy_url_base: &str, proxy_key: &str) -> V
let result = if let Some(result_int) = result_int {
result_int.to_string()
} else if let Some(result_balance) = result_balance {
u256_to_rust_dec(result_balance, Some(18))
.unwrap()
.to_string()
result_balance.to_eth().unwrap().to_string()
} else if c.method == "eth_getTransactionReceipt" {
"details?".to_string()
} else if call.status_code != 200 {
Expand Down
Loading

0 comments on commit d5f68fb

Please sign in to comment.