1use ethers::{
2 core::rand,
3 signers::{LocalWallet, MnemonicBuilder, coins_bip39::English},
4 types::{H256, transaction::eip2718::TypedTransaction},
5 utils::{self, rlp},
6};
7
8pub fn create_wallet_from_private_key(
19 private_key: &str,
20) -> Result<LocalWallet, Box<dyn std::error::Error>> {
21 let wallet = private_key.parse::<LocalWallet>()?;
22 Ok(wallet)
23}
24
25pub fn create_random_wallet() -> LocalWallet {
27 LocalWallet::new(&mut rand::thread_rng())
28}
29
30pub fn create_wallet_from_mnemonic(
41 mnemonic: &str,
42 derivation_path: Option<&str>,
43) -> Result<LocalWallet, Box<dyn std::error::Error>> {
44 let path = derivation_path.unwrap_or("m/44'/60'/0'/0/0");
45 let wallet = MnemonicBuilder::<English>::default()
46 .phrase(mnemonic)
47 .derivation_path(path)?
48 .build()?;
49 Ok(wallet)
50}
51
52pub fn validate_signed_transaction(tx_hex: &str) -> Result<(), Box<dyn std::error::Error>> {
54 if !tx_hex.starts_with("0x") {
55 return Err("Transaction must start with 0x".into());
56 }
57 let tx_bytes = hex::decode(&tx_hex[2..])?;
58
59 if tx_bytes.len() < 1 {
60 return Err("Transaction data too short".into());
61 }
62 Ok(())
63}
64
65pub fn calculate_transaction_hash(tx_hex: &str) -> Result<H256, Box<dyn std::error::Error>> {
77 let tx_bytes = hex::decode(&tx_hex[2..])?;
78 let hash = utils::keccak256(tx_bytes);
79 Ok(H256::from_slice(&hash))
80}
81
82pub fn decode_transaction(tx_hex: &str) -> Result<TypedTransaction, Box<dyn std::error::Error>> {
84 let tx_bytes = hex::decode(&tx_hex[2..])?;
85 let rlp = rlp::Rlp::new(&tx_bytes);
86 let (tx, _signature) = TypedTransaction::decode_signed(&rlp)?;
87 Ok(tx)
88}