refactor: Refactor keypair and Ethereum wallet handling
Some checks are pending
Rhai Tests / Run Rhai Tests (push) Waiting to run

- Moved `prepare_function_arguments` and `convert_token_to_rhai` to the `ethereum` module for better organization.
- Updated `keypair` module to use the new `session_manager` structure improving code clarity.
- Changed `KeyPair` type usage to new `vault::keyspace::keypair_types::KeyPair` for consistency.
- Improved error handling and clarity in `EthereumWallet` methods.
This commit is contained in:
Mahmoud Emad 2025-05-13 13:55:04 +03:00
parent a4438d63e0
commit 25f2ae6fa9
2 changed files with 43 additions and 31 deletions

View File

@ -11,8 +11,8 @@ use std::str::FromStr;
use std::sync::Mutex;
use tokio::runtime::Runtime;
use crate::vault::ethereum::contract_utils::{convert_token_to_rhai, prepare_function_arguments};
use crate::vault::{ethereum, keypair};
use crate::vault::ethereum;
use crate::vault::keyspace::session_manager as keypair;
use crate::vault::symmetric::implementation as symmetric_impl;
// Global Tokio runtime for blocking async operations
@ -83,7 +83,7 @@ fn load_key_space(name: &str, password: &str) -> bool {
}
fn create_key_space(name: &str, password: &str) -> bool {
match keypair::session_manager::create_space(name) {
match keypair::create_space(name) {
Ok(_) => {
// Get the current space
match keypair::get_current_space() {
@ -763,7 +763,7 @@ fn call_contract_read(contract_json: &str, function_name: &str, args: rhai::Arra
};
// Prepare the arguments
let tokens = match prepare_function_arguments(&contract.abi, function_name, &args) {
let tokens = match ethereum::prepare_function_arguments(&contract.abi, function_name, &args) {
Ok(tokens) => tokens,
Err(e) => {
log::error!("Error preparing arguments: {}", e);
@ -793,7 +793,7 @@ fn call_contract_read(contract_json: &str, function_name: &str, args: rhai::Arra
match rt.block_on(async {
ethereum::call_read_function(&contract, &provider, function_name, tokens).await
}) {
Ok(result) => convert_token_to_rhai(&result),
Ok(result) => ethereum::convert_token_to_rhai(&result),
Err(e) => {
log::error!("Failed to call contract function: {}", e);
Dynamic::UNIT
@ -818,7 +818,7 @@ fn call_contract_write(contract_json: &str, function_name: &str, args: rhai::Arr
};
// Prepare the arguments
let tokens = match prepare_function_arguments(&contract.abi, function_name, &args) {
let tokens = match ethereum::prepare_function_arguments(&contract.abi, function_name, &args) {
Ok(tokens) => tokens,
Err(e) => {
log::error!("Error preparing arguments: {}", e);

View File

@ -4,12 +4,12 @@ use ethers::prelude::*;
use ethers::signers::{LocalWallet, Signer, Wallet};
use ethers::utils::hex;
use k256::ecdsa::SigningKey;
use sha2::{Digest, Sha256};
use std::str::FromStr;
use sha2::{Sha256, Digest};
use crate::vault::error::CryptoError;
use crate::vault::keypair::KeyPair;
use super::networks::NetworkConfig;
use crate::vault;
use crate::vault::error::CryptoError;
/// An Ethereum wallet derived from a keypair.
#[derive(Debug, Clone)]
@ -21,91 +21,103 @@ pub struct EthereumWallet {
impl EthereumWallet {
/// Creates a new Ethereum wallet from a keypair for a specific network.
pub fn from_keypair(keypair: &KeyPair, network: NetworkConfig) -> Result<Self, CryptoError> {
pub fn from_keypair(
keypair: &vault::keyspace::keypair_types::KeyPair,
network: NetworkConfig,
) -> Result<Self, CryptoError> {
// Get the private key bytes from the keypair
let private_key_bytes = keypair.signing_key.to_bytes();
// Convert to a hex string (without 0x prefix)
let private_key_hex = hex::encode(private_key_bytes);
// Create an Ethereum wallet from the private key
let wallet = LocalWallet::from_str(&private_key_hex)
.map_err(|_e| CryptoError::InvalidKeyLength)?
.with_chain_id(network.chain_id);
// Get the Ethereum address
let address = wallet.address();
Ok(EthereumWallet {
address,
wallet,
network,
})
}
/// Creates a new Ethereum wallet from a name and keypair (deterministic derivation) for a specific network.
pub fn from_name_and_keypair(name: &str, keypair: &KeyPair, network: NetworkConfig) -> Result<Self, CryptoError> {
pub fn from_name_and_keypair(
name: &str,
keypair: &vault::keyspace::keypair_types::KeyPair,
network: NetworkConfig,
) -> Result<Self, CryptoError> {
// Get the private key bytes from the keypair
let private_key_bytes = keypair.signing_key.to_bytes();
// Create a deterministic seed by combining name and private key
let mut hasher = Sha256::default();
hasher.update(name.as_bytes());
hasher.update(&private_key_bytes);
let seed = hasher.finalize();
// Use the seed as a private key
let private_key_hex = hex::encode(seed);
// Create an Ethereum wallet from the derived private key
let wallet = LocalWallet::from_str(&private_key_hex)
.map_err(|_e| CryptoError::InvalidKeyLength)?
.with_chain_id(network.chain_id);
// Get the Ethereum address
let address = wallet.address();
Ok(EthereumWallet {
address,
wallet,
network,
})
}
/// Creates a new Ethereum wallet from a private key for a specific network.
pub fn from_private_key(private_key: &str, network: NetworkConfig) -> Result<Self, CryptoError> {
pub fn from_private_key(
private_key: &str,
network: NetworkConfig,
) -> Result<Self, CryptoError> {
// Remove 0x prefix if present
let private_key_clean = private_key.trim_start_matches("0x");
// Create an Ethereum wallet from the private key
let wallet = LocalWallet::from_str(private_key_clean)
.map_err(|_e| CryptoError::InvalidKeyLength)?
.with_chain_id(network.chain_id);
// Get the Ethereum address
let address = wallet.address();
Ok(EthereumWallet {
address,
wallet,
network,
})
}
/// Gets the Ethereum address as a string.
pub fn address_string(&self) -> String {
format!("{:?}", self.address)
}
/// Signs a message with the Ethereum wallet.
pub async fn sign_message(&self, message: &[u8]) -> Result<String, CryptoError> {
let signature = self.wallet.sign_message(message)
let signature = self
.wallet
.sign_message(message)
.await
.map_err(|e| CryptoError::SignatureFormatError(e.to_string()))?;
Ok(signature.to_string())
}
/// Gets the private key as a hex string.
pub fn private_key_hex(&self) -> String {
let bytes = self.wallet.signer().to_bytes();