The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
test(web3): probe wallet chain status hermetically
Steven Enamakel1729e0227a1a
diff --git a/crates/openhuman-core/src/web3/seams_tests.rs b/crates/openhuman-core/src/web3/seams_tests.rsindex 2e72c7e633..8cbe0fb66c 100644--- a/crates/openhuman-core/src/web3/seams_tests.rs+++ b/crates/openhuman-core/src/web3/seams_tests.rs@@ -1,6 +1,6 @@use super::*;use crate::security::approval::ApprovalChatContext;-use crate::web3::wallet::test_support::{setup_wallet_in, TEST_LOCK};+use crate::web3::wallet::test_support::{setup_wallet_in, UnreachableRpcGuard, TEST_LOCK};use crate::web3::wallet::{execute_prepared, prepare_transfer, prepared_quotes_for_test, ExecutePreparedParams,PrepareTransferParams,@@ -134,10 +134,25 @@ async fn the_accounts_seam_reports_the_stored_wallet() {assert!(status.configured);assert_eq!(status.accounts.len(), 4);- // The engine reads the same state through the seam.+ // The engine reads the same state through the seam. Every endpoint is+ // pointed at a closed loopback port, so nothing leaves the machine.+ let _endpoints = UnreachableRpcGuard::set();let rows = engine().chain_status().await.unwrap();assert_eq!(rows.len(), 9);assert!(rows.iter().all(|row| row.configured));+ // The wallet has an account for every chain, but no endpoint answers, so+ // the rows say so instead of claiming the provider is ready.+ for row in &rows {+ assert_eq!(+ row.provider_status,+ crate::web3::wallet::ProviderStatus::Missing,+ "{row:?}"+ );+ assert!(+ row.error.is_some(),+ "a failed probe carries its error: {row:?}"+ );+ }// And the endpoints it reports are the host's, not a default of the crate's.for row in &rows {let expected = match row.evm_network {diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.mdindex dbb03797a5..2ae1b62708 100644--- a/crates/openhuman-core/src/web3/wallet/README.md+++ b/crates/openhuman-core/src/web3/wallet/README.md@@ -96,7 +96,7 @@ Namespace `wallet` (method form `openhuman.wallet_<function>`), 13 controllers r| `network_defaults` | RPC/explorer/capability flags + asset catalogs per chain. || `supported_assets` | Built-in asset catalog including default EVM ERC-20s / BEP20s. || `encode_erc20_transfer` | Encode `transfer(address,uint256)` calldata (EVM only). |-| `chain_status` | Per-chain readiness + active RPC URL. |+| `chain_status` | Per-chain readiness + active RPC URL. An account's endpoint is probed (chain tip) through the transport; a failure reports `missing` with `error`. || `prepare_transfer` | Quote a native/token transfer (all four chains). || `execute_prepared` | Confirm (`confirmed: true`) and execute a quote by `quoteId` (tx send). || `tx_status` | Check a transaction's lifecycle state (pending/confirmed/failed/not_found) by hash. |diff --git a/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs b/crates/openhuman-core/src/web3/wallet/endpoints_tests.rsindex 1467c783ff..fd351fc6f3 100644--- a/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs+++ b/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs@@ -1,8 +1,9 @@use super::*;-// The variables read here are process-global. Serialise these tests so they do-// not race each other, and restore what they touched.-static ENDPOINT_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+// The variables read here are process-global. Serialise these tests (and the+// ones that repoint every endpoint) so they do not race each other, and restore+// what they touched.+use crate::web3::wallet::test_support::RPC_ENV_LOCK as ENDPOINT_ENV_LOCK;fn with_env<T>(pairs: &[(&str, Option<&str>)], f: impl FnOnce() -> T) -> T {let _guard = ENDPOINT_ENV_LOCKdiff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rsindex a44d688c40..223f2518b6 100644--- a/crates/openhuman-core/src/web3/wallet/schemas.rs+++ b/crates/openhuman-core/src/web3/wallet/schemas.rs@@ -204,7 +204,7 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema {outputs: vec![FieldSchema {name: "result",ty: TypeSchema::Json,- comment: "Array of {chain, network, chainId?, rpcUrl, rpcSource, explorerTxUrlBase, supportsBroadcast, supportsTokenTransfers, supportsContractCalls, assets[]}.",+ comment: "Array of {chain, network, chainId?, rpcUrl, rpcSource, explorerTxUrlBase, explorerTxUrlSuffix?, supportsBroadcast, supportsTokenTransfers, supportsContractCalls, assets[]}.",required: true,}],},@@ -242,12 +242,12 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema {namespace: "wallet",function: "chain_status",description:- "Per-chain readiness: whether a wallet account is derived plus the active RPC URL (default or env override).",+ "Per-chain readiness: whether a wallet account is derived, the active RPC URL (default or env override), and whether that endpoint answered a chain-tip probe.",inputs: vec![],outputs: vec![FieldSchema {name: "result",ty: TypeSchema::Json,- comment: "Array of {chain, configured, providerStatus, rpcUrl}.",+ comment: "Array of {chain, evmNetwork?, configured, providerStatus, rpcUrl, error?}. providerStatus is ready only when the endpoint answered the probe; otherwise missing, with the failure in error (absent when no account exists).",required: true,}],},diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rsindex 328a06d1d9..9b67ae1b25 100644--- a/crates/openhuman-core/src/web3/wallet/test_support.rs+++ b/crates/openhuman-core/src/web3/wallet/test_support.rs@@ -88,6 +88,63 @@ impl Drop for WorkspaceEnvGuard {}}+/// Every environment variable that overrides a wallet endpoint.+const WALLET_RPC_ENV_VARS: [&str; 9] = [+ "OPENHUMAN_WALLET_RPC_EVM",+ "OPENHUMAN_WALLET_RPC_BASE",+ "OPENHUMAN_WALLET_RPC_ARBITRUM",+ "OPENHUMAN_WALLET_RPC_OPTIMISM",+ "OPENHUMAN_WALLET_RPC_POLYGON",+ "OPENHUMAN_WALLET_RPC_BSC",+ "OPENHUMAN_WALLET_RPC_BTC",+ "OPENHUMAN_WALLET_RPC_SOLANA",+ "OPENHUMAN_WALLET_RPC_TRON",+];++/// Serialises tests that read or write the wallet endpoint variables, which are+/// process-global.+pub(crate) static RPC_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());++/// Points every wallet endpoint at a loopback port nothing listens on, so a+/// test that reaches a chain fails fast and never leaves the machine. The+/// previous values are restored on drop.+pub(crate) struct UnreachableRpcGuard {+ previous: Vec<(&'static str, Option<std::ffi::OsString>)>,+ _env_lock: std::sync::MutexGuard<'static, ()>,+}++impl UnreachableRpcGuard {+ pub(crate) fn set() -> Self {+ let env_lock = RPC_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ // Bind then drop to learn a port that is free, hence refusing.+ let port = std::net::TcpListener::bind("127.0.0.1:0")+ .and_then(|listener| listener.local_addr())+ .map_or(1, |addr| addr.port());+ let previous = WALLET_RPC_ENV_VARS+ .iter()+ .map(|name| (*name, std::env::var_os(name)))+ .collect();+ for name in WALLET_RPC_ENV_VARS {+ std::env::set_var(name, format!("http://127.0.0.1:{port}"));+ }+ Self {+ previous,+ _env_lock: env_lock,+ }+ }+}++impl Drop for UnreachableRpcGuard {+ fn drop(&mut self) {+ for (name, value) in self.previous.drain(..) {+ match value {+ Some(v) => std::env::set_var(name, v),+ None => std::env::remove_var(name),+ }+ }+ }+}+pub(crate) fn set_workspace_env_for_test(temp: &TempDir) -> WorkspaceEnvGuard {WorkspaceEnvGuard::set(temp.path())}diff --git a/tests/json_rpc_e2e.rs b/tests/json_rpc_e2e.rsindex 548fd4e489..77802d7bc4 100644--- a/tests/json_rpc_e2e.rs+++ b/tests/json_rpc_e2e.rs@@ -784,6 +784,8 @@ async fn mock_wallet_evm_rpc(}"eth_getBalance" => Value::String("0x0".to_string()),"eth_blockNumber" => Value::String("0x14".to_string()),+ // Solana's liveness probe, so one mock can stand in for every chain.+ "getHealth" => Value::String("ok".to_string()),"eth_getTransactionByHash" => {json!({"hash": params.first().cloned().unwrap_or(Value::Null)})}@@ -798,6 +800,16 @@ async fn mock_wallet_evm_rpc(Json(json!({"jsonrpc":"2.0","id":1,"result":result}))}+/// Esplora's chain-tip read, which the wallet's Bitcoin status probe uses.+async fn mock_wallet_btc_tip() -> &'static str {+ "850000"+}++/// TronGrid's latest-block read, which the wallet's Tron status probe uses.+async fn mock_wallet_tron_now_block() -> Json<Value> {+ Json(json!({"blockID": "0000000000000001", "block_header": {}}))+}+async fn start_mock_wallet_evm_rpc() -> (SocketAddr, Arc<Mutex<Vec<String>>>) {let raw_txs = Arc::new(Mutex::new(Vec::new()));let state = MockWalletRpcState {@@ -805,6 +817,8 @@ async fn start_mock_wallet_evm_rpc() -> (SocketAddr, Arc<Mutex<Vec<String>>>) {};let app = Router::new().route("/", post(mock_wallet_evm_rpc))+ .route("/blocks/tip/height", get(mock_wallet_btc_tip))+ .route("/wallet/getnowblock", post(mock_wallet_tron_now_block)).with_state(state);let (addr, _join) = serve_on_ephemeral(app).await;(addr, raw_txs)@@ -5266,9 +5280,22 @@ async fn json_rpc_wallet_execution_surface_round_trips() {"OPENHUMAN_WALLET_RPC_EVM",&format!("http://{wallet_rpc_addr}"),);- let _btc_provider_guard = EnvVarGuard::unset("OPENHUMAN_WALLET_RPC_BTC");- let _sol_provider_guard = EnvVarGuard::unset("OPENHUMAN_WALLET_RPC_SOLANA");- let _tron_provider_guard = EnvVarGuard::unset("OPENHUMAN_WALLET_RPC_TRON");+ // The same mock stands in for every other chain, so the run never reaches a+ // public endpoint: chain_status probes each one.+ let mock_endpoint = format!("http://{wallet_rpc_addr}");+ let _other_provider_guards: Vec<EnvVarGuard> = [+ "OPENHUMAN_WALLET_RPC_BASE",+ "OPENHUMAN_WALLET_RPC_ARBITRUM",+ "OPENHUMAN_WALLET_RPC_OPTIMISM",+ "OPENHUMAN_WALLET_RPC_POLYGON",+ "OPENHUMAN_WALLET_RPC_BSC",+ "OPENHUMAN_WALLET_RPC_SOLANA",+ "OPENHUMAN_WALLET_RPC_TRON",+ ]+ .into_iter()+ .map(|name| EnvVarGuard::set(name, &mock_endpoint))+ .collect();+ let _btc_provider_guard = EnvVarGuard::set("OPENHUMAN_WALLET_RPC_BTC", &mock_endpoint);let (mock_addr, mock_join) = serve_on_ephemeral(mock_upstream_router()).await;let mock_origin = format!("http://{}", mock_addr);@@ -5351,7 +5378,8 @@ async fn json_rpc_wallet_execution_surface_round_trips() {"expected default USDC token in catalog: {result}");- // chain_status: every chain is configured, so the provider row is ready.+ // chain_status: every chain is configured and its endpoint answers the+ // tip probe, so the provider row is ready and carries no error.let cs = post_json_rpc(&rpc_base, 2003, "openhuman.wallet_chain_status", json!({})).await;let body = assert_no_jsonrpc_error(&cs, "wallet_chain_status");let result = body.get("result").unwrap_or(body);@@ -5363,6 +5391,49 @@ async fn json_rpc_wallet_execution_surface_round_trips() {.all(|r| r.get("providerStatus").and_then(Value::as_str) == Some("ready")),"expected providerStatus=ready for configured chain rows: {result}");+ assert!(+ rows.iter().all(|r| r.get("error").is_none()),+ "a healthy row has no error member: {result}"+ );++ // An endpoint that cannot be reached is reported, not assumed ready: point+ // Bitcoin at a port nothing listens on and read the row again.+ let closed_port = std::net::TcpListener::bind("127.0.0.1:0")+ .expect("bind")+ .local_addr()+ .expect("addr")+ .port();+ let _dead_btc_guard = EnvVarGuard::set(+ "OPENHUMAN_WALLET_RPC_BTC",+ &format!("http://127.0.0.1:{closed_port}"),+ );+ let cs = post_json_rpc(&rpc_base, 20031, "openhuman.wallet_chain_status", json!({})).await;+ let body = assert_no_jsonrpc_error(&cs, "wallet_chain_status_unreachable");+ let result = body.get("result").unwrap_or(body);+ let rows = result.as_array().expect("chain_status array");+ let btc = rows+ .iter()+ .find(|r| r.get("chain").and_then(Value::as_str) == Some("btc"))+ .expect("btc row");+ assert_eq!(+ btc.get("providerStatus").and_then(Value::as_str),+ Some("missing"),+ "an unreachable endpoint is not ready: {btc}"+ );+ assert_eq!(btc.get("configured").and_then(Value::as_bool), Some(true));+ assert!(+ btc.get("error")+ .and_then(Value::as_str)+ .is_some_and(|e| !e.is_empty()),+ "the row carries the probe failure: {btc}"+ );+ assert_eq!(+ rows.iter()+ .filter(|r| r.get("providerStatus").and_then(Value::as_str) == Some("ready"))+ .count(),+ 8,+ "only the dead endpoint changed: {result}"+ );// balances: one row per native asset. The EVM account fans out into one// row per displayed network (Ethereum, Base, BNB Chain), so 3 EVM rows +