//! Synchronous wrappers for async EVM client APIs for use in Rhai bindings.
//! These use block_on for native, and should be adapted for WASM as needed.

use crate::EvmClient;
use rhai::Map;

#[cfg(not(target_arch = "wasm32"))]
use tokio::runtime::Handle;

/// Synchronously get the balance using the EVM client.
#[cfg(not(target_arch = "wasm32"))]
pub fn get_balance_sync(
    evm_client: &EvmClient,
    address: ethers_core::types::Address,
) -> Result<String, String> {
    Handle::current().block_on(async {
        evm_client.get_balance(address)
            .await
            .map(|b| b.to_string())
            .map_err(|e| format!("get_balance error: {e}"))
    })
}

/// Synchronously send a transaction using the EVM client.
#[cfg(not(target_arch = "wasm32"))]
pub fn send_transaction_sync(
    evm_client: &EvmClient,
    tx: crate::provider::Transaction,
    signer: &dyn crate::signer::Signer,
) -> Result<String, String> {
    Handle::current().block_on(async {
        evm_client.send_transaction(tx, signer)
            .await
            .map(|tx| format!("0x{:x}", tx))
            .map_err(|e| format!("send_transaction error: {e}"))
    })
}
