Skip to content

Commit

Permalink
working on deposit closing
Browse files Browse the repository at this point in the history
  • Loading branch information
scx1332 committed Mar 13, 2024
1 parent 028ec62 commit 1846024
Show file tree
Hide file tree
Showing 6 changed files with 178 additions and 74 deletions.
23 changes: 23 additions & 0 deletions crates/erc20_payment_lib/src/contracts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,17 @@ pub fn encode_deposit_transfer(
)
}

pub fn encode_deposit_transfer_and_close(
deposit_id: U256,
packed: Vec<[u8; 32]>,
) -> Result<Vec<u8>, web3::ethabi::Error> {
contract_encode(
&LOCK_CONTRACT_TEMPLATE,
"depositTransferAndClose",
(deposit_id, packed),
)
}

pub fn encode_multi_direct(
recipients: Vec<Address>,
amounts: Vec<U256>,
Expand Down Expand Up @@ -180,6 +191,18 @@ pub fn encode_payout_single(
)
}

pub fn encode_payout_single_and_close(
id: U256,
recipient: Address,
amount: U256,
) -> Result<Vec<u8>, web3::ethabi::Error> {
contract_encode(
&LOCK_CONTRACT_TEMPLATE,
"depositSingleTransferAndClose",
(id, recipient, amount),
)
}

pub fn encode_get_deposit_details(id: U256) -> Result<Vec<u8>, web3::ethabi::Error> {
contract_encode(&LOCK_CONTRACT_TEMPLATE, "getDeposit", (id,))
}
39 changes: 26 additions & 13 deletions crates/erc20_payment_lib/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use crate::signer::{Signer, SignerAccount};
use crate::transaction::{
create_faucet_mint, create_make_deposit, create_terminate_deposit,
create_token_transfer, find_receipt_extended, FindReceiptParseResult,
create_faucet_mint, create_make_deposit, create_terminate_deposit, create_token_transfer,
find_receipt_extended, FindReceiptParseResult,
};
use crate::{err_custom_create, err_from};
use erc20_payment_lib_common::create_sqlite_connection;
use erc20_payment_lib_common::ops::{cleanup_allowance_tx, cleanup_token_transfer_tx, delete_tx, get_last_unsent_tx, get_token_transfers_by_deposit_id, get_transaction_chain, get_transactions, get_unpaid_token_transfers, insert_token_transfer, insert_token_transfer_with_deposit_check, insert_tx, update_token_transfer};
use erc20_payment_lib_common::ops::{
cleanup_allowance_tx, cleanup_token_transfer_tx, delete_tx, get_last_unsent_tx,
get_token_transfers_by_deposit_id, get_transaction_chain, get_transactions,
get_unpaid_token_transfers, insert_token_transfer, insert_token_transfer_with_deposit_check,
insert_tx, update_token_transfer,
};
use std::collections::BTreeMap;
use std::ops::DerefMut;
use std::path::PathBuf;
Expand All @@ -28,6 +33,7 @@ use crate::eth::{
use crate::sender::service_loop;
use crate::utils::{DecimalConvExt, StringConvExt, U256ConvExt};
use chrono::{DateTime, Utc};
use erc20_payment_lib_common::model::TokenTransferDbObj;
use erc20_payment_lib_common::{
DriverEvent, DriverEventContent, FaucetData, SharedInfoTx, StatusProperty,
TransactionFailedReason, TransactionStuckReason, Web3RpcPoolContent,
Expand All @@ -41,7 +47,6 @@ use std::time::Duration;
use tokio::sync::{broadcast, mpsc, Mutex, Notify};
use tokio::task::{JoinError, JoinHandle};
use web3::types::{Address, H256, U256};
use erc20_payment_lib_common::model::TokenTransferDbObj;

#[derive(Debug, Clone, Serialize)]
pub struct SharedState {
Expand Down Expand Up @@ -1137,7 +1142,6 @@ pub async fn close_deposit(
from: Address,
opt: CloseDepositOptionsInt,
) -> Result<(), PaymentError> {

//let mut block_info: Option<Web3BlockInfo> = None;
if !opt.skip_deposit_check {
let deposit_details =
Expand All @@ -1158,14 +1162,20 @@ pub async fn close_deposit(

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


let current_token_transfers = get_token_transfers_by_deposit_id(&mut *db_transaction, chain_id as i64, &format!("{:#x}", opt.deposit_id))
.await
.map_err(err_from!())?;
let current_token_transfers = get_token_transfers_by_deposit_id(
&mut *db_transaction,
chain_id as i64,
&format!("{:#x}", opt.deposit_id),
)
.await
.map_err(err_from!())?;

for tt in &current_token_transfers {
if tt.deposit_finish > 0 {
return Err(err_custom_create!("Deposit {} already being closed or closed", opt.deposit_id));
return Err(err_custom_create!(
"Deposit {} already being closed or closed",
opt.deposit_id
));
}
}
let mut candidate_for_mark_close: Option<&TokenTransferDbObj> = None;
Expand All @@ -1186,7 +1196,9 @@ pub async fn close_deposit(
if let Some(tt) = candidate_for_mark_close {
let mut tt = tt.clone();
tt.deposit_finish = 1;
update_token_transfer(&mut *db_transaction, &tt).await.map_err(err_from!())?;
update_token_transfer(&mut *db_transaction, &tt)
.await
.map_err(err_from!())?;
} else {
//empty transfer is just a marker that we need deposit to be closed
let new_tt = TokenTransferDbObj {
Expand All @@ -1205,10 +1217,11 @@ pub async fn close_deposit(
fee_paid: None,
error: None,
};
insert_token_transfer(&mut *db_transaction, &new_tt).await.map_err(err_from!())?;
insert_token_transfer(&mut *db_transaction, &new_tt)
.await
.map_err(err_from!())?;
}


//let mut db_transaction = conn.begin().await.map_err(err_from!())?;
//let make_deposit_tx = insert_tx(&mut *db_transaction, &free_deposit_tx_id)
// .await
Expand Down
76 changes: 50 additions & 26 deletions crates/erc20_payment_lib/src/sender/batching.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ use erc20_payment_lib_common::ops::*;

use crate::error::{AllowanceRequest, ErrorBag, PaymentError};

use crate::transaction::{create_close_deposit, create_erc20_deposit_transfer, create_erc20_transfer, create_erc20_transfer_multi, create_erc20_transfer_multi_deposit, create_eth_transfer, MultiTransferArgs, MultiTransferDepositArgs};
use crate::transaction::{
create_close_deposit, create_erc20_deposit_transfer, create_erc20_transfer,
create_erc20_transfer_multi, create_erc20_transfer_multi_deposit, create_eth_transfer,
MultiTransferArgs, MultiTransferDepositArgs, SingleTransferDepositArgs,
};

use crate::setup::PaymentSetup;
use crate::{err_create, err_custom_create, err_from};
Expand Down Expand Up @@ -79,23 +83,29 @@ pub async fn gather_transactions_pre(
}
if let Some(deposit_id) = f.deposit_id.as_ref() {
if f.deposit_finish > 0 {
log::info!("Creating close deposit transaction for deposit id: {}", deposit_id);
log::info!(
"Creating close deposit transaction for deposit id: {}",
deposit_id
);

let deposit_id_u256 = U256::from_str(deposit_id).map_err(
|err| err_custom_create!("Invalid deposit id: {}", deposit_id),
)?;
let deposit_id_u256 = U256::from_str(deposit_id)
.map_err(|_| err_custom_create!("Invalid deposit id: {}", deposit_id))?;

let lock_contract_address = payment_setup.chain_setup.get(&f.chain_id).ok_or(err_custom_create!(
let lock_contract_address = payment_setup
.chain_setup
.get(&f.chain_id)
.ok_or(err_custom_create!(
"No setup found for chain id: {}",
f.chain_id
))?.lock_contract_address.ok_or(err_custom_create!(
))?
.lock_contract_address
.ok_or(err_custom_create!(
"Lock contract address not set for chain id: {}",
f.chain_id
))?;

let from_addr = Address::from_str(&f.from_addr).map_err(err_from!())?;


let close_deposit_tx_id = create_close_deposit(
from_addr,
lock_contract_address,
Expand All @@ -106,11 +116,15 @@ pub async fn gather_transactions_pre(

let mut transaction = conn.begin().await.map_err(err_from!())?;

let new_tx = insert_tx(&mut *transaction, &close_deposit_tx_id).await.map_err(err_from!())?;
let new_tx = insert_tx(&mut *transaction, &close_deposit_tx_id)
.await
.map_err(err_from!())?;

let mut tt = f.clone();
tt.tx_id = Some(new_tx.id);
update_token_transfer(&mut *transaction, &tt).await.map_err(err_from!())?;
update_token_transfer(&mut *transaction, &tt)
.await
.map_err(err_from!())?;

transaction.commit().await.map_err(err_from!())?;
continue;
Expand Down Expand Up @@ -233,10 +247,15 @@ pub async fn gather_transactions_batch_multi(
for smaller_order in split_orders {
let mut erc20_to = Vec::with_capacity(smaller_order.len());
let mut erc20_amounts = Vec::with_capacity(smaller_order.len());
let mut is_deposit_finish = false;
for token_t in &mut *smaller_order {
let mut sum = U256::zero();
for token_transfer in &token_t.token_transfers {
sum += U256::from_dec_str(&token_transfer.token_amount).map_err(err_from!())?;
//close deposit if needed
if token_transfer.deposit_finish > 0 {
is_deposit_finish = true;
}
}
erc20_to.push(token_t.receiver);
erc20_amounts.push(sum);
Expand Down Expand Up @@ -266,15 +285,16 @@ pub async fn gather_transactions_batch_multi(
))?;
let deposit_id = U256::from_str(deposit_id)
.map_err(|err| err_custom_create!("Invalid deposit id: {}", err))?;
create_erc20_deposit_transfer(
Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
erc20_to[0],
erc20_amounts[0],
token_transfer.chain_id as u64,
None,
lock_contract_address,
create_erc20_deposit_transfer(SingleTransferDepositArgs {
from: Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
lock_contract: lock_contract_address,
erc20_to: erc20_to[0],
erc20_amount: erc20_amounts[0],
chain_id: token_transfer.chain_id as u64,
gas_limit: None,
deposit_id,
)?
deposit_finish: is_deposit_finish,
})?
} else {
create_erc20_transfer(
Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
Expand All @@ -298,6 +318,7 @@ pub async fn gather_transactions_batch_multi(
lock_contract_address,
erc20_to.len(),
);

create_erc20_transfer_multi_deposit(MultiTransferDepositArgs {
from: Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
lock_contract: lock_contract_address,
Expand All @@ -306,6 +327,7 @@ pub async fn gather_transactions_batch_multi(
chain_id: token_transfer.chain_id as u64,
gas_limit: None,
deposit_id,
deposit_finish: is_deposit_finish,
})?
} else if let Some(multi_contract_address) = chain_setup.multi_contract_address {
log::info!(
Expand Down Expand Up @@ -392,15 +414,17 @@ pub async fn gather_transactions_batch(
let deposit_id = U256::from_str(deposit_id)
.map_err(|err| err_custom_create!("Invalid deposit id: {}", err))?;

create_erc20_deposit_transfer(
Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
Address::from_str(&token_transfer.receiver_addr).map_err(err_from!())?,
sum,
token_transfer.chain_id as u64,
None,
lock_contract_address,
let is_deposit_finish = token_transfers.iter().any(|f| f.deposit_finish > 0);
create_erc20_deposit_transfer(SingleTransferDepositArgs {
from: Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
lock_contract: lock_contract_address,
erc20_to: Address::from_str(&token_transfer.receiver_addr).map_err(err_from!())?,
erc20_amount: sum,
chain_id: token_transfer.chain_id as u64,
gas_limit: None,
deposit_id,
)?
deposit_finish: is_deposit_finish,
})?
} else {
create_erc20_transfer(
Address::from_str(&token_transfer.from_addr).map_err(err_from!())?,
Expand Down
Loading

0 comments on commit 1846024

Please sign in to comment.