Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(wallet): add wallet host module with backend abstraction

Steven Enamakelb547de0d2254
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index 88dc3ebe00..b710821f95 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -135,6 +135,8 @@ pub mod voice;
#[cfg(feature = "modules")]
pub mod wallet;
#[cfg(feature = "web3")]
+pub mod wallet_backend;
+#[cfg(feature = "web3")]
mod wallet_host;
#[cfg(feature = "web3")]
pub(crate) mod wallet_service;
diff --git a/crates/openhuman-core/src/modules/wallet_backend.rs b/crates/openhuman-core/src/modules/wallet_backend.rs
new file mode 100644
index 0000000000..f188d8e96a
--- /dev/null
+++ b/crates/openhuman-core/src/modules/wallet_backend.rs
@@ -0,0 +1,92 @@
+//! The authenticated wallet-backend hook.
+//!
+//! The wallet module asks its host for three network reads/quotes (the supported
+//! routes, a swap transaction, a bridge transaction) through the
+//! `WalletBackend` callback. The core does not know who answers them: a host
+//! that has such a service registers a handler here, keyed by id, and the
+//! callback forwards to the first registered handler. With nothing registered
+//! the callback fails with the `BACKEND_UNAVAILABLE:` sentinel, exactly like a
+//! core with no hosted connection.
+//!
+//! The registry is generic: it carries a [`WalletBackendCall`] and a JSON
+//! answer and knows nothing about the service behind it.
+
+use std::future::Future;
+use std::pin::Pin;
+use std::sync::Arc;
+
+use serde_json::Value;
+
+use crate::config::Config;
+use crate::core::slots::HookSlot;
+
+/// One wallet-backend request, as the wallet module asked for it.
+#[derive(Debug, Clone, PartialEq)]
+pub enum WalletBackendCall {
+ /// The chains the backend can swap/bridge between.
+ Routes,
+ /// A single-chain swap quote and transaction for `body`.
+ SwapTransaction(Value),
+ /// A cross-chain bridge quote and transaction for `body`.
+ BridgeTransaction(Value),
+}
+
+/// The pending answer of a [`WalletBackendHandler`].
+pub type WalletBackendFuture = Pin<Box<dyn Future<Output = Result<Value, String>> + Send>>;
+
+/// A registered wallet-backend handler. It receives the loaded config so it can
+/// resolve its own endpoint and credential.
+pub type WalletBackendHandler =
+ Arc<dyn Fn(Config, WalletBackendCall) -> WalletBackendFuture + Send + Sync>;
+
+static HANDLERS: HookSlot<WalletBackendHandler> = HookSlot::new("modules::wallet_backend");
+
+/// Registers `handler` under `id` for the whole process. Re-registering an id
+/// replaces it in place.
+pub fn register_wallet_backend<F>(id: impl Into<String>, handler: F)
+where
+ F: Fn(Config, WalletBackendCall) -> WalletBackendFuture + Send + Sync + 'static,
+{
+ HANDLERS.register(id, Arc::new(handler));
+}
+
+/// Registers a handler for the context built from `extensions`.
+pub fn register_wallet_backend_in<F>(
+ extensions: &crate::core::slots::Extensions,
+ id: impl Into<String>,
+ handler: F,
+) where
+ F: Fn(Config, WalletBackendCall) -> WalletBackendFuture + Send + Sync + 'static,
+{
+ HANDLERS.register_in(extensions, id, Arc::new(handler));
+}
+
+/// Removes the process-wide handler `id`.
+pub fn unregister_wallet_backend(id: &str) -> bool {
+ HANDLERS.unregister(id)
+}
+
+/// Forwards `call` to the first registered handler, or answers with the
+/// `BACKEND_UNAVAILABLE:` sentinel when none is registered.
+pub(super) async fn call_wallet_backend(
+ config: Config,
+ call: WalletBackendCall,
+) -> Result<Value, String> {
+ match HANDLERS.first() {
+ Some(handler) => {
+ tracing::debug!("[wallet-backend] forwarding to the registered handler");
+ handler(config, call).await
+ }
+ None => {
+ tracing::debug!("[wallet-backend] no handler registered");
+ Err(format!(
+ "{}wallet backend is not available in this build",
+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
+ ))
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "wallet_backend_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/wallet_backend_tests.rs b/crates/openhuman-core/src/modules/wallet_backend_tests.rs
new file mode 100644
index 0000000000..357617c427
--- /dev/null
+++ b/crates/openhuman-core/src/modules/wallet_backend_tests.rs
@@ -0,0 +1,33 @@
+use super::*;
+use serde_json::json;
+
+#[tokio::test]
+async fn with_no_handler_the_call_answers_the_backend_unavailable_sentinel() {
+ let error = call_wallet_backend(Config::default(), WalletBackendCall::Routes)
+ .await
+ .expect_err("nothing is registered");
+ assert!(
+ error.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX),
+ "got: {error}"
+ );
+}
+
+#[tokio::test]
+async fn a_registered_handler_answers_the_call() {
+ register_wallet_backend("test-wallet-backend", |_config, call| {
+ Box::pin(async move {
+ match call {
+ WalletBackendCall::SwapTransaction(body) => Ok(json!({ "echo": body })),
+ other => Err(format!("unexpected call: {other:?}")),
+ }
+ })
+ });
+ let data = call_wallet_backend(
+ Config::default(),
+ WalletBackendCall::SwapTransaction(json!({ "chainId": 1 })),
+ )
+ .await
+ .expect("handler answers");
+ assert_eq!(data, json!({ "echo": { "chainId": 1 } }));
+ assert!(unregister_wallet_backend("test-wallet-backend"));
+}
diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs
index 8f0277ac56..655184efd3 100644
--- a/crates/openhuman-core/src/modules/wallet_host.rs
+++ b/crates/openhuman-core/src/modules/wallet_host.rs
@@ -641,14 +641,18 @@ impl WalletHost {
.load_config()
.await
.map_err(callback_error)?;
- let client =
- crate::web3::client::CryptoClient::from_config(&config).map_err(callback_error)?;
- let data = match request {
- WalletBackendRequest::Routes => client.routes().await,
- WalletBackendRequest::SwapTransaction { body } => client.swap_tx(&body).await,
- WalletBackendRequest::BridgeTransaction { body } => client.bridge_tx(&body).await,
- }
- .map_err(callback_error)?;
+ let call = match request {
+ WalletBackendRequest::Routes => super::wallet_backend::WalletBackendCall::Routes,
+ WalletBackendRequest::SwapTransaction { body } => {
+ super::wallet_backend::WalletBackendCall::SwapTransaction(body)
+ }
+ WalletBackendRequest::BridgeTransaction { body } => {
+ super::wallet_backend::WalletBackendCall::BridgeTransaction(body)
+ }
+ };
+ let data = super::wallet_backend::call_wallet_backend(config, call)
+ .await
+ .map_err(callback_error)?;
Ok(HostResponse::WalletBackend(WalletBackendResponse { data }))
}