Skip to content

Commit

Permalink
f
Browse files Browse the repository at this point in the history
  • Loading branch information
scx1332 committed Mar 20, 2024
1 parent c97baca commit ce93d24
Show file tree
Hide file tree
Showing 11 changed files with 59 additions and 148 deletions.
80 changes: 0 additions & 80 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -187,86 +187,6 @@ jobs:
- name: Run tests (docker_03_problems)
run: cargo test --test docker_03_problems --profile=release-fast -- --test-threads=10

test_faucet:
name: Test Goerli faucet
timeout-minutes: 20

runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v3

- name: Cache dependencies
uses: Swatinem/rust-cache@v2
with:
shared-key: "dev-build-cache"

- name: Build
run: cargo build

- name: Run tests (faucet)
run: cargo run -- generate-key -n 1 > .env

- name: Check if balance is 0
run: |
[ $(cargo run -- balance -c goerli | jq -r '.[] | .gasDecimal') == "0" ]
[ $(cargo run -- balance -c goerli | jq -r '.[] | .tokenDecimal') == "0" ]
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Get ETH from faucet
run: cargo run -- get-dev-eth -c goerli
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Check ETH balance after getting funds from faucet (should be 0.01)
run: |
sleep 60 # give time for the blockchain to propagate info about the transaction
[ $(cargo run -- balance -c goerli | jq -r '.[] | .gasDecimal') == "0.01" ]
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Mint tokens
run: |
cargo run -- mint-test-tokens -c goerli
cargo run -- run
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Check token balance
run: |
[ $(cargo run -- balance -c goerli | jq -r '.[] | .tokenDecimal') == "1000" ]
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Transfer 166.6 GLM tokens
run: |
cargo run -- transfer -c goerli --recipient 0x5b984629E2Cc7570cBa7dD745b83c3dD23Ba6d0f --token glm --amount 166.6
cargo run -- run
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Transfer all GLM tokens
run: |
cargo run -- transfer -c goerli --recipient 0x5b984629E2Cc7570cBa7dD745b83c3dD23Ba6d0f --token glm --all
cargo run -- run
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Check token balance zero
run: |
[ $(cargo run -- balance -c goerli | jq -r '.[] | .tokenDecimal') == "0" ]
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

- name: Transfer all left ETH tokens
run: |
cargo run -- transfer -c goerli --recipient 0x5b984629E2Cc7570cBa7dD745b83c3dD23Ba6d0f --token eth --all
cargo run -- run
env:
GOERLI_GETH_ADDR: ${{ secrets.GOERLI_RPC_ADDRESS }}

test_faucet_holesky:
name: Test Holesky faucet
timeout-minutes: 20
Expand Down
49 changes: 26 additions & 23 deletions crates/erc20_payment_lib/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use crate::utils::{DecimalConvExt, StringConvExt, U256ConvExt};
use chrono::{DateTime, Utc};
use erc20_payment_lib_common::{
DriverEvent, DriverEventContent, FaucetData, SharedInfoTx, StatusProperty,
TransactionFailedReason, TransactionStuckReason, Web3RpcPoolContent,
TransactionStuckReason, Web3RpcPoolContent,
};
use erc20_rpc_pool::{Web3ExternalSources, Web3FullNodeData, Web3PoolType, Web3RpcPool};
use rust_decimal::prelude::FromPrimitive;
Expand Down Expand Up @@ -125,12 +125,6 @@ impl StatusTracker {
for old_property in status_props.iter_mut() {
use StatusProperty::*;
match (old_property, &new_property) {
(InvalidChainId { chain_id: id1 }, InvalidChainId { chain_id: id2 })
if id1 == id2 =>
{
return false;
}

(
CantSign {
chain_id: id1,
Expand Down Expand Up @@ -211,7 +205,6 @@ impl StatusTracker {

#[allow(clippy::match_like_matches_macro)]
status_props.retain(|s| match s {
StatusProperty::InvalidChainId { chain_id } if *chain_id == ok_chain_id => false,
StatusProperty::CantSign { chain_id, .. } if *chain_id == ok_chain_id => false,
StatusProperty::NoGas { chain_id, .. } if *chain_id == ok_chain_id => false,
StatusProperty::NoToken { chain_id, .. } if *chain_id == ok_chain_id => false,
Expand All @@ -236,14 +229,6 @@ impl StatusTracker {
while let Some(ev) = status_rx.recv().await {
let mut pass_raw_message = true;
let emit_changed = match &ev.content {
DriverEventContent::TransactionFailed(
TransactionFailedReason::InvalidChainId(chain_id),
) => Self::update(
status.lock().await.deref_mut(),
StatusProperty::InvalidChainId {
chain_id: *chain_id,
},
),
DriverEventContent::CantSign(details) => Self::update(
status.lock().await.deref_mut(),
StatusProperty::CantSign {
Expand Down Expand Up @@ -651,7 +636,11 @@ impl PaymentRuntime {
return false;
}
for chain_id in self.chains() {
log::info!("Starting service loop for account: {} and chain id: {}", payment_account.address, chain_id);
log::info!(
"Starting service loop for account: {} and chain id: {}",
payment_account.address,
chain_id
);
let jh = self.start_service_loop(
payment_account.address,
chain_id,
Expand Down Expand Up @@ -1083,9 +1072,16 @@ pub async fn mint_golem_token(
let mut db_transaction = conn.begin().await.map_err(err_from!())?;
let filter = "method=\"FAUCET.create\" AND fee_paid is NULL";

let tx_existing = get_transactions(&mut *db_transaction, Some(from), Some(filter), None, None, Some(chain_id as i64))
.await
.map_err(err_from!())?;
let tx_existing = get_transactions(
&mut *db_transaction,
Some(from),
Some(filter),
None,
None,
Some(chain_id as i64),
)
.await
.map_err(err_from!())?;

if let Some(tx) = tx_existing.first() {
return Err(err_custom_create!(
Expand Down Expand Up @@ -1469,9 +1465,16 @@ pub async fn deposit_funds(

let mut db_transaction = conn.begin().await.map_err(err_from!())?;
let filter = "method=\"LOCK.deposit\" AND fee_paid is NULL";
let tx_existing = get_transactions(&mut *db_transaction, Some(from), Some(filter), None, None, Some(chain_id as i64))
.await
.map_err(err_from!())?;
let tx_existing = get_transactions(
&mut *db_transaction,
Some(from),
Some(filter),
None,
None,
Some(chain_id as i64),
)
.await
.map_err(err_from!())?;

if let Some(tx) = tx_existing.first() {
return Err(err_custom_create!(
Expand Down
12 changes: 2 additions & 10 deletions crates/erc20_payment_lib/src/sender/batching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ use crate::{err_create, err_custom_create, err_from};
use sqlx::SqlitePool;
use tokio::sync::mpsc;

use crate::runtime::send_driver_event;
use crate::signer::SignerAccount;
use erc20_payment_lib_common::model::TokenTransferDbObj;
use erc20_payment_lib_common::{DriverEvent, DriverEventContent, TransactionFailedReason};
use erc20_payment_lib_common::DriverEvent;
use web3::types::{Address, U256};

#[derive(Eq, Hash, PartialEq, Debug, Clone)]
Expand Down Expand Up @@ -322,7 +321,7 @@ pub async fn gather_transactions_batch_multi(
}

pub async fn gather_transactions_batch(
event_sender: Option<mpsc::Sender<DriverEvent>>,
_event_sender: Option<mpsc::Sender<DriverEvent>>,
conn: &SqlitePool,
payment_setup: &PaymentSetup,
token_transfers: &mut [TokenTransferDbObj],
Expand All @@ -334,13 +333,6 @@ pub async fn gather_transactions_batch(
}

let Some(chain_setup) = payment_setup.chain_setup.get(&token_transfer.chain_id) else {
send_driver_event(
&event_sender,
DriverEventContent::TransactionFailed(TransactionFailedReason::InvalidChainId(
token_transfer.chain_id,
)),
)
.await;
return Err(err_custom_create!(
"No setup found for chain id: {}",
token_transfer.chain_id
Expand Down
9 changes: 1 addition & 8 deletions crates/erc20_payment_lib/src/sender/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use erc20_payment_lib_common::ops::{
};
use erc20_payment_lib_common::{
CantSignContent, DriverEvent, DriverEventContent, GasLowInfo, NoGasDetails,
TransactionFailedReason, TransactionStuckReason,
TransactionStuckReason,
};
use rust_decimal::prelude::Zero;
use rust_decimal::Decimal;
Expand Down Expand Up @@ -62,13 +62,6 @@ pub async fn process_transaction(
) -> Result<(TxDbObj, ProcessTransactionResult), PaymentError> {
let chain_id = web3_tx_dao.chain_id;
let Some(chain_setup) = payment_setup.chain_setup.get(&chain_id) else {
send_driver_event(
&event_sender,
DriverEventContent::TransactionFailed(TransactionFailedReason::InvalidChainId(
chain_id,
)),
)
.await;
return Ok((web3_tx_dao.clone(), ProcessTransactionResult::DoNotSave));
};

Expand Down
6 changes: 5 additions & 1 deletion crates/erc20_payment_lib/src/sender/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,11 @@ pub async fn service_loop(
let mut process_tx_needed;
let mut last_stats_time: Option<Instant> = None;
loop {
log::info!("Sender service loop - start loop chain id: {} - account: {:#x}", chain_id, account);
log::info!(
"Sender service loop - start loop chain id: {} - account: {:#x}",
chain_id,
account
);
metrics::counter!(metric_label_start, 1);
let signer_account = match shared_state
.lock()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ AND chain_id = $2
",
)
.bind(format!("{:#x}", account))
.bind(chain_id)
.bind(chain_id)
.fetch_all(conn)
.await?;
Ok(rows)
Expand Down
6 changes: 3 additions & 3 deletions crates/erc20_payment_lib_common/src/db/ops/tx_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ pub async fn get_transactions<'c, E>(
filter: Option<&str>,
limit: Option<i64>,
order: Option<&str>,
chain_id: Option<i64>
chain_id: Option<i64>,
) -> Result<Vec<TxDbObj>, sqlx::Error>
where
E: Executor<'c, Database = Sqlite>,
Expand Down Expand Up @@ -170,15 +170,15 @@ pub async fn get_next_transactions_to_process(
conn: &SqlitePool,
account: Option<Address>,
limit: i64,
chain_id: i64
chain_id: i64,
) -> Result<Vec<TxDbObj>, sqlx::Error> {
get_transactions(
conn,
account,
Some(TRANSACTION_FILTER_TO_PROCESS),
Some(limit),
Some(TRANSACTION_ORDER_BY_ID_AND_REPLACEMENT_ID),
Some(chain_id)
Some(chain_id),
)
.await
}
Expand Down
4 changes: 0 additions & 4 deletions crates/erc20_payment_lib_common/src/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,6 @@ use web3::types::Address;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum StatusProperty {
InvalidChainId {
chain_id: i64,
},
CantSign {
chain_id: i64,
address: String,
Expand Down Expand Up @@ -87,7 +84,6 @@ pub enum TransactionStuckReason {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TransactionFailedReason {
InvalidChainId(i64),
Unknown,
}

Expand Down
24 changes: 16 additions & 8 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -949,10 +949,14 @@ async fn main_internal() -> Result<(), PaymentError> {
}
}
if cleanup_options.remove_tx_stuck {
let mut transactions =
get_next_transactions_to_process(&conn.clone().unwrap(), None, 1, cleanup_options.chain_id)
.await
.map_err(err_from!())?;
let mut transactions = get_next_transactions_to_process(
&conn.clone().unwrap(),
None,
1,
cleanup_options.chain_id,
)
.await
.map_err(err_from!())?;

let Some(tx) = transactions.get_mut(0) else {
println!("No transactions found to remove");
Expand Down Expand Up @@ -980,10 +984,14 @@ async fn main_internal() -> Result<(), PaymentError> {
}
}
if cleanup_options.remove_tx_unsafe {
let mut transactions =
get_next_transactions_to_process(&conn.clone().unwrap(), None, 1, cleanup_options.chain_id)
.await
.map_err(err_from!())?;
let mut transactions = get_next_transactions_to_process(
&conn.clone().unwrap(),
None,
1,
cleanup_options.chain_id,
)
.await
.map_err(err_from!())?;

let Some(tx) = transactions.get_mut(0) else {
println!("No transactions found to remove");
Expand Down
4 changes: 1 addition & 3 deletions src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -356,9 +356,7 @@ pub struct CleanupOptions {
)]
pub remove_tx_unsafe: bool,

#[structopt(
long = "chain-id",
help = "Chain id to use")]
#[structopt(long = "chain-id", help = "Chain id to use")]
pub chain_id: i64,
}

Expand Down
11 changes: 4 additions & 7 deletions tests/docker_02_errors/wrong_chain_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use erc20_payment_lib::signer::PrivateKeySigner;
use erc20_payment_lib::transaction::create_token_transfer;
use erc20_payment_lib_common::ops::insert_token_transfer;
use erc20_payment_lib_common::utils::U256ConvExt;
use erc20_payment_lib_common::DriverEvent;
use erc20_payment_lib_common::DriverEventContent::*;
use erc20_payment_lib_common::{DriverEvent, TransactionFailedReason};
use erc20_payment_lib_test::*;
use std::str::FromStr;
use std::sync::Arc;
Expand All @@ -27,7 +27,7 @@ async fn test_wrong_chain_id() -> Result<(), anyhow::Error> {
let receiver_loop = tokio::spawn(async move {
let mut transfer_finished_message_count = 0;
let mut tx_confirmed_message_count = 0;
let mut tx_invalid_chain_id_message_count = 0;
let tx_invalid_chain_id_message_count = 0;
let mut fee_paid = U256::from(0_u128);
while let Some(msg) = receiver.recv().await {
log::info!("Received message: {:?}", msg);
Expand All @@ -42,11 +42,8 @@ async fn test_wrong_chain_id() -> Result<(), anyhow::Error> {
log::info!("Transaction stuck: {:?}", reason);
},
TransactionFailed(reason) => {
#[allow(clippy::match_single_binding)]
match reason {
TransactionFailedReason::InvalidChainId(chain_id) => {
log::info!("Invalid chain id: {chain_id}");
tx_invalid_chain_id_message_count += 1;
},
_ => {
log::error!("Unexpected transaction failed reason: {:?}", reason);
panic!("Unexpected transaction failed reason: {:?}", reason)
Expand All @@ -65,7 +62,7 @@ async fn test_wrong_chain_id() -> Result<(), anyhow::Error> {
}
}

assert!(tx_invalid_chain_id_message_count > 0);
assert!(tx_invalid_chain_id_message_count == 0);
assert_eq!(tx_confirmed_message_count, 0);
assert_eq!(transfer_finished_message_count, 0);
fee_paid
Expand Down

0 comments on commit ce93d24

Please sign in to comment.