55 lines
1.7 KiB
Rust
55 lines
1.7 KiB
Rust
//! Ethereum transaction functionality.
|
|
|
|
use ethers::prelude::*;
|
|
|
|
use crate::hero_vault::error::CryptoError;
|
|
use super::wallet::EthereumWallet;
|
|
use super::networks::NetworkConfig;
|
|
|
|
/// Formats a token balance for display.
|
|
pub fn format_balance(balance: U256, network: &NetworkConfig) -> String {
|
|
let wei = balance.as_u128();
|
|
let divisor = 10u128.pow(network.decimals as u32) as f64;
|
|
let token = wei as f64 / divisor;
|
|
|
|
// Display with the appropriate number of decimal places
|
|
let display_decimals = std::cmp::min(6, network.decimals);
|
|
|
|
format!("{:.*} {}", display_decimals as usize, token, network.token_symbol)
|
|
}
|
|
|
|
/// Gets the balance of an Ethereum address.
|
|
pub async fn get_balance(provider: &Provider<Http>, address: Address) -> Result<U256, CryptoError> {
|
|
provider.get_balance(address, None)
|
|
.await
|
|
.map_err(|e| CryptoError::SerializationError(format!("Failed to get balance: {}", e)))
|
|
}
|
|
|
|
/// Sends Ethereum from one address to another.
|
|
pub async fn send_eth(
|
|
wallet: &EthereumWallet,
|
|
provider: &Provider<Http>,
|
|
to: Address,
|
|
amount: U256,
|
|
) -> Result<H256, CryptoError> {
|
|
// Create a client with the wallet
|
|
let client = SignerMiddleware::new(
|
|
provider.clone(),
|
|
wallet.wallet.clone(),
|
|
);
|
|
|
|
// Create the transaction
|
|
let tx = TransactionRequest::new()
|
|
.to(to)
|
|
.value(amount)
|
|
.gas(21000);
|
|
|
|
// Send the transaction
|
|
let pending_tx = client.send_transaction(tx, None)
|
|
.await
|
|
.map_err(|e| CryptoError::SerializationError(format!("Failed to send transaction: {}", e)))?;
|
|
|
|
// Return the transaction hash instead of waiting for the receipt
|
|
Ok(pending_tx.tx_hash())
|
|
}
|