Skip to content

Commit

Permalink
test(withdraw): Add/improve withdraw related calls.
Browse files Browse the repository at this point in the history
  • Loading branch information
ceyhunsen committed Feb 28, 2025
1 parent f2a8e20 commit d8b4e04
Show file tree
Hide file tree
Showing 3 changed files with 105 additions and 9 deletions.
9 changes: 9 additions & 0 deletions core/src/test/common/citrea/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! # Citrea Related Utilities
use crate::config::BridgeConfig;
use alloy::sol;
use citrea_e2e::{
bitcoin::BitcoinNode,
config::{EmptyConfig, SequencerConfig},
Expand Down Expand Up @@ -41,6 +42,14 @@ pub const EVM_ADDRESSES: [&str; 10] = [
"a0Ee7A142d267C1f36714E4a8F75612F20a79720",
];

// Codegen from ABI file to interact with the contract.
sol!(
#[allow(missing_docs)]
#[sol(rpc)]
BRIDGE_CONTRACT,
"src/test/common/citrea/Bridge.json"
);

/// Starts typical nodes with typical configs for a test that needs Citrea.
pub async fn start_citrea(
sequencer_config: SequencerConfig,
Expand Down
56 changes: 53 additions & 3 deletions core/src/test/common/citrea/requests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::errors::BridgeError;
use crate::test::common::citrea::parameters::get_deposit_params;
use crate::EVMAddress;
use alloy::consensus::constants::{ETH_TO_WEI, GWEI_TO_WEI};
use bitcoin::hashes::Hash;
use bitcoin::{Block, Transaction, Txid};
use jsonrpsee::core::client::ClientT;
Expand Down Expand Up @@ -61,6 +62,41 @@ pub async fn eth_get_balance(
Ok(ret)
}

pub async fn eth_get_transaction_count(
client: HttpClient,
evm_address: EVMAddress,
) -> Result<u128, BridgeError> {
let params = rpc_params![evm_address.0, "latest"];

let response: String = client.request("eth_getTransactionCount", params).await?;
let ret = u128::from_str_radix(&response[2..], 16)
.map_err(|e| BridgeError::Error(format!("Can't convert hex to int: {}", e)))?;

Ok(ret)
}

pub async fn get_withdrawal_count(client: HttpClient) -> Result<u32, BridgeError> {
let params = rpc_params![
json!({
"to": CITREA_ADDRESS,
"data": "0x781952a8"
}),
"latest"
];

let response: String = client.request("eth_call", params).await?;

let decoded_hex = hex::decode(&response[2..]).map_err(|e| BridgeError::Error(e.to_string()))?;
let block_number = decoded_hex
.iter()
.rev()
.take(4)
.rev()
.fold(0u32, |acc, &byte| (acc << 8) | byte as u32);

Ok(block_number)
}

pub async fn deposit(
client: HttpClient,
block: Block,
Expand Down Expand Up @@ -109,15 +145,27 @@ pub async fn declare_withdraw_filler(

pub async fn withdraw(
client: HttpClient,
from_address: &str,
withdrawal_txid: Txid,
withdrawal_index: u32,
withdrawal_amount: u64,
gas: u64,
gas_price: u128,
nonce: u128,
) -> Result<(), BridgeError> {
let withdrawal_amount = withdrawal_amount as u128 * ETH_TO_WEI;
let gas_price = gas_price * GWEI_TO_WEI as u128;

let params = rpc_params![
json!({
"from": from_address,
"to": CITREA_ADDRESS,
"data": format!("0x8786dba7{}{}", hex::encode(withdrawal_txid.as_byte_array()), hex::encode(withdrawal_index.to_be_bytes())),
"value": format!("0x{}", withdrawal_amount.to_string())
"value": format!("0x{}", hex::encode(withdrawal_amount.to_be_bytes())),
"gas": gas * 2,
"gasPrice": format!("0x{}", hex::encode(gas_price.to_be_bytes())),
"chainId": 5655, // TODO: Accept as parameter
"nonce": nonce
}),
"latest"
];
Expand All @@ -140,10 +188,12 @@ pub async fn withdrawal_utxos(
}),
"latest"
];
let response: String = client.request("eth_call", params).await?;
let response: String = client.request("eth_call", params).await.unwrap();

let txid_str_slice = &response[2..66];
let txid = hex::decode(txid_str_slice).map_err(|e| BridgeError::Error(e.to_string()))?;
let txid = hex::decode(txid_str_slice)
.map_err(|e| BridgeError::Error(e.to_string()))
.unwrap();
// txid.reverse(); // TODO: we should need to reverse this, test this with declareWithdrawalFiller

Ok(Txid::from_slice(&txid)?)
Expand Down
49 changes: 43 additions & 6 deletions core/src/test/withdraw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ impl TestCase for CitreaWithdraw {
config.protocol_paramset().bridge_amount.to_sat()
- 2 * config.operator_withdrawal_fee_sats.unwrap().to_sat(),
);
let (_withdrawal_tx, _withdrawal_tx_signature) =
let (withdrawal_tx, _withdrawal_tx_signature) =
generate_withdrawal_transaction_and_signature(
&config,
&rpc,
Expand All @@ -125,25 +125,62 @@ impl TestCase for CitreaWithdraw {
let alice = primitives::Address::from_str(EVM_ADDRESSES[0]).unwrap();
let bob = primitives::Address::from_str(EVM_ADDRESSES[1]).unwrap();

let tx = TransactionRequest::default()
let nonce =
citrea::eth_get_transaction_count(sequencer.client.http_client().clone(), evm_address)
.await
.unwrap();

let tx_req = TransactionRequest::default()
.with_from(alice)
.with_to(bob)
.with_nonce(0)
.with_nonce(nonce.try_into().unwrap())
.with_chain_id(chain_id)
.with_value(U256::from(withdrawal_amount.to_sat()))
.with_max_priority_fee_per_gas(10)
.with_max_fee_per_gas(1000000001);
let gas = provider.estimate_gas(&tx).await.unwrap();
let req = tx.gas_limit(gas);
let gas = provider.estimate_gas(&tx_req).await.unwrap();
let gas_price = provider.get_gas_price().await.unwrap();
let tx_req = tx_req.gas_limit(gas);
tracing::info!("Gas: {}, gas price: {}", gas, gas_price);

let call_set_value_req = provider.send_transaction(req).await.unwrap();
let call_set_value_req = provider.send_transaction(tx_req).await.unwrap();
let tx_hash = call_set_value_req
.get_receipt()
.await
.unwrap()
.transaction_hash;
tracing::info!("EVM tx hash: {:?}", tx_hash);

let balance_after =
citrea::eth_get_balance(sequencer.client.http_client().clone(), evm_address)
.await
.unwrap();
assert_ne!(balance, balance_after);

assert_eq!(
citrea::get_withdrawal_count(sequencer.client.http_client().clone())
.await
.unwrap(),
0
);

let nonce =
citrea::eth_get_transaction_count(sequencer.client.http_client().clone(), evm_address)
.await
.unwrap();
citrea::withdraw(
sequencer.client.http_client().clone(),
EVM_ADDRESSES[0],
*withdrawal_tx.get_txid(),
0,
withdrawal_amount.to_sat(),
gas,
gas_price,
nonce,
)
.await
.unwrap();

Ok(())
}
}
Expand Down

0 comments on commit d8b4e04

Please sign in to comment.