From 9bb94c5df54fa4a919e961b4e51ee23d6419245f Mon Sep 17 00:00:00 2001 From: danielSanchezQ <3danimanimal@gmail.com> Date: Tue, 3 Feb 2026 09:17:33 +0000 Subject: [PATCH] Initialize runtime automatically when needed --- wallet-ffi/src/lib.rs | 43 +++++++++++++++++------------------------ wallet-ffi/wallet_ffi.h | 12 ------------ 2 files changed, 18 insertions(+), 37 deletions(-) diff --git a/wallet-ffi/src/lib.rs b/wallet-ffi/src/lib.rs index 75032300..e7f2ce98 100644 --- a/wallet-ffi/src/lib.rs +++ b/wallet-ffi/src/lib.rs @@ -28,6 +28,8 @@ pub mod transfer; pub mod types; pub mod wallet; +use std::sync::OnceLock; + // Re-export public types for cbindgen pub use error::WalletFfiError as FfiError; use tokio::runtime::Handle; @@ -35,9 +37,23 @@ pub use types::*; use crate::error::{print_error, WalletFfiError}; +static TOKIO_RUNTIME: OnceLock = OnceLock::new(); + /// Get a reference to the global runtime. -pub(crate) fn get_runtime() -> Result { - Handle::try_current().map_err(|_| WalletFfiError::RuntimeError) +pub(crate) fn get_runtime() -> Result<&'static Handle, WalletFfiError> { + let runtime = TOKIO_RUNTIME.get_or_init(|| { + match tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + { + Ok(runtime) => runtime, + Err(e) => { + print_error(format!("{e}")); + panic!("Error initializing tokio runtime"); + } + } + }); + Ok(runtime.handle()) } /// Run an async future on the global runtime, blocking until completion. @@ -45,26 +61,3 @@ pub(crate) fn block_on(future: F) -> Result WalletFfiError { - let result = tokio::runtime::Builder::new_multi_thread() - .enable_all() - .build(); - - match result { - Ok(_) => WalletFfiError::Success, - Err(e) => { - print_error(format!("Failed to initialize runtime: {}", e)); - WalletFfiError::RuntimeError - } - } -} diff --git a/wallet-ffi/wallet_ffi.h b/wallet-ffi/wallet_ffi.h index 4786e5cc..70229e96 100644 --- a/wallet-ffi/wallet_ffi.h +++ b/wallet-ffi/wallet_ffi.h @@ -206,18 +206,6 @@ typedef struct FfiTransferResult { bool success; } FfiTransferResult; -/** - * Initialize the global Tokio runtime. - * - * This must be called before any async operations (like network calls). - * Safe to call multiple times - subsequent calls are no-ops. - * - * # Returns - * - `Success` if the runtime was initialized or already exists - * - `RuntimeError` if runtime creation failed - */ -enum WalletFfiError wallet_ffi_init_runtime(void); - /** * Create a new public account. *