Skip to content

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

refactor(web3): move wallet, swap, bridge, dapp and x402 logic into tinywallet

Steven Enamakelbcf53ec46057
diff --git a/AGENTS.md b/AGENTS.md
index 563748e470..3d77d5a215 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -478,7 +478,7 @@ Direct rendered submodules under `vendor/`:
| `tinysearch` | Web-search module, provider dispatch, tool declarations, and execution behind its TinyBus contract. |
| `tinyskills` | Host-independent skill/workflow bundle parsing, discovery, scope resolution, resource inventory, and safe reads. OpenHuman owns trust and execution policy. |
| `tinyvoice` | Host-agnostic voice primitives such as audio framing, VAD, wake-word gating, routing, and STT hallucination detection. |
-| `tinywallet` | Pure multi-chain wallet primitives such as address formats, validation, and encoding conversions; no key custody or transaction broadcast. |
+| `tinywallet` | Multi-chain wallet: `tinywallet-crypto` (address, asset, chain, `rpc::Transport`, tx codec), `tinywallet-x402` (x402 wire, payment, spending ledger, `x402_request` tool), `tinywallet-web3` (wallet engine, per-chain build/sign/broadcast flows, swap/bridge/dapp quotes, agent tools) behind host seams (`WalletSigner`, `PaymentSigner`, `WalletAccounts`, `RpcEndpoints`, `QuoteScope`, `Web3Backend`, `ProxyPolicy`), and the loadable `tinywallet-module` that derives keys and signs. OpenHuman keeps keyring, consent, credentials, config, controllers and the seam impls under `web3/`. |
| `motosan-ai-oauth` | Provider-agnostic PKCE OAuth login and token-refresh primitives. |
Some rendered submodules are shared dependencies nested inside those projects,
@@ -510,7 +510,7 @@ method constants, request and response types, and its contract version.
| `tinyvoice-bus` | `voice` |
| `tinyjuice-bus` | inference kernel |
| `tinyruntime-bus` | runtime clients |
-| `tinywallet-bus` | `web3` |
+| `tinywallet-bus` | `web3` (contract; the chain primitives are in `tinywallet-crypto`) |
| `tinymcp-bus` | `mcp` |
| `tinychannels-bus` | channel vocabulary |
| `tinyconnectors-bus` | OAuth connector (Composio) wire contract; called through `integrations/composio/module_client.rs` |
diff --git a/Cargo.lock b/Cargo.lock
index 333b11fbe3..6da9b9af77 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3853,7 +3853,6 @@ dependencies = [
"chrono-tz",
"cpal",
"cron",
- "curve25519-dalek",
"directories",
"dirs 6.0.0",
"dotenvy",
@@ -3938,6 +3937,8 @@ dependencies = [
"tinyvoice-bus",
"tinywallet",
"tinywallet-bus",
+ "tinywallet-web3",
+ "tinywallet-x402",
"tokio",
"tokio-stream",
"tokio-tungstenite 0.29.0",
@@ -6882,12 +6883,23 @@ dependencies = [
"sha3 0.12.0",
"thiserror 2.0.20",
"tinywallet-bus",
+ "tinywallet-crypto",
+ "tinywallet-x402",
"zeroize",
]
[[package]]
name = "tinywallet-bus"
version = "0.5.3"
+dependencies = [
+ "serde",
+ "tinywallet-crypto",
+ "tinywallet-x402",
+]
+
+[[package]]
+name = "tinywallet-crypto"
+version = "0.5.3"
dependencies = [
"async-trait",
"bech32 0.12.0",
@@ -6900,6 +6912,50 @@ dependencies = [
"thiserror 2.0.20",
]
+[[package]]
+name = "tinywallet-web3"
+version = "0.5.3"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "base64 0.22.1",
+ "bs58",
+ "curve25519-dalek",
+ "hex",
+ "log",
+ "parking_lot",
+ "serde",
+ "serde_json",
+ "sha2 0.11.0",
+ "tinytools 0.4.1",
+ "tinywallet-bus",
+ "tinywallet-crypto",
+ "tinywallet-x402",
+]
+
+[[package]]
+name = "tinywallet-x402"
+version = "0.5.3"
+dependencies = [
+ "anyhow",
+ "async-trait",
+ "base64 0.22.1",
+ "bs58",
+ "chrono",
+ "curve25519-dalek",
+ "hex",
+ "log",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "sha2 0.11.0",
+ "sha3 0.12.0",
+ "thiserror 2.0.20",
+ "tinytools 0.4.1",
+ "tinywallet-crypto",
+ "uuid",
+]
+
[[package]]
name = "tokio"
version = "1.53.1"
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index c852d2f18d..35c4214184 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -469,8 +469,6 @@ starship-battery = { version = "0.10", optional = true }
# - bs58: Solana base58 addresses + Tron base58check addresses.
ed25519-dalek = { version = "2", default-features = false, features = ["std", "rand_core"] }
bs58 = { version = "0.5", default-features = false, features = ["std", "check"] }
-# Solana off-curve check for ATA derivation (find_program_address).
-curve25519-dalek = { version = "4", default-features = false, features = ["alloc"], optional = true }
# The WhatsApp Web provider (and its `whatsapp-rust` / `wacore` / `serde-big-array`
# stack) now lives in the tinychannels crate; the `whatsapp-web` feature forwards
@@ -609,6 +607,14 @@ tinyhosts = { path = "../../vendor/tinyhosts", default-features = false, feature
# derive a known account. Dev-dependency features are not linked into the
# shipped binary, so that does not undo the shed.
tinywallet-bus = { path = "../../vendor/tinywallet/crates/tinywallet-bus", default-features = false, features = ["btc", "evm", "solana", "tron", "keccak", "net", "wire", "eip712", "abi", "tx-codec"], optional = true }
+# The x402 payment flow (402 challenge, EVM/Solana payment builders, the
+# spending ledger, the `x402_request` tool), moved out of `web3/x402`. The host
+# keeps signing, proxy policy and RPC controllers and hands them in as seams.
+tinywallet-x402 = { path = "../../vendor/tinywallet/crates/tinywallet-x402", default-features = false, features = ["wire", "pay", "ledger", "tools"], optional = true }
+# The wallet engine and the swap/bridge/dapp service, moved out of `web3/`.
+# The host implements its seams (signer, accounts, RPC endpoints, quote scope,
+# backend) and keeps the controllers, keyring and consent.
+tinywallet-web3 = { path = "../../vendor/tinywallet/crates/tinywallet-web3", default-features = false, features = ["tools"], optional = true }
# secp256k1 signing over the digests the wallet module hands back. Pure Rust,
# and already in the graph beneath `coins-bip32` (which derives the key being
@@ -906,9 +912,9 @@ voice = [
# surface, and the x402 machine-payment protocol. Default-ON — the desktop app
# always ships with the wallet. Slim / headless builds opt out via
# `--no-default-features --features "<explicit list without web3>"`, which
-# drops the exclusive `bitcoin` (P2WPKH PSBT) + `curve25519-dalek` (Solana
-# off-curve ATA) + `ethers-core` / `ethers-signers` / `coins-bip39` (EVM/mnemonic
-# signing, used by the multi-chain wallet's EVM path) dependencies. Composes
+# drops the exclusive `bitcoin` (P2WPKH PSBT) + `ethers-core` / `ethers-signers`
+# / `coins-bip39` (EVM/mnemonic signing, used by the multi-chain wallet's EVM
+# path) dependencies. Composes
# with the runtime `DomainSet::Web3` flag (#4796): the feature narrows the
# compile-time surface, `DomainSet` gates it at runtime.
# `k256` and `coins-bip39` are gone from this list: nothing in the shipped
@@ -917,11 +923,13 @@ voice = [
# checks a signature against a fixed vector; `coins-bip39` is gone entirely
# (the fixtures derive through `tinywallet`'s own copy).
#
-# `curve25519-dalek` stays: `associated_token_account` needs the off-curve check
-# to derive a Solana ATA, which is address arithmetic rather than signing.
+# `curve25519-dalek` is gone from this list: the Solana off-curve check that
+# derives an Associated Token Account is address arithmetic that now lives in
+# `tinywallet-web3` (and `tinywallet-x402`), which own their own copy.
web3 = [
"dep:tinywallet-bus",
- "dep:curve25519-dalek",
+ "dep:tinywallet-x402",
+ "dep:tinywallet-web3",
"modules",
]
diff --git a/crates/openhuman-core/src/modules/README.md b/crates/openhuman-core/src/modules/README.md
index f61e9efdcc..f74ebb753d 100644
--- a/crates/openhuman-core/src/modules/README.md
+++ b/crates/openhuman-core/src/modules/README.md
@@ -128,7 +128,7 @@ method constants, request/response types, and its contract version:
| `tinyvoice-bus` | `voice` |
| `tinyjuice-bus` | inference kernel |
| `tinyruntime-bus` | runtime clients |
-| `tinywallet-bus` | `web3` |
+| `tinywallet-bus` | `web3` (contract; the chain primitives are in `tinywallet-crypto`) |
| `tinymcp-bus` | `mcp` |
| `tinysearch-bus` | search provider declarations and bus payloads |
| `tinychannels-bus` | channel vocabulary |
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser.rs b/crates/openhuman-core/src/tools/impl/browser/browser.rs
index d715f75a42..a3ad05da79 100644
--- a/crates/openhuman-core/src/tools/impl/browser/browser.rs
+++ b/crates/openhuman-core/src/tools/impl/browser/browser.rs
@@ -1,8 +1,6 @@
//! Agent-facing browser backed by the TinyComputer module's browser and task members.
#[path = "browser_cleanup.rs"]
mod cleanup;
-#[path = "browser_drop.rs"]
-mod browser_drop;
#[path = "browser_pending.rs"]
mod pending;
#[path = "browser_session_pool.rs"]
diff --git a/crates/openhuman-core/src/tools/impl/browser/browser_drop.rs b/crates/openhuman-core/src/tools/impl/browser/browser_drop.rs
deleted file mode 100644
index efadaa0f72..0000000000
--- a/crates/openhuman-core/src/tools/impl/browser/browser_drop.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use super::BrowserTool;
-
-impl Drop for BrowserTool {
- fn drop(&mut self) {
- if self.thread_key.lock().ok().is_some_and(|key| key.is_some()) {
- // A later turn in this conversation reuses the module session.
- // Explicit `close` removes it; module shutdown owns final cleanup.
- return;
- }
- if let Ok(mut held) = self.session.try_lock() {
- if let Some(id) = held.take() {
- let client = self.client.clone();
- if let Ok(runtime) = tokio::runtime::Handle::try_current() {
- runtime.spawn(async move {
- let _ = client.close_session(&id).await;
- });
- }
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 6eea89b3dd..e4df8e8fe3 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -378,19 +378,20 @@ pub fn all_tools_with_runtime(
// Wallet tools — expose wallet operations to the agent tool-call pipeline
// so the crypto sub-agent can prepare transfers, check status, etc.
// Gated with the `web3` feature (the wallet domain is compiled out when
- // web3 is disabled; the concrete tool types live under `wallet::tools`).
+ // web3 is disabled; the concrete tool types live in `tinywallet-web3`,
+ // re-exported under `wallet::tools`, and run over the process-wide engine).
#[cfg(feature = "web3")]
- Box::new(WalletStatusTool::new()),
+ Box::new(WalletStatusTool::new(crate::web3::seams::engine())),
#[cfg(feature = "web3")]
- Box::new(WalletChainStatusTool::new()),
+ Box::new(WalletChainStatusTool::new(crate::web3::seams::engine())),
#[cfg(feature = "web3")]
- Box::new(WalletPrepareTransferTool::new()),
+ Box::new(WalletPrepareTransferTool::new(crate::web3::seams::engine())),
#[cfg(feature = "web3")]
- Box::new(WalletTxStatusTool::new()),
+ Box::new(WalletTxStatusTool::new(crate::web3::seams::engine())),
#[cfg(feature = "web3")]
- Box::new(WalletTxReceiptTool::new()),
+ Box::new(WalletTxReceiptTool::new(crate::web3::seams::engine())),
#[cfg(feature = "web3")]
- Box::new(WalletLookupTxTool::new()),
+ Box::new(WalletLookupTxTool::new(crate::web3::seams::engine())),
// The memory surface the model sees. The eleven per-operation tools it
// dispatches to stay registered as `ToolExposure::Hidden` so a
// replayed transcript or a saved skill naming `memory_*` still works —
@@ -728,7 +729,7 @@ pub fn all_tools_with_runtime(
// or SPL payment signing, and ledger recording. Gated with the `web3`
// feature (the x402 domain is compiled out when web3 is disabled).
#[cfg(feature = "web3")]
- tools.push(Box::new(crate::web3::x402::tools::X402RequestTool::new()));
+ tools.push(Box::new(crate::web3::x402::request_tool()));
// Coding-harness baseline `web_fetch` (issue #1205) — single-purpose
// GET-and-read primitive that reuses the same allowed-domains gate
diff --git a/crates/openhuman-core/src/web3/README.md b/crates/openhuman-core/src/web3/README.md
index 9881a9a254..d83bc5990e 100644
--- a/crates/openhuman-core/src/web3/README.md
+++ b/crates/openhuman-core/src/web3/README.md
@@ -47,21 +47,25 @@ behind the default-ON `web3` Cargo feature. When the feature is off,
`tools/ops.rs` need no per-call `#[cfg]`. `cargo check --no-default-features`
is the only thing that catches drift between the real and stub signatures.
+## Where the logic lives
+
+The swap/bridge/dapp logic is in the vendored `tinywallet-web3` crate
+(`vendor/tinywallet/crates/tinywallet-web3`, `crypto::service`), not here: quote
+preparation, the confirm-then-execute quote store and the agent tools. This
+module is the host adapter. The crate reaches OpenHuman only through seams,
+implemented in `seams.rs`.
+
## Key files
| File | Role |
| --- | --- |
-| `mod.rs` | Export-focused root: aggregates `all_web3_controller_schemas` / `all_web3_registered_controllers` / `all_web3_agent_tools`, plus shared schema/tool helpers. |
-| `types.rs` | deBridge chain-id to local signer mapping (`chain_family`, `DEBRIDGE_SOLANA_CHAIN_ID`), request params, `UnsignedTx`, `Web3QuoteKind`. |
-| `client.rs` | `CryptoClient`, a thin wrapper over the shared `IntegrationClient` for `/agent-integrations/crypto/*` (Bearer JWT auth, envelope unwrap). |
-| `store.rs` | In-memory prepared-quote store (TTL'd, capped, chat-thread owner-bound like the wallet) plus the shared confirm-then-execute path. |
-| `ops.rs` | Shared op logic: `routes`, `quote_swap`, `quote_bridge`, `prepare_dapp_call` (address defaulting, backend call, unsigned-tx extraction). |
+| `mod.rs` | Export-focused root: aggregates `all_web3_controller_schemas` / `all_web3_registered_controllers` / `all_web3_agent_tools` (which builds the crate's tools over the process-wide service), plus shared schema helpers. Re-exports the crate's request/quote types as `web3::types`. |
+| `seams.rs` | The host implementations of the crate's seams (`HostSigner`, `HostAccounts`, `TaskLocalScope`, `HostBackend`) and the `OnceLock` holding the process-wide `WalletEngine` and `Web3Service` (`engine()`, `service()`). |
+| `client.rs` | `CryptoClient`, a thin wrapper over the shared `IntegrationClient` for `/agent-integrations/crypto/*` (Bearer JWT auth, envelope unwrap). Reached through `HostBackend`. |
| `stub.rs` | Disabled facade compiled when `web3` is off; empty `all_web3_registered_controllers` / `all_web3_controller_schemas` / `all_web3_agent_tools`. See Compile-time gate above. |
-| `web3_tests.rs` | `#[cfg(all(test, feature = "web3"))]` tests for `chain_family` mapping and the quote store's confirm/execute gate. |
-| `ops_tests.rs` | Tests for the shared op logic in `ops.rs` (unsigned-tx extraction, dapp/swap/bridge param rejection). |
+| `seams_tests.rs` | Composition tests over the real wallet state, and the regression test that `TaskLocalScope` reads `APPROVAL_CHAT_CONTEXT`. |
| `stub_tests.rs` | Runs only in the disabled build; pins that the three stub entry points return empty collections. |
-| `{swap,bridge,dapp}/schemas.rs` | Per-namespace RPC controllers and handlers. |
-| `{swap,bridge,dapp}/tools.rs` | Per-namespace agent tools. |
+| `{swap,bridge,dapp}/schemas.rs` | Per-namespace RPC controllers and handlers (namespace strings are wire contracts). |
## RPC / controllers
@@ -79,8 +83,10 @@ quote with a refreshed TTL.
`web3_swap_quote`, `web3_swap_execute`, `web3_swap_routes`,
`web3_bridge_quote`, `web3_bridge_execute`, `web3_dapp_call`,
-`web3_dapp_execute` (registered in `crates/openhuman-core/src/tools/ops.rs`). They call the
-backend per-invocation and error gracefully when the user is not signed in.
+`web3_dapp_execute` are defined in `tinywallet_web3::tools::web3` and built over
+the process-wide service by `all_web3_agent_tools()` (registered in
+`crates/openhuman-core/src/tools/ops.rs`). They call the backend
+per-invocation and error gracefully when the user is not signed in.
## Chain-id mapping
@@ -97,11 +103,12 @@ are rejected at quote time.
## Dependencies
-- [`crate::web3::wallet`]: `sign_and_broadcast_evm` / `sign_and_broadcast_solana` (crate-internal), `status` for address resolution, `EvmNetwork` / `WalletChain`.
-- [`crate::integrations`] (`IntegrationClient`, `build_client`): backend auth and transport.
-- `crate::security::approval::APPROVAL_CHAT_CONTEXT`: quote-owner binding.
+- `tinywallet-web3` (`vendor/tinywallet/crates/tinywallet-web3`, optional, feature `tools`, enabled by the `web3` feature): the swap/bridge/dapp service, quote store and tools. Its seams are implemented in `seams.rs`.
+- [`crate::web3::wallet`]: `status` (through `HostAccounts`) and `secret_material` (through `HostSigner`).
+- [`crate::integrations`] (`IntegrationClient`, `build_client`): backend auth and transport, through `HostBackend`.
+- `crate::security::approval::APPROVAL_CHAT_CONTEXT`: quote-owner binding, read by `TaskLocalScope`.
- `crate::core::all` / `crate::core`: RPC controller registry wiring.
-- `tinywallet-bus` (`crates/openhuman-core/Cargo.toml` around line 864, optional, gated by the `web3` feature; features `btc`, `evm`, `solana`, `tron`, `keccak`, `net`, `wire`, `eip712`, `abi`, `tx-codec`): not imported by `web3/*.rs` itself, but the contract crate its `wallet/` and `x402/` members build on. It supplies address validation, the `SecretMaterial`/`TransactionSpec` wire types handed to the wallet module, the `Transport` seam, the EIP-712/ERC-20 encoders used by x402, and the Tron verifier.
+- `tinywallet-bus` (optional, gated by the `web3` feature): the contract crate. It supplies the `SecretMaterial`/`TransactionSpec` wire types the signer hands to the wallet module and the `Transport` seam types.
## Notes / gotchas
diff --git a/crates/openhuman-core/src/web3/bridge/mod.rs b/crates/openhuman-core/src/web3/bridge/mod.rs
index 82bbe47df0..cf6cd7dc7f 100644
--- a/crates/openhuman-core/src/web3/bridge/mod.rs
+++ b/crates/openhuman-core/src/web3/bridge/mod.rs
@@ -1,8 +1,6 @@
-//! `web3_bridge` — cross-chain bridges via deBridge DLN. Logic lives in the
-//! shared [`super::ops`]/[`super::store`]; this module owns the RPC controllers
-//! and agent tools.
+//! `web3_bridge` — cross-chain bridges via deBridge DLN. Logic lives in
+//! `tinywallet_web3::crypto::service` (reached through [`super::seams`]); this
+//! module owns the RPC controllers and their schemas. The agent tools are in
+//! `tinywallet_web3::tools::web3`.
pub mod schemas;
-pub mod tools;
-
-pub use tools::{Web3BridgeExecuteTool, Web3BridgeQuoteTool};
diff --git a/crates/openhuman-core/src/web3/bridge/schemas.rs b/crates/openhuman-core/src/web3/bridge/schemas.rs
index 08b014b549..bfdc180b2f 100644
--- a/crates/openhuman-core/src/web3/bridge/schemas.rs
+++ b/crates/openhuman-core/src/web3/bridge/schemas.rs
@@ -4,9 +4,9 @@
use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::store::execute_quote;
+use super::super::seams::service;
use super::super::types::{BridgeQuoteParams, ExecuteQuoteParams};
use super::super::{execute_inputs, json_result, opt_str, req_json};
@@ -74,9 +74,8 @@ fn handle_quote(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: BridgeQuoteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- super::super::ops::quote_bridge(parsed)
- .await?
- .into_cli_compatible_json()
+ let quote = service().quote_bridge(parsed).await?;
+ Outcome::new(quote, vec!["web3 bridge prepared".to_string()]).into_cli_compatible_json()
})
}
@@ -84,6 +83,8 @@ fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- execute_quote(parsed).await?.into_cli_compatible_json()
+ let result = service().execute_quote(parsed).await?;
+ Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
+ .into_cli_compatible_json()
})
}
diff --git a/crates/openhuman-core/src/web3/bridge/tools.rs b/crates/openhuman-core/src/web3/bridge/tools.rs
deleted file mode 100644
index b781e10680..0000000000
--- a/crates/openhuman-core/src/web3/bridge/tools.rs
+++ /dev/null
@@ -1,114 +0,0 @@
-//! `web3_bridge` agent tools: quote a cross-chain bridge and execute it.
-
-use async_trait::async_trait;
-use serde_json::json;
-
-use crate::web3::store::execute_quote;
-use crate::web3::types::{BridgeQuoteParams, ExecuteQuoteParams};
-use crate::web3::{execute_tool_schema, ops, to_tool_result};
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct Web3BridgeQuoteTool;
-pub struct Web3BridgeExecuteTool;
-
-impl Default for Web3BridgeQuoteTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3BridgeQuoteTool {
- pub fn new() -> Self {
- Self
- }
-}
-impl Default for Web3BridgeExecuteTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3BridgeExecuteTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for Web3BridgeQuoteTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_bridge_quote"
- }
- fn description(&self) -> &str {
- "Prepare a cross-chain bridge via deBridge DLN. Returns a quote + quoteId to confirm with web3_bridge_execute. Source and destination chains must differ."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "srcChainId": {"type": "integer", "description": "Source deBridge chain id."},
- "srcChainTokenIn": {"type": "string", "description": "Source token address."},
- "srcChainTokenInAmount": {"type": "string", "description": "Source amount in the token's smallest unit."},
- "dstChainId": {"type": "integer", "description": "Destination deBridge chain id (must differ from source)."},
- "dstChainTokenOut": {"type": "string", "description": "Destination token address."},
- "dstChainTokenOutAmount": {"type": "string", "description": "Optional. 'auto' for market rate (default)."},
- "dstChainTokenOutRecipient": {"type": "string", "description": "Optional. Defaults to the wallet's own destination address."},
- "srcChainOrderAuthorityAddress": {"type": "string", "description": "Optional. Defaults to the wallet's source address."},
- "dstChainOrderAuthorityAddress": {"type": "string", "description": "Optional. Defaults to the wallet's destination address."}
- },
- "required": ["srcChainId", "srcChainTokenIn", "srcChainTokenInAmount", "dstChainId", "dstChainTokenOut"],
- "additionalProperties": false
- })
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: BridgeQuoteParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(ops::quote_bridge(params).await))
- }
-}
-
-#[async_trait]
-impl Tool for Web3BridgeExecuteTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_bridge_execute"
- }
- fn description(&self) -> &str {
- "Confirm and execute a prepared web3_bridge quote (signs + broadcasts the source-chain tx)."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- execute_tool_schema()
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: ExecuteQuoteParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(execute_quote(params).await))
- }
-}
diff --git a/crates/openhuman-core/src/web3/dapp/README.md b/crates/openhuman-core/src/web3/dapp/README.md
index 946205b1ae..0a02d639c9 100644
--- a/crates/openhuman-core/src/web3/dapp/README.md
+++ b/crates/openhuman-core/src/web3/dapp/README.md
@@ -9,21 +9,20 @@ confirm-then-execute flow.
## What it does
-`prepare_dapp_call` (in the shared `super::ops`) validates the contract
+`Web3Service::prepare_dapp_call` (in the vendored `tinywallet-web3` crate) validates the contract
address and calldata (must be `0x`-prefixed, even-length hex), confirms the
wallet has an EVM account on the requested network, and stores an
`UnsignedTx::Evm` quote. This module owns the RPC controllers (`schemas.rs`)
-and agent tools (`tools.rs`) for the `web3_dapp` namespace; the validation and
-storage logic lives in `super::ops` and `super::store`, shared with `swap` and
-`bridge`.
+for the `web3_dapp` namespace; the validation and storage logic lives in the
+crate's `crypto::service`, shared with `swap` and `bridge`, and the agent tools
+in `tinywallet_web3::tools::web3`.
## Key files
| File | Role |
| --- | --- |
-| `mod.rs` | Re-exports `Web3DappCallTool`, `Web3DappExecuteTool` from `tools.rs`. |
-| `schemas.rs` | `web3_dapp` RPC controller schemas and handlers: `call`, `execute`. Handlers deserialize params and delegate to `super::super::ops::prepare_dapp_call` / `super::super::store::execute_quote`. |
-| `tools.rs` | The two agent tools: `Web3DappCallTool` (`web3_dapp_call`), `Web3DappExecuteTool` (`web3_dapp_execute`). Delegate to the same `ops`/`store` functions as the RPC handlers. |
+| `mod.rs` | Module docs. |
+| `schemas.rs` | `web3_dapp` RPC controller schemas and handlers: `call`, `execute`. Handlers deserialize params and delegate to the process-wide `Web3Service` (`prepare_dapp_call` / `execute_quote`), wrapping the result in `Outcome`. |
## RPC / controllers
diff --git a/crates/openhuman-core/src/web3/dapp/mod.rs b/crates/openhuman-core/src/web3/dapp/mod.rs
index 4899c2f165..1487f15466 100644
--- a/crates/openhuman-core/src/web3/dapp/mod.rs
+++ b/crates/openhuman-core/src/web3/dapp/mod.rs
@@ -1,8 +1,6 @@
//! `web3_dapp` — generic EVM contract interactions from caller-supplied
-//! calldata. Logic lives in the shared [`super::ops`]/[`super::store`]; this
-//! module owns the RPC controllers and agent tools.
+//! calldata. Logic lives in `tinywallet_web3::crypto::service` (reached through
+//! [`super::seams`]); this module owns the RPC controllers and their schemas.
+//! The agent tools are in `tinywallet_web3::tools::web3`.
pub mod schemas;
-pub mod tools;
-
-pub use tools::{Web3DappCallTool, Web3DappExecuteTool};
diff --git a/crates/openhuman-core/src/web3/dapp/schemas.rs b/crates/openhuman-core/src/web3/dapp/schemas.rs
index 74f2c5db01..011a0639d5 100644
--- a/crates/openhuman-core/src/web3/dapp/schemas.rs
+++ b/crates/openhuman-core/src/web3/dapp/schemas.rs
@@ -4,9 +4,9 @@
use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::store::execute_quote;
+use super::super::seams::service;
use super::super::types::{DappCallParams, ExecuteQuoteParams};
use super::super::{execute_inputs, json_result, opt_str, req_json};
@@ -69,9 +69,8 @@ fn handle_call(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: DappCallParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- super::super::ops::prepare_dapp_call(parsed)
- .await?
- .into_cli_compatible_json()
+ let quote = service().prepare_dapp_call(parsed).await?;
+ Outcome::new(quote, vec!["web3 dapp call prepared".to_string()]).into_cli_compatible_json()
})
}
@@ -79,6 +78,8 @@ fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- execute_quote(parsed).await?.into_cli_compatible_json()
+ let result = service().execute_quote(parsed).await?;
+ Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
+ .into_cli_compatible_json()
})
}
diff --git a/crates/openhuman-core/src/web3/dapp/tools.rs b/crates/openhuman-core/src/web3/dapp/tools.rs
deleted file mode 100644
index e677e908e2..0000000000
--- a/crates/openhuman-core/src/web3/dapp/tools.rs
+++ /dev/null
@@ -1,113 +0,0 @@
-//! `web3_dapp` agent tools: prepare a generic EVM contract call and execute it.
-
-use async_trait::async_trait;
-use serde_json::json;
-
-use crate::web3::store::execute_quote;
-use crate::web3::types::{DappCallParams, ExecuteQuoteParams};
-use crate::web3::{execute_tool_schema, ops, to_tool_result};
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct Web3DappCallTool;
-pub struct Web3DappExecuteTool;
-
-impl Default for Web3DappCallTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3DappCallTool {
- pub fn new() -> Self {
- Self
- }
-}
-impl Default for Web3DappExecuteTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3DappExecuteTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for Web3DappCallTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_dapp_call"
- }
- fn description(&self) -> &str {
- "Prepare a generic EVM dapp contract call from pre-encoded calldata. Returns a quoteId to confirm with web3_dapp_execute."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "contractAddress": {"type": "string", "description": "Target contract address."},
- "calldata": {"type": "string", "description": "0x-prefixed hex calldata."},
- "valueRaw": {"type": "string", "description": "Optional native value (smallest unit). Defaults to '0'."},
- "evmNetwork": {
- "type": "string",
- "enum": ["ethereum_mainnet", "base_mainnet", "arbitrum_one", "optimism_mainnet", "polygon_mainnet", "bsc_mainnet"],
- "description": "Optional EVM network. Defaults to ethereum_mainnet."
- }
- },
- "required": ["contractAddress", "calldata"],
- "additionalProperties": false
- })
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: DappCallParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(ops::prepare_dapp_call(params).await))
- }
-}
-
-#[async_trait]
-impl Tool for Web3DappExecuteTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_dapp_execute"
- }
- fn description(&self) -> &str {
- "Confirm and execute a prepared web3_dapp call (signs + broadcasts)."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- execute_tool_schema()
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: ExecuteQuoteParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(execute_quote(params).await))
- }
-}
diff --git a/crates/openhuman-core/src/web3/mod.rs b/crates/openhuman-core/src/web3/mod.rs
index d16242c957..443fb64211 100644
--- a/crates/openhuman-core/src/web3/mod.rs
+++ b/crates/openhuman-core/src/web3/mod.rs
@@ -2,15 +2,17 @@
//! signing primitives. Focuses on EVM/Solana dapp interactions: swaps, bridges,
//! and generic contract calls.
//!
-//! Quotes + unsigned transactions come from the backend deBridge proxy
-//! (`/agent-integrations/crypto/*`); signing/broadcast is delegated to the
-//! wallet's crate-internal `sign_and_broadcast_*` primitives so private keys
-//! never leave the wallet. Three sub-modules expose distinct RPC namespaces +
-//! tool families:
+//! The swap/bridge/dapp logic (quote preparation, the confirm-then-execute quote
+//! store, the agent tools) lives in `tinywallet_web3::crypto::service`. What
+//! stays here is the host adapter: the RPC controllers and their schemas (the
+//! namespace strings are wire contracts), the [`client`] over the backend's
+//! deBridge proxy (`/agent-integrations/crypto/*`), and [`seams`], which holds
+//! the host implementations of the crate's seams and the process-wide service.
+//! Three sub-modules expose distinct RPC namespaces:
//! - [`swap`] (`web3_swap`) — single-chain swaps (cross-chain → `web3_bridge`).
//! - [`bridge`] (`web3_bridge`) — cross-chain DLN bridges.
//! - [`dapp`] (`web3_dapp`) — generic EVM contract calls.
-
+//!
//! ## Compile-time gate (`web3` feature)
//!
//! `pub mod web3;` is ALWAYS compiled — it is a facade. The real swap/bridge/
@@ -28,13 +30,13 @@ pub mod client;
#[cfg(feature = "web3")]
pub mod dapp;
#[cfg(feature = "web3")]
-pub mod ops;
-#[cfg(feature = "web3")]
-pub mod store;
+pub mod seams;
#[cfg(feature = "web3")]
pub mod swap;
+/// The swap/bridge/dapp request and quote types, re-exported from
+/// `tinywallet-web3` under their historical path.
#[cfg(feature = "web3")]
-pub mod types;
+pub use tinywallet_web3::crypto::service as types;
// Ungated family members: `wallet` and `x402` are facades in their own right —
// each keeps its own `stub.rs` and gates its real submodules on the same
@@ -44,21 +46,12 @@ pub mod types;
pub mod wallet;
pub mod x402;
-#[cfg(all(test, feature = "web3"))]
-#[path = "web3_tests.rs"]
-mod tests;
-
-#[cfg(feature = "web3")]
-use serde::Serialize;
-
#[cfg(feature = "web3")]
use crate::core::all::RegisteredController;
#[cfg(feature = "web3")]
-use crate::core::Outcome;
-#[cfg(feature = "web3")]
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
#[cfg(feature = "web3")]
-use tinytools::{Tool, ToolResult};
+use tinytools::Tool;
// ---------------------------------------------------------------------------
// Disabled facade — compiled only when the `web3` feature is OFF.
@@ -114,32 +107,6 @@ pub(crate) fn execute_inputs() -> Vec<FieldSchema> {
]
}
-/// Shared agent-tool JSON Schema for the execute tools.
-#[cfg(feature = "web3")]
-pub(crate) fn execute_tool_schema() -> serde_json::Value {
- serde_json::json!({
- "type": "object",
- "properties": {
- "quoteId": {"type": "string", "description": "quoteId from a prior web3 quote/call."},
- "confirmed": {"type": "boolean", "description": "Must be true to execute."}
- },
- "required": ["quoteId", "confirmed"],
- "additionalProperties": false
- })
-}
-
-/// Convert an op result into a `ToolResult` with pretty-printed JSON on success.
-#[cfg(feature = "web3")]
-pub(crate) fn to_tool_result<T: Serialize>(result: Result<Outcome<T>, String>) -> ToolResult {
- match result {
- Ok(outcome) => match serde_json::to_string_pretty(&outcome.value) {
- Ok(s) => ToolResult::success(s),
- Err(e) => ToolResult::error(format!("failed to serialize web3 result: {e}")),
- },
- Err(e) => ToolResult::error(e),
- }
-}
-
/// All web3 controller schemas across the swap/bridge/dapp namespaces.
#[cfg(feature = "web3")]
pub fn all_web3_controller_schemas() -> Vec<ControllerSchema> {
@@ -162,13 +129,19 @@ pub fn all_web3_registered_controllers() -> Vec<RegisteredController> {
/// gracefully (rather than being hidden) when the user is not signed in.
#[cfg(feature = "web3")]
pub fn all_web3_agent_tools() -> Vec<Box<dyn Tool>> {
+ use tinywallet_web3::tools::web3::{
+ Web3BridgeExecuteTool, Web3BridgeQuoteTool, Web3DappCallTool, Web3DappExecuteTool,
+ Web3SwapExecuteTool, Web3SwapQuoteTool, Web3SwapRoutesTool,
+ };
+
+ let service = seams::service();
vec![
- Box::new(swap::Web3SwapQuoteTool::new()),
- Box::new(swap::Web3SwapExecuteTool::new()),
- Box::new(swap::Web3SwapRoutesTool::new()),
- Box::new(bridge::Web3BridgeQuoteTool::new()),
- Box::new(bridge::Web3BridgeExecuteTool::new()),
- Box::new(dapp::Web3DappCallTool::new()),
- Box::new(dapp::Web3DappExecuteTool::new()),
+ Box::new(Web3SwapQuoteTool::new(service.clone())),
+ Box::new(Web3SwapExecuteTool::new(service.clone())),
+ Box::new(Web3SwapRoutesTool::new(service.clone())),
+ Box::new(Web3BridgeQuoteTool::new(service.clone())),
+ Box::new(Web3BridgeExecuteTool::new(service.clone())),
+ Box::new(Web3DappCallTool::new(service.clone())),
+ Box::new(Web3DappExecuteTool::new(service)),
]
}
diff --git a/crates/openhuman-core/src/web3/ops.rs b/crates/openhuman-core/src/web3/ops.rs
deleted file mode 100644
index 1589cb42a1..0000000000
--- a/crates/openhuman-core/src/web3/ops.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-//! web3 operation logic shared by the swap / bridge / dapp surfaces. Each op
-//! resolves the caller's wallet address (defaulting recipients/authorities to
-//! the wallet's own derived address), calls the backend deBridge proxy for a
-//! quote + unsigned transaction, and stores a confirm→execute quote bound to
-//! the signing primitive in the wallet.
-
-use serde_json::{json, Value};
-
-use crate::config::rpc as config_rpc;
-use crate::core::Outcome;
-use crate::web3::wallet::{self, EvmNetwork, WalletChain};
-
-use super::client::CryptoClient;
-use super::store::{self, Web3Quote};
-use super::types::{
- chain_family, BridgeQuoteParams, ChainFamily, DappCallParams, SwapQuoteParams, UnsignedTx,
- Web3QuoteKind,
-};
-
-const LOG_PREFIX: &str = "[web3]";
-
-/// Resolve the wallet's derived address for a deBridge chain family.
-async fn wallet_address(family: ChainFamily) -> Result<String, String> {
- let chain = match family {
- ChainFamily::Evm(_) => WalletChain::Evm,
- ChainFamily::Solana => WalletChain::Solana,
- };
- let status = wallet::status().await?.value;
- if !status.configured {
- return Err(wallet::WALLET_NOT_CONFIGURED_MESSAGE.to_string());
- }
- status
- .accounts
- .into_iter()
- .find(|a| a.chain == chain)
- .map(|a| a.address)
- .ok_or_else(|| "wallet has no derived account for the requested chain".to_string())
-}
-
-/// Pull a deBridge `value` field (string or number) into a decimal string.
-fn value_to_string(tx: &Value) -> String {
- match tx.get("value") {
- Some(Value::String(s)) => s.clone(),
- Some(Value::Number(n)) => n.to_string(),
- _ => "0".to_string(),
- }
-}
-
-/// Extract the unsigned transaction from a deBridge quote response for the
-/// given source chain family.
-fn unsigned_from_response(resp: &Value, family: ChainFamily) -> Result<UnsignedTx, String> {
- let tx = resp
- .get("tx")
- .ok_or_else(|| "backend response missing unsigned `tx`".to_string())?;
- match family {
- ChainFamily::Evm(network) => {
- let to = tx
- .get("to")
- .and_then(Value::as_str)
- .ok_or_else(|| "EVM unsigned tx missing `to`".to_string())?
- .to_string();
- let data = tx.get("data").and_then(Value::as_str).map(str::to_string);
- Ok(UnsignedTx::Evm {
- network,
- to,
- data,
- value: value_to_string(tx),
- })
- }
- ChainFamily::Solana => {
- let blob = tx
- .get("data")
- .and_then(Value::as_str)
- .ok_or_else(|| "Solana unsigned tx missing hex `data` blob".to_string())?
- .to_string();
- Ok(UnsignedTx::Solana { tx_blob_hex: blob })
- }
- }
-}
-
-/// List the chains deBridge can swap/bridge between.
-pub async fn routes() -> Result<Outcome<Value>, String> {
- let config = config_rpc::load_config_with_timeout().await?;
- let client = CryptoClient::from_config(&config)?;
- let data = client.routes().await?;
- Ok(Outcome::new(
- data,
- vec!["web3 supported routes listed".to_string()],
- ))
-}
-
-/// Prepare a single-chain swap. Cross-chain requests are rejected here with a
-/// pointer to `web3_bridge` (deBridge `/swap` is single-chain only).
-pub async fn quote_swap(params: SwapQuoteParams) -> Result<Outcome<Web3Quote>, String> {
- let family = chain_family(params.chain_id).ok_or_else(|| {
- format!(
- "chain id {} is not signable by the local wallet (no EVM/Solana signer)",
- params.chain_id
- )
- })?;
- let own = wallet_address(family).await?;
- let sender = params.sender_address.clone().unwrap_or_else(|| own.clone());
- let recipient = params.token_out_recipient.clone().unwrap_or(own);
-
- let config = config_rpc::load_config_with_timeout().await?;
- let client = CryptoClient::from_config(&config)?;
- let body = json!({
- "chainId": params.chain_id,
- "tokenIn": params.token_in,
- "tokenInAmount": params.token_in_amount,
- "tokenOut": params.token_out,
- "tokenOutRecipient": recipient,
- "senderAddress": sender,
- "slippage": params.slippage.clone().unwrap_or_else(|| "auto".to_string()),
- });
- let resp = client.swap_tx(&body).await?;
- let unsigned = unsigned_from_response(&resp, family)?;
- tracing::debug!(
- "{LOG_PREFIX} quote_swap chain_id={} tokenIn={} tokenOut={}",
- params.chain_id,
- params.token_in,
- params.token_out
- );
- Ok(Outcome::new(
- store::store_quote(Web3QuoteKind::Swap, unsigned, resp),
- vec!["web3 swap prepared".to_string()],
- ))
-}
-
-/// Prepare a cross-chain bridge. Same-chain requests are rejected (mirrors the
-/// backend) — use `web3_swap` for single-chain swaps.
-pub async fn quote_bridge(params: BridgeQuoteParams) -> Result<Outcome<Web3Quote>, String> {
- if params.src_chain_id == params.dst_chain_id {
- return Err(
- "bridge requires different source and destination chains; use web3_swap for same-chain swaps"
- .to_string(),
- );
- }
- let src_family = chain_family(params.src_chain_id).ok_or_else(|| {
- format!(
- "source chain id {} is not signable by the local wallet",
- params.src_chain_id
- )
- })?;
- let dst_family = chain_family(params.dst_chain_id);
- let src_addr = wallet_address(src_family).await?;
- // Destination recipient/authority default to our address on the dst family
- // when we can sign there, else fall back to the source address.
- let dst_addr = match dst_family {
- Some(f) => wallet_address(f).await.unwrap_or_else(|_| src_addr.clone()),
- None => src_addr.clone(),
- };
-
- let config = config_rpc::load_config_with_timeout().await?;
- let client = CryptoClient::from_config(&config)?;
- let body = json!({
- "srcChainId": params.src_chain_id,
- "srcChainTokenIn": params.src_chain_token_in,
- "srcChainTokenInAmount": params.src_chain_token_in_amount,
- "dstChainId": params.dst_chain_id,
- "dstChainTokenOut": params.dst_chain_token_out,
- "dstChainTokenOutAmount": params
- .dst_chain_token_out_amount
- .clone()
- .unwrap_or_else(|| "auto".to_string()),
- "dstChainTokenOutRecipient": params
- .dst_chain_token_out_recipient
- .clone()
- .unwrap_or_else(|| dst_addr.clone()),
- "srcChainOrderAuthorityAddress": params
- .src_chain_order_authority_address
- .clone()
- .unwrap_or_else(|| src_addr.clone()),
- "dstChainOrderAuthorityAddress": params
- .dst_chain_order_authority_address
- .clone()
- .unwrap_or(dst_addr),
- });
- let resp = client.bridge_tx(&body).await?;
- // The unsigned tx is always signed+broadcast on the SOURCE chain.
- let unsigned = unsigned_from_response(&resp, src_family)?;
- tracing::debug!(
- "{LOG_PREFIX} quote_bridge src={} dst={}",
- params.src_chain_id,
- params.dst_chain_id
- );
- Ok(Outcome::new(
- store::store_quote(Web3QuoteKind::Bridge, unsigned, resp),
- vec!["web3 bridge prepared".to_string()],
- ))
-}
-
-/// Prepare a generic EVM dapp contract call from caller-supplied calldata.
-pub async fn prepare_dapp_call(params: DappCallParams) -> Result<Outcome<Web3Quote>, String> {
- let network = params.evm_network.unwrap_or(EvmNetwork::EthereumMainnet);
- let contract = params.contract_address.trim();
- if contract.is_empty() {
- return Err("contract_address is empty".to_string());
- }
- let calldata = params.calldata.trim();
- let hex_body = calldata
- .strip_prefix("0x")
- .ok_or_else(|| "calldata must be 0x-prefixed hex".to_string())?;
- if hex_body.len() % 2 != 0 || !hex_body.bytes().all(|b| b.is_ascii_hexdigit()) {
- return Err("calldata must be valid even-length hex".to_string());
- }
- let value = params.value_raw.clone().unwrap_or_else(|| "0".to_string());
- // Confirm the wallet has an EVM account before quoting.
- let _ = wallet_address(ChainFamily::Evm(network)).await?;
-
- let summary = json!({
- "type": "dapp_call",
- "network": network.as_str(),
- "contractAddress": contract,
- "calldata": calldata,
- "valueRaw": value,
- });
- let unsigned = UnsignedTx::Evm {
- network,
- to: contract.to_string(),
- data: Some(calldata.to_string()),
- value,
- };
- tracing::debug!(
- "{LOG_PREFIX} prepare_dapp_call network={} contract={}",
- network.as_str(),
- contract
- );
- Ok(Outcome::new(
- store::store_quote(Web3QuoteKind::DappCall, unsigned, summary),
- vec!["web3 dapp call prepared".to_string()],
- ))
-}
-
-#[cfg(test)]
-#[path = "ops_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/ops_tests.rs b/crates/openhuman-core/src/web3/ops_tests.rs
deleted file mode 100644
index 4ebc51d0ad..0000000000
--- a/crates/openhuman-core/src/web3/ops_tests.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-use super::*;
-
-#[test]
-fn value_to_string_handles_string_number_and_missing() {
- assert_eq!(value_to_string(&json!({"value": "123"})), "123");
- assert_eq!(value_to_string(&json!({"value": 456})), "456");
- assert_eq!(value_to_string(&json!({})), "0");
-}
-
-#[test]
-fn unsigned_from_evm_response_extracts_to_data_value() {
- let resp = json!({"tx": {"to": "0xabc", "data": "0xdeadbeef", "value": "10"}});
- let unsigned = unsigned_from_response(&resp, ChainFamily::Evm(EvmNetwork::BscMainnet)).unwrap();
- match unsigned {
- UnsignedTx::Evm {
- network,
- to,
- data,
- value,
- } => {
- assert_eq!(network, EvmNetwork::BscMainnet);
- assert_eq!(to, "0xabc");
- assert_eq!(data.as_deref(), Some("0xdeadbeef"));
- assert_eq!(value, "10");
- }
- _ => panic!("expected EVM unsigned tx"),
- }
-}
-
-#[test]
-fn unsigned_from_solana_response_extracts_blob() {
- let resp = json!({"tx": {"data": "0011aabb"}});
- let unsigned = unsigned_from_response(&resp, ChainFamily::Solana).unwrap();
- match unsigned {
- UnsignedTx::Solana { tx_blob_hex } => assert_eq!(tx_blob_hex, "0011aabb"),
- _ => panic!("expected Solana unsigned tx"),
- }
-}
-
-#[test]
-fn unsigned_from_response_errors_when_tx_missing() {
- let err = unsigned_from_response(
- &json!({"estimation": {}}),
- ChainFamily::Evm(EvmNetwork::EthereumMainnet),
- )
- .unwrap_err();
- assert!(err.contains("missing unsigned"), "got: {err}");
-}
-
-#[tokio::test]
-async fn prepare_dapp_call_rejects_empty_contract() {
- let err = prepare_dapp_call(DappCallParams {
- contract_address: " ".to_string(),
- calldata: "0xabcd".to_string(),
- value_raw: None,
- evm_network: None,
- })
- .await
- .unwrap_err();
- assert!(err.contains("contract_address is empty"), "got: {err}");
-}
-
-#[tokio::test]
-async fn prepare_dapp_call_rejects_non_hex_calldata() {
- let err = prepare_dapp_call(DappCallParams {
- contract_address: "0x1111111111111111111111111111111111111111".to_string(),
- calldata: "notHex".to_string(),
- value_raw: None,
- evm_network: None,
- })
- .await
- .unwrap_err();
- assert!(err.contains("0x-prefixed hex"), "got: {err}");
-}
-
-#[tokio::test]
-async fn quote_swap_rejects_unsignable_chain() {
- let err = quote_swap(SwapQuoteParams {
- chain_id: 999_999,
- token_in: "0x0".to_string(),
- token_in_amount: "1".to_string(),
- token_out: "0x1".to_string(),
- token_out_recipient: None,
- sender_address: None,
- slippage: None,
- })
- .await
- .unwrap_err();
- assert!(err.contains("not signable"), "got: {err}");
-}
-
-#[tokio::test]
-async fn quote_bridge_rejects_same_chain() {
- let err = quote_bridge(BridgeQuoteParams {
- src_chain_id: 1,
- src_chain_token_in: "0x0".to_string(),
- src_chain_token_in_amount: "1".to_string(),
- dst_chain_id: 1,
- dst_chain_token_out: "0x1".to_string(),
- dst_chain_token_out_amount: None,
- dst_chain_token_out_recipient: None,
- src_chain_order_authority_address: None,
- dst_chain_order_authority_address: None,
- })
- .await
- .unwrap_err();
- assert!(
- err.contains("different source and destination"),
- "got: {err}"
- );
-}
diff --git a/crates/openhuman-core/src/web3/seams.rs b/crates/openhuman-core/src/web3/seams.rs
new file mode 100644
index 0000000000..4067b438e6
--- /dev/null
+++ b/crates/openhuman-core/src/web3/seams.rs
@@ -0,0 +1,246 @@
+//! The host's implementations of the `tinywallet-web3` seams, and the process
+//! wide engine and service built on them.
+//!
+//! `tinywallet-web3` holds the wallet, swap, bridge and dapp logic and none of
+//! its configuration; this file is where OpenHuman's own state is plugged in:
+//!
+//! | Seam | Host implementation |
+//! | --- | --- |
+//! | `Transport` | [`OpenHumanTransport`](super::wallet::transport::OpenHumanTransport) over the wallet RPC layer |
+//! | `RpcEndpoints` | [`HostEndpoints`](super::wallet::endpoints::HostEndpoints), the `OPENHUMAN_WALLET_RPC_*` env |
+//! | `WalletSigner` | [`HostSigner`]: keyring, then the loaded wallet module |
+//! | `WalletAccounts` | [`HostAccounts`]: the wallet's stored state |
+//! | `QuoteScope` | [`TaskLocalScope`]: the chat turn's `APPROVAL_CHAT_CONTEXT` |
+//! | `Web3Backend` | [`HostBackend`]: the integrations client |
+//!
+//! State is instance-owned in the crate; the process holds exactly one engine
+//! and one service, built lazily the first time either is needed. Every seam
+//! resolves its configuration per call, so building early costs nothing.
+
+use std::sync::{Arc, OnceLock};
+
+use async_trait::async_trait;
+use serde_json::Value;
+use tinywallet_bus::wire::{
+ DerivedAccount, Scheme, SecretMaterial, Signature, SignedTransaction, TransactionSpec,
+};
+use tinywallet_web3::crypto::seams::{WalletAccounts, WalletSigner, Web3Backend};
+use tinywallet_web3::crypto::service::Web3Service;
+use tinywallet_web3::crypto::wallet::{WalletEngine, WalletSeams, WalletStatus};
+use tinywallet_web3::quote::QuoteOwner;
+use tinywallet_web3::seams::QuoteScope;
+
+use crate::config::rpc as config_rpc;
+use crate::config::Config;
+use crate::security::approval::APPROVAL_CHAT_CONTEXT;
+
+use super::client::CryptoClient;
+use super::wallet::endpoints::HostEndpoints;
+use super::wallet::transport::OpenHumanTransport;
+use super::wallet::{self, WalletChain};
+
+const LOG_PREFIX: &str = "[web3:seams]";
+
+/// The engine and the service built over it.
+struct Web3Runtime {
+ engine: Arc<WalletEngine>,
+ service: Arc<Web3Service>,
+}
+
+static RUNTIME: OnceLock<Web3Runtime> = OnceLock::new();
+
+fn runtime() -> &'static Web3Runtime {
+ RUNTIME.get_or_init(|| {
+ log::debug!("{LOG_PREFIX} building the wallet engine and web3 service");
+ let engine = Arc::new(WalletEngine::new(WalletSeams {
+ transport: Arc::new(OpenHumanTransport::new()),
+ endpoints: Arc::new(HostEndpoints),
+ signer: Arc::new(HostSigner),
+ accounts: Arc::new(HostAccounts),
+ scope: Arc::new(TaskLocalScope),
+ }));
+ let service = Arc::new(Web3Service::new(engine.clone(), Arc::new(HostBackend)));
+ Web3Runtime { engine, service }
+ })
+}
+
+/// The process-wide wallet engine.
+pub fn engine() -> Arc<WalletEngine> {
+ runtime().engine.clone()
+}
+
+/// The process-wide swap/bridge/dapp service.
+pub fn service() -> Arc<Web3Service> {
+ runtime().service.clone()
+}
+
+// ---------------------------------------------------------------------------
+// Signing
+// ---------------------------------------------------------------------------
+
+/// The chain's name as it appears in signer error messages.
+fn label(chain: WalletChain) -> &'static str {
+ match chain {
+ WalletChain::Evm => "EVM",
+ WalletChain::Btc => "BTC",
+ WalletChain::Solana => "Solana",
+ WalletChain::Tron => "Tron",
+ }
+}
+
+/// Wording of a failed account derivation.
+fn derive_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {
+ format!("failed to derive the {} account: {error}", label(chain))
+}
+
+/// Wording of a failed transaction signature.
+fn sign_transaction_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {
+ format!("failed to sign {} transaction: {error}", label(chain))
+}
+
+/// Wording of a failed message signature.
+fn sign_message_failure(chain: WalletChain, error: &impl std::fmt::Display) -> String {
+ format!("failed to sign the {} message: {error}", label(chain))
+}
+
+/// Derives accounts and signs by handing the recovery phrase to the loaded
+/// wallet module over a confidential call.
+///
+/// The phrase is decrypted here, for the one call, and sent only to a module
+/// that has proved it is an artifact this build pinned (see
+/// `modules::wallet::attested_proxy`). No private key is assembled in this
+/// process, and no mnemonic enters `tinywallet-web3`.
+///
+/// Errors from before the module call (wallet not set up, keyring, config,
+/// decrypt) are returned as they are; errors from the module carry the
+/// per-operation prefix the wallet has always used.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct HostSigner;
+
+impl HostSigner {
+ /// The config and decrypted secret material for `chain`.
+ async fn secret(chain: WalletChain) -> Result<(Config, SecretMaterial), String> {
+ let secret = wallet::secret_material(chain).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let mnemonic =
+ crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
+ .await?
+ .value;
+ Ok((
+ config,
+ SecretMaterial {
+ mnemonic,
+ derivation_path: secret.derivation_path,
+ chain: chain.to_chain(),
+ },
+ ))
+ }
+}
+
+#[async_trait]
+impl WalletSigner for HostSigner {
+ async fn derive_account(&self, chain: WalletChain) -> Result<DerivedAccount, String> {
+ let (config, secret) = Self::secret(chain).await?;
+ crate::modules::wallet::derive_account(&config, &secret)
+ .await
+ .map_err(|e| derive_failure(chain, &e))
+ }
+
+ async fn sign_transaction(
+ &self,
+ chain: WalletChain,
+ transaction: &TransactionSpec,
+ ) -> Result<SignedTransaction, String> {
+ let (config, secret) = Self::secret(chain).await?;
+ crate::modules::wallet::sign_transaction_in_module(&config, transaction, &secret)
+ .await
+ .map_err(|e| sign_transaction_failure(chain, &e))
+ }
+
+ async fn sign_message(
+ &self,
+ chain: WalletChain,
+ message: &[u8],
+ scheme: Scheme,
+ ) -> Result<Signature, String> {
+ let (config, secret) = Self::secret(chain).await?;
+ crate::modules::wallet::sign_message(&config, &secret, message, scheme)
+ .await
+ .map_err(|e| sign_message_failure(chain, &e))
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Accounts, scope, backend
+// ---------------------------------------------------------------------------
+
+/// Reports the wallet's stored set-up state.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct HostAccounts;
+
+#[async_trait]
+impl WalletAccounts for HostAccounts {
+ async fn status(&self) -> Result<WalletStatus, String> {
+ Ok(wallet::status().await?.value)
+ }
+}
+
+/// Reads the chat turn's owner from `APPROVAL_CHAT_CONTEXT`.
+///
+/// `Some(owner)` inside an interactive chat turn (the web channel installs the
+/// task-local around `run_chat_task`), `None` for non-chat callers (CLI, direct
+/// JSON-RPC, background triage, cron, sub-agents), which have no shared channel
+/// a quote id could leak through and so stay executable without an owner.
+///
+/// `tokio::task_local!` propagates across `.await` but **not** across
+/// `tokio::spawn`. If the chat path ever detaches the tool loop onto a
+/// freshly-spawned task without re-installing the scope, this silently starts
+/// returning `None` and the owner gate becomes a no-op. The crate calls this
+/// synchronously on the tool's own task, and the regression test in
+/// `seams_tests.rs` pins that it reads the task-local.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct TaskLocalScope;
+
+impl QuoteScope for TaskLocalScope {
+ fn current_owner(&self) -> Option<QuoteOwner> {
+ APPROVAL_CHAT_CONTEXT
+ .try_with(|ctx| QuoteOwner {
+ thread_id: ctx.thread_id.clone(),
+ client_id: ctx.client_id.clone(),
+ })
+ .ok()
+ }
+}
+
+/// The hosted swap/bridge quote service, over the integrations client.
+///
+/// Errors when the user is not signed in (no backend auth token), the same
+/// gate the composio tools use.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct HostBackend;
+
+impl HostBackend {
+ async fn client() -> Result<CryptoClient, String> {
+ let config = config_rpc::load_config_with_timeout().await?;
+ CryptoClient::from_config(&config)
+ }
+}
+
+#[async_trait]
+impl Web3Backend for HostBackend {
+ async fn routes(&self) -> Result<Value, String> {
+ Self::client().await?.routes().await
+ }
+
+ async fn swap_tx(&self, body: &Value) -> Result<Value, String> {
+ Self::client().await?.swap_tx(body).await
+ }
+
+ async fn bridge_tx(&self, body: &Value) -> Result<Value, String> {
+ Self::client().await?.bridge_tx(body).await
+ }
+}
+
+#[cfg(test)]
+#[path = "seams_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/seams_tests.rs b/crates/openhuman-core/src/web3/seams_tests.rs
new file mode 100644
index 0000000000..2e72c7e633
--- /dev/null
+++ b/crates/openhuman-core/src/web3/seams_tests.rs
@@ -0,0 +1,213 @@
+use super::*;
+use crate::security::approval::ApprovalChatContext;
+use crate::web3::wallet::test_support::{setup_wallet_in, TEST_LOCK};
+use crate::web3::wallet::{
+ execute_prepared, prepare_transfer, prepared_quotes_for_test, ExecutePreparedParams,
+ PrepareTransferParams,
+};
+use tempfile::TempDir;
+
+fn chat_ctx(name: &str) -> ApprovalChatContext {
+ ApprovalChatContext {
+ thread_id: format!("thread-{name}"),
+ client_id: format!("client-{name}"),
+ request_id: None,
+ }
+}
+
+fn owner(name: &str) -> QuoteOwner {
+ QuoteOwner {
+ thread_id: format!("thread-{name}"),
+ client_id: format!("client-{name}"),
+ }
+}
+
+// ── QuoteScope: the regression that guards the owner gate ────────────────
+
+/// The owner gate is only as good as this read. If the scope stopped reading
+/// `APPROVAL_CHAT_CONTEXT`, every quote would be ownerless and executable from
+/// any thread.
+#[tokio::test]
+async fn the_scope_reads_the_approval_chat_context_task_local() {
+ assert_eq!(
+ TaskLocalScope.current_owner(),
+ None,
+ "outside a chat turn there is no owner"
+ );
+ let inside = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("A"), async { TaskLocalScope.current_owner() })
+ .await;
+ assert_eq!(inside, Some(owner("A")));
+ // Nested scopes see the innermost turn, and the outer one is restored.
+ let nested = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("A"), async {
+ let inner = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("B"), async { TaskLocalScope.current_owner() })
+ .await;
+ (inner, TaskLocalScope.current_owner())
+ })
+ .await;
+ assert_eq!(nested, (Some(owner("B")), Some(owner("A"))));
+}
+
+/// `tokio::task_local!` does not cross `tokio::spawn`. The scope is documented
+/// as needing the tool's own task; this pins the behaviour the documentation
+/// warns about, so a change in it is noticed.
+#[tokio::test]
+async fn the_scope_does_not_cross_a_spawned_task() {
+ let spawned = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("A"), async {
+ tokio::spawn(async { TaskLocalScope.current_owner() })
+ .await
+ .unwrap()
+ })
+ .await;
+ assert_eq!(spawned, None);
+}
+
+// ── signer wording ───────────────────────────────────────────────────────
+
+#[test]
+fn signer_failures_keep_the_wording_the_wallet_has_always_used() {
+ assert_eq!(
+ derive_failure(WalletChain::Solana, &"no module"),
+ "failed to derive the Solana account: no module"
+ );
+ assert_eq!(
+ derive_failure(WalletChain::Tron, &"no module"),
+ "failed to derive the Tron account: no module"
+ );
+ assert_eq!(
+ sign_transaction_failure(WalletChain::Evm, &"no module"),
+ "failed to sign EVM transaction: no module"
+ );
+ assert_eq!(
+ sign_transaction_failure(WalletChain::Btc, &"no module"),
+ "failed to sign BTC transaction: no module"
+ );
+ assert_eq!(
+ sign_transaction_failure(WalletChain::Tron, &"no module"),
+ "failed to sign Tron transaction: no module"
+ );
+ assert_eq!(
+ sign_message_failure(WalletChain::Solana, &"no module"),
+ "failed to sign the Solana message: no module"
+ );
+ assert_eq!(label(WalletChain::Evm), "EVM");
+}
+
+// ── composition over the real wallet state ───────────────────────────────
+
+#[test]
+fn the_process_holds_one_engine_and_one_service() {
+ assert!(Arc::ptr_eq(&engine(), &engine()));
+ assert!(Arc::ptr_eq(&service(), &service()));
+}
+
+#[test]
+fn the_registered_agent_tools_run_over_the_process_service() {
+ let names: Vec<String> = crate::web3::all_web3_agent_tools()
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect();
+ assert_eq!(
+ names,
+ [
+ "web3_swap_quote",
+ "web3_swap_execute",
+ "web3_swap_routes",
+ "web3_bridge_quote",
+ "web3_bridge_execute",
+ "web3_dapp_call",
+ "web3_dapp_execute",
+ ]
+ );
+}
+
+#[tokio::test]
+async fn the_accounts_seam_reports_the_stored_wallet() {
+ let _guard = TEST_LOCK.lock();
+ let temp = TempDir::new().unwrap();
+ let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
+
+ let status = HostAccounts.status().await.unwrap();
+ assert!(status.configured);
+ assert_eq!(status.accounts.len(), 4);
+
+ // The engine reads the same state through the seam.
+ let rows = engine().chain_status().await.unwrap();
+ assert_eq!(rows.len(), 9);
+ assert!(rows.iter().all(|row| row.configured));
+ // 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 {
+ Some(network) => super::wallet::endpoints::rpc_url_for_evm_network(network),
+ None => super::wallet::endpoints::rpc_url_for_chain(row.chain),
+ };
+ assert_eq!(row.rpc_url, expected);
+ }
+}
+
+#[tokio::test]
+async fn the_backend_seam_needs_a_signed_in_session() {
+ let _guard = TEST_LOCK.lock();
+ let temp = TempDir::new().unwrap();
+ let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
+ let err = HostBackend.routes().await.unwrap_err();
+ assert!(err.contains("signed-in session"), "got: {err}");
+ let err = service().routes().await.unwrap_err();
+ assert!(err.contains("signed-in session"), "got: {err}");
+}
+
+/// A quote prepared in one chat turn cannot be executed from another, through
+/// the whole host stack: task-local scope, engine, quote store.
+#[tokio::test]
+async fn a_prepared_quote_is_bound_to_the_chat_thread_that_prepared_it() {
+ let _guard = TEST_LOCK.lock();
+ let temp = TempDir::new().unwrap();
+ let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
+
+ let prepared = APPROVAL_CHAT_CONTEXT
+ .scope(
+ chat_ctx("A"),
+ prepare_transfer(PrepareTransferParams {
+ chain: WalletChain::Evm,
+ to_address: "0x1111111111111111111111111111111111111111".into(),
+ amount_raw: "1000".into(),
+ asset_symbol: None,
+ evm_network: None,
+ }),
+ )
+ .await
+ .unwrap()
+ .value;
+ let quote_id = prepared.quote_id.clone();
+ let execute = |confirmed| ExecutePreparedParams {
+ quote_id: quote_id.clone(),
+ confirmed,
+ };
+ let not_found = format!("quote '{quote_id}' not found");
+
+ // Another thread gets the same answer as for a quote that never existed.
+ let from_b = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("B"), execute_prepared(execute(true)))
+ .await
+ .unwrap_err();
+ assert_eq!(from_b, not_found);
+ // So does a caller with no chat context at all.
+ let from_background = execute_prepared(execute(true)).await.unwrap_err();
+ assert_eq!(from_background, not_found);
+ // Neither attempt consumed it.
+ assert!(prepared_quotes_for_test()
+ .iter()
+ .any(|q| q.quote_id == quote_id));
+ // And confirmation is still required before anything is attempted.
+ let unconfirmed = APPROVAL_CHAT_CONTEXT
+ .scope(chat_ctx("A"), execute_prepared(execute(false)))
+ .await
+ .unwrap_err();
+ assert!(
+ unconfirmed.contains("confirmed: true"),
+ "got: {unconfirmed}"
+ );
+}
diff --git a/crates/openhuman-core/src/web3/store.rs b/crates/openhuman-core/src/web3/store.rs
deleted file mode 100644
index dcede9a152..0000000000
--- a/crates/openhuman-core/src/web3/store.rs
+++ /dev/null
@@ -1,206 +0,0 @@
-//! In-memory store for prepared web3 quotes plus the shared confirm→execute
-//! path. Mirrors the wallet quote store's security model: each quote is bound
-//! to the chat thread that prepared it (so a `quoteId` leaked into a shared
-//! channel can't be hijacked from another agent session), TTL'd, and capped.
-//!
-//! On execute the stored [`UnsignedTx`] is routed to the matching crate-internal
-//! wallet signer — EVM `to`/`data`/`value` or a Solana `VersionedTransaction`
-//! hex blob — which signs from the wallet's encrypted recovery phrase and
-//! broadcasts. The wallet remains the only place private keys are touched.
-
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-use once_cell::sync::Lazy;
-use parking_lot::Mutex;
-use serde::Serialize;
-use serde_json::Value;
-
-use crate::web3::wallet;
-
-use super::types::{ExecuteQuoteParams, UnsignedTx, Web3QuoteKind};
-
-const LOG_PREFIX: &str = "[web3]";
-const QUOTE_TTL_MS: u64 = 5 * 60 * 1000;
-const QUOTE_STORE_CAP: usize = 64;
-
-static QUOTE_STORE: Lazy<Mutex<Vec<StoredQuote>>> = Lazy::new(|| Mutex::new(Vec::new()));
-static QUOTE_COUNTER: AtomicU64 = AtomicU64::new(1);
-
-/// Identity of the chat thread that prepared a quote (see wallet quote-owner).
-#[derive(Debug, Clone, PartialEq, Eq)]
-struct QuoteOwner {
- thread_id: String,
- client_id: String,
-}
-
-fn current_owner() -> Option<QuoteOwner> {
- crate::security::approval::APPROVAL_CHAT_CONTEXT
- .try_with(|ctx| QuoteOwner {
- thread_id: ctx.thread_id.clone(),
- client_id: ctx.client_id.clone(),
- })
- .ok()
-}
-
-#[derive(Clone)]
-pub struct StoredQuote {
- pub quote_id: String,
- pub kind: Web3QuoteKind,
- pub unsigned: UnsignedTx,
- /// Human/agent-facing summary returned at prepare time and echoed on execute.
- pub summary: Value,
- owner: Option<QuoteOwner>,
- expires_at_ms: u64,
-}
-
-/// Result returned to the agent / RPC caller after broadcasting.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Web3ExecutionResult {
- pub quote_id: String,
- pub kind: Web3QuoteKind,
- pub transaction_hash: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub explorer_url: Option<String>,
- /// Simulated fee in the chain's smallest unit; `None` when not known at
- /// broadcast time (e.g. Solana's dynamic fee).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub fee_raw: Option<String>,
-}
-
-/// The prepared-quote envelope returned to the caller.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct Web3Quote {
- pub quote_id: String,
- pub kind: Web3QuoteKind,
- pub expires_at_ms: u64,
- /// Backend (deBridge) quote/estimation passthrough, or a dapp-call summary.
- pub quote: Value,
-}
-
-pub(crate) fn now_ms() -> u64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
-
-fn next_quote_id() -> String {
- let n = QUOTE_COUNTER.fetch_add(1, Ordering::Relaxed);
- format!("w3_{}_{}", now_ms(), n)
-}
-
-/// Store a prepared quote and return the caller-facing envelope.
-pub fn store_quote(kind: Web3QuoteKind, unsigned: UnsignedTx, summary: Value) -> Web3Quote {
- let now = now_ms();
- let expires_at_ms = now + QUOTE_TTL_MS;
- let quote = StoredQuote {
- quote_id: next_quote_id(),
- kind,
- unsigned,
- summary: summary.clone(),
- owner: current_owner(),
- expires_at_ms,
- };
- let envelope = Web3Quote {
- quote_id: quote.quote_id.clone(),
- kind,
- expires_at_ms,
- quote: summary,
- };
- let mut store = QUOTE_STORE.lock();
- store.retain(|q| q.expires_at_ms > now);
- if store.len() >= QUOTE_STORE_CAP {
- store.remove(0);
- }
- store.push(quote);
- envelope
-}
-
-/// Remove the quote iff the caller's chat-thread owner matches. Returns the
-/// byte-identical "not found" error on owner mismatch (no enumeration oracle).
-fn take_quote_for(quote_id: &str, caller: Option<QuoteOwner>) -> Result<StoredQuote, String> {
- let not_found = || format!("quote '{quote_id}' not found");
- let mut store = QUOTE_STORE.lock();
- let now = now_ms();
- let pos = store
- .iter()
- .position(|q| q.quote_id == quote_id)
- .ok_or_else(not_found)?;
- if store[pos].owner != caller {
- return Err(not_found());
- }
- let quote = store.remove(pos);
- if quote.expires_at_ms <= now {
- return Err(format!("quote '{quote_id}' expired"));
- }
- Ok(quote)
-}
-
-#[cfg(test)]
-pub(crate) fn reset_store_for_tests() {
- QUOTE_STORE.lock().clear();
-}
-
-#[cfg(test)]
-pub(crate) fn stored_quote_count() -> usize {
- QUOTE_STORE.lock().len()
-}
-
-/// Confirm and execute a prepared quote: sign+broadcast the stored unsigned
-/// transaction via the wallet, restoring the quote (refreshed TTL) on failure
-/// so it stays retryable.
-pub async fn execute_quote(
- params: ExecuteQuoteParams,
-) -> Result<crate::core::Outcome<Web3ExecutionResult>, String> {
- if !params.confirmed {
- return Err("execute requires `confirmed: true`".to_string());
- }
- let caller = current_owner();
- let quote = take_quote_for(&params.quote_id, caller)?;
- let kind = quote.kind;
- let restorable = quote.clone();
-
- let result = match &quote.unsigned {
- UnsignedTx::Evm {
- network,
- to,
- data,
- value,
- } => wallet::sign_and_broadcast_evm(*network, to, data.clone(), value).await,
- UnsignedTx::Solana { tx_blob_hex } => wallet::sign_and_broadcast_solana(tx_blob_hex).await,
- };
-
- let broadcast = match result {
- Ok(b) => b,
- Err(error) => {
- // Restore with a refreshed TTL so the caller can retry.
- let mut refreshed = restorable;
- refreshed.expires_at_ms = now_ms() + QUOTE_TTL_MS;
- let mut store = QUOTE_STORE.lock();
- if store.len() >= QUOTE_STORE_CAP {
- store.remove(0);
- }
- store.push(refreshed);
- tracing::warn!(
- "{LOG_PREFIX} execute quote_id={} kind={:?} failed (restored): {error}",
- params.quote_id,
- kind
- );
- return Err(error);
- }
- };
-
- Ok(crate::core::Outcome::new(
- Web3ExecutionResult {
- quote_id: params.quote_id,
- kind,
- transaction_hash: broadcast.transaction_hash,
- explorer_url: broadcast.explorer_url,
- fee_raw: broadcast.fee_raw,
- },
- vec!["web3 transaction broadcast".to_string()],
- ))
-}
diff --git a/crates/openhuman-core/src/web3/swap/README.md b/crates/openhuman-core/src/web3/swap/README.md
index b7d15d8d9c..cda5da497f 100644
--- a/crates/openhuman-core/src/web3/swap/README.md
+++ b/crates/openhuman-core/src/web3/swap/README.md
@@ -11,17 +11,17 @@ A swap quote asks deBridge for a route to exchange one token for another on
the same chain. Cross-chain requests are rejected here with a pointer to
`web3_bridge`, since deBridge's `/swap` endpoint is single-chain only. The
actual quote logic (address defaulting, the backend call, unsigned-tx
-extraction) lives in the shared `super::ops::quote_swap`; this module only
-owns the RPC controllers (`schemas.rs`) and the agent tools (`tools.rs`) for
-the `web3_swap` namespace.
+extraction) lives in `Web3Service::quote_swap` in the vendored `tinywallet-web3`
+crate; this module only owns the RPC controllers (`schemas.rs`) for the
+`web3_swap` namespace. The agent tools are in
+`tinywallet_web3::tools::web3`.
## Key files
| File | Role |
| --- | --- |
-| `mod.rs` | Re-exports `Web3SwapExecuteTool`, `Web3SwapQuoteTool`, `Web3SwapRoutesTool` from `tools.rs`. |
-| `schemas.rs` | `web3_swap` RPC controller schemas and handlers: `quote`, `execute`, `routes`. Handlers deserialize params and delegate to `super::super::ops::quote_swap` / `super::super::store::execute_quote` / `super::super::ops::routes`. |
-| `tools.rs` | The three agent tools: `Web3SwapQuoteTool` (`web3_swap_quote`), `Web3SwapExecuteTool` (`web3_swap_execute`), `Web3SwapRoutesTool` (`web3_swap_routes`). All delegate to the same `ops`/`store` functions as the RPC handlers, so behavior is identical between the two entry points. |
+| `mod.rs` | Module docs. |
+| `schemas.rs` | `web3_swap` RPC controller schemas and handlers: `quote`, `execute`, `routes`. Handlers deserialize params and delegate to the process-wide `Web3Service` (`web3::seams::service()`): `quote_swap` / `execute_quote` / `routes`, wrapping the result in `Outcome`. |
## RPC / controllers
diff --git a/crates/openhuman-core/src/web3/swap/mod.rs b/crates/openhuman-core/src/web3/swap/mod.rs
index ab55a02ee5..4d72f60bc7 100644
--- a/crates/openhuman-core/src/web3/swap/mod.rs
+++ b/crates/openhuman-core/src/web3/swap/mod.rs
@@ -1,9 +1,6 @@
//! `web3_swap` — single-chain swaps via deBridge. Cross-chain swaps are
-//! redirected to `web3_bridge`. Logic lives in the shared
-//! [`super::ops`]/[`super::store`]; this module owns the RPC controllers and
-//! agent tools.
+//! redirected to `web3_bridge`. Logic lives in `tinywallet_web3::crypto::service`
+//! (reached through [`super::seams`]); this module owns the RPC controllers and
+//! their schemas. The agent tools are in `tinywallet_web3::tools::web3`.
pub mod schemas;
-pub mod tools;
-
-pub use tools::{Web3SwapExecuteTool, Web3SwapQuoteTool, Web3SwapRoutesTool};
diff --git a/crates/openhuman-core/src/web3/swap/schemas.rs b/crates/openhuman-core/src/web3/swap/schemas.rs
index cd2881698a..f9f47281e3 100644
--- a/crates/openhuman-core/src/web3/swap/schemas.rs
+++ b/crates/openhuman-core/src/web3/swap/schemas.rs
@@ -5,9 +5,9 @@
use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
+use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::store::execute_quote;
+use super::super::seams::service;
use super::super::types::{ExecuteQuoteParams, SwapQuoteParams};
use super::super::{execute_inputs, json_result, opt_str, req_json};
@@ -88,9 +88,8 @@ fn handle_quote(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: SwapQuoteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- super::super::ops::quote_swap(parsed)
- .await?
- .into_cli_compatible_json()
+ let quote = service().quote_swap(parsed).await?;
+ Outcome::new(quote, vec!["web3 swap prepared".to_string()]).into_cli_compatible_json()
})
}
@@ -98,14 +97,16 @@ fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- execute_quote(parsed).await?.into_cli_compatible_json()
+ let result = service().execute_quote(parsed).await?;
+ Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
+ .into_cli_compatible_json()
})
}
fn handle_routes(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- super::super::ops::routes()
- .await?
+ let routes = service().routes().await?;
+ Outcome::new(routes, vec!["web3 supported routes listed".to_string()])
.into_cli_compatible_json()
})
}
diff --git a/crates/openhuman-core/src/web3/swap/tools.rs b/crates/openhuman-core/src/web3/swap/tools.rs
deleted file mode 100644
index 6bf88fe132..0000000000
--- a/crates/openhuman-core/src/web3/swap/tools.rs
+++ /dev/null
@@ -1,154 +0,0 @@
-//! `web3_swap` agent tools: quote a single-chain swap, execute a prepared
-//! quote, and list supported routes. All delegate to [`super::super::ops`] /
-//! [`super::super::store`]; signing happens in the wallet.
-
-use async_trait::async_trait;
-use serde_json::json;
-
-use crate::web3::store::execute_quote;
-use crate::web3::types::{ExecuteQuoteParams, SwapQuoteParams};
-use crate::web3::{execute_tool_schema, ops, to_tool_result};
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct Web3SwapQuoteTool;
-pub struct Web3SwapExecuteTool;
-pub struct Web3SwapRoutesTool;
-
-impl Default for Web3SwapQuoteTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3SwapQuoteTool {
- pub fn new() -> Self {
- Self
- }
-}
-impl Default for Web3SwapExecuteTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3SwapExecuteTool {
- pub fn new() -> Self {
- Self
- }
-}
-impl Default for Web3SwapRoutesTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl Web3SwapRoutesTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for Web3SwapQuoteTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_swap_quote"
- }
- fn description(&self) -> &str {
- "Prepare a single-chain crypto swap via deBridge. Returns a quote + quoteId to confirm with web3_swap_execute. For cross-chain swaps use web3_bridge_quote."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "chainId": {"type": "integer", "description": "deBridge chain id (1 ETH, 56 BNB, 137 Polygon, 8453 Base, 42161 Arbitrum, 10 Optimism, 7565164 Solana)."},
- "tokenIn": {"type": "string", "description": "Input token address (zero address for native)."},
- "tokenInAmount": {"type": "string", "description": "Input amount in the token's smallest unit."},
- "tokenOut": {"type": "string", "description": "Output token address."},
- "tokenOutRecipient": {"type": "string", "description": "Optional. Defaults to the wallet's own address."},
- "senderAddress": {"type": "string", "description": "Optional. Defaults to the wallet's own address."},
- "slippage": {"type": "string", "description": "Optional slippage percent or 'auto' (default 'auto')."}
- },
- "required": ["chainId", "tokenIn", "tokenInAmount", "tokenOut"],
- "additionalProperties": false
- })
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: SwapQuoteParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(ops::quote_swap(params).await))
- }
-}
-
-#[async_trait]
-impl Tool for Web3SwapExecuteTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_swap_execute"
- }
- fn description(&self) -> &str {
- "Confirm and execute a prepared web3_swap quote (signs + broadcasts)."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- execute_tool_schema()
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: ExecuteQuoteParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => return Ok(ToolResult::error(format!("invalid arguments: {e}"))),
- };
- Ok(to_tool_result(execute_quote(params).await))
- }
-}
-
-#[async_trait]
-impl Tool for Web3SwapRoutesTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "web3_swap_routes"
- }
- fn description(&self) -> &str {
- "List the chains deBridge can swap/bridge between."
- }
- fn parameters_schema(&self) -> serde_json::Value {
- json!({"type": "object", "properties": {}, "additionalProperties": false})
- }
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
- async fn execute_with_options(
- &self,
- _args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- Ok(to_tool_result(ops::routes().await))
- }
-}
diff --git a/crates/openhuman-core/src/web3/types.rs b/crates/openhuman-core/src/web3/types.rs
deleted file mode 100644
index 444b1f389e..0000000000
--- a/crates/openhuman-core/src/web3/types.rs
+++ /dev/null
@@ -1,123 +0,0 @@
-//! Shared web3 types: deBridge chain-id ↔ local signer mapping, request
-//! params for the swap/bridge/dapp surfaces, and the stored quote shape.
-//!
-//! The backend (`/agent-integrations/crypto/*`, deBridge DLN) returns a
-//! ready-to-sign **unsigned transaction**. This module only needs to know the
-//! *chain family* of a deBridge chain id so it can route signing to the right
-//! wallet primitive (EVM `to`/`data`/`value`, or a Solana `VersionedTransaction`
-//! hex blob).
-
-use serde::{Deserialize, Serialize};
-
-use crate::web3::wallet::EvmNetwork;
-
-/// deBridge's internal chain id for Solana mainnet (`/supported-chains-info`).
-/// EVM chains use their real chain ids; Solana is a synthetic id. Mirrors the
-/// backend's `DEBRIDGE_SOLANA_CHAIN_ID` default.
-pub const DEBRIDGE_SOLANA_CHAIN_ID: u64 = 7_565_164;
-
-/// Which local signer can sign for a given deBridge chain id.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum ChainFamily {
- /// An EVM chain — sign+broadcast `to`/`data`/`value`.
- Evm(EvmNetwork),
- /// Solana — sign+broadcast a serialized `VersionedTransaction`.
- Solana,
-}
-
-/// Map a deBridge chain id to the local signer family, or `None` when the
-/// wallet has no signer for it (deBridge may route chains we can't sign for).
-pub fn chain_family(debridge_chain_id: u64) -> Option<ChainFamily> {
- match debridge_chain_id {
- 1 => Some(ChainFamily::Evm(EvmNetwork::EthereumMainnet)),
- 10 => Some(ChainFamily::Evm(EvmNetwork::OptimismMainnet)),
- 56 => Some(ChainFamily::Evm(EvmNetwork::BscMainnet)),
- 137 => Some(ChainFamily::Evm(EvmNetwork::PolygonMainnet)),
- 8453 => Some(ChainFamily::Evm(EvmNetwork::BaseMainnet)),
- 42161 => Some(ChainFamily::Evm(EvmNetwork::ArbitrumOne)),
- DEBRIDGE_SOLANA_CHAIN_ID => Some(ChainFamily::Solana),
- _ => None,
- }
-}
-
-/// Single-chain swap request (forwarded to backend `/crypto/swap`).
-/// `senderAddress` / `tokenOutRecipient` default to the wallet's own derived
-/// address for the chain family when omitted.
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SwapQuoteParams {
- pub chain_id: u64,
- pub token_in: String,
- pub token_in_amount: String,
- pub token_out: String,
- #[serde(default)]
- pub token_out_recipient: Option<String>,
- #[serde(default)]
- pub sender_address: Option<String>,
- #[serde(default)]
- pub slippage: Option<String>,
-}
-
-/// Cross-chain bridge request (forwarded to backend `/crypto/bridge`).
-/// Authority + recipient addresses default to the wallet's derived addresses
-/// for the relevant chain family when omitted.
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BridgeQuoteParams {
- pub src_chain_id: u64,
- pub src_chain_token_in: String,
- pub src_chain_token_in_amount: String,
- pub dst_chain_id: u64,
- pub dst_chain_token_out: String,
- #[serde(default)]
- pub dst_chain_token_out_amount: Option<String>,
- #[serde(default)]
- pub dst_chain_token_out_recipient: Option<String>,
- #[serde(default)]
- pub src_chain_order_authority_address: Option<String>,
- #[serde(default)]
- pub dst_chain_order_authority_address: Option<String>,
-}
-
-/// Generic EVM dapp contract call (no backend; signed directly via the wallet).
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DappCallParams {
- pub contract_address: String,
- pub calldata: String,
- #[serde(default)]
- pub value_raw: Option<String>,
- #[serde(default)]
- pub evm_network: Option<EvmNetwork>,
-}
-
-/// Confirm + execute a prepared web3 quote.
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ExecuteQuoteParams {
- pub quote_id: String,
- pub confirmed: bool,
-}
-
-/// What a stored quote signs+broadcasts on execute.
-#[derive(Debug, Clone)]
-pub enum UnsignedTx {
- /// EVM transaction: `(network, to, data, value)`.
- Evm {
- network: EvmNetwork,
- to: String,
- data: Option<String>,
- value: String,
- },
- /// Solana serialized `VersionedTransaction`, hex-encoded.
- Solana { tx_blob_hex: String },
-}
-
-/// The kind of web3 operation a quote represents (for summaries/logging).
-#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum Web3QuoteKind {
- Swap,
- Bridge,
- DappCall,
-}
diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md
index c92ced5e7b..dbb03797a5 100644
--- a/crates/openhuman-core/src/web3/wallet/README.md
+++ b/crates/openhuman-core/src/web3/wallet/README.md
@@ -17,14 +17,26 @@ broadcasts. The binary never assembles a private key outside `cfg(test)`.
Higher-level DeFi affordances (swaps, bridges, generic dapp/contract calls)
live in the separate [`web3`](../README.md) module, which builds on the
-wallet's crate-internal `sign_and_broadcast_evm` / `sign_and_broadcast_solana`
-primitives. They are not part of the wallet's agent or RPC surface.
+engine's `sign_and_broadcast_evm` / `sign_and_broadcast_solana` primitives.
+They are not part of the wallet's agent or RPC surface.
+
+## Where the logic lives
+
+The wallet engine (balances, the prepare/confirm/execute flow, the per-chain
+signing choreography, static reference data, the agent tools) lives in the
+vendored `tinywallet-web3` crate (`vendor/tinywallet/crates/tinywallet-web3`,
+`crypto::{wallet, execution, chains, defaults, abi}` and `tools::wallet`). What
+stays here is the host: onboarding state and secrets (`ops`), the `Outcome`
+adapters (`execution.rs`), endpoint resolution from the environment
+(`endpoints.rs`), the host `Transport` (`transport.rs`, `rpc.rs`) and the RPC
+controllers (`schemas.rs`). The crate reaches this module only through seams,
+implemented in [`web3/seams.rs`](../seams.rs).
## Compile-time gate (`web3` feature)
`pub mod wallet;` in `web3/mod.rs` is always compiled: it is a facade. The
-real implementation (`ops`, `execution`, `defaults`, `abi`, `chains`,
-`schemas`, `tools`, `transport`) is gated behind the default-ON `web3` Cargo
+real implementation (`ops`, `execution`, `endpoints`, `schemas`, `tools`,
+`transport`) is gated behind the default-ON `web3` Cargo
feature (shared with `web3` and `web3::x402`). When the feature is off,
`stub` takes its place and mirrors the subset of the public surface that
always-on or other-gated callers depend on: `WALLET_NOT_CONFIGURED_MESSAGE`,
@@ -45,41 +57,31 @@ Signatures must match the real ones exactly; `cargo check
- Sign and broadcast confirmed quotes per chain; restore (and TTL-refresh) the quote on failure so it stays retryable.
- Bind each quote to the chat thread that prepared it so a leaked `quote_id` in a shared channel can't be hijacked from another agent session.
- Expose six agent tools (`wallet_status`, `wallet_chain_status`, `wallet_prepare_transfer`, `wallet_tx_status`, `wallet_tx_receipt`, `wallet_lookup_tx`) and thirteen `wallet.*` RPC controllers.
-- Provide crate-internal `sign_and_broadcast_evm` / `sign_and_broadcast_solana` primitives for the `web3` layer (sign and broadcast an externally-built unsigned transaction). Not exposed to the agent or RPC surface.
+- The engine provides `sign_and_broadcast_evm` / `sign_and_broadcast_solana` primitives for the `web3` layer (sign and broadcast an externally-built unsigned transaction). Not exposed to the agent or RPC surface.
## Key files
| File | Role |
| --- | --- |
| `crates/openhuman-core/src/web3/wallet/mod.rs` | Export-focused module root; module docstring, `mod`/`pub use` re-exports. |
-| `crates/openhuman-core/src/web3/wallet/ops.rs` | Onboarding metadata and secret persistence: `WalletChain`/`WalletAccount`/`WalletStatus` types, `setup`/`status`/`reveal_recovery_phrase`, atomic `wallet-state.json` writes (temp-file + fsync), corrupt-state quarantine, keychain load/save/migrate, `validate_setup`, and `secret_material` (crate-internal) used by chain signers. |
-| `crates/openhuman-core/src/web3/wallet/execution.rs` | Execution surface: balances/network_defaults/supported_assets/chain_status reads, `prepare_transfer`/`execute_prepared` (native and token transfers only), `tx_status`/`tx_receipt`/`lookup_tx` readers, the crate-internal `sign_and_broadcast_evm`/`sign_and_broadcast_solana` wrappers over `chains::`, the in-memory quote store (TTL'd, capped at 64), `QuoteOwner` chat-thread binding, amount/address/calldata validation, fee estimation, hex/u256 helpers. |
-| `crates/openhuman-core/src/web3/wallet/defaults.rs` | `EvmNetwork` enum (chain id, default RPC, explorer base, env var), default RPC/REST URLs for BTC/Solana/Tron, env-override resolution, and per-chain/per-network asset catalogs. |
-| `crates/openhuman-core/src/web3/wallet/abi.rs` | `encode_erc20_transfer`, which delegates the `transfer(address,uint256)` calldata encoding to `tinywallet_bus::abi`, mapping its typed errors (`InvalidRecipient`/`InvalidAmount`) to the plain-`String` shape the RPC/tool surface uses. |
+| `crates/openhuman-core/src/web3/wallet/ops.rs` | Onboarding metadata and secret persistence: `setup`/`status`/`reveal_recovery_phrase`, atomic `wallet-state.json` writes (temp-file + fsync), corrupt-state quarantine, keychain load/save/migrate, `validate_setup`, and `secret_material` (crate-internal) used by the host signer. `ops/types.rs` re-exports `WalletChain`/`WalletAccount`/`WalletStatus`/`WALLET_NOT_CONFIGURED_MESSAGE` from `tinywallet-web3` and keeps the persisted shape and the setup params. |
+| `crates/openhuman-core/src/web3/wallet/execution.rs` | `Outcome` adapters over the process-wide engine: `balances`/`network_defaults`/`supported_assets`/`chain_status`, `prepare_transfer`/`execute_prepared`, `tx_status`/`tx_receipt`/`lookup_tx`, `prepared_quotes_for_test`. Re-exports the engine's wire types. |
+| `crates/openhuman-core/src/web3/wallet/endpoints.rs` | The `OPENHUMAN_WALLET_RPC_*` / `OPENHUMAN_SOLANA_CLUSTER` environment resolution, and `HostEndpoints`, the `RpcEndpoints` seam. The static defaults are in the crate. |
| `crates/openhuman-core/src/web3/wallet/schemas.rs` | RPC controller schemas and `handle_*` dispatchers delegating to `ops`/`execution`; `all_wallet_controller_schemas` / `all_wallet_registered_controllers`. |
-| `crates/openhuman-core/src/web3/wallet/rpc.rs` | Network transport, not RPC controllers: shared `reqwest::Client`, JSON-RPC POST (`rpc_call`, `evm_rpc_call`, `rpc_call_to`), REST GET/POST helpers, URL redaction for logs. |
+| `crates/openhuman-core/src/web3/wallet/rpc.rs` | Network transport, not RPC controllers: shared `reqwest::Client`, JSON-RPC POST (`rpc_call`, `rpc_call_to`), REST GET/POST helpers, URL redaction for logs. |
| `crates/openhuman-core/src/web3/wallet/transport.rs` | OpenHuman's implementation of the `tinywallet_bus::rpc::Transport` seam: resolves a `tinywallet_bus::rpc::NetworkId` to an endpoint (including `OPENHUMAN_WALLET_RPC_<CHAIN>` overrides), redacts URLs for logs, and reuses `rpc.rs`'s shared `reqwest` client. Classifies errors conservatively: anything it cannot prove is a transport failure is reported as `TransportError::Rpc` (authoritative) rather than `Unreachable` (retryable), so an unclassifiable error stops a failover loop instead of risking a double broadcast. |
-| `crates/openhuman-core/src/web3/wallet/tools.rs` | Re-exports the six agent tool structs from `tools/`. |
-| `crates/openhuman-core/src/web3/wallet/tools/status.rs` | `WalletStatusTool` (`wallet_status`). |
-| `crates/openhuman-core/src/web3/wallet/tools/chain_status.rs` | `WalletChainStatusTool` (`wallet_chain_status`). |
-| `crates/openhuman-core/src/web3/wallet/tools/prepare_transfer.rs` | `WalletPrepareTransferTool` (`wallet_prepare_transfer`). |
-| `crates/openhuman-core/src/web3/wallet/tools/tx_query.rs` | `WalletTxStatusTool` (`wallet_tx_status`), `WalletTxReceiptTool` (`wallet_tx_receipt`), `WalletLookupTxTool` (`wallet_lookup_tx`); these share a `{chain, hash, evmNetwork?}` input and delegate to the matching `wallet::*` dispatcher. |
-| `crates/openhuman-core/src/web3/wallet/chains/mod.rs` | Per-chain executor namespace; docstring of the small per-chain surface (`execute_*_quote`, `native_balance`, `validate_*_address`). |
-| `crates/openhuman-core/src/web3/wallet/chains/evm.rs` | EVM path: validates addresses with `tinywallet_bus::address::evm::validate`, gathers `eth_chainId`/nonce/`eth_gasPrice`/`eth_estimateGas` over JSON-RPC, builds a legacy gas-price `tinywallet_bus::wire::TransactionSpec::Evm`, signs it in the module via `modules::wallet::sign_transaction_in_module`, and broadcasts with `eth_sendRawTransaction`. One derivation path shared across all EVM networks. Also hosts the crate-internal `sign_and_broadcast_evm`. |
-| `crates/openhuman-core/src/web3/wallet/chains/btc.rs` | Bitcoin P2WPKH (BIP84) path: Esplora REST UTXO discovery, largest-first coin selection and fee policy stay here; the `TransactionSpec::Btc` (selected UTXOs, amount, fee) is encoded and signed in the module via `sign_transaction_in_module`, then broadcast over Esplora. Address checks via `tinywallet_bus::address::btc::{validate, validate_sender}`. |
-| `crates/openhuman-core/src/web3/wallet/chains/solana.rs` | Solana native and SPL transfers: hand-rolled message/transaction wire format (`sha2`, `bs58`, `curve25519_dalek` for the off-curve ATA check) so `solana-sdk` is not pulled in; the message is signed in the module via `modules::wallet::sign_message` (`Scheme::Ed25519`), broadcast over JSON-RPC. The `ed25519_dalek` local signer is `cfg(test)` only. Also hosts `sign_and_broadcast_versioned` behind the crate-internal `sign_and_broadcast_solana`. |
-| `crates/openhuman-core/src/web3/wallet/chains/tron.rs` | Tron native and TRC20 transfers over TronGrid REST: the node builds the raw transaction, `tinywallet_bus::tx::tron::{recompute_txid, verify_contract}` checks it matches what was requested, then it is signed in the module as `TransactionSpec::Tron`. Address checks via `tinywallet_bus::address::tron`. |
+| `crates/openhuman-core/src/web3/wallet/tools.rs` | Re-exports the six agent tool structs from `tinywallet_web3::tools::wallet`. |
| `crates/openhuman-core/src/web3/wallet/stub.rs` | Disabled-wallet facade compiled when `web3` is off; mirrors the subset of the real surface that always-on or other-gated callers need, with no-op or disabled-error bodies. See the Compile-time gate section. |
-| `crates/openhuman-core/src/web3/wallet/test_support.rs` | `#[cfg(test)]` shared plumbing: `TEST_LOCK`, `setup_wallet_in` (deterministic "abandon ... about" mnemonic), per-chain sample addresses. |
+| `crates/openhuman-core/src/web3/wallet/test_support.rs` | `#[cfg(test)]` shared plumbing for the keyring/setup tests: `TEST_LOCK`, `setup_wallet_in` (deterministic "abandon ... about" mnemonic), per-chain sample addresses. The chain, execution and quote tests moved to `tinywallet-web3` with fakes. |
## Public surface
From `mod.rs` re-exports:
- Onboarding (`ops`): `setup`, `status`, `reveal_recovery_phrase`, `RevealRecoveryPhraseResult`, `WalletAccount`, `WalletChain`, `WalletSetupParams`, `WalletSetupSource`, `WalletStatus`, `WALLET_NOT_CONFIGURED_MESSAGE`; `pub(crate) secret_material`.
-- Execution (`execution`): `balances`, `chain_status`, `execute_prepared`, `wallet_network_defaults`, `prepare_transfer`, `tx_status`, `tx_receipt`, `lookup_tx`, `supported_assets`, `prepared_quotes_for_test`; types `BalanceInfo`, `ChainStatus`, `ExecutePreparedParams`, `ExecutionResult`, `PrepareTransferParams`, `PreparedKind` (NativeTransfer / TokenTransfer), `PreparedStatus`, `PreparedTransaction`, `ProviderStatus`, `SupportedAsset`, `TxState`, `TxStatusInfo`, `TxReceiptInfo`, `TxLookupInfo`. Crate-internal: `sign_and_broadcast_evm`, `sign_and_broadcast_solana`, `RawBroadcastResult`.
-- Defaults (`defaults`): `asset_catalog`, `default_rpc_url`, `env_var_for_chain`, `evm_asset_catalog`, `explorer_tx_url`, `find_asset`, `find_asset_for_network`, `network_defaults`, `rpc_source_for_chain`, `rpc_url_for_chain`, `rpc_url_for_evm_network`, `solana_cluster`, `EvmNetwork`, `RpcSource`, `SolanaCluster`, `WalletAssetDefinition`, `WalletNetworkDefaults`.
-- ABI: `encode_erc20_transfer`.
+- Execution (`execution`): `balances`, `chain_status`, `execute_prepared`, `wallet_network_defaults`, `prepare_transfer`, `tx_status`, `tx_receipt`, `lookup_tx`, `supported_assets`, `prepared_quotes_for_test`; types `BalanceInfo`, `ChainStatus`, `ExecutePreparedParams`, `ExecutionResult`, `PrepareTransferParams`, `PreparedKind`, `PreparedStatus`, `PreparedTransaction`, `ProviderStatus`, `SupportedAsset`, `TxState`, `TxStatusInfo`, `TxReceiptInfo`, `TxLookupInfo` (all from `tinywallet-web3`).
+- Defaults: `solana_cluster` (host, env-driven) and, from `tinywallet-web3`, `evm_asset_catalog`, `explorer_tx_url`, `EvmNetwork`, `RpcSource`, `SolanaCluster`, `WalletAssetDefinition`, `WalletNetworkDefaults`.
+- ABI: `encode_erc20_transfer` (from `tinywallet-web3`).
- Schemas: `all_controller_schemas`, `all_registered_controllers`, `all_wallet_controller_schemas`, `all_wallet_registered_controllers`, `schemas`, `wallet_schemas`.
## RPC / controllers
@@ -106,7 +108,7 @@ Wired into the registry in `crates/openhuman-core/src/core/all.rs` (controllers
## Agent tools
-Owned in `tools/`, re-exported via `tools.rs`:
+Defined in `tinywallet_web3::tools::wallet`, re-exported via `tools.rs`, built over the process-wide engine in `tools/ops.rs`:
- `WalletStatusTool`, tool name `wallet_status`
- `WalletChainStatusTool`, tool name `wallet_chain_status`
@@ -125,20 +127,20 @@ None. The module publishes or subscribes no `DomainEvent`s and has no `bus.rs`.
- `{workspace_dir}/state/wallet-state.json`: `StoredWalletState`, consent flag, source, mnemonic word count, accounts, `updated_at_ms`, and (only as fallback) the encrypted mnemonic. Written atomically (temp file + `sync_all` + dir fsync + `persist`), guarded by a process-wide `WALLET_STATE_FILE_LOCK`. Corrupt/unreadable/invalid files are quarantined to `...json.corrupted.<ts>`.
- OS keychain: preferred home for the encrypted mnemonic under key `wallet.mnemonic`, scoped by a workspace-derived user id (`crate::security::keyring`), used only when `keyring_consent::policy::check_secret_access()` returns `Proceed` and the keyring is available. When available, the secret is stripped from JSON; load promotes any JSON-resident secret into the keychain.
-- In-memory quote store (`execution.rs`): `PreparedTransaction`s, 5-minute TTL, cap 64, pruned on access. Not persisted across restarts.
+- In-memory quote store (instance-owned by the `WalletEngine`, `tinywallet_web3::quote::QuoteStore`): `PreparedTransaction`s, 5-minute TTL, cap 64, pruned on insert. Not persisted across restarts.
## Dependencies
- `crate::config` (`Config`, `config::rpc::load_config_with_timeout`): resolves workspace dir and config for state paths, keychain user id, and decryption.
- `crate::security::keyring` (`is_available`/`get`/`set`): OS keychain storage for the encrypted mnemonic.
-- `crate::security::encryption::rpc` (`encrypt_secret`/`decrypt_secret`): chain executors decrypt the recovery phrase before handing it to the wallet module.
+- `crate::security::encryption::rpc` (`encrypt_secret`/`decrypt_secret`): `HostSigner` decrypts the recovery phrase before handing it to the wallet module.
- `crate::modules::wallet` (`derive_account`, `sign_transaction_in_module`, `sign_message`): the loaded `tinywallet` native module does every derivation and signature; the phrase is only sent after the module passes the attestation check (`modules::wallet::attested_proxy`).
-- `crate::security::approval::APPROVAL_CHAT_CONTEXT`: task-local chat owner (`thread_id`/`client_id`) used to bind quotes to their originating thread.
-- `tinytools`: `Tool`/`ToolResult`/`ToolCallOptions` for the agent tools.
+- `crate::security::approval::APPROVAL_CHAT_CONTEXT`: task-local chat owner (`thread_id`/`client_id`), read by `TaskLocalScope`, used to bind quotes to their originating thread.
+- `tinywallet-web3` (optional, feature `tools`, enabled by `web3`): the engine, chains, quote store and agent tools; the host implements its seams in `web3/seams.rs`.
- `crate::core::all` (`ControllerFuture`, `RegisteredController`) and `crate::core` (`ControllerSchema`, `FieldSchema`, `TypeSchema`): RPC controller registry wiring.
- `crate::core::Outcome`: standard RPC return shape.
- `tinywallet-bus` (`vendor/tinywallet/crates/tinywallet-bus`, optional, gated by the `web3` feature; features `btc`, `evm`, `solana`, `tron`, `keccak`, `net`, `wire`, `eip712`, `abi`, `tx-codec`): the contract crate. It owns address formats (parsing/validation/conversion) and the wire types crossing the `Transport` seam (`SecretMaterial`, `TransactionSpec`, `NetworkId`), the ERC-20/EIP-712 encoders, and the Tron verifier. Per Cargo.toml's own rationale, this is taken as the contract crate and not the root `tinywallet` crate: key derivation, transaction building, signing and the chain clients (including the `bitcoin` crate and its native secp256k1 build) live inside that loaded module now, so this binary links none of it. The root `tinywallet` crate is still a dev-dependency, used only so test fixtures can derive a known account from a BIP-39 vector phrase.
-- Other external crates: `curve25519-dalek` (optional, pulled in by the `web3` feature; Solana off-curve ATA check), `bs58` (Solana base58 program ids/addresses), `sha2` (Solana ATA/PDA derivation), `hex`, `reqwest`, `serde`/`serde_json`, `tempfile`, `parking_lot`, `once_cell`. `k256`, `coins-bip39`, `ed25519-dalek` and the root `tinywallet` crate are test-only here (the `web3` feature does not enable `k256`/`coins-bip39`): they back the `cfg(test)` local signers in `chains/solana.rs`, `execution.rs` and the test fixtures, so unit tests can run without a loaded module.
+- Other external crates: `reqwest`, `serde`/`serde_json`, `tempfile`, `parking_lot`, `once_cell`. `curve25519-dalek`, `bs58`, `sha2` and the Solana wire code moved to `tinywallet-web3`; `k256`, `coins-bip39` and the root `tinywallet` crate remain test-only dev-dependencies for the keyring/setup fixtures.
## Used by
@@ -149,8 +151,8 @@ None. The module publishes or subscribes no `DomainEvent`s and has no `bus.rs`.
## Notes / gotchas
- `rpc.rs` here is network transport, not RPC controllers. RPC controllers live in `schemas.rs`. This is an exception to the canonical "`rpc.rs` = domain API" convention.
-- Quote-owner binding (`execution.rs`): `execute_prepared` only runs when the caller's `current_owner()` equals the prepare-time owner. On mismatch it returns the byte-identical `quote '...' not found` error as a true miss, not an enumeration oracle. Non-chat callers (CLI, direct RPC, background/cron) have `owner == None` and can only execute quotes they also prepared with no chat context. `current_owner()` relies on the inline `.await` chain in `web_chat::run_chat_task`; detaching the tool loop onto a fresh `tokio::spawn` without re-scoping `APPROVAL_CHAT_CONTEXT` would silently disable the gate.
-- Quotes are consumed atomically: `take_quote_for` removes the quote before broadcast so concurrent confirmations can't double-submit; on failure the quote is restored with a refreshed TTL.
+- Quote-owner binding (`tinywallet_web3::quote::QuoteStore`): `execute_prepared` only runs when the caller's `QuoteScope::current_owner()` equals the prepare-time owner. On mismatch it returns the byte-identical `quote '...' not found` error as a true miss, not an enumeration oracle. Non-chat callers (CLI, direct RPC, background/cron) have `owner == None` and can only execute quotes they also prepared with no chat context. The host's `TaskLocalScope` (`web3/seams.rs`) reads `APPROVAL_CHAT_CONTEXT` synchronously on the tool's own task and relies on the inline `.await` chain in `web_chat::run_chat_task`; detaching the tool loop onto a fresh `tokio::spawn` without re-scoping `APPROVAL_CHAT_CONTEXT` would silently disable the gate.
+- Quotes are consumed atomically: `QuoteStore::take_for` removes the quote before broadcast so concurrent confirmations can't double-submit; on failure the quote is restored with a refreshed TTL.
- Setup requires exactly one account per chain (EVM, BTC, Solana, Tron) and a non-empty encrypted mnemonic; valid mnemonic word counts are 12/15/18/21/24.
- EVM is one `WalletChain::Evm` variant across 6 networks (Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain) selected by `EvmNetwork` (defaults to `ethereum_mainnet`); other chains ignore `evmNetwork`. BTC rejects token transfers. Swaps, bridges and contract calls are not in the wallet; they live in the [`web3`](../README.md) module.
- RPC endpoints are overridable per chain/network via `OPENHUMAN_WALLET_RPC_*` env vars (used by tests pointing at an axum mock). Log lines redact URLs to scheme and host.
diff --git a/crates/openhuman-core/src/web3/wallet/abi.rs b/crates/openhuman-core/src/web3/wallet/abi.rs
deleted file mode 100644
index 7f06fa952a..0000000000
--- a/crates/openhuman-core/src/web3/wallet/abi.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-//! ERC-20 calldata, delegated to `tinywallet-bus`.
-//!
-//! This used to hand-build an `ethers_core::abi::Function` to encode one call.
-//! That worked, and it cost the whole `ethers-core` ABI machinery — a type
-//! grammar, a bignum, and their tails — to produce a four-byte selector
-//! followed by two 32-byte words.
-//!
-//! `tinywallet_bus::abi` owns that encoding now, over `sha3` alone, and
-//! deliberately sits outside its `tx` gate: calldata is an *input* to building
-//! a transaction, so a host that builds elsewhere still needs it locally rather
-//! than paying a bus round trip for keccak over 68 bytes.
-//!
-//! What stays here is the error shape. The wallet's RPC surface and its agent
-//! tool both report failures as a plain `String`, so the crate's typed error is
-//! flattened rather than propagated — the same host-side mapping every other
-//! call in this domain does.
-
-/// ABI-encode an ERC-20 `transfer(address,uint256)` call.
-///
-/// `amount_raw` is a base-10 string in the token's smallest unit: an
-/// 18-decimal token puts ordinary balances past `u64`, and a caller almost
-/// always has the value as text from an RPC or a user.
-///
-/// # Errors
-///
-/// A human-readable message if the recipient is not a valid EVM address or the
-/// amount is not a non-negative integer that fits in 256 bits.
-#[allow(unreachable_patterns)]
-pub fn encode_erc20_transfer(to_address: &str, amount_raw: &str) -> Result<String, String> {
- tinywallet_bus::abi::encode_erc20_transfer(to_address, amount_raw).map_err(
- |error| match error {
- tinywallet_bus::abi::Error::InvalidRecipient { .. } => {
- format!("invalid EVM recipient address '{to_address}': {error}")
- }
- // Preserves the wording the previous implementation used, because the
- // agent tool's schema documents it and a model reads it to correct
- // itself.
- tinywallet_bus::abi::Error::InvalidAmount { .. } => {
- format!("amount '{amount_raw}' is not a valid non-negative integer")
- }
- _ => error.to_string(),
- },
- )
-}
-
-#[cfg(test)]
-#[path = "abi_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/abi_tests.rs b/crates/openhuman-core/src/web3/wallet/abi_tests.rs
deleted file mode 100644
index 053f96ea79..0000000000
--- a/crates/openhuman-core/src/web3/wallet/abi_tests.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use super::*;
-
-#[test]
-fn encode_erc20_transfer_matches_known_selector() {
- let calldata =
- encode_erc20_transfer("0x1111111111111111111111111111111111111111", "5").unwrap();
- assert!(calldata.starts_with("0xa9059cbb"));
-}
-
-#[test]
-fn encode_erc20_transfer_accepts_full_u256_amounts() {
- let calldata = encode_erc20_transfer(
- "0x1111111111111111111111111111111111111111",
- "340282366920938463463374607431768211456",
- )
- .unwrap();
- assert!(calldata.starts_with("0xa9059cbb"));
-}
-
-#[test]
-fn the_encoding_is_unchanged_by_the_delegation() {
- // Pinned against the bytes the `ethers-core` implementation produced,
- // so moving the encoder cannot quietly change what gets signed.
- assert_eq!(
- encode_erc20_transfer("0x1111111111111111111111111111111111111111", "1000000").unwrap(),
- "0xa9059cbb\
- 0000000000000000000000001111111111111111111111111111111111111111\
- 00000000000000000000000000000000000000000000000000000000000f4240"
- );
-}
-
-#[test]
-fn an_invalid_recipient_still_names_the_address() {
- let error = encode_erc20_transfer("not-an-address", "5").unwrap_err();
- assert!(error.contains("not-an-address"), "{error}");
-}
-
-#[test]
-fn an_invalid_amount_still_reads_the_way_the_tool_schema_says() {
- let error =
- encode_erc20_transfer("0x1111111111111111111111111111111111111111", "-1").unwrap_err();
- assert!(
- error.contains("not a valid non-negative integer"),
- "{error}"
- );
-}
diff --git a/crates/openhuman-core/src/web3/wallet/chains/btc.rs b/crates/openhuman-core/src/web3/wallet/chains/btc.rs
deleted file mode 100644
index b246e9d205..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/btc.rs
+++ /dev/null
@@ -1,398 +0,0 @@
-//! Bitcoin P2WPKH signing + broadcast. Uses the `bitcoin` crate plus the
-//! Esplora REST API (https://blockstream.info/api) for UTXO discovery and
-//! transaction broadcast. Tests can point at any URL via
-//! `OPENHUMAN_WALLET_RPC_BTC`.
-//!
-//! Address derivation uses BIP84 (`m/84'/0'/0'/0/0` mainnet) so any wallet
-//! seeded with a standard recovery phrase + this path produces a `bc1q…`
-//! native segwit address.
-
-use log::debug;
-use serde::Deserialize;
-
-use crate::config::rpc as config_rpc;
-
-use super::super::defaults::{explorer_tx_url, rpc_url_for_chain};
-use super::super::execution::{
- ExecutionResult, PreparedKind, PreparedStatus, PreparedTransaction, TxLookupInfo,
- TxReceiptInfo, TxState, TxStatusInfo,
-};
-use super::super::ops::{secret_material, WalletChain};
-use super::super::rpc::{rest_get_json, rest_get_text, rest_post_text};
-
-const LOG_PREFIX: &str = "[wallet::btc]";
-/// Hardcoded fee rate (sat/vbyte) used to estimate fees for prepared quotes
-/// and to size the change output. Conservative — Bitcoin mempools cap out
-/// around 50 sat/vB during congested periods; 20 keeps us in-range without
-/// burning sats during quiet times.
-const DEFAULT_FEE_RATE_SAT_VB: u64 = 20;
-/// Approx vbytes of a 1-input, 2-output P2WPKH tx (in/out + witness).
-const TYPICAL_TX_VBYTES: u64 = 141;
-
-#[derive(Debug, Deserialize, Clone)]
-pub struct EsploraUtxo {
- pub txid: String,
- pub vout: u32,
- pub value: u64,
-}
-
-#[derive(Debug, Deserialize)]
-struct EsploraAddressInfo {
- chain_stats: EsploraAddressStats,
- mempool_stats: EsploraAddressStats,
-}
-
-#[derive(Debug, Deserialize)]
-struct EsploraAddressStats {
- funded_txo_sum: u64,
- spent_txo_sum: u64,
-}
-
-pub fn estimated_btc_fee_sats() -> u64 {
- DEFAULT_FEE_RATE_SAT_VB * TYPICAL_TX_VBYTES
-}
-
-/// Generic BTC address validation — any well-formed mainnet address is OK.
-/// Used for recipients (we don't care what address type they prefer; the
-/// `bitcoin` crate's script_pubkey() will encode P2WPKH/P2TR/P2SH correctly).
-///
-/// Delegates to the vendored [`tinywallet_bus`] crate, which owns the address
-/// format itself. Nothing about parsing a Bitcoin address is OpenHuman-
-/// specific, so the rules live where any host can reach them; what stays here
-/// is the `Result<_, String>` shape the rest of this domain speaks.
-pub fn validate_btc_address(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::btc::validate(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address role=recipient result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-/// Sender-side validation — must be P2WPKH because we only know how to
-/// derive + sign for native segwit (`bc1q…`). Recipients can be any type.
-///
-/// See [`validate_btc_address`] for why this delegates. `tinywallet-bus` keeps the
-/// two rules as separate functions for the same reason this module does: using
-/// the recipient rule for a sender accepts an address that only fails later,
-/// at signing time.
-pub fn validate_btc_sender_address(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::btc::validate_sender(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address role=sender result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-pub async fn native_balance(address: &str) -> Result<u128, String> {
- validate_btc_address(address)?;
- let base = rpc_url_for_chain(WalletChain::Btc);
- let url = format!("{}/address/{}", base.trim_end_matches('/'), address);
- let info: EsploraAddressInfo = rest_get_json(&url).await?;
- let confirmed = info
- .chain_stats
- .funded_txo_sum
- .saturating_sub(info.chain_stats.spent_txo_sum);
- let pending = info
- .mempool_stats
- .funded_txo_sum
- .saturating_sub(info.mempool_stats.spent_txo_sum);
- Ok((confirmed + pending) as u128)
-}
-
-pub async fn fetch_utxos(address: &str) -> Result<Vec<EsploraUtxo>, String> {
- let base = rpc_url_for_chain(WalletChain::Btc);
- let url = format!("{}/address/{}/utxo", base.trim_end_matches('/'), address);
- rest_get_json(&url).await
-}
-
-pub async fn broadcast_raw_hex(tx_hex: &str) -> Result<String, String> {
- let base = rpc_url_for_chain(WalletChain::Btc);
- let url = format!("{}/tx", base.trim_end_matches('/'));
- rest_post_text(&url, tx_hex, "text/plain").await
-}
-
-/// Derive the P2WPKH signing key for `derivation_path` from a BIP-39 mnemonic.
-///
-/// Test-only, and deliberately on the **root** `tinywallet` crate rather than
-/// `tinywallet-bus`: `key` is one of the gates that did not move into the
-/// contract crate, because deriving is the module's job. The root crate is a
-/// dev-dependency here, so this derivation stack is not linked into the shipped
-/// binary. Production derives inside the wallet module, via
-/// `modules::wallet::derive_account`.
-///
-/// Custody stays here: the mnemonic is decrypted from the keyring by this crate
-/// and handed over as a `&str` that is not retained.
-#[cfg(test)]
-fn derive_btc_private_key(
- mnemonic: &str,
- derivation_path: &str,
-) -> Result<(Vec<u8>, Vec<u8>), String> {
- let derived = tinywallet::key::derive(tinywallet::Chain::Btc, mnemonic, derivation_path)
- .map_err(|e| e.to_string())?;
- let secret = derived.secret_bytes().to_vec();
- // Compressed, because a P2WPKH witness program is defined over the
- // compressed encoding — the uncompressed form yields a valid-looking
- // address for an account holding no funds.
- let public_key = super::super::execution::compressed_public_key(&secret)
- .map_err(|_| "tinywallet returned an unusable BTC key".to_string())?;
- Ok((secret, public_key))
-}
-
-/// Select UTXOs to cover `amount_sats + fee_sats`, returning the selected
-/// set and the change. Simple greedy: largest-first.
-fn select_utxos(
- utxos: &[EsploraUtxo],
- amount_sats: u64,
- fee_sats: u64,
-) -> Result<(Vec<EsploraUtxo>, u64), String> {
- let mut sorted = utxos.to_vec();
- sorted.sort_by_key(|item| std::cmp::Reverse(item.value));
- let target = amount_sats
- .checked_add(fee_sats)
- .ok_or_else(|| "amount + fee overflow".to_string())?;
- let mut total: u64 = 0;
- let mut chosen = Vec::new();
- for utxo in sorted {
- total = total
- .checked_add(utxo.value)
- .ok_or_else(|| "utxo sum overflow".to_string())?;
- chosen.push(utxo);
- if total >= target {
- return Ok((chosen, total - target));
- }
- }
- Err(format!(
- "insufficient BTC: have {total} sats, need {target} (amount {amount_sats} + fee {fee_sats})"
- ))
-}
-
-pub async fn execute_btc_quote(mut quote: PreparedTransaction) -> Result<ExecutionResult, String> {
- if !matches!(quote.kind, PreparedKind::NativeTransfer) {
- return Err(format!(
- "BTC only supports native transfers; got kind {:?}",
- quote.kind
- ));
- }
- let amount_sats: u64 = quote
- .amount_raw
- .parse()
- .map_err(|e| format!("invalid BTC amount '{}': {e}", quote.amount_raw))?;
- let from_addr = quote.from_address.clone();
- let to_addr = quote.to_address.clone();
- validate_btc_sender_address(&from_addr)?;
- validate_btc_address(&to_addr)?;
-
- let utxos = fetch_utxos(&from_addr).await?;
- if utxos.is_empty() {
- return Err(format!("no spendable UTXOs for {from_addr}"));
- }
- let fee_sats = estimated_btc_fee_sats();
- let (selected, change_sats) = select_utxos(&utxos, amount_sats, fee_sats)?;
-
- let secret = secret_material(WalletChain::Btc).await?;
- let config = config_rpc::load_config_with_timeout().await?;
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
- .await?
- .value;
- // Derivation and signing both happen in the loaded wallet module now, so no
- // private key is reassembled here. The phrase travels over a confidential
- // call to a module that has proved it is an artifact this build pinned —
- // see `modules::wallet::attested_proxy`.
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Btc,
- };
-
- // Selection stays here — this crate knows the fee policy and the UTXO
- // source — but the transaction itself is encoded by the loaded wallet
- // module, which also re-runs the same largest-first selection over the
- // UTXOs it is handed. Passing only the already-selected set keeps the two
- // in agreement: the module's `select_coins` and `select_utxos` above are
- // the same algorithm, down to the 546-sat dust rule, so it reselects
- // exactly what was chosen here.
- let transaction = tinywallet_bus::wire::TransactionSpec::Btc {
- from: from_addr.clone(),
- to: to_addr.clone(),
- amount_sat: amount_sats,
- fee_sat: fee_sats,
- utxos: selected
- .iter()
- .map(|utxo| tinywallet_bus::wire::Utxo {
- txid: utxo.txid.clone(),
- vout: utxo.vout,
- value: utxo.value,
- })
- .collect(),
- };
- // One signature per selected input, all produced inside the module and
- // applied there in input order — see `modules::wallet`.
- let signed =
- crate::modules::wallet::sign_transaction_in_module(&config, &transaction, &signing_secret)
- .await
- .map_err(|e| format!("failed to sign BTC transaction: {e}"))?;
-
- let tx_hex = signed.raw;
- let txid_hex = broadcast_raw_hex(&tx_hex).await?;
- quote.estimated_fee_raw = fee_sats.to_string();
- quote.status = PreparedStatus::Broadcasted;
- debug!(
- "{LOG_PREFIX} broadcast quote_id={} txid={} amount_sats={} change_sats={}",
- quote.quote_id, txid_hex, amount_sats, change_sats
- );
- let explorer_url = explorer_tx_url(WalletChain::Btc, &txid_hex);
- Ok(ExecutionResult {
- quote_id: quote.quote_id.clone(),
- status: PreparedStatus::Broadcasted,
- chain: WalletChain::Btc,
- evm_network: None,
- transaction_hash: txid_hex,
- explorer_url,
- transaction: quote,
- })
-}
-
-/// Esplora `/tx/:txid/status` → normalized status. Confirmations are derived
-/// from the chain tip (`/blocks/tip/height`) when the tx is confirmed.
-pub async fn tx_status(hash: &str) -> Result<TxStatusInfo, String> {
- let base = rpc_url_for_chain(WalletChain::Btc);
- let base = base.trim_end_matches('/');
- let status: serde_json::Value = match rest_get_json(&format!("{base}/tx/{hash}/status")).await {
- Ok(v) => v,
- // Esplora returns 404 for unknown txids; surface as NotFound.
- Err(e) if e.contains("status=404") => {
- return Ok(TxStatusInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- state: TxState::NotFound,
- confirmations: None,
- block_number: None,
- });
- }
- Err(e) => return Err(e),
- };
- let confirmed = status
- .get("confirmed")
- .and_then(serde_json::Value::as_bool)
- .unwrap_or(false);
- if !confirmed {
- return Ok(TxStatusInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- state: TxState::Pending,
- confirmations: Some(0),
- block_number: None,
- });
- }
- let block_number = status
- .get("block_height")
- .and_then(serde_json::Value::as_u64);
- let confirmations = match block_number {
- Some(bn) => {
- let tip = rest_get_text(&format!("{base}/blocks/tip/height"))
- .await
- .ok();
- tip.and_then(|t| t.trim().parse::<u64>().ok())
- .map(|tip| tip.saturating_sub(bn).saturating_add(1))
- }
- None => None,
- };
- Ok(TxStatusInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- state: TxState::Confirmed,
- confirmations,
- block_number,
- })
-}
-
-/// Esplora `/tx/:txid` → normalized receipt (fee + confirmed height).
-pub async fn tx_receipt(hash: &str) -> Result<TxReceiptInfo, String> {
- let base = rpc_url_for_chain(WalletChain::Btc);
- let base = base.trim_end_matches('/');
- let tx: serde_json::Value = match rest_get_json(&format!("{base}/tx/{hash}")).await {
- Ok(v) => v,
- Err(e) if e.contains("status=404") => {
- return Ok(TxReceiptInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- found: false,
- success: None,
- block_number: None,
- gas_used: None,
- fee_raw: None,
- raw: serde_json::Value::Null,
- });
- }
- Err(e) => return Err(e),
- };
- let confirmed = tx
- .get("status")
- .and_then(|s| s.get("confirmed"))
- .and_then(serde_json::Value::as_bool)
- .unwrap_or(false);
- let block_number = tx
- .get("status")
- .and_then(|s| s.get("block_height"))
- .and_then(serde_json::Value::as_u64);
- let fee_raw = tx
- .get("fee")
- .and_then(serde_json::Value::as_u64)
- .map(|f| f.to_string());
- // Leave `success` unset until the tx is confirmed — an unconfirmed mempool
- // tx is pending (see tx_status), not a failure.
- let success = if confirmed { Some(true) } else { None };
- Ok(TxReceiptInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- found: true,
- success,
- block_number,
- gas_used: None,
- fee_raw,
- raw: tx,
- })
-}
-
-/// Esplora `/tx/:txid` → raw transaction passthrough.
-pub async fn lookup_tx(hash: &str) -> Result<TxLookupInfo, String> {
- let base = rpc_url_for_chain(WalletChain::Btc);
- let base = base.trim_end_matches('/');
- match rest_get_json::<serde_json::Value>(&format!("{base}/tx/{hash}")).await {
- Ok(tx) => Ok(TxLookupInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- found: true,
- raw: tx,
- }),
- Err(e) if e.contains("status=404") => Ok(TxLookupInfo {
- chain: WalletChain::Btc,
- evm_network: None,
- hash: hash.to_string(),
- found: false,
- raw: serde_json::Value::Null,
- }),
- Err(e) => Err(e),
- }
-}
-
-#[cfg(test)]
-#[path = "btc_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/chains/btc_tests.rs b/crates/openhuman-core/src/web3/wallet/chains/btc_tests.rs
deleted file mode 100644
index 2b537d4dd5..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/btc_tests.rs
+++ /dev/null
@@ -1,320 +0,0 @@
-use super::*;
-use crate::web3::wallet::execution::{
- insert_quote_for_test, now_ms, reset_quote_store_for_tests, PreparedKind, PreparedStatus,
- PreparedTransaction,
-};
-use crate::web3::wallet::test_support::{sample_btc_address, setup_wallet_in, TEST_LOCK};
-use axum::{
- routing::{get, post},
- Router,
-};
-use serde_json::json;
-use std::sync::Arc;
-use tempfile::TempDir;
-use tokio::net::TcpListener;
-
-#[test]
-fn validate_btc_address_accepts_known_p2wpkh() {
- // bech32 P2WPKH from BIP173 examples.
- let addr = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4";
- assert_eq!(validate_btc_address(addr).unwrap(), addr);
-}
-
-#[test]
-fn validate_btc_address_rejects_testnet() {
- let err = validate_btc_address("tb1qw508d6qejxtdg4y5r3zarvary0c5xw7kxpjzsx").unwrap_err();
- // `tinywallet-bus` reports a wrong-network address as a distinct condition
- // from a malformed one, so the message names the required network.
- assert!(err.contains("not on mainnet"), "got: {err}");
-}
-
-#[test]
-fn validate_btc_sender_address_rejects_p2tr() {
- // P2TR (bech32m, bc1p…) is a valid recipient but cannot be a sender —
- // we only know how to sign P2WPKH inputs in this iteration.
- let p2tr = "bc1p5cyxnuxmeuwuvkwfem96lqzszd02n6xdcjrs20cac6yqjjwudpxqkedrcr";
- // Generic validation must accept it (recipients can be any type).
- assert_eq!(validate_btc_address(p2tr).unwrap(), p2tr);
- // Sender validation must reject it.
- let err = validate_btc_sender_address(p2tr).unwrap_err();
- assert!(err.contains("P2WPKH"), "got: {err}");
- assert!(
- err.contains("not supported as a sender"),
- "the message should name the role that failed: {err}"
- );
-}
-
-#[test]
-fn select_utxos_largest_first_returns_change() {
- let utxos = vec![
- EsploraUtxo {
- txid: "a".into(),
- vout: 0,
- value: 5000,
- },
- EsploraUtxo {
- txid: "b".into(),
- vout: 0,
- value: 10_000,
- },
- EsploraUtxo {
- txid: "c".into(),
- vout: 0,
- value: 1_000,
- },
- ];
- let (chosen, change) = select_utxos(&utxos, 6_000, 2_000).unwrap();
- assert_eq!(chosen.len(), 1);
- assert_eq!(chosen[0].txid, "b");
- assert_eq!(change, 2_000);
-}
-
-#[test]
-fn select_utxos_combines_multiple_when_needed() {
- let utxos = vec![
- EsploraUtxo {
- txid: "a".into(),
- vout: 0,
- value: 5000,
- },
- EsploraUtxo {
- txid: "b".into(),
- vout: 0,
- value: 5000,
- },
- EsploraUtxo {
- txid: "c".into(),
- vout: 0,
- value: 5000,
- },
- ];
- let (chosen, change) = select_utxos(&utxos, 11_000, 1_000).unwrap();
- assert_eq!(chosen.len(), 3);
- assert_eq!(change, 3_000);
-}
-
-#[test]
-fn select_utxos_errors_when_insufficient() {
- let utxos = vec![EsploraUtxo {
- txid: "a".into(),
- vout: 0,
- value: 1_000,
- }];
- let err = select_utxos(&utxos, 5_000, 1_000).unwrap_err();
- assert!(err.contains("insufficient"), "got: {err}");
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_btc_quote_builds_psbt_signs_and_broadcasts -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_btc_quote_builds_psbt_signs_and_broadcasts() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- // Mock state: collect raw tx hex posted to /tx.
- let raw_txs: Arc<parking_lot::Mutex<Vec<String>>> =
- Arc::new(parking_lot::Mutex::new(Vec::new()));
- let raw_txs_clone = raw_txs.clone();
- let from_addr = sample_btc_address().to_string();
- // Real-shaped UTXO; value high enough to cover amount + fee.
- let utxo_txid = "1111111111111111111111111111111111111111111111111111111111111111";
- let utxo_json = json!([
- { "txid": utxo_txid, "vout": 0, "value": 100_000u64 }
- ]);
- let utxo_clone = utxo_json.clone();
- let app = Router::new()
- .route(
- "/address/{addr}/utxo",
- get(move || {
- let body = utxo_clone.clone();
- async move { axum::Json(body) }
- }),
- )
- .route(
- "/tx",
- post(move |body: String| {
- let raw_txs = raw_txs_clone.clone();
- async move {
- raw_txs.lock().push(body);
- // Return a known fake txid the test can assert on.
- "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string()
- }
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_BTC", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_btc_native_1".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Btc,
- evm_network: None,
- from_address: from_addr.clone(),
- to_address: "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string(),
- asset_symbol: "BTC".to_string(),
- amount_raw: "50000".to_string(),
- amount_formatted: "0.00050000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "5000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let result = execute_btc_quote(quote).await.expect("btc broadcast ok");
- assert_eq!(result.status, PreparedStatus::Broadcasted);
- assert_eq!(
- result.transaction_hash,
- "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
- );
- let raw = raw_txs.lock().clone();
- assert_eq!(raw.len(), 1, "exactly one broadcast call");
- let tx_hex = &raw[0];
- assert!(!tx_hex.is_empty(), "tx hex must be non-empty");
- // Witness-segwit transactions include the BIP141 marker+flag (0x0001).
- assert!(
- tx_hex.contains("0001"),
- "expected segwit marker, got: {tx_hex}"
- );
-}
-
-#[tokio::test]
-async fn execute_btc_quote_rejects_insufficient_utxos() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- // Empty UTXO set — must error.
- let app = Router::new().route(
- "/address/{addr}/utxo",
- get(|| async { axum::Json(json!([])) }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_BTC", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_btc_native_empty".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Btc,
- evm_network: None,
- from_address: sample_btc_address().to_string(),
- to_address: "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4".to_string(),
- asset_symbol: "BTC".to_string(),
- amount_raw: "50000".to_string(),
- amount_formatted: "0.00050000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "5000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- let err = execute_btc_quote(quote).await.unwrap_err();
- assert!(err.contains("no spendable UTXOs"), "got: {err}");
-}
-
-#[test]
-fn derive_btc_key_produces_known_p2wpkh_from_test_mnemonic() {
- // BIP84 m/84'/0'/0'/0/0 from "abandon x11 about" → bc1qcr8...
- // The compressed pubkey should serialize to 33 bytes.
- let mnemonic =
- "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
- let (secret, pubkey) = derive_btc_private_key(mnemonic, "m/84'/0'/0'/0/0").unwrap();
- assert_eq!(secret.len(), 32);
- // Compressed SEC1. The uncompressed form would be 65 bytes and would
- // hash to a different — spendable by nobody — address.
- assert_eq!(pubkey.len(), 33);
- assert!(matches!(pubkey[0], 0x02 | 0x03));
-
- // The known-good vector for this mnemonic and path, unchanged by the
- // move off the `bitcoin` crate. Derived through the root `tinywallet`
- // crate, which is the same code that produces the address in
- // `execute_btc_quote` — in production it runs inside the wallet module
- // rather than here, but it is the same crate and the same walk.
- let derived =
- tinywallet::key::derive(tinywallet::Chain::Btc, mnemonic, "m/84'/0'/0'/0/0").unwrap();
- assert_eq!(
- derived.address(),
- "bc1qcr8te4kr609gcawutmrza0j4xv80jy8z306fyu"
- );
- assert_eq!(derived.secret_bytes(), secret.as_slice());
-}
-
-#[tokio::test]
-async fn tx_status_confirmed_with_tip_confirmations() {
- let _guard = TEST_LOCK.lock();
- let _env_guard = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let app = Router::new()
- .route(
- "/tx/{txid}/status",
- get(|| async { axum::Json(json!({"confirmed": true, "block_height": 800_000u64})) }),
- )
- .route("/blocks/tip/height", get(|| async { "800002" }));
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_BTC", format!("http://{addr}"));
- let info = tx_status("deadbeef").await.unwrap();
- assert_eq!(
- info.state,
- crate::web3::wallet::execution::TxState::Confirmed
- );
- assert_eq!(info.block_number, Some(800_000));
- assert_eq!(info.confirmations, Some(3));
-}
-
-#[tokio::test]
-async fn lookup_tx_not_found_on_404() {
- let _guard = TEST_LOCK.lock();
- let _env_guard = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let app = Router::new().route(
- "/tx/{txid}",
- get(|| async { (axum::http::StatusCode::NOT_FOUND, "Transaction not found") }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_BTC", format!("http://{addr}"));
- let info = lookup_tx("deadbeef").await.unwrap();
- assert!(!info.found);
-}
diff --git a/crates/openhuman-core/src/web3/wallet/chains/evm.rs b/crates/openhuman-core/src/web3/wallet/chains/evm.rs
deleted file mode 100644
index 9a649bf025..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/evm.rs
+++ /dev/null
@@ -1,358 +0,0 @@
-//! EVM signing + broadcast (Ethereum mainnet + L2s: Base, Arbitrum,
-//! Optimism, Polygon). Single key derivation path (`m/44'/60'/...`) — every
-//! EVM network shares the same address.
-//!
-//! Network selection comes from `PreparedTransaction.evm_network`. If it's
-//! `None` (legacy quotes or callers that didn't specify), Ethereum mainnet
-//! is assumed.
-
-use log::debug;
-use serde_json::json;
-
-use crate::config::rpc as config_rpc;
-
-use super::super::abi::encode_erc20_transfer;
-use super::super::defaults::{
- explorer_tx_url_for_evm_network, rpc_url_for_evm_network, EvmNetwork,
-};
-use super::super::execution::{
- hex_to_u128, u128_to_hex, ExecutionResult, PreparedKind, PreparedStatus, PreparedTransaction,
- RawBroadcastResult, TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,
-};
-use super::super::ops::{secret_material, WalletChain};
-use super::super::rpc::{evm_rpc_call, rpc_call_to};
-
-const LOG_PREFIX: &str = "[wallet::evm]";
-
-pub async fn evm_balance(network: EvmNetwork, address: &str) -> Result<u128, String> {
- let raw: String = evm_rpc_call(network, "eth_getBalance", json!([address, "latest"])).await?;
- hex_to_u128(&raw)
-}
-
-/// Sign an EVM transaction `(to, value, data)` from the wallet's encrypted
-/// recovery phrase and broadcast it on `network`. Shared core behind both
-/// [`execute_evm_quote`] (native + token transfers) and
-/// [`sign_and_broadcast_evm`] (raw / dapp / swap calldata from the web3 layer).
-///
-/// Returns `(tx_hash, fee_raw)` where `fee_raw` is the simulated `gas * gasPrice`.
-async fn sign_and_broadcast(
- network: EvmNetwork,
- from_address: &str,
- to: &str,
- value_raw: &str,
- tx_data: Option<String>,
-) -> Result<(String, u128), String> {
- let rpc_url = rpc_url_for_evm_network(network);
- let secret = secret_material(WalletChain::Evm).await?;
- let config = config_rpc::load_config_with_timeout().await?;
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
- .await?
- .value;
- // Neither derivation nor signing happens in this binary any more. The
- // phrase decrypted above is handed to the loaded wallet module over a
- // confidential call, which derives, encodes, signs and assembles; this
- // process never holds a private key for the transaction it is sending.
- //
- // The module is only sent the phrase once it has proved it is an artifact
- // this build pinned — see `modules::wallet::attested_proxy`.
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Evm,
- };
-
- let to = tinywallet_bus::address::evm::validate(to)
- .map_err(|e| format!("invalid EVM target address '{to}': {e}"))?;
-
- let chain_id_hex: String = rpc_call_to(&rpc_url, "eth_chainId", json!([])).await?;
- // Use "pending" so already-submitted-but-not-mined txs don't cause a
- // nonce collision when two confirmations land back-to-back.
- let nonce_hex: String = rpc_call_to(
- &rpc_url,
- "eth_getTransactionCount",
- json!([from_address, "pending"]),
- )
- .await?;
- let gas_price_hex: String = rpc_call_to(&rpc_url, "eth_gasPrice", json!([])).await?;
- let value = value_raw
- .trim()
- .parse::<u128>()
- .map_err(|e| format!("invalid native value '{value_raw}': {e}"))?;
- let mut estimate_tx = json!({
- "from": from_address,
- "to": to,
- "value": u128_to_hex(value),
- });
- if let Some(data_hex) = tx_data.as_deref() {
- estimate_tx["data"] = json!(data_hex);
- }
- let gas_hex: String = rpc_call_to(&rpc_url, "eth_estimateGas", json!([estimate_tx])).await?;
- let chain_id = u64::try_from(hex_to_u128(&chain_id_hex)?)
- .map_err(|_| format!("EVM RPC reported an implausible chain_id '{chain_id_hex}'"))?;
- if chain_id != network.chain_id() {
- return Err(format!(
- "EVM RPC chain_id mismatch: rpc reported {} but network {} expects {}",
- chain_id,
- network.as_str(),
- network.chain_id()
- ));
- }
- let nonce = u64::try_from(hex_to_u128(&nonce_hex)?)
- .map_err(|_| format!("EVM RPC reported an implausible nonce '{nonce_hex}'"))?;
- let gas_price = hex_to_u128(&gas_price_hex)?;
- let gas_limit = u64::try_from(hex_to_u128(&gas_hex)?)
- .map_err(|_| format!("EVM RPC reported an implausible gas limit '{gas_hex}'"))?;
-
- let transaction = tinywallet_bus::wire::TransactionSpec::Evm {
- to,
- value_wei: value.to_string(),
- data_hex: tx_data.unwrap_or_default(),
- nonce,
- gas_limit,
- gas_price_wei: gas_price.to_string(),
- chain_id,
- };
- let signed =
- crate::modules::wallet::sign_transaction_in_module(&config, &transaction, &signing_secret)
- .await
- .map_err(|e| format!("failed to sign EVM transaction: {e}"))?;
-
- let tx_hash: String =
- rpc_call_to(&rpc_url, "eth_sendRawTransaction", json!([signed.raw])).await?;
- let fee = gas_price
- .checked_mul(u128::from(gas_limit))
- .unwrap_or_default();
- debug!(
- "{LOG_PREFIX} sign_and_broadcast network={} tx_hash={}",
- network.as_str(),
- tx_hash
- );
- Ok((tx_hash, fee))
-}
-
-pub async fn execute_evm_quote(mut quote: PreparedTransaction) -> Result<ExecutionResult, String> {
- let network = quote.evm_network.unwrap_or(EvmNetwork::EthereumMainnet);
- let (tx_to, tx_value, tx_data) = match quote.kind {
- // A native transfer pays the recipient directly and carries no data.
- PreparedKind::NativeTransfer => (
- tinywallet_bus::address::evm::validate(&quote.to_address).map_err(|e| {
- format!("invalid EVM recipient address '{}': {e}", quote.to_address)
- })?,
- quote.amount_raw.clone(),
- None,
- ),
- // A token transfer pays the *contract* zero and puts the recipient and
- // the amount in the calldata instead.
- PreparedKind::TokenTransfer => {
- let token = quote
- .token_address
- .as_deref()
- .ok_or_else(|| "prepared token transfer is missing token_address".to_string())?;
- let calldata = encode_erc20_transfer(&quote.to_address, &quote.amount_raw)?;
- (
- tinywallet_bus::address::evm::validate(token)
- .map_err(|e| format!("invalid ERC20 token contract address '{token}': {e}"))?,
- "0".to_string(),
- Some(calldata),
- )
- }
- };
-
- let (tx_hash, fee) =
- sign_and_broadcast(network, &quote.from_address, &tx_to, &tx_value, tx_data).await?;
- quote.estimated_fee_raw = fee.to_string();
- quote.status = PreparedStatus::Broadcasted;
- debug!(
- "{LOG_PREFIX} execute_prepared quote_id={} network={} tx_hash={}",
- quote.quote_id,
- network.as_str(),
- tx_hash
- );
- Ok(ExecutionResult {
- quote_id: quote.quote_id.clone(),
- status: PreparedStatus::Broadcasted,
- chain: WalletChain::Evm,
- evm_network: Some(network),
- transaction_hash: tx_hash.clone(),
- explorer_url: explorer_tx_url_for_evm_network(network, &tx_hash),
- transaction: quote,
- })
-}
-
-/// Crate-internal primitive: sign an externally-built unsigned EVM transaction
-/// (`to` / `data` / `value`) with the wallet's key and broadcast it. Used by
-/// the `web3` layer for deBridge swap/bridge transactions and generic dapp
-/// contract calls. Not exposed as an agent tool or RPC controller.
-pub(crate) async fn sign_and_broadcast_evm(
- network: EvmNetwork,
- to: &str,
- data_hex: Option<String>,
- value_raw: &str,
-) -> Result<RawBroadcastResult, String> {
- let account = super::super::execution::require_evm_account().await?;
- let data = data_hex
- .map(|d| super::super::execution::validate_calldata(&d))
- .transpose()?;
- // `to` and `value_raw` are validated inside `sign_and_broadcast`, which is
- // the only place that needs them parsed.
- let (tx_hash, fee) = sign_and_broadcast(network, &account, to, value_raw, data).await?;
- Ok(RawBroadcastResult {
- transaction_hash: tx_hash.clone(),
- explorer_url: explorer_tx_url_for_evm_network(network, &tx_hash),
- fee_raw: Some(fee.to_string()),
- })
-}
-
-/// `eth_getTransactionReceipt` + `eth_blockNumber` → normalized status.
-pub async fn tx_status(network: EvmNetwork, hash: &str) -> Result<TxStatusInfo, String> {
- let rpc_url = rpc_url_for_evm_network(network);
- let receipt: serde_json::Value =
- rpc_call_to(&rpc_url, "eth_getTransactionReceipt", json!([hash])).await?;
- if receipt.is_null() {
- // No receipt yet — distinguish pending (tx known) from not-found.
- let tx: serde_json::Value =
- rpc_call_to(&rpc_url, "eth_getTransactionByHash", json!([hash])).await?;
- let state = if tx.is_null() {
- TxState::NotFound
- } else {
- TxState::Pending
- };
- return Ok(TxStatusInfo {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- hash: hash.to_string(),
- state,
- confirmations: None,
- block_number: None,
- });
- }
- let status_ok = receipt
- .get("status")
- .and_then(|v| v.as_str())
- .map(|s| hex_to_u128(s).map(|v| v != 0).unwrap_or(true))
- .unwrap_or(true);
- let block_number = receipt
- .get("blockNumber")
- .and_then(|v| v.as_str())
- .and_then(|s| hex_to_u128(s).ok())
- .map(|v| u64::try_from(v).unwrap_or(u64::MAX));
- let confirmations = match block_number {
- Some(bn) => {
- let head_hex: String = rpc_call_to(&rpc_url, "eth_blockNumber", json!([])).await?;
- hex_to_u128(&head_hex).ok().map(|head| {
- u64::try_from(head)
- .unwrap_or(u64::MAX)
- .saturating_sub(bn)
- .saturating_add(1)
- })
- }
- None => None,
- };
- Ok(TxStatusInfo {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- hash: hash.to_string(),
- state: if status_ok {
- TxState::Confirmed
- } else {
- TxState::Failed
- },
- confirmations,
- block_number,
- })
-}
-
-/// `eth_getTransactionReceipt` → normalized receipt with raw passthrough.
-pub async fn tx_receipt(network: EvmNetwork, hash: &str) -> Result<TxReceiptInfo, String> {
- let rpc_url = rpc_url_for_evm_network(network);
- let receipt: serde_json::Value =
- rpc_call_to(&rpc_url, "eth_getTransactionReceipt", json!([hash])).await?;
- if receipt.is_null() {
- // No receipt yet — a freshly broadcast tx is still "found" if the node
- // knows the tx hash; only report not-found when both calls are null.
- let tx: serde_json::Value =
- rpc_call_to(&rpc_url, "eth_getTransactionByHash", json!([hash])).await?;
- return Ok(TxReceiptInfo {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- hash: hash.to_string(),
- found: !tx.is_null(),
- success: None,
- block_number: None,
- gas_used: None,
- fee_raw: None,
- raw: serde_json::Value::Null,
- });
- }
- let success = receipt
- .get("status")
- .and_then(|v| v.as_str())
- .map(|s| hex_to_u128(s).map(|v| v != 0).unwrap_or(true));
- let block_number = receipt
- .get("blockNumber")
- .and_then(|v| v.as_str())
- .and_then(|s| hex_to_u128(s).ok())
- .map(|v| u64::try_from(v).unwrap_or(u64::MAX));
- let gas_used = receipt
- .get("gasUsed")
- .and_then(|v| v.as_str())
- .and_then(|s| hex_to_u128(s).ok());
- let effective_gas_price = receipt
- .get("effectiveGasPrice")
- .and_then(|v| v.as_str())
- .and_then(|s| hex_to_u128(s).ok());
- let fee_raw = match (gas_used, effective_gas_price) {
- (Some(g), Some(p)) => g.checked_mul(p).map(|f| f.to_string()),
- _ => None,
- };
- Ok(TxReceiptInfo {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- hash: hash.to_string(),
- found: true,
- success,
- block_number,
- gas_used: gas_used.map(|g| g.to_string()),
- fee_raw,
- raw: receipt,
- })
-}
-
-/// `eth_getTransactionByHash` → raw transaction passthrough.
-pub async fn lookup_tx(network: EvmNetwork, hash: &str) -> Result<TxLookupInfo, String> {
- let rpc_url = rpc_url_for_evm_network(network);
- let tx: serde_json::Value =
- rpc_call_to(&rpc_url, "eth_getTransactionByHash", json!([hash])).await?;
- Ok(TxLookupInfo {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- hash: hash.to_string(),
- found: !tx.is_null(),
- raw: tx,
- })
-}
-
-/// Validate an EVM address (20 bytes, 40 hex digits, optional `0x`).
-///
-/// Delegates to the vendored [`tinywallet_bus`] crate, which owns the address
-/// format; this wrapper keeps the `Result<_, String>` shape the rest of the
-/// domain speaks. Accepts exactly what the previous `ethers-core` based check
-/// accepted — prefixed, unprefixed, and any hex case, but not an uppercase
-/// `0X` prefix.
-pub fn validate_evm_address(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::evm::validate(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-#[cfg(test)]
-#[path = "evm_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/chains/evm_tests.rs b/crates/openhuman-core/src/web3/wallet/chains/evm_tests.rs
deleted file mode 100644
index 0280520c67..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/evm_tests.rs
+++ /dev/null
@@ -1,198 +0,0 @@
-use super::*;
-use crate::web3::wallet::execution::TxState;
-use crate::web3::wallet::test_support::{setup_wallet_in, TEST_LOCK};
-use axum::{routing::post, Router};
-use serde_json::Value as JsonValue;
-use std::sync::Arc;
-use tempfile::TempDir;
-use tokio::net::TcpListener;
-
-/// Mock EVM JSON-RPC node. `receipt` is the value returned for
-/// `eth_getTransactionReceipt`; `tx` for `eth_getTransactionByHash`.
-async fn start_evm_mock(
- receipt: JsonValue,
- tx: JsonValue,
-) -> (
- std::net::SocketAddr,
- Arc<parking_lot::Mutex<Vec<JsonValue>>>,
-) {
- let calls: Arc<parking_lot::Mutex<Vec<JsonValue>>> =
- Arc::new(parking_lot::Mutex::new(Vec::new()));
- let calls_c = calls.clone();
- let app = Router::new().route(
- "/",
- post(move |axum::Json(payload): axum::Json<JsonValue>| {
- let calls = calls_c.clone();
- let receipt = receipt.clone();
- let tx = tx.clone();
- async move {
- calls.lock().push(payload.clone());
- let method = payload
- .get("method")
- .and_then(JsonValue::as_str)
- .unwrap_or_default();
- let result = match method {
- "eth_getTransactionReceipt" => receipt,
- "eth_getTransactionByHash" => tx,
- "eth_blockNumber" => JsonValue::String("0x12".to_string()),
- "eth_chainId" => JsonValue::String("0x1".to_string()),
- "eth_getTransactionCount" => JsonValue::String("0x1".to_string()),
- "eth_gasPrice" => JsonValue::String("0x3b9aca00".to_string()),
- "eth_estimateGas" => JsonValue::String("0x5208".to_string()),
- "eth_sendRawTransaction" => JsonValue::String(format!("0x{}", "ab".repeat(32))),
- _ => JsonValue::Null,
- };
- axum::Json(serde_json::json!({"jsonrpc":"2.0","id":1,"result":result}))
- }
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- (addr, calls)
-}
-
-fn set_evm_rpc(addr: std::net::SocketAddr) {
- std::env::set_var("OPENHUMAN_WALLET_RPC_EVM", format!("http://{addr}"));
-}
-
-#[tokio::test]
-async fn tx_status_confirmed_with_confirmations() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let receipt = serde_json::json!({"status": "0x1", "blockNumber": "0x10"});
- let (addr, _calls) = start_evm_mock(receipt, JsonValue::Null).await;
- set_evm_rpc(addr);
- let info = tx_status(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert_eq!(info.state, TxState::Confirmed);
- assert_eq!(info.block_number, Some(16));
- // tip 0x12 (18) - block 16 + 1 = 3 confirmations.
- assert_eq!(info.confirmations, Some(3));
-}
-
-#[tokio::test]
-async fn tx_status_pending_when_no_receipt_but_tx_present() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let (addr, _calls) =
- start_evm_mock(JsonValue::Null, serde_json::json!({"hash": "0xabc"})).await;
- set_evm_rpc(addr);
- let info = tx_status(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert_eq!(info.state, TxState::Pending);
-}
-
-#[tokio::test]
-async fn tx_status_not_found_when_receipt_and_tx_null() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let (addr, _calls) = start_evm_mock(JsonValue::Null, JsonValue::Null).await;
- set_evm_rpc(addr);
- let info = tx_status(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert_eq!(info.state, TxState::NotFound);
-}
-
-#[tokio::test]
-async fn tx_receipt_extracts_fee_and_success() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let receipt = serde_json::json!({
- "status": "0x1",
- "blockNumber": "0x10",
- "gasUsed": "0x5208", // 21000
- "effectiveGasPrice": "0x3b9aca00" // 1 gwei
- });
- let (addr, _calls) = start_evm_mock(receipt, JsonValue::Null).await;
- set_evm_rpc(addr);
- let info = tx_receipt(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert!(info.found);
- assert_eq!(info.success, Some(true));
- assert_eq!(info.gas_used.as_deref(), Some("21000"));
- // 21000 * 1_000_000_000 = 21_000_000_000_000
- assert_eq!(info.fee_raw.as_deref(), Some("21000000000000"));
-}
-
-#[tokio::test]
-async fn tx_receipt_pending_is_found_when_tx_known() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- // No receipt yet, but the node knows the tx hash → pending, found=true.
- let (addr, _calls) =
- start_evm_mock(JsonValue::Null, serde_json::json!({"hash": "0xabc"})).await;
- set_evm_rpc(addr);
- let info = tx_receipt(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert!(info.found);
- assert_eq!(info.success, None);
-}
-
-#[tokio::test]
-async fn lookup_tx_reports_found_flag() {
- let _guard = TEST_LOCK.lock();
- let _env = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let (addr, _calls) =
- start_evm_mock(JsonValue::Null, serde_json::json!({"hash": "0xabc"})).await;
- set_evm_rpc(addr);
- let info = lookup_tx(EvmNetwork::EthereumMainnet, "0xabc")
- .await
- .unwrap();
- assert!(info.found);
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// sign_and_broadcast_evm_signs_raw_calldata -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn sign_and_broadcast_evm_signs_raw_calldata() {
- let _guard = TEST_LOCK.lock();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- let (addr, calls) = start_evm_mock(JsonValue::Null, JsonValue::Null).await;
- set_evm_rpc(addr);
- let result = sign_and_broadcast_evm(
- EvmNetwork::EthereumMainnet,
- "0x1111111111111111111111111111111111111111",
- Some("0xabcdef".to_string()),
- "0",
- )
- .await
- .expect("broadcast ok");
- assert_eq!(result.transaction_hash, format!("0x{}", "ab".repeat(32)));
- assert!(result.explorer_url.is_some());
- // The raw tx must have been broadcast.
- let sent = calls
- .lock()
- .iter()
- .any(|c| c.get("method").and_then(|v| v.as_str()) == Some("eth_sendRawTransaction"));
- assert!(sent, "expected eth_sendRawTransaction call");
-}
diff --git a/crates/openhuman-core/src/web3/wallet/chains/mod.rs b/crates/openhuman-core/src/web3/wallet/chains/mod.rs
deleted file mode 100644
index ef0f24bb24..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/mod.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-//! Per-chain wallet executors. Each submodule owns its own key derivation,
-//! transaction encoding, signing, and broadcast against a JSON-RPC or REST
-//! endpoint. The shared [`super::execution`] module is a thin dispatcher.
-//!
-//! All execute_* fns are async and return [`ExecutionResult`] on success.
-//! All preparation logic (validation, fee estimate, quote storage) lives in
-//! `execution.rs`; chain modules only run when a quote is being broadcast.
-//!
-//! Every chain exposes a small surface:
-//! - `execute_*_quote(quote: PreparedTransaction) -> Result<ExecutionResult, String>`
-//! - `native_balance(address: &str) -> Result<u128, String>`
-//! - `validate_*_address(addr: &str) -> Result<String, String>`
-//! - `tx_status` / `tx_receipt` / `lookup_tx` — read-only inspection by hash.
-//!
-//! EVM and Solana additionally expose crate-internal `sign_and_broadcast_*`
-//! primitives (sign+broadcast an externally-built unsigned transaction) that the
-//! [`crate::web3`] layer builds on.
-
-pub(super) mod btc;
-pub(super) mod evm;
-pub(super) mod solana;
-pub(super) mod tron;
diff --git a/crates/openhuman-core/src/web3/wallet/chains/solana.rs b/crates/openhuman-core/src/web3/wallet/chains/solana.rs
deleted file mode 100644
index 36b1641262..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/solana.rs
+++ /dev/null
@@ -1,690 +0,0 @@
-//! Solana native SOL + SPL token transfer. We hand-build the wire format so
-//! we don't pull in `solana-sdk` (which transitively brings in ~150 crates).
-//!
-//! Key derivation: SLIP-0010 ed25519 (`m/44'/501'/0'/0'`). Solana mainnet
-//! addresses are 32-byte ed25519 public keys, base58-encoded.
-//!
-//! Wire format references:
-//! - https://docs.solana.com/developing/programming-model/transactions
-//! - https://docs.solana.com/developing/programming-model/runtime#compact-u16
-//! - https://spl.solana.com/token
-
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-use curve25519_dalek::edwards::CompressedEdwardsY;
-#[cfg(test)]
-use ed25519_dalek::{SigningKey, SECRET_KEY_LENGTH};
-use log::debug;
-use serde::Deserialize;
-use serde_json::json;
-use sha2::{Digest, Sha256};
-
-use crate::config::rpc as config_rpc;
-
-use super::super::defaults::explorer_tx_url;
-use super::super::execution::{
- ExecutionResult, PreparedKind, PreparedStatus, PreparedTransaction, RawBroadcastResult,
- TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,
-};
-use super::super::ops::{secret_material, WalletChain};
-use super::super::rpc::rpc_call;
-
-const LOG_PREFIX: &str = "[wallet::sol]";
-
-/// System Program ID (all zeros).
-const SYSTEM_PROGRAM_ID: [u8; 32] = [0u8; 32];
-
-fn token_program_id() -> [u8; 32] {
- let mut out = [0u8; 32];
- let v = bs58::decode("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")
- .into_vec()
- .expect("static base58");
- out.copy_from_slice(&v);
- out
-}
-
-fn ata_program_id() -> [u8; 32] {
- let mut out = [0u8; 32];
- let v = bs58::decode("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")
- .into_vec()
- .expect("static base58");
- out.copy_from_slice(&v);
- out
-}
-
-#[derive(Debug, Deserialize)]
-struct BlockhashResponse {
- value: BlockhashValue,
-}
-
-#[derive(Debug, Deserialize)]
-struct BlockhashValue {
- blockhash: String,
-}
-
-/// Validate a Solana address (a base58 ed25519 public key).
-///
-/// Delegates to the vendored [`tinywallet_bus`] crate, which owns the address
-/// format; this wrapper keeps the `Result<_, String>` shape the rest of the
-/// domain speaks.
-pub fn validate_solana_address(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::solana::validate(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-pub async fn native_balance(address: &str) -> Result<u128, String> {
- validate_solana_address(address)?;
- #[derive(Deserialize)]
- struct BalanceResult {
- value: u64,
- }
- let result: BalanceResult =
- rpc_call(WalletChain::Solana, "getBalance", json!([address])).await?;
- Ok(result.value as u128)
-}
-
-/// Derive the Solana signing key for `derivation_path` from a BIP-39 mnemonic.
-///
-/// Test-only, and deliberately on the **root** `tinywallet` crate rather than
-/// `tinywallet-bus`: `key` is one of the gates that did not move into the
-/// contract crate. The root crate is a dev-dependency here, so this derivation
-/// stack is not linked into the shipped binary. Production derives inside the
-/// wallet module, via `modules::wallet::derive_account`.
-///
-/// The root crate owns SLIP-0010 ed25519 derivation; the hand-rolled HMAC walk
-/// and path parser that used to live here moved there wholesale — nothing about
-/// "derive an ed25519 key at a hardened path" is OpenHuman-specific. Custody
-/// stays here: the mnemonic arrives already decrypted from the keyring and
-/// `tinywallet` never sees a stored secret.
-///
-/// One behavioural note: `tinywallet` reports a non-hardened Solana path as
-/// its own error variant rather than folding it into a generic parse failure,
-/// because such a path is derivable-looking but underivable on ed25519 — and
-/// silently hardening it would return a different account than the path names.
-/// Test-only: production derives inside the wallet module.
-#[cfg(test)]
-fn derive_solana_keypair(mnemonic: &str, derivation_path: &str) -> Result<SigningKey, String> {
- let derived = tinywallet::key::derive(tinywallet::Chain::Solana, mnemonic, derivation_path)
- .map_err(|e| e.to_string())?;
- let bytes: [u8; SECRET_KEY_LENGTH] = derived
- .secret_bytes()
- .try_into()
- .map_err(|_| "tinywallet returned an unexpected Solana key length".to_string())?;
- Ok(SigningKey::from_bytes(&bytes))
-}
-
-/// Solana compact-u16 (shortvec) encoding.
-fn encode_shortvec(value: u16) -> Vec<u8> {
- let mut out = Vec::new();
- let mut v = value as u32;
- loop {
- let mut byte = (v & 0x7f) as u8;
- v >>= 7;
- if v == 0 {
- out.push(byte);
- return out;
- }
- byte |= 0x80;
- out.push(byte);
- }
-}
-
-/// Decode a Solana compact-u16 (shortvec). Returns `(value, bytes_consumed)`.
-fn decode_shortvec(bytes: &[u8]) -> Result<(u16, usize), String> {
- let mut value: u32 = 0;
- let mut shift = 0u32;
- for (i, byte) in bytes.iter().enumerate() {
- if i >= 3 {
- return Err("shortvec too long".to_string());
- }
- value |= u32::from(byte & 0x7f) << shift;
- if byte & 0x80 == 0 {
- if value > u16::MAX as u32 {
- return Err("shortvec exceeds u16 range".to_string());
- }
- return Ok((value as u16, i + 1));
- }
- shift += 7;
- }
- Err("shortvec truncated".to_string())
-}
-
-#[derive(Debug, Clone)]
-struct CompiledInstruction {
- program_id_index: u8,
- accounts: Vec<u8>,
- data: Vec<u8>,
-}
-
-fn encode_compiled_instruction(ins: &CompiledInstruction) -> Vec<u8> {
- let mut out = Vec::new();
- out.push(ins.program_id_index);
- out.extend(encode_shortvec(ins.accounts.len() as u16));
- out.extend(&ins.accounts);
- out.extend(encode_shortvec(ins.data.len() as u16));
- out.extend(&ins.data);
- out
-}
-
-fn encode_message(
- header: [u8; 3],
- account_keys: &[[u8; 32]],
- recent_blockhash: &[u8; 32],
- instructions: &[CompiledInstruction],
-) -> Vec<u8> {
- let mut out = Vec::new();
- out.extend(&header);
- out.extend(encode_shortvec(account_keys.len() as u16));
- for key in account_keys {
- out.extend(key);
- }
- out.extend(recent_blockhash);
- out.extend(encode_shortvec(instructions.len() as u16));
- for ins in instructions {
- out.extend(encode_compiled_instruction(ins));
- }
- out
-}
-
-/// Solana `find_program_address` — iterates a bump seed 255..=0, returning
-/// the first off-curve PDA. Used to derive Associated Token Accounts.
-fn find_program_address(seeds: &[&[u8]], program_id: &[u8; 32]) -> Result<([u8; 32], u8), String> {
- let pda_marker = b"ProgramDerivedAddress";
- for bump in (0u8..=255).rev() {
- let mut hasher = Sha256::new();
- for seed in seeds {
- hasher.update(seed);
- }
- hasher.update([bump]);
- hasher.update(program_id);
- hasher.update(pda_marker);
- let candidate: [u8; 32] = hasher.finalize().into();
- // Off-curve means it cannot be a public key.
- if CompressedEdwardsY(candidate).decompress().is_none() {
- return Ok((candidate, bump));
- }
- }
- Err("no off-curve PDA found".to_string())
-}
-
-pub fn associated_token_account(owner: &[u8; 32], mint: &[u8; 32]) -> Result<[u8; 32], String> {
- let token_program = token_program_id();
- let ata_program = ata_program_id();
- let (pda, _bump) =
- find_program_address(&[&owner[..], &token_program[..], &mint[..]], &ata_program)?;
- Ok(pda)
-}
-
-fn b58_to_pubkey(addr: &str) -> Result<[u8; 32], String> {
- let v = bs58::decode(addr)
- .into_vec()
- .map_err(|e| format!("invalid base58 '{addr}': {e}"))?;
- if v.len() != 32 {
- return Err(format!("expected 32-byte pubkey, got {}", v.len()));
- }
- let mut out = [0u8; 32];
- out.copy_from_slice(&v);
- Ok(out)
-}
-
-fn pubkey_to_b58(pubkey: &[u8; 32]) -> String {
- bs58::encode(pubkey).into_string()
-}
-
-/// The wallet's Solana account, and the phrase to sign with.
-///
-/// Derivation and signing both happen in the loaded wallet module; this process
-/// holds the phrase only long enough to hand it over on a confidential call,
-/// and never assembles a private key. The module is sent it only after proving
-/// it is an artifact this build pinned — see `modules::wallet::attested_proxy`.
-///
-/// # The `cfg(test)` branch
-///
-/// Under `cfg(test)` this derives locally instead of calling the module, and so
-/// does [`solana_sign`]. A unit test has no loaded module, and the coverage
-/// these tests carry is the RPC choreography and wire format around signing —
-/// how many calls go out, in what order, and what bytes get broadcast — none of
-/// which is about *who* holds the key.
-///
-/// What that deliberately does not cover is the module wiring itself. That is
-/// covered where it can be honest: tinywallet's loader E2E signs through a real
-/// `dlopen`'d module over a real broker, and `modules::wallet`'s own tests pin
-/// the attestation guard. The local branch cannot exist in a shipped binary.
-async fn solana_signer(
- config: &crate::config::Config,
-) -> Result<(tinywallet_bus::wire::SecretMaterial, [u8; 32]), String> {
- let secret = secret_material(WalletChain::Solana).await?;
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(config, &secret.encrypted_mnemonic)
- .await?
- .value;
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Solana,
- };
- #[cfg(test)]
- {
- let _ = config;
- let derived =
- derive_solana_keypair(&signing_secret.mnemonic, &signing_secret.derivation_path)?;
- return Ok((signing_secret, derived.verifying_key().to_bytes()));
- }
-
- #[cfg(not(test))]
- {
- let account = crate::modules::wallet::derive_account(config, &signing_secret)
- .await
- .map_err(|e| format!("failed to derive the Solana account: {e}"))?;
- let pubkey = b58_to_pubkey(&account.address)?;
- Ok((signing_secret, pubkey))
- }
-}
-
-/// Sign `message` with the wallet key, inside the module.
-async fn solana_sign(
- config: &crate::config::Config,
- signing_secret: &tinywallet_bus::wire::SecretMaterial,
- message: &[u8],
-) -> Result<[u8; 64], String> {
- #[cfg(test)]
- {
- use ed25519_dalek::Signer as _;
- let _ = config;
- let key = derive_solana_keypair(&signing_secret.mnemonic, &signing_secret.derivation_path)?;
- return Ok(key.sign(message).to_bytes());
- }
-
- #[cfg(not(test))]
- let signature = crate::modules::wallet::sign_message(
- config,
- signing_secret,
- message,
- tinywallet_bus::wire::Scheme::Ed25519,
- )
- .await
- .map_err(|e| format!("failed to sign the Solana message: {e}"))?;
- #[cfg(not(test))]
- {
- let tinywallet_bus::wire::Signature::Ed25519 { signature_hex } = signature else {
- return Err("the wallet module returned a non-ed25519 Solana signature".to_string());
- };
- let bytes = hex_to_bytes(&signature_hex)?;
- <[u8; 64]>::try_from(bytes.as_slice())
- .map_err(|_| "the wallet module returned a malformed Solana signature".to_string())
- }
-}
-
-/// Decode lowercase hex.
-fn hex_to_bytes(value: &str) -> Result<Vec<u8>, String> {
- if !value.len().is_multiple_of(2) {
- return Err("odd-length hex from the wallet module".to_string());
- }
- (0..value.len() / 2)
- .map(|i| {
- u8::from_str_radix(&value[i * 2..i * 2 + 2], 16)
- .map_err(|e| format!("invalid hex from the wallet module: {e}"))
- })
- .collect()
-}
-
-fn build_native_transfer_message(
- from: [u8; 32],
- to: [u8; 32],
- lamports: u64,
- recent_blockhash: [u8; 32],
-) -> Vec<u8> {
- // accounts: [from (signer, writable), to (writable), system_program (read-only)]
- let account_keys = vec![from, to, SYSTEM_PROGRAM_ID];
- // header: 1 required sig, 0 readonly signed, 1 readonly unsigned (system program)
- let header = [1u8, 0u8, 1u8];
- let mut data = vec![2u8, 0u8, 0u8, 0u8]; // SystemInstruction::Transfer = 2
- data.extend(&lamports.to_le_bytes());
- let ins = CompiledInstruction {
- program_id_index: 2,
- accounts: vec![0, 1],
- data,
- };
- encode_message(header, &account_keys, &recent_blockhash, &[ins])
-}
-
-fn build_spl_transfer_message(
- from_owner: [u8; 32],
- src_ata: [u8; 32],
- dst_ata: [u8; 32],
- amount: u64,
- recent_blockhash: [u8; 32],
-) -> Vec<u8> {
- let token_program = token_program_id();
- // accounts:
- // 0: from_owner (signer, writable — to pay fee)
- // 1: src_ata (writable)
- // 2: dst_ata (writable)
- // 3: token_program (readonly, unsigned)
- let account_keys = vec![from_owner, src_ata, dst_ata, token_program];
- let header = [1u8, 0u8, 1u8];
- let mut data = vec![3u8]; // SPL Token instruction: Transfer = 3
- data.extend(&amount.to_le_bytes());
- let ins = CompiledInstruction {
- program_id_index: 3,
- accounts: vec![1, 2, 0], // src, dst, owner(signer)
- data,
- };
- encode_message(header, &account_keys, &recent_blockhash, &[ins])
-}
-
-/// Best-effort `getAccountInfo` check — returns `Ok(true)` when the account
-/// exists, `Ok(false)` when the RPC reports `value: null`, or propagates the
-/// transport error.
-async fn account_exists(address_b58: &str) -> Result<bool, String> {
- #[derive(Deserialize)]
- struct AccountInfoResponse {
- value: serde_json::Value,
- }
- let resp: AccountInfoResponse = rpc_call(
- WalletChain::Solana,
- "getAccountInfo",
- json!([address_b58, {"encoding": "base64"}]),
- )
- .await?;
- Ok(!resp.value.is_null())
-}
-
-async fn fetch_recent_blockhash() -> Result<[u8; 32], String> {
- let result: BlockhashResponse = rpc_call(
- WalletChain::Solana,
- "getLatestBlockhash",
- json!([{"commitment": "finalized"}]),
- )
- .await?;
- b58_to_pubkey(&result.value.blockhash)
-}
-
-async fn broadcast_solana(signed: &[u8]) -> Result<String, String> {
- let b64 = B64.encode(signed);
- let tx_sig: String = rpc_call(
- WalletChain::Solana,
- "sendTransaction",
- json!([b64, {"encoding": "base64", "preflightCommitment": "processed"}]),
- )
- .await?;
- Ok(tx_sig)
-}
-
-pub async fn execute_solana_quote(
- mut quote: PreparedTransaction,
-) -> Result<ExecutionResult, String> {
- let from_addr = quote.from_address.clone();
- let to_addr = quote.to_address.clone();
- validate_solana_address(&from_addr)?;
- validate_solana_address(&to_addr)?;
- let amount: u64 = quote
- .amount_raw
- .parse()
- .map_err(|e| format!("invalid Solana amount '{}': {e}", quote.amount_raw))?;
-
- let config = config_rpc::load_config_with_timeout().await?;
- let (signing_secret, from_pk) = solana_signer(&config).await?;
- let expected_from = b58_to_pubkey(&from_addr)?;
- if from_pk != expected_from {
- return Err(format!(
- "Solana key derivation mismatch: derived {} but expected {}",
- pubkey_to_b58(&from_pk),
- from_addr
- ));
- }
-
- let recent_blockhash = fetch_recent_blockhash().await?;
- let to_pubkey = b58_to_pubkey(&to_addr)?;
-
- let message_bytes = match quote.kind {
- PreparedKind::NativeTransfer => {
- build_native_transfer_message(from_pk, to_pubkey, amount, recent_blockhash)
- }
- PreparedKind::TokenTransfer => {
- let mint_addr = quote
- .token_address
- .as_deref()
- .ok_or_else(|| "SPL transfer missing token_address (mint)".to_string())?;
- let mint = b58_to_pubkey(mint_addr)?;
- let src_ata = associated_token_account(&from_pk, &mint)?;
- let dst_ata = associated_token_account(&to_pubkey, &mint)?;
- // Preflight: refuse to send to a non-existent ATA so we don't
- // burn the broadcast on a guaranteed on-chain failure. The
- // caller (or a future PR) can prepend a CreateAssociatedTokenAccount
- // instruction; for now we fail loudly with a clear message.
- if !account_exists(&pubkey_to_b58(&dst_ata)).await? {
- return Err(format!(
- "SPL preflight: destination Associated Token Account does not exist for mint {} owner {}; create it before transferring",
- mint_addr,
- pubkey_to_b58(&to_pubkey)
- ));
- }
- build_spl_transfer_message(from_pk, src_ata, dst_ata, amount, recent_blockhash)
- }
- };
-
- let sig_bytes = solana_sign(&config, &signing_secret, &message_bytes).await?;
- let mut wire = Vec::with_capacity(1 + 64 + message_bytes.len());
- wire.extend(encode_shortvec(1));
- wire.extend(&sig_bytes);
- wire.extend(&message_bytes);
-
- let tx_sig = broadcast_solana(&wire).await?;
- quote.status = PreparedStatus::Broadcasted;
- debug!(
- "{LOG_PREFIX} broadcast quote_id={} sig={} kind={:?}",
- quote.quote_id, tx_sig, quote.kind
- );
- let explorer_url = explorer_tx_url(WalletChain::Solana, &tx_sig);
- Ok(ExecutionResult {
- quote_id: quote.quote_id.clone(),
- status: PreparedStatus::Broadcasted,
- chain: WalletChain::Solana,
- evm_network: None,
- transaction_hash: tx_sig,
- explorer_url,
- transaction: quote,
- })
-}
-
-/// Crate-internal primitive: sign an externally-built, hex-encoded
-/// `VersionedTransaction` (e.g. a deBridge swap/bridge tx) with the wallet's
-/// Solana key and broadcast it. Not exposed as an agent tool or RPC.
-///
-/// Wire layout (Solana transaction): `shortvec(num_signatures)` followed by
-/// `num_signatures * 64` signature slots, then the serialized message. We fill
-/// the signature slot at the index whose `account_keys[i]` equals our pubkey,
-/// signing the full message bytes (legacy or v0 — the message slice includes
-/// the v0 version prefix, which is what Solana signs).
-pub(crate) async fn sign_and_broadcast_versioned(
- tx_blob_hex: &str,
-) -> Result<RawBroadcastResult, String> {
- let trimmed = tx_blob_hex.trim();
- let normalized = trimmed.strip_prefix("0x").unwrap_or(trimmed);
- let mut wire =
- hex::decode(normalized).map_err(|e| format!("invalid Solana transaction hex blob: {e}"))?;
-
- let (num_signatures, sig_count_len) = decode_shortvec(&wire)?;
- let sigs_start = sig_count_len;
- let message_start = sigs_start + (num_signatures as usize) * 64;
- if message_start > wire.len() {
- return Err("Solana tx blob truncated before message".to_string());
- }
- let message = &wire[message_start..];
- if message.is_empty() {
- return Err("Solana tx blob has empty message".to_string());
- }
-
- // Determine message version + header offset.
- let versioned = message[0] & 0x80 != 0;
- let header_off = if versioned { 1 } else { 0 };
- if message.len() < header_off + 3 {
- return Err("Solana message header truncated".to_string());
- }
- let num_required_signatures = message[header_off] as usize;
- if num_required_signatures == 0 {
- return Err("Solana message declares zero required signatures".to_string());
- }
- // Parse account keys (need at least the signer keys to find our index).
- let keys_off = header_off + 3;
- let (account_count, count_len) = decode_shortvec(&message[keys_off..])?;
- let keys_start = keys_off + count_len;
- if account_count as usize > num_required_signatures.max(account_count as usize) {
- // sanity only; continue
- }
- let signer_keys = num_required_signatures.min(account_count as usize);
- if keys_start + signer_keys * 32 > message.len() {
- return Err("Solana account keys region truncated".to_string());
- }
-
- // Derive our signing key.
- let config = config_rpc::load_config_with_timeout().await?;
- let (signing_secret, our_pubkey) = solana_signer(&config).await?;
-
- // Find our signer index.
- let mut our_index: Option<usize> = None;
- for i in 0..signer_keys {
- let off = keys_start + i * 32;
- if message[off..off + 32] == our_pubkey {
- our_index = Some(i);
- break;
- }
- }
- let our_index = our_index.ok_or_else(|| {
- format!(
- "wallet Solana address {} is not a required signer of this transaction",
- pubkey_to_b58(&our_pubkey)
- )
- })?;
- if our_index >= num_signatures as usize {
- return Err("Solana signer index exceeds signature slot count".to_string());
- }
-
- // Sign the message bytes and write into our signature slot.
- let sig_bytes = solana_sign(&config, &signing_secret, message).await?;
- let slot_off = sigs_start + our_index * 64;
- wire[slot_off..slot_off + 64].copy_from_slice(&sig_bytes);
-
- let tx_sig = broadcast_solana(&wire).await?;
- debug!("{LOG_PREFIX} sign_and_broadcast_versioned sig={tx_sig}");
- Ok(RawBroadcastResult {
- transaction_hash: tx_sig.clone(),
- explorer_url: explorer_tx_url(WalletChain::Solana, &tx_sig),
- // Solana fees are dynamic (base + priority) and only known once the tx
- // is confirmed — leave unset rather than misreporting a free transfer.
- fee_raw: None,
- })
-}
-
-/// `getSignatureStatuses` → normalized status.
-pub async fn tx_status(hash: &str) -> Result<TxStatusInfo, String> {
- #[derive(Deserialize)]
- struct StatusResp {
- value: Vec<Option<SigStatus>>,
- }
- #[derive(Deserialize)]
- struct SigStatus {
- slot: u64,
- confirmations: Option<u64>,
- err: Option<serde_json::Value>,
- }
- let resp: StatusResp = rpc_call(
- WalletChain::Solana,
- "getSignatureStatuses",
- json!([[hash], {"searchTransactionHistory": true}]),
- )
- .await?;
- let entry = resp.value.into_iter().next().flatten();
- let (state, confirmations, block_number) = match entry {
- None => (TxState::NotFound, None, None),
- Some(status) => {
- let state = if status.err.is_some() {
- TxState::Failed
- } else if status.confirmations.is_none() {
- // null confirmations means "finalized / rooted".
- TxState::Confirmed
- } else {
- TxState::Pending
- };
- (state, status.confirmations, Some(status.slot))
- }
- };
- Ok(TxStatusInfo {
- chain: WalletChain::Solana,
- evm_network: None,
- hash: hash.to_string(),
- state,
- confirmations,
- block_number,
- })
-}
-
-/// `getTransaction` → normalized receipt with raw passthrough.
-pub async fn tx_receipt(hash: &str) -> Result<TxReceiptInfo, String> {
- let tx: serde_json::Value = rpc_call(
- WalletChain::Solana,
- "getTransaction",
- json!([hash, {"maxSupportedTransactionVersion": 0, "encoding": "json"}]),
- )
- .await?;
- if tx.is_null() {
- return Ok(TxReceiptInfo {
- chain: WalletChain::Solana,
- evm_network: None,
- hash: hash.to_string(),
- found: false,
- success: None,
- block_number: None,
- gas_used: None,
- fee_raw: None,
- raw: serde_json::Value::Null,
- });
- }
- let meta = tx.get("meta");
- let success = meta.map(|m| m.get("err").map(|e| e.is_null()).unwrap_or(true));
- let fee_raw = meta
- .and_then(|m| m.get("fee"))
- .and_then(|v| v.as_u64())
- .map(|f| f.to_string());
- let block_number = tx.get("slot").and_then(|v| v.as_u64());
- Ok(TxReceiptInfo {
- chain: WalletChain::Solana,
- evm_network: None,
- hash: hash.to_string(),
- found: true,
- success,
- block_number,
- gas_used: None,
- fee_raw,
- raw: tx,
- })
-}
-
-/// `getTransaction` → raw transaction passthrough.
-pub async fn lookup_tx(hash: &str) -> Result<TxLookupInfo, String> {
- let tx: serde_json::Value = rpc_call(
- WalletChain::Solana,
- "getTransaction",
- json!([hash, {"maxSupportedTransactionVersion": 0, "encoding": "json"}]),
- )
- .await?;
- Ok(TxLookupInfo {
- chain: WalletChain::Solana,
- evm_network: None,
- hash: hash.to_string(),
- found: !tx.is_null(),
- raw: tx,
- })
-}
-
-#[cfg(test)]
-#[path = "solana_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/chains/solana_tests.rs b/crates/openhuman-core/src/web3/wallet/chains/solana_tests.rs
deleted file mode 100644
index 5d4a8dc841..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/solana_tests.rs
+++ /dev/null
@@ -1,486 +0,0 @@
-use super::*;
-use crate::web3::wallet::execution::{
- insert_quote_for_test, now_ms, reset_quote_store_for_tests, PreparedKind, PreparedStatus,
- PreparedTransaction,
-};
-use crate::web3::wallet::test_support::{sample_solana_address, setup_wallet_in, TEST_LOCK};
-use axum::{routing::post, Router};
-use std::sync::Arc;
-use tempfile::TempDir;
-use tokio::net::TcpListener;
-
-#[test]
-fn shortvec_encodes_small_and_large_values() {
- assert_eq!(encode_shortvec(0), vec![0]);
- assert_eq!(encode_shortvec(1), vec![1]);
- assert_eq!(encode_shortvec(127), vec![127]);
- assert_eq!(encode_shortvec(128), vec![0x80, 1]);
- assert_eq!(encode_shortvec(16_383), vec![0xff, 0x7f]);
- assert_eq!(encode_shortvec(16_384), vec![0x80, 0x80, 1]);
-}
-
-#[test]
-fn validate_solana_address_accepts_known_32_byte_pubkey() {
- let addr = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
- assert_eq!(validate_solana_address(addr).unwrap(), addr);
-}
-
-#[test]
-fn validate_solana_address_rejects_wrong_length() {
- // "tooShort" decodes to ~6 bytes, not 32.
- let err = validate_solana_address("tooShort").unwrap_err();
- assert!(err.contains("32 bytes"), "got: {err}");
-}
-
-#[test]
-fn unhardened_paths_are_rejected() {
- // Path parsing lives in the root `tinywallet` crate, so this exercises
- // the rule through the derivation entry point rather than a private
- // helper.
- const MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon \
- abandon abandon abandon abandon abandon about";
- assert!(derive_solana_keypair(MNEMONIC, "m/44'/501'/0'/0'").is_ok());
- // Non-hardened segments are underivable on ed25519, not merely
- // unsupported — silently hardening them would yield a different account.
- assert!(derive_solana_keypair(MNEMONIC, "m/44/501/0/0").is_err());
- assert!(derive_solana_keypair(MNEMONIC, "m").is_err());
-}
-
-#[test]
-fn derive_solana_keypair_produces_known_address_for_test_mnemonic() {
- // SLIP-0010 ed25519 hardened derivation at m/44'/501'/0'/0' from the
- // standard "abandon × 11 about" mnemonic. Deterministic output —
- // pinned here so a regression in HMAC-SHA512 path traversal or seed
- // derivation flips this test before it ships.
- let mnemonic =
- "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
- let signing = derive_solana_keypair(mnemonic, "m/44'/501'/0'/0'").unwrap();
- let pk = signing.verifying_key().to_bytes();
- let addr = pubkey_to_b58(&pk);
- assert_eq!(addr, "HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk");
- validate_solana_address(&addr).expect("derived addr is 32-byte base58");
-}
-
-#[test]
-fn native_transfer_message_round_trips_basic_structure() {
- let from = [1u8; 32];
- let to = [2u8; 32];
- let bh = [3u8; 32];
- let msg = build_native_transfer_message(from, to, 1_000_000, bh);
- // header is first 3 bytes.
- assert_eq!(&msg[..3], &[1u8, 0u8, 1u8]);
- // shortvec(3) = [3], then 3 keys = 96 bytes.
- assert_eq!(msg[3], 3);
- assert_eq!(&msg[4..36], &from);
- assert_eq!(&msg[36..68], &to);
- assert_eq!(&msg[68..100], &SYSTEM_PROGRAM_ID);
- // blockhash next
- assert_eq!(&msg[100..132], &bh);
- // shortvec(1) instructions = [1]
- assert_eq!(msg[132], 1);
- // program_id_index = 2 (system program)
- assert_eq!(msg[133], 2);
- // shortvec(2) accounts = [2]
- assert_eq!(msg[134], 2);
- assert_eq!(msg[135], 0); // from
- assert_eq!(msg[136], 1); // to
- // shortvec(12) data length = [12]
- assert_eq!(msg[137], 12);
- // Transfer discriminator + 8 LE amount bytes
- assert_eq!(&msg[138..142], &[2u8, 0u8, 0u8, 0u8]);
- let amt = u64::from_le_bytes(msg[142..150].try_into().unwrap());
- assert_eq!(amt, 1_000_000);
-}
-
-async fn start_solana_mock(
- sig: &'static str,
-) -> (
- std::net::SocketAddr,
- Arc<parking_lot::Mutex<Vec<serde_json::Value>>>,
-) {
- let calls: Arc<parking_lot::Mutex<Vec<serde_json::Value>>> =
- Arc::new(parking_lot::Mutex::new(Vec::new()));
- let calls_clone = calls.clone();
- let app = Router::new().route(
- "/",
- post(move |axum::Json(payload): axum::Json<serde_json::Value>| {
- let calls = calls_clone.clone();
- async move {
- calls.lock().push(payload.clone());
- let method = payload
- .get("method")
- .and_then(serde_json::Value::as_str)
- .unwrap_or_default();
- let result = match method {
- "getLatestBlockhash" => json!({
- "context": {"slot": 0},
- "value": {
- "blockhash": "GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi",
- "lastValidBlockHeight": 0u64
- }
- }),
- "getBalance" => json!({
- "context": {"slot": 0},
- "value": 1_000_000u64
- }),
- "getAccountInfo" => json!({
- "context": {"slot": 0},
- "value": {
- "lamports": 2_039_280u64,
- "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
- "data": ["", "base64"],
- "executable": false,
- "rentEpoch": 0u64
- }
- }),
- "sendTransaction" => serde_json::Value::String(sig.to_string()),
- _ => serde_json::Value::Null,
- };
- axum::Json(json!({"jsonrpc":"2.0","id":1,"result":result}))
- }
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- (addr, calls)
-}
-
-#[tokio::test]
-async fn execute_solana_quote_signs_and_broadcasts_native_transfer() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let fake_sig =
- "5xS9pXmqVz8R1nuRZTfsdsAxBdBFmtnAtuYbCsmK5DYzGn5vR4VqWGmiR5McLnYx8oFqLdo62q4qiUZpQyR4Hkn3";
- let (addr, calls) = start_solana_mock(fake_sig).await;
- std::env::set_var("OPENHUMAN_WALLET_RPC_SOLANA", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_sol_native_1".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Solana,
- evm_network: None,
- from_address: sample_solana_address().to_string(),
- to_address: "Vote111111111111111111111111111111111111111".to_string(),
- asset_symbol: "SOL".to_string(),
- amount_raw: "1000".to_string(),
- amount_formatted: "0.000001000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "5000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let result = execute_solana_quote(quote)
- .await
- .expect("solana broadcast ok");
- assert_eq!(result.status, PreparedStatus::Broadcasted);
- assert_eq!(result.transaction_hash, fake_sig);
- // Two RPC calls: getLatestBlockhash + sendTransaction.
- let recorded = calls.lock().clone();
- assert_eq!(recorded.len(), 2);
- assert_eq!(
- recorded[0].get("method").and_then(|v| v.as_str()),
- Some("getLatestBlockhash")
- );
- assert_eq!(
- recorded[1].get("method").and_then(|v| v.as_str()),
- Some("sendTransaction")
- );
-}
-
-#[tokio::test]
-async fn execute_solana_quote_signs_and_broadcasts_spl_transfer() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let fake_sig =
- "5xS9pXmqVz8R1nuRZTfsdsAxBdBFmtnAtuYbCsmK5DYzGn5vR4VqWGmiR5McLnYx8oFqLdo62q4qiUZpQyR4Hkn3";
- let (addr, calls) = start_solana_mock(fake_sig).await;
- std::env::set_var("OPENHUMAN_WALLET_RPC_SOLANA", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_sol_spl_1".to_string(),
- kind: PreparedKind::TokenTransfer,
- chain: WalletChain::Solana,
- evm_network: None,
- from_address: sample_solana_address().to_string(),
- to_address: "Vote111111111111111111111111111111111111111".to_string(),
- asset_symbol: "USDC".to_string(),
- amount_raw: "1000000".to_string(),
- amount_formatted: "1.000000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: Some("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string()),
- estimated_fee_raw: "5000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let result = execute_solana_quote(quote).await.expect("spl broadcast ok");
- assert_eq!(result.status, PreparedStatus::Broadcasted);
- let recorded = calls.lock().clone();
- // SPL preflight calls getAccountInfo somewhere in the request set, plus
- // getLatestBlockhash + sendTransaction.
- assert_eq!(recorded.len(), 3);
- assert!(
- recorded
- .iter()
- .any(|c| c.get("method").and_then(|v| v.as_str()) == Some("getAccountInfo")),
- "SPL preflight must call getAccountInfo"
- );
- // The sendTransaction param[0] is base64-encoded signed tx; pull the
- // base64 string and decode it to confirm it carries the SPL token
- // program ID in its account_keys.
- // sendTransaction is the last call after getAccountInfo + getLatestBlockhash.
- let send_call = recorded
- .iter()
- .rev()
- .find(|c| c.get("method").and_then(|v| v.as_str()) == Some("sendTransaction"))
- .expect("sendTransaction call recorded");
- let params = send_call.get("params").and_then(|v| v.as_array()).unwrap();
- let tx_b64 = params[0].as_str().unwrap();
- let raw = B64.decode(tx_b64).expect("valid base64");
- // shortvec(1) signature + 64-byte sig + message
- assert_eq!(raw[0], 1, "exactly one signature");
- let message = &raw[1 + 64..];
- // header (3) + shortvec(4) + 4*32 keys: token program must be one of them.
- let token_program = token_program_id();
- assert!(
- message.windows(32).any(|w| w == token_program),
- "expected token program in account_keys"
- );
-}
-
-#[tokio::test]
-async fn execute_solana_quote_refuses_spl_when_destination_ata_missing() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- // Custom mock that returns null for getAccountInfo — simulates an ATA
- // that was never created on-chain.
- let app = Router::new().route(
- "/",
- post(
- |axum::Json(payload): axum::Json<serde_json::Value>| async move {
- let method = payload
- .get("method")
- .and_then(serde_json::Value::as_str)
- .unwrap_or_default();
- let result = match method {
- "getAccountInfo" => json!({"context": {"slot": 0}, "value": null}),
- "getLatestBlockhash" => json!({
- "context": {"slot": 0},
- "value": {
- "blockhash": "GHtXQBsoZHVnNFa9YevAzFr17DJjgHXk3ycTKD5xD3Zi",
- "lastValidBlockHeight": 0u64
- }
- }),
- _ => serde_json::Value::Null,
- };
- axum::Json(json!({"jsonrpc":"2.0","id":1,"result":result}))
- },
- ),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_SOLANA", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_sol_spl_missing_ata".to_string(),
- kind: PreparedKind::TokenTransfer,
- chain: WalletChain::Solana,
- evm_network: None,
- from_address: sample_solana_address().to_string(),
- to_address: "Vote111111111111111111111111111111111111111".to_string(),
- asset_symbol: "USDC".to_string(),
- amount_raw: "1000000".to_string(),
- amount_formatted: "1.000000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: Some("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string()),
- estimated_fee_raw: "5000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let err = execute_solana_quote(quote).await.unwrap_err();
- assert!(
- err.contains("SPL preflight") && err.contains("Associated Token Account does not exist"),
- "got: {err}"
- );
-}
-
-#[test]
-fn associated_token_account_derives_off_curve_pda_for_usdc_mint() {
- // find_program_address must produce an off-curve point (else it
- // would be a valid pubkey, which violates the ATA program's
- // contract). We verify two invariants:
- // - derivation is deterministic for fixed (owner, mint)
- // - result is off-curve (CompressedEdwardsY::decompress is None)
- let owner = b58_to_pubkey("HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk").unwrap();
- let mint = b58_to_pubkey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v").unwrap();
- let ata_a = associated_token_account(&owner, &mint).unwrap();
- let ata_b = associated_token_account(&owner, &mint).unwrap();
- assert_eq!(ata_a, ata_b, "ATA derivation must be deterministic");
- assert!(
- CompressedEdwardsY(ata_a).decompress().is_none(),
- "ATA must be off-curve"
- );
-}
-
-#[test]
-fn spl_transfer_message_uses_token_program_and_correct_accounts() {
- let from = [1u8; 32];
- let src = [2u8; 32];
- let dst = [3u8; 32];
- let bh = [4u8; 32];
- let msg = build_spl_transfer_message(from, src, dst, 42, bh);
- // 4 account keys: from, src, dst, token_program
- assert_eq!(msg[3], 4);
- let token_program = token_program_id();
- let key3 = &msg[4 + 96..4 + 128];
- assert_eq!(key3, &token_program);
-}
-
-#[test]
-fn decode_shortvec_round_trips_encode() {
- for v in [0u16, 1, 127, 128, 16_383, 16_384, 65_535] {
- let enc = encode_shortvec(v);
- let (decoded, len) = decode_shortvec(&enc).unwrap();
- assert_eq!(decoded, v, "value {v} round-trips");
- assert_eq!(len, enc.len(), "consumed length matches for {v}");
- }
-}
-
-/// Build a minimal legacy VersionedTransaction wire with `signer` as the
-/// sole required signer and an empty signature slot.
-fn build_unsigned_legacy(signer: &[u8; 32]) -> Vec<u8> {
- let mut message = Vec::new();
- message.extend([1u8, 0u8, 0u8]); // header: 1 required sig
- message.extend(encode_shortvec(1)); // 1 account key
- message.extend(signer);
- message.extend([0u8; 32]); // recent blockhash
- message.extend(encode_shortvec(0)); // 0 instructions
- let mut wire = Vec::new();
- wire.extend(encode_shortvec(1)); // 1 signature slot
- wire.extend([0u8; 64]); // empty sig
- wire.extend(&message);
- wire
-}
-
-#[tokio::test]
-async fn sign_and_broadcast_versioned_fills_signature_and_broadcasts() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let fake_sig =
- "5xS9pXmqVz8R1nuRZTfsdsAxBdBFmtnAtuYbCsmK5DYzGn5vR4VqWGmiR5McLnYx8oFqLdo62q4qiUZpQyR4Hkn3";
- let (addr, calls) = start_solana_mock(fake_sig).await;
- std::env::set_var("OPENHUMAN_WALLET_RPC_SOLANA", format!("http://{addr}"));
-
- let signer = b58_to_pubkey(sample_solana_address()).unwrap();
- let wire = build_unsigned_legacy(&signer);
- let result = sign_and_broadcast_versioned(&hex::encode(&wire))
- .await
- .expect("sign+broadcast ok");
- assert_eq!(result.transaction_hash, fake_sig);
-
- // The broadcast tx must carry a non-zero signature in slot 0.
- let send = calls
- .lock()
- .iter()
- .rev()
- .find(|c| c.get("method").and_then(|v| v.as_str()) == Some("sendTransaction"))
- .cloned()
- .expect("sendTransaction recorded");
- let b64 = send.get("params").and_then(|p| p.as_array()).unwrap()[0]
- .as_str()
- .unwrap()
- .to_string();
- let raw = B64.decode(b64).unwrap();
- // shortvec(1) + 64-byte sig; the sig must not be all zeros now.
- assert_eq!(raw[0], 1);
- assert!(raw[1..1 + 64].iter().any(|b| *b != 0), "signature filled");
-}
-
-#[tokio::test]
-async fn sign_and_broadcast_versioned_rejects_non_signer() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- // A signer pubkey that is NOT our wallet — sign must refuse.
- let other = [7u8; 32];
- let wire = build_unsigned_legacy(&other);
- let err = sign_and_broadcast_versioned(&hex::encode(&wire))
- .await
- .unwrap_err();
- assert!(err.contains("not a required signer"), "got: {err}");
-}
-
-#[tokio::test]
-async fn tx_status_reads_signature_status() {
- let _guard = TEST_LOCK.lock();
- let _env_guard = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let app = Router::new().route(
- "/",
- post(|axum::Json(_p): axum::Json<serde_json::Value>| async move {
- axum::Json(json!({
- "jsonrpc": "2.0", "id": 1,
- "result": {"context": {"slot": 0}, "value": [
- {"slot": 123u64, "confirmations": null, "err": null}
- ]}
- }))
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_SOLANA", format!("http://{addr}"));
- let info = tx_status("somesig").await.unwrap();
- assert_eq!(
- info.state,
- crate::web3::wallet::execution::TxState::Confirmed
- );
- assert_eq!(info.block_number, Some(123));
-}
diff --git a/crates/openhuman-core/src/web3/wallet/chains/tron.rs b/crates/openhuman-core/src/web3/wallet/chains/tron.rs
deleted file mode 100644
index cdc0941ca1..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/tron.rs
+++ /dev/null
@@ -1,503 +0,0 @@
-//! Tron native TRX + TRC20 token transfer. Uses the TronGrid REST API
-//! (https://api.trongrid.io) — `wallet/createtransaction`,
-//! `wallet/triggersmartcontract`, `wallet/broadcasttransaction`.
-//!
-//! Derivation: BIP44 m/44'/195'/0'/0/0 → secp256k1 key. Tron addresses are
-//! `sha3_256(uncompressed_pubkey[1..])[12..]` prefixed with 0x41, base58check.
-
-use log::debug;
-use serde::Deserialize;
-use serde_json::{json, Value};
-
-use crate::config::rpc as config_rpc;
-
-use super::super::defaults::{explorer_tx_url, rpc_url_for_chain};
-use super::super::execution::{
- ExecutionResult, PreparedKind, PreparedStatus, PreparedTransaction, TxLookupInfo,
- TxReceiptInfo, TxState, TxStatusInfo,
-};
-use super::super::ops::{secret_material, WalletChain};
-use super::super::rpc::rest_post_json;
-
-const LOG_PREFIX: &str = "[wallet::tron]";
-/// Tron address prefix (mainnet).
-const TRON_PREFIX: u8 = 0x41;
-/// Fixed TRC20 fee_limit (15 TRX = 15_000_000 SUN). Safe upper bound.
-const TRC20_FEE_LIMIT_SUN: u64 = 15_000_000;
-
-/// Validate a Tron mainnet base58check address.
-///
-/// Delegates to the vendored [`tinywallet_bus`] crate, which owns the address
-/// format; this wrapper keeps the `Result<_, String>` shape the rest of the
-/// domain speaks.
-pub fn validate_tron_address(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::tron::validate(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-/// Convert a base58check Tron address into the 42-hex-digit form the TronGrid
-/// API expects, version prefix included.
-///
-/// Delegates to [`tinywallet_bus`]. Note this now validates the address before
-/// converting, where the previous local implementation decoded without a
-/// length check — a malformed address that happened to base58check-decode to
-/// the wrong length used to produce a short hex string and fail further
-/// downstream at the API call.
-pub fn tron_address_to_hex(addr: &str) -> Result<String, String> {
- let result = tinywallet_bus::address::tron::to_hex(addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} address_to_hex result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-pub async fn native_balance(address: &str) -> Result<u128, String> {
- validate_tron_address(address)?;
- let base = rpc_url_for_chain(WalletChain::Tron);
- let url = format!("{}/wallet/getaccount", base.trim_end_matches('/'));
- let body = json!({
- "address": tron_address_to_hex(address)?,
- "visible": false,
- });
- let resp: Value = rest_post_json(&url, &body).await?;
- let balance = resp.get("balance").and_then(Value::as_u64).unwrap_or(0);
- Ok(balance as u128)
-}
-
-#[derive(Debug, Deserialize)]
-struct CreateTransactionResponse {
- #[serde(rename = "txID")]
- tx_id: String,
- raw_data: Value,
- raw_data_hex: String,
-}
-
-#[derive(Debug, Deserialize)]
-struct TriggerSmartContractResponse {
- transaction: CreateTransactionResponse,
-}
-
-/// What the node was asked to build, for verifying what it returned.
-///
-/// [`tinywallet_bus::wire::TronTransfer`] is that type — it is already on the
-/// host/module wire contract, so a second local mirror of it would be one more
-/// thing to keep in step for no gain. The one thing it deliberately does not
-/// carry is the fee limit, because only the caller knows what it pinned; that
-/// rides alongside as [`verify_contract`]'s last argument.
-type TronTransferVerification = tinywallet_bus::wire::TronTransfer;
-
-/// Check a node-built Tron transaction, then describe it for the signer.
-///
-/// The verification itself lives in [`tinywallet_bus::tx::tron::verify_contract`],
-/// which parses `raw_data` structurally. The protobuf reader, the contract
-/// unwrapping and the per-contract field checks used to be hand-rolled here;
-/// they are the same rules for every host, so they moved into the crate. What
-/// stays is the part that is OpenHuman's: the fee limit this client pins, and
-/// the [`tinywallet_bus::wire::TransactionSpec`] handed to the wallet module.
-fn tron_transaction_spec(
- raw_tx: &CreateTransactionResponse,
- expected_to: String,
- transfer: &TronTransferVerification,
-) -> Result<tinywallet_bus::wire::TransactionSpec, String> {
- let recomputed_txid = tinywallet_bus::tx::tron::recompute_txid(&raw_tx.raw_data_hex)
- .map_err(|error| format!("invalid Tron raw_data_hex: {error}"))?;
-
- // The fee limit is ours, not the crate's: it is what this client pinned in
- // the `createtransaction` request, and only a TRC-20 trigger carries one.
- let fee_limit_sun = match transfer {
- TronTransferVerification::Native { .. } => None,
- TronTransferVerification::Trc20 { .. } => Some(TRC20_FEE_LIMIT_SUN),
- };
-
- tinywallet_bus::tx::tron::verify_contract(
- &raw_tx.raw_data_hex,
- &expected_to,
- &raw_tx.tx_id,
- transfer,
- fee_limit_sun,
- )
- .map_err(|error| format!("Tron node response rejected: {error}"))?;
-
- Ok(tinywallet_bus::wire::TransactionSpec::Tron {
- raw_data_hex: raw_tx.raw_data_hex.clone(),
- expected_to,
- expected_txid: recomputed_txid,
- // Carried onto the wire so the wallet module re-checks it against the
- // bytes it is about to sign, rather than trusting this side's verdict.
- transfer: transfer.clone(),
- })
-}
-
-/// Derive the Tron signing key and its base58check address.
-///
-/// Test-only, and deliberately on the **root** `tinywallet` crate rather than
-/// `tinywallet-bus`: `key` is one of the gates that did not move into the
-/// contract crate. The root crate is a dev-dependency here, so this derivation
-/// stack is not linked into the shipped binary. Production derives inside the
-/// wallet module, via `modules::wallet::derive_account`.
-///
-/// The root crate owns BIP-32 secp256k1 derivation and the
-/// Keccak-then-base58check address construction; the hand-rolled BIP-32 walk
-/// and path parser that used to live here moved there wholesale. Custody stays
-/// here.
-#[cfg(test)]
-fn derive_tron_keypair(mnemonic: &str, derivation_path: &str) -> Result<(Vec<u8>, String), String> {
- let derived = tinywallet::key::derive(tinywallet::Chain::Tron, mnemonic, derivation_path)
- .map_err(|e| e.to_string())?;
- Ok((
- derived.secret_bytes().to_vec(),
- derived.address().to_string(),
- ))
-}
-
-fn pad_left_32(bytes: &[u8]) -> Vec<u8> {
- let mut out = vec![0u8; 32];
- if bytes.len() <= 32 {
- out[32 - bytes.len()..].copy_from_slice(bytes);
- } else {
- out.copy_from_slice(&bytes[bytes.len() - 32..]);
- }
- out
-}
-
-fn encode_trc20_transfer_param(to_hex: &str, amount: u128) -> Result<String, String> {
- // For TRC20 triggerSmartContract `parameter` field: hex-encoded ABI args
- // (no 4-byte selector — TronGrid prepends it from `function_selector`).
- // arg0: address (left-padded to 32 bytes, drop the 0x41 prefix → keep
- // last 20 bytes of the hex address).
- let addr_bytes = hex::decode(to_hex).map_err(|e| format!("invalid hex addr: {e}"))?;
- if addr_bytes.len() != 21 {
- return Err(format!(
- "expected 21-byte Tron address, got {}",
- addr_bytes.len()
- ));
- }
- let mut param = vec![0u8; 32];
- param[12..].copy_from_slice(&addr_bytes[1..]); // skip the 0x41 prefix
- let amount_bytes = amount.to_be_bytes();
- param.extend(pad_left_32(&amount_bytes[..]));
- Ok(hex::encode(param))
-}
-
-async fn create_native_transaction(
- owner_hex: &str,
- to_hex: &str,
- amount_sun: u64,
-) -> Result<CreateTransactionResponse, String> {
- let base = rpc_url_for_chain(WalletChain::Tron);
- let url = format!("{}/wallet/createtransaction", base.trim_end_matches('/'));
- let body = json!({
- "owner_address": owner_hex,
- "to_address": to_hex,
- "amount": amount_sun,
- "visible": false,
- });
- rest_post_json(&url, &body).await
-}
-
-async fn trigger_trc20_transfer(
- owner_hex: &str,
- contract_hex: &str,
- parameter_hex: &str,
-) -> Result<CreateTransactionResponse, String> {
- let base = rpc_url_for_chain(WalletChain::Tron);
- let url = format!("{}/wallet/triggersmartcontract", base.trim_end_matches('/'));
- let body = json!({
- "owner_address": owner_hex,
- "contract_address": contract_hex,
- "function_selector": "transfer(address,uint256)",
- "parameter": parameter_hex,
- "fee_limit": TRC20_FEE_LIMIT_SUN,
- "call_value": 0,
- "visible": false,
- });
- let resp: TriggerSmartContractResponse = rest_post_json(&url, &body).await?;
- Ok(resp.transaction)
-}
-
-async fn broadcast_signed(tx_json: Value) -> Result<Value, String> {
- let base = rpc_url_for_chain(WalletChain::Tron);
- let url = format!("{}/wallet/broadcasttransaction", base.trim_end_matches('/'));
- rest_post_json(&url, &tx_json).await
-}
-
-pub async fn execute_tron_quote(mut quote: PreparedTransaction) -> Result<ExecutionResult, String> {
- validate_tron_address(&quote.from_address)?;
- validate_tron_address(&quote.to_address)?;
- let amount: u128 = quote
- .amount_raw
- .parse()
- .map_err(|e| format!("invalid Tron amount '{}': {e}", quote.amount_raw))?;
-
- let owner_hex = tron_address_to_hex(&quote.from_address)?;
- let to_hex = tron_address_to_hex(&quote.to_address)?;
-
- let secret = secret_material(WalletChain::Tron).await?;
- let config = config_rpc::load_config_with_timeout().await?;
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
- .await?
- .value;
- // Derivation and signing both happen in the loaded wallet module now, so
- // this process never holds the key. The phrase goes over a confidential
- // call, and only to a module that has proved it is an artifact this build
- // pinned — see `modules::wallet::attested_proxy`.
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Tron,
- };
- let derived_addr = crate::modules::wallet::derive_account(&config, &signing_secret)
- .await
- .map_err(|e| format!("failed to derive the Tron account: {e}"))?
- .address;
- if derived_addr != quote.from_address {
- return Err(format!(
- "Tron key derivation mismatch: derived {derived_addr} but expected {}",
- quote.from_address
- ));
- }
-
- // Which address the *transaction* pays, which is not always the address the
- // user is paying. A native transfer pays the recipient; a TRC20 transfer
- // pays the token contract and carries the recipient inside the call
- // parameter, left-padded to 32 bytes and so without the `41` prefix that
- // appears in `raw_data` for a native transfer. Verifying a TRC20 against
- // the user's recipient would therefore never match.
- let (verified_recipient, transfer, raw_tx) = match quote.kind {
- PreparedKind::NativeTransfer => {
- let amount_sun: u64 = amount
- .try_into()
- .map_err(|_| format!("Tron amount {amount} exceeds u64"))?;
- (
- quote.to_address.clone(),
- TronTransferVerification::Native { amount_sun },
- create_native_transaction(&owner_hex, &to_hex, amount_sun).await?,
- )
- }
- PreparedKind::TokenTransfer => {
- let contract = quote
- .token_address
- .as_deref()
- .ok_or_else(|| "TRC20 transfer missing token_address".to_string())?;
- validate_tron_address(contract)?;
- let contract_hex = tron_address_to_hex(contract)?;
- let parameter = encode_trc20_transfer_param(&to_hex, amount)?;
- (
- contract.to_string(),
- TronTransferVerification::Trc20 {
- parameter_hex: parameter.clone(),
- },
- trigger_trc20_transfer(&owner_hex, &contract_hex, &parameter).await?,
- )
- }
- };
-
- // The node builds the transaction, so verify every requested field here
- // before the module hands back a digest to sign. The module independently
- // rechecks the locally recomputed txid and recipient; the host additionally
- // binds the native amount or full TRC20 parameter.
- let transfer_kind = match &transfer {
- TronTransferVerification::Native { .. } => "native",
- TronTransferVerification::Trc20 { .. } => "trc20",
- };
- let transaction = match tron_transaction_spec(&raw_tx, verified_recipient, &transfer) {
- Ok(transaction) => {
- debug!(
- "{LOG_PREFIX} validation=accepted quote_id={} txid={} kind={transfer_kind}",
- quote.quote_id, raw_tx.tx_id
- );
- transaction
- }
- Err(error) => {
- debug!(
- "{LOG_PREFIX} validation=rejected quote_id={} txid={} kind={transfer_kind} reason={error}",
- quote.quote_id, raw_tx.tx_id
- );
- return Err(error);
- }
- };
- let signed =
- crate::modules::wallet::sign_transaction_in_module(&config, &transaction, &signing_secret)
- .await
- .map_err(|e| format!("failed to sign Tron transaction: {e}"))?;
- let sig_hex = signed.raw;
-
- let mut tx_with_sig = serde_json::to_value(serde_json::json!({
- "txID": raw_tx.tx_id,
- "raw_data": raw_tx.raw_data,
- "raw_data_hex": raw_tx.raw_data_hex,
- "signature": [sig_hex],
- }))
- .map_err(|e| format!("failed to build Tron signed tx: {e}"))?;
- // visible: false flag for broadcast
- tx_with_sig
- .as_object_mut()
- .expect("object")
- .insert("visible".to_string(), Value::Bool(false));
-
- let response = broadcast_signed(tx_with_sig).await?;
- let ok = response
- .get("result")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- if !ok {
- let code = response.get("code").and_then(Value::as_str).unwrap_or("");
- let msg = response
- .get("message")
- .and_then(Value::as_str)
- .unwrap_or_default();
- return Err(format!(
- "Tron broadcast rejected: code={code} message={msg}"
- ));
- }
- let txid = response
- .get("txid")
- .and_then(Value::as_str)
- .map(str::to_string)
- .unwrap_or_else(|| raw_tx.tx_id.clone());
-
- quote.status = PreparedStatus::Broadcasted;
- debug!(
- "{LOG_PREFIX} broadcast quote_id={} txid={} kind={:?}",
- quote.quote_id, txid, quote.kind
- );
- let explorer_url = explorer_tx_url(WalletChain::Tron, &txid);
- Ok(ExecutionResult {
- quote_id: quote.quote_id.clone(),
- status: PreparedStatus::Broadcasted,
- chain: WalletChain::Tron,
- evm_network: None,
- transaction_hash: txid,
- explorer_url,
- transaction: quote,
- })
-}
-
-async fn tron_post(path: &str, body: Value) -> Result<Value, String> {
- let base = rpc_url_for_chain(WalletChain::Tron);
- let url = format!(
- "{}/{}",
- base.trim_end_matches('/'),
- path.trim_start_matches('/')
- );
- rest_post_json(&url, &body).await
-}
-
-/// TronGrid `/wallet/gettransactioninfobyid` → normalized status.
-pub async fn tx_status(hash: &str) -> Result<TxStatusInfo, String> {
- let info = tron_post("wallet/gettransactioninfobyid", json!({ "value": hash })).await?;
- let block_number = info.get("blockNumber").and_then(Value::as_u64);
- let (state, block_number) = match block_number {
- None => {
- // The info endpoint only has a row once the tx is mined. A freshly
- // broadcast tx is still pending — disambiguate via gettransactionbyid.
- let tx = tron_post("wallet/gettransactionbyid", json!({ "value": hash })).await?;
- let seen = tx.get("txID").is_some() || tx.get("raw_data").is_some();
- (
- if seen {
- TxState::Pending
- } else {
- TxState::NotFound
- },
- None,
- )
- }
- Some(bn) => {
- // `receipt.result` carries SUCCESS / REVERT / FAILED for contract txs;
- // a bare TRX transfer omits it but is successful once mined.
- let result = info
- .get("receipt")
- .and_then(|r| r.get("result"))
- .and_then(Value::as_str);
- let state = match result {
- Some("SUCCESS") | None => TxState::Confirmed,
- Some(_) => TxState::Failed,
- };
- (state, Some(bn))
- }
- };
- Ok(TxStatusInfo {
- chain: WalletChain::Tron,
- evm_network: None,
- hash: hash.to_string(),
- state,
- confirmations: None,
- block_number,
- })
-}
-
-/// TronGrid `/wallet/gettransactioninfobyid` → normalized receipt.
-pub async fn tx_receipt(hash: &str) -> Result<TxReceiptInfo, String> {
- let info = tron_post("wallet/gettransactioninfobyid", json!({ "value": hash })).await?;
- let block_number = info.get("blockNumber").and_then(Value::as_u64);
- if block_number.is_none() {
- return Ok(TxReceiptInfo {
- chain: WalletChain::Tron,
- evm_network: None,
- hash: hash.to_string(),
- found: false,
- success: None,
- block_number: None,
- gas_used: None,
- fee_raw: None,
- raw: serde_json::Value::Null,
- });
- }
- let result = info
- .get("receipt")
- .and_then(|r| r.get("result"))
- .and_then(Value::as_str);
- let success = Some(matches!(result, Some("SUCCESS") | None));
- let fee_raw = info
- .get("fee")
- .and_then(Value::as_u64)
- .map(|f| f.to_string());
- let gas_used = info
- .get("receipt")
- .and_then(|r| r.get("energy_usage_total"))
- .and_then(Value::as_u64)
- .map(|g| g.to_string());
- Ok(TxReceiptInfo {
- chain: WalletChain::Tron,
- evm_network: None,
- hash: hash.to_string(),
- found: true,
- success,
- block_number,
- gas_used,
- fee_raw,
- raw: info,
- })
-}
-
-/// TronGrid `/wallet/gettransactionbyid` → raw transaction passthrough.
-pub async fn lookup_tx(hash: &str) -> Result<TxLookupInfo, String> {
- let tx = tron_post("wallet/gettransactionbyid", json!({ "value": hash })).await?;
- // TronGrid returns `{}` for an unknown id.
- let found = tx.get("txID").is_some() || tx.get("raw_data").is_some();
- Ok(TxLookupInfo {
- chain: WalletChain::Tron,
- evm_network: None,
- hash: hash.to_string(),
- found,
- raw: tx,
- })
-}
-
-#[cfg(test)]
-#[path = "tron_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/chains/tron_tests.rs b/crates/openhuman-core/src/web3/wallet/chains/tron_tests.rs
deleted file mode 100644
index 1c9f993093..0000000000
--- a/crates/openhuman-core/src/web3/wallet/chains/tron_tests.rs
+++ /dev/null
@@ -1,612 +0,0 @@
-use super::*;
-use crate::web3::wallet::execution::{
- insert_quote_for_test, now_ms, reset_quote_store_for_tests, PreparedKind, PreparedStatus,
- PreparedTransaction,
-};
-use crate::web3::wallet::test_support::{sample_tron_address, setup_wallet_in, TEST_LOCK};
-use axum::{routing::post, Router};
-use std::sync::Arc;
-use tempfile::TempDir;
-use tokio::net::TcpListener;
-
-#[derive(Clone, Default)]
-struct TronMockRecord {
- create_calls: Arc<parking_lot::Mutex<Vec<Value>>>,
- trigger_calls: Arc<parking_lot::Mutex<Vec<Value>>>,
- broadcast_calls: Arc<parking_lot::Mutex<Vec<Value>>>,
-}
-
-fn push_varint_field(out: &mut Vec<u8>, number: u64, value: u64) {
- out.extend(tinywallet_bus::tx::proto::encode_varint(number << 3));
- out.extend(tinywallet_bus::tx::proto::encode_varint(value));
-}
-
-fn push_bytes_field(out: &mut Vec<u8>, number: u64, value: &[u8]) {
- out.extend(tinywallet_bus::tx::proto::encode_varint((number << 3) | 2));
- out.extend(tinywallet_bus::tx::proto::encode_varint(value.len() as u64));
- out.extend(value);
-}
-
-fn tron_raw_contract(kind: u64, type_name: &str, payload: &[u8]) -> String {
- let mut any = Vec::new();
- push_bytes_field(
- &mut any,
- 1,
- format!("type.googleapis.com/protocol.{type_name}").as_bytes(),
- );
- push_bytes_field(&mut any, 2, payload);
-
- let mut contract = Vec::new();
- push_varint_field(&mut contract, 1, kind);
- push_bytes_field(&mut contract, 2, &any);
-
- let mut raw = Vec::new();
- push_bytes_field(&mut raw, 11, &contract);
- hex::encode(raw)
-}
-
-fn native_raw(recipient_hex: &str, amount: u64) -> String {
- let mut payload = Vec::new();
- push_bytes_field(&mut payload, 2, &hex::decode(recipient_hex).unwrap());
- push_varint_field(&mut payload, 3, amount);
- tron_raw_contract(1, "TransferContract", &payload)
-}
-
-fn trc20_raw_with_values(
- contract_hex: &str,
- parameter_hex: &str,
- call_value: Option<u64>,
- fee_limit: Option<u64>,
-) -> String {
- let mut payload = Vec::new();
- push_bytes_field(&mut payload, 2, &hex::decode(contract_hex).unwrap());
- if let Some(call_value) = call_value {
- push_varint_field(&mut payload, 3, call_value);
- }
- let mut data = hex::decode("a9059cbb").unwrap();
- data.extend(hex::decode(parameter_hex).unwrap());
- push_bytes_field(&mut payload, 4, &data);
- let mut raw = hex::decode(tron_raw_contract(31, "TriggerSmartContract", &payload)).unwrap();
- if let Some(fee_limit) = fee_limit {
- push_varint_field(&mut raw, 18, fee_limit);
- }
- hex::encode(raw)
-}
-
-fn trc20_raw(contract_hex: &str, parameter_hex: &str) -> String {
- trc20_raw_with_values(
- contract_hex,
- parameter_hex,
- Some(0),
- Some(TRC20_FEE_LIMIT_SUN),
- )
-}
-
-async fn start_tron_mock(record: TronMockRecord) -> std::net::SocketAddr {
- let create = record.create_calls.clone();
- let trigger = record.trigger_calls.clone();
- let broadcast = record.broadcast_calls.clone();
- let app = Router::new()
- .route(
- "/wallet/createtransaction",
- post(move |axum::Json(payload): axum::Json<Value>| {
- let create = create.clone();
- async move {
- let recipient = payload["to_address"].as_str().unwrap();
- let amount = payload["amount"].as_u64().unwrap();
- let raw = native_raw(recipient, amount);
- let txid = tinywallet_bus::tx::tron::recompute_txid(&raw).unwrap();
- create.lock().push(payload);
- axum::Json(json!({
- "txID": txid,
- "raw_data": {"contract": []},
- "raw_data_hex": raw,
- }))
- }
- }),
- )
- .route(
- "/wallet/triggersmartcontract",
- post(move |axum::Json(payload): axum::Json<Value>| {
- let trigger = trigger.clone();
- async move {
- let contract = payload["contract_address"].as_str().unwrap();
- let parameter = payload["parameter"].as_str().unwrap();
- let raw = trc20_raw(contract, parameter);
- let txid = tinywallet_bus::tx::tron::recompute_txid(&raw).unwrap();
- trigger.lock().push(payload);
- axum::Json(json!({
- "transaction": {
- "txID": txid,
- "raw_data": {"contract": []},
- "raw_data_hex": raw,
- }
- }))
- }
- }),
- )
- .route(
- "/wallet/broadcasttransaction",
- post(move |axum::Json(payload): axum::Json<Value>| {
- let broadcast = broadcast.clone();
- async move {
- broadcast.lock().push(payload);
- axum::Json(json!({
- "result": true,
- "txid": "ab".repeat(32),
- }))
- }
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- addr
-}
-
-#[test]
-fn tron_specs_bind_native_and_trc20_verification_fields() {
- let recipient = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
- let contract = "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH";
- let recipient_hex = tron_address_to_hex(recipient).unwrap();
- let contract_hex = tron_address_to_hex(contract).unwrap();
-
- let native_raw_hex = native_raw(&recipient_hex, 1_000_000);
- let native_txid = tinywallet_bus::tx::tron::recompute_txid(&native_raw_hex).unwrap();
- let native_tx = CreateTransactionResponse {
- tx_id: native_txid.clone(),
- raw_data: json!({}),
- raw_data_hex: native_raw_hex.clone(),
- };
- let native = tron_transaction_spec(
- &native_tx,
- recipient.to_string(),
- &TronTransferVerification::Native {
- amount_sun: 1_000_000,
- },
- )
- .unwrap();
- assert_eq!(
- native,
- tinywallet_bus::wire::TransactionSpec::Tron {
- raw_data_hex: native_raw_hex,
- expected_to: recipient.to_string(),
- expected_txid: native_txid,
- // Carried through to the module, which re-verifies it against
- // the bytes rather than trusting this side's check.
- transfer: TronTransferVerification::Native {
- amount_sun: 1_000_000,
- },
- }
- );
-
- let parameter = "01".repeat(64);
- let token_raw = trc20_raw(&contract_hex, &parameter);
- let token_txid = tinywallet_bus::tx::tron::recompute_txid(&token_raw).unwrap();
- let token_tx = CreateTransactionResponse {
- tx_id: token_txid.clone(),
- raw_data: json!({}),
- raw_data_hex: token_raw.clone(),
- };
- let token = tron_transaction_spec(
- &token_tx,
- contract.to_string(),
- &TronTransferVerification::Trc20 {
- parameter_hex: parameter.clone(),
- },
- )
- .unwrap();
- assert_eq!(
- token,
- tinywallet_bus::wire::TransactionSpec::Tron {
- raw_data_hex: token_raw,
- expected_to: contract.to_string(),
- expected_txid: token_txid,
- transfer: TronTransferVerification::Trc20 {
- parameter_hex: parameter.clone(),
- },
- }
- );
- assert_ne!(contract, recipient);
-
- assert!(tron_transaction_spec(
- &native_tx,
- recipient.to_string(),
- &TronTransferVerification::Native { amount_sun: 2 },
- )
- .unwrap_err()
- .contains("different native amount"));
- assert!(tron_transaction_spec(
- &token_tx,
- contract.to_string(),
- &TronTransferVerification::Trc20 {
- parameter_hex: "02".repeat(64),
- },
- )
- .unwrap_err()
- .contains("different TRC20 transfer data"));
-
- for (raw_data_hex, expected_error) in [
- (
- trc20_raw_with_values(
- &contract_hex,
- &parameter,
- Some(1),
- Some(TRC20_FEE_LIMIT_SUN),
- ),
- "non-zero TRC20 call_value",
- ),
- (
- trc20_raw_with_values(
- &contract_hex,
- &parameter,
- Some(0),
- Some(TRC20_FEE_LIMIT_SUN + 1),
- ),
- "different fee_limit",
- ),
- ] {
- let altered_tx = CreateTransactionResponse {
- tx_id: tinywallet_bus::tx::tron::recompute_txid(&raw_data_hex).unwrap(),
- raw_data: json!({}),
- raw_data_hex,
- };
- assert!(tron_transaction_spec(
- &altered_tx,
- contract.to_string(),
- &TronTransferVerification::Trc20 {
- parameter_hex: parameter.clone(),
- },
- )
- .unwrap_err()
- .contains(expected_error));
- }
-
- // A matching value hidden in an unrelated raw-data field must not
- // satisfy validation when the selected contract pays something else.
- let mut spoofed_raw = hex::decode(native_raw(&contract_hex, 2)).unwrap();
- let mut decoy = hex::decode(&recipient_hex).unwrap();
- decoy.extend(tinywallet_bus::tx::proto::encode_varint(1_000_000));
- push_bytes_field(&mut spoofed_raw, 10, &decoy);
- let spoofed_raw = hex::encode(spoofed_raw);
- let spoofed_tx = CreateTransactionResponse {
- tx_id: tinywallet_bus::tx::tron::recompute_txid(&spoofed_raw).unwrap(),
- raw_data: json!({}),
- raw_data_hex: spoofed_raw,
- };
- assert!(tron_transaction_spec(
- &spoofed_tx,
- recipient.to_string(),
- &TronTransferVerification::Native {
- amount_sun: 1_000_000,
- },
- )
- .unwrap_err()
- .contains("requested recipient"));
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_tron_quote_signs_and_broadcasts_native_transfer -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_tron_quote_signs_and_broadcasts_native_transfer() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let record = TronMockRecord::default();
- let addr = start_tron_mock(record.clone()).await;
- std::env::set_var("OPENHUMAN_WALLET_RPC_TRON", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_tron_native_1".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Tron,
- evm_network: None,
- from_address: sample_tron_address().to_string(),
- to_address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t".to_string(),
- asset_symbol: "TRX".to_string(),
- amount_raw: "1000000".to_string(),
- amount_formatted: "1.000000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "1000000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let result = execute_tron_quote(quote).await.expect("tron broadcast ok");
- assert_eq!(result.status, PreparedStatus::Broadcasted);
- assert_eq!(result.transaction_hash, "ab".repeat(32));
- assert_eq!(record.create_calls.lock().len(), 1);
- assert_eq!(record.trigger_calls.lock().len(), 0);
- assert_eq!(record.broadcast_calls.lock().len(), 1);
- // Signed broadcast carries a 65-byte signature (hex = 130 chars).
- let payload = record.broadcast_calls.lock()[0].clone();
- let sig = payload
- .get("signature")
- .and_then(|v| v.as_array())
- .and_then(|arr| arr.first())
- .and_then(|v| v.as_str())
- .unwrap();
- assert_eq!(sig.len(), 130, "expected 65-byte signature, got: {sig}");
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_tron_quote_signs_and_broadcasts_trc20_transfer -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_tron_quote_signs_and_broadcasts_trc20_transfer() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let record = TronMockRecord::default();
- let addr = start_tron_mock(record.clone()).await;
- std::env::set_var("OPENHUMAN_WALLET_RPC_TRON", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_tron_trc20_1".to_string(),
- kind: PreparedKind::TokenTransfer,
- chain: WalletChain::Tron,
- evm_network: None,
- from_address: sample_tron_address().to_string(),
- to_address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t".to_string(),
- asset_symbol: "USDT".to_string(),
- amount_raw: "5000000".to_string(),
- amount_formatted: "5.000000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: Some("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t".to_string()),
- estimated_fee_raw: "15000000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- insert_quote_for_test(quote.clone());
-
- let result = execute_tron_quote(quote).await.expect("trc20 broadcast ok");
- assert_eq!(result.status, PreparedStatus::Broadcasted);
- assert_eq!(record.create_calls.lock().len(), 0);
- assert_eq!(record.trigger_calls.lock().len(), 1);
- assert_eq!(record.broadcast_calls.lock().len(), 1);
- // The triggersmartcontract payload must carry the ABI parameter and
- // selector for transfer(address,uint256).
- let trigger = record.trigger_calls.lock()[0].clone();
- assert_eq!(
- trigger.get("function_selector").and_then(|v| v.as_str()),
- Some("transfer(address,uint256)")
- );
- let param = trigger.get("parameter").and_then(|v| v.as_str()).unwrap();
- assert_eq!(param.len(), 128, "64-byte ABI args, hex-encoded");
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_tron_quote_surfaces_node_rejection -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_tron_quote_surfaces_node_rejection() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- // Custom mock returning result=false on broadcast.
- let app = Router::new()
- .route(
- "/wallet/createtransaction",
- post(|axum::Json(payload): axum::Json<Value>| async move {
- let recipient = payload["to_address"].as_str().unwrap();
- let amount = payload["amount"].as_u64().unwrap();
- let raw = native_raw(recipient, amount);
- let txid = tinywallet_bus::tx::tron::recompute_txid(&raw).unwrap();
- axum::Json(json!({
- "txID": txid,
- "raw_data": {"contract": []},
- "raw_data_hex": raw,
- }))
- }),
- )
- .route(
- "/wallet/broadcasttransaction",
- post(|| async {
- axum::Json(json!({
- "result": false,
- "code": "BANDWIDTH_ERROR",
- "message": "not enough bandwidth",
- }))
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_TRON", format!("http://{addr}"));
-
- let now = now_ms();
- let quote = PreparedTransaction {
- quote_id: "q_tron_reject_1".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Tron,
- evm_network: None,
- from_address: sample_tron_address().to_string(),
- to_address: "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t".to_string(),
- asset_symbol: "TRX".to_string(),
- amount_raw: "1000000".to_string(),
- amount_formatted: "1.000000".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "1000000".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- let err = execute_tron_quote(quote).await.unwrap_err();
- assert!(err.contains("BANDWIDTH_ERROR"), "got: {err}");
-}
-
-#[test]
-fn validate_tron_address_accepts_known_address() {
- // USDT TRC20 contract address — real mainnet, valid base58check.
- let addr = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
- assert_eq!(validate_tron_address(addr).unwrap(), addr);
-}
-
-#[test]
-fn validate_tron_address_rejects_btc_format() {
- let err = validate_tron_address("bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4").unwrap_err();
- assert!(err.contains("invalid"), "got: {err}");
-}
-
-#[test]
-fn tron_address_to_hex_roundtrips_prefix_byte() {
- let addr = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t";
- let h = tron_address_to_hex(addr).unwrap();
- assert!(h.starts_with("41"), "expected 0x41 prefix, got: {h}");
- assert_eq!(h.len(), 42); // 21 bytes * 2 hex chars
-}
-
-#[test]
-fn tron_address_to_hex_rejects_a_wrong_length_decoded_address() {
- // A valid Base58Check encoding with the Tron prefix but a 20-byte
- // decoded payload must not be accepted as a 21-byte Tron address.
- let short = bs58::encode([TRON_PREFIX; 20]).with_check().into_string();
- assert!(tron_address_to_hex(&short).is_err());
-}
-
-#[test]
-fn derive_tron_address_for_known_test_mnemonic() {
- // BIP44 m/44'/195'/0'/0/0 from the standard "abandon × 11 about" mnemonic.
- // Deterministic output of our SLIP-44 / secp256k1 / keccak256 / base58check
- // pipeline — pinning here so regressions in any of those primitives are caught.
- let mnemonic =
- "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
- let (_sk, addr) = derive_tron_keypair(mnemonic, "m/44'/195'/0'/0/0").unwrap();
- assert_eq!(addr, "TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH");
- // Address must be a valid base58check 0x41 mainnet address.
- validate_tron_address(&addr).expect("derived addr passes validation");
-}
-
-#[test]
-fn encode_trc20_transfer_param_pads_addr_and_amount() {
- let to_hex = tron_address_to_hex("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t").unwrap();
- let param = encode_trc20_transfer_param(&to_hex, 12345).unwrap();
- // 64 bytes hex = 32 bytes addr param + 32 bytes amount param = 128 hex chars.
- assert_eq!(param.len(), 128);
- // First 12 bytes = 24 hex chars zero-padded.
- assert!(
- param.starts_with("000000000000000000000000"),
- "expected 12-byte zero padding, got: {param}"
- );
- // Amount 12345 = 0x3039 → last 8 hex chars should be "00003039".
- assert!(param.ends_with("00003039"), "got: {param}");
-}
-
-#[test]
-fn pad_left_32_zero_pads_short_input() {
- let p = pad_left_32(&[1, 2, 3]);
- assert_eq!(p.len(), 32);
- assert_eq!(&p[..29], &[0u8; 29]);
- assert_eq!(&p[29..], &[1, 2, 3]);
-}
-
-#[tokio::test]
-async fn tx_status_confirmed_from_info() {
- let _guard = TEST_LOCK.lock();
- let _env_guard = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let app = Router::new().route(
- "/wallet/gettransactioninfobyid",
- post(|| async {
- axum::Json(json!({
- "id": "ab".repeat(32),
- "blockNumber": 555u64,
- "receipt": {"result": "SUCCESS"},
- "fee": 1100u64
- }))
- }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_TRON", format!("http://{addr}"));
- let info = tx_status("ab").await.unwrap();
- assert_eq!(info.state, TxState::Confirmed);
- assert_eq!(info.block_number, Some(555));
- let receipt = tx_receipt("ab").await.unwrap();
- assert!(receipt.found);
- assert_eq!(receipt.success, Some(true));
- assert_eq!(receipt.fee_raw.as_deref(), Some("1100"));
-}
-
-#[tokio::test]
-async fn tx_status_not_found_on_empty_info() {
- let _guard = TEST_LOCK.lock();
- let _env_guard = crate::config::TEST_ENV_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let app = Router::new()
- .route(
- "/wallet/gettransactioninfobyid",
- post(|| async { axum::Json(json!({})) }),
- )
- .route(
- "/wallet/gettransactionbyid",
- post(|| async { axum::Json(json!({})) }),
- );
- let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- std::env::set_var("OPENHUMAN_WALLET_RPC_TRON", format!("http://{addr}"));
- let info = tx_status("missing").await.unwrap();
- assert_eq!(info.state, TxState::NotFound);
-}
diff --git a/crates/openhuman-core/src/web3/wallet/defaults.rs b/crates/openhuman-core/src/web3/wallet/defaults.rs
deleted file mode 100644
index 8e0fd00ec0..0000000000
--- a/crates/openhuman-core/src/web3/wallet/defaults.rs
+++ /dev/null
@@ -1,518 +0,0 @@
-//! Wallet defaults — RPC URLs, env-var overrides, explorer URLs, and
-//! per-asset catalogs. EVM is parameterized by [`EvmNetwork`] so the same
-//! `WalletChain::Evm` variant covers Ethereum mainnet plus L2s (Base,
-//! Arbitrum, Optimism, Polygon).
-
-use serde::{Deserialize, Serialize};
-
-use super::ops::WalletChain;
-
-const ETHERSCAN_TX_BASE: &str = "https://etherscan.io/tx/";
-const BASESCAN_TX_BASE: &str = "https://basescan.org/tx/";
-const ARBISCAN_TX_BASE: &str = "https://arbiscan.io/tx/";
-const OPTIMISTIC_TX_BASE: &str = "https://optimistic.etherscan.io/tx/";
-const POLYGONSCAN_TX_BASE: &str = "https://polygonscan.com/tx/";
-const BSCSCAN_TX_BASE: &str = "https://bscscan.com/tx/";
-const BLOCKSTREAM_TX_BASE: &str = "https://blockstream.info/tx/";
-const SOLSCAN_TX_BASE: &str = "https://solscan.io/tx/";
-const TRONSCAN_TX_BASE: &str = "https://tronscan.org/#/transaction/";
-
-const DEFAULT_BTC_REST_URL: &str = "https://blockstream.info/api";
-const DEFAULT_SOLANA_RPC_URL: &str = "https://api.mainnet-beta.solana.com";
-const DEVNET_SOLANA_RPC_URL: &str = "https://api.devnet.solana.com";
-const DEFAULT_TRON_REST_URL: &str = "https://api.trongrid.io";
-
-// USDC SPL-token mint per Solana cluster. The mainnet and devnet mints differ,
-// so the selected cluster must drive both the RPC endpoint and the mint.
-const SOLANA_USDC_MINT_MAINNET: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
-const SOLANA_USDC_MINT_DEVNET: &str = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";
-
-/// The Solana cluster the wallet broadcasts to, selected via the
-/// `OPENHUMAN_SOLANA_CLUSTER` env (default [`SolanaCluster::Mainnet`]).
-///
-/// Drives **both** the default Solana RPC endpoint and the USDC SPL mint, so a
-/// devnet x402 payment challenge's on-chain transfer lands on devnet with the
-/// devnet mint rather than mainnet.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum SolanaCluster {
- Mainnet,
- Devnet,
-}
-
-impl SolanaCluster {
- /// Default JSON-RPC endpoint for the cluster (overridable per-call by
- /// `OPENHUMAN_WALLET_RPC_SOLANA`).
- pub fn rpc_url(self) -> &'static str {
- match self {
- Self::Mainnet => DEFAULT_SOLANA_RPC_URL,
- Self::Devnet => DEVNET_SOLANA_RPC_URL,
- }
- }
-
- /// USDC SPL-token mint address for the cluster.
- pub fn usdc_mint(self) -> &'static str {
- match self {
- Self::Mainnet => SOLANA_USDC_MINT_MAINNET,
- Self::Devnet => SOLANA_USDC_MINT_DEVNET,
- }
- }
-}
-
-/// Resolve the configured Solana cluster from `OPENHUMAN_SOLANA_CLUSTER`
-/// (case-insensitive `devnet` → [`SolanaCluster::Devnet`]; anything else or
-/// unset → [`SolanaCluster::Mainnet`], preserving the default behaviour).
-pub fn solana_cluster() -> SolanaCluster {
- let configured = std::env::var("OPENHUMAN_SOLANA_CLUSTER")
- .ok()
- .map(|v| v.trim().to_ascii_lowercase());
- match configured.as_deref() {
- Some("devnet") => {
- log::debug!("[wallet] Solana cluster = devnet (via OPENHUMAN_SOLANA_CLUSTER)");
- SolanaCluster::Devnet
- }
- _ => SolanaCluster::Mainnet,
- }
-}
-
-/// Recognized EVM networks. New L2s plug in here.
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
-#[serde(rename_all = "snake_case")]
-pub enum EvmNetwork {
- EthereumMainnet,
- BaseMainnet,
- ArbitrumOne,
- OptimismMainnet,
- PolygonMainnet,
- BscMainnet,
-}
-
-impl EvmNetwork {
- pub const ALL: [Self; 6] = [
- Self::EthereumMainnet,
- Self::BaseMainnet,
- Self::ArbitrumOne,
- Self::OptimismMainnet,
- Self::PolygonMainnet,
- Self::BscMainnet,
- ];
-
- pub fn as_str(self) -> &'static str {
- match self {
- Self::EthereumMainnet => "ethereum_mainnet",
- Self::BaseMainnet => "base_mainnet",
- Self::ArbitrumOne => "arbitrum_one",
- Self::OptimismMainnet => "optimism_mainnet",
- Self::PolygonMainnet => "polygon_mainnet",
- Self::BscMainnet => "bsc_mainnet",
- }
- }
-
- pub fn chain_id(self) -> u64 {
- match self {
- Self::EthereumMainnet => 1,
- Self::BaseMainnet => 8453,
- Self::ArbitrumOne => 42161,
- Self::OptimismMainnet => 10,
- Self::PolygonMainnet => 137,
- Self::BscMainnet => 56,
- }
- }
-
- pub fn rpc_env_var(self) -> &'static str {
- match self {
- Self::EthereumMainnet => "OPENHUMAN_WALLET_RPC_EVM",
- Self::BaseMainnet => "OPENHUMAN_WALLET_RPC_BASE",
- Self::ArbitrumOne => "OPENHUMAN_WALLET_RPC_ARBITRUM",
- Self::OptimismMainnet => "OPENHUMAN_WALLET_RPC_OPTIMISM",
- Self::PolygonMainnet => "OPENHUMAN_WALLET_RPC_POLYGON",
- Self::BscMainnet => "OPENHUMAN_WALLET_RPC_BSC",
- }
- }
-
- pub fn default_rpc_url(self) -> &'static str {
- match self {
- Self::EthereumMainnet => "https://ethereum-rpc.publicnode.com",
- Self::BaseMainnet => "https://mainnet.base.org",
- Self::ArbitrumOne => "https://arb1.arbitrum.io/rpc",
- Self::OptimismMainnet => "https://mainnet.optimism.io",
- Self::PolygonMainnet => "https://polygon-rpc.com",
- Self::BscMainnet => "https://bsc-dataseed.binance.org",
- }
- }
-
- pub fn explorer_tx_base(self) -> &'static str {
- match self {
- Self::EthereumMainnet => ETHERSCAN_TX_BASE,
- Self::BaseMainnet => BASESCAN_TX_BASE,
- Self::ArbitrumOne => ARBISCAN_TX_BASE,
- Self::OptimismMainnet => OPTIMISTIC_TX_BASE,
- Self::PolygonMainnet => POLYGONSCAN_TX_BASE,
- Self::BscMainnet => BSCSCAN_TX_BASE,
- }
- }
-
- pub fn network_label(self) -> &'static str {
- match self {
- Self::EthereumMainnet => "ethereum-mainnet",
- Self::BaseMainnet => "base-mainnet",
- Self::ArbitrumOne => "arbitrum-one",
- Self::OptimismMainnet => "optimism-mainnet",
- Self::PolygonMainnet => "polygon-mainnet",
- Self::BscMainnet => "bsc-mainnet",
- }
- }
-
- pub fn rpc_url(self) -> String {
- std::env::var(self.rpc_env_var())
- .ok()
- .map(|value| value.trim().to_string())
- .filter(|value| !value.is_empty())
- .unwrap_or_else(|| self.default_rpc_url().to_string())
- }
-
- pub fn rpc_source(self) -> RpcSource {
- let raw = std::env::var(self.rpc_env_var()).unwrap_or_default();
- if raw.trim().is_empty() {
- RpcSource::Default
- } else {
- RpcSource::EnvOverride
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum RpcSource {
- Default,
- EnvOverride,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct WalletAssetDefinition {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub symbol: String,
- pub name: String,
- pub native: bool,
- pub decimals: u8,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub contract_address: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct WalletNetworkDefaults {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub network: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub chain_id: Option<u64>,
- pub rpc_url: String,
- pub rpc_source: RpcSource,
- pub explorer_tx_url_base: String,
- pub supports_broadcast: bool,
- pub supports_token_transfers: bool,
- pub supports_contract_calls: bool,
- pub assets: Vec<WalletAssetDefinition>,
-}
-
-pub fn default_rpc_url(chain: WalletChain) -> &'static str {
- match chain {
- WalletChain::Evm => EvmNetwork::EthereumMainnet.default_rpc_url(),
- WalletChain::Btc => DEFAULT_BTC_REST_URL,
- WalletChain::Solana => solana_cluster().rpc_url(),
- WalletChain::Tron => DEFAULT_TRON_REST_URL,
- }
-}
-
-pub fn rpc_url_for_chain(chain: WalletChain) -> String {
- match chain {
- WalletChain::Evm => EvmNetwork::EthereumMainnet.rpc_url(),
- WalletChain::Btc => env_or_default("OPENHUMAN_WALLET_RPC_BTC", DEFAULT_BTC_REST_URL),
- WalletChain::Solana => {
- env_or_default("OPENHUMAN_WALLET_RPC_SOLANA", solana_cluster().rpc_url())
- }
- WalletChain::Tron => env_or_default("OPENHUMAN_WALLET_RPC_TRON", DEFAULT_TRON_REST_URL),
- }
-}
-
-/// Trimmed value of `env_var`, or `None` when unset/blank.
-fn env_nonempty(env_var: &str) -> Option<String> {
- std::env::var(env_var)
- .ok()
- .map(|value| value.trim().to_string())
- .filter(|value| !value.is_empty())
-}
-
-pub fn rpc_url_for_evm_network(network: EvmNetwork) -> String {
- network.rpc_url()
-}
-
-fn env_or_default(env_var: &str, default: &str) -> String {
- std::env::var(env_var)
- .ok()
- .map(|value| value.trim().to_string())
- .filter(|value| !value.is_empty())
- .unwrap_or_else(|| default.to_string())
-}
-
-pub fn rpc_source_for_chain(chain: WalletChain) -> RpcSource {
- match chain {
- WalletChain::Evm => EvmNetwork::EthereumMainnet.rpc_source(),
- WalletChain::Btc => env_or_source("OPENHUMAN_WALLET_RPC_BTC"),
- WalletChain::Solana => env_or_source("OPENHUMAN_WALLET_RPC_SOLANA"),
- WalletChain::Tron => env_or_source("OPENHUMAN_WALLET_RPC_TRON"),
- }
-}
-
-fn env_or_source(env_var: &str) -> RpcSource {
- let raw = std::env::var(env_var).unwrap_or_default();
- if raw.trim().is_empty() {
- RpcSource::Default
- } else {
- RpcSource::EnvOverride
- }
-}
-
-pub fn explorer_tx_url(chain: WalletChain, tx_hash: &str) -> Option<String> {
- let base = match chain {
- WalletChain::Evm => EvmNetwork::EthereumMainnet.explorer_tx_base(),
- WalletChain::Btc => BLOCKSTREAM_TX_BASE,
- WalletChain::Solana => SOLSCAN_TX_BASE,
- WalletChain::Tron => TRONSCAN_TX_BASE,
- };
- Some(format!("{base}{tx_hash}"))
-}
-
-pub fn explorer_tx_url_for_evm_network(network: EvmNetwork, tx_hash: &str) -> Option<String> {
- Some(format!("{}{}", network.explorer_tx_base(), tx_hash))
-}
-
-pub fn env_var_for_chain(chain: WalletChain) -> &'static str {
- match chain {
- WalletChain::Evm => "OPENHUMAN_WALLET_RPC_EVM",
- WalletChain::Btc => "OPENHUMAN_WALLET_RPC_BTC",
- WalletChain::Solana => "OPENHUMAN_WALLET_RPC_SOLANA",
- WalletChain::Tron => "OPENHUMAN_WALLET_RPC_TRON",
- }
-}
-
-pub fn asset_catalog(chain: WalletChain) -> Vec<WalletAssetDefinition> {
- match chain {
- WalletChain::Evm => evm_asset_catalog(EvmNetwork::EthereumMainnet),
- WalletChain::Btc => vec![WalletAssetDefinition {
- chain,
- evm_network: None,
- symbol: "BTC".to_string(),
- name: "Bitcoin".to_string(),
- native: true,
- decimals: 8,
- contract_address: None,
- }],
- WalletChain::Solana => vec![
- WalletAssetDefinition {
- chain,
- evm_network: None,
- symbol: "SOL".to_string(),
- name: "Solana".to_string(),
- native: true,
- decimals: 9,
- contract_address: None,
- },
- WalletAssetDefinition {
- chain,
- evm_network: None,
- symbol: "USDC".to_string(),
- name: "USD Coin (Solana)".to_string(),
- native: false,
- decimals: 6,
- contract_address: Some(solana_cluster().usdc_mint().to_string()),
- },
- ],
- WalletChain::Tron => vec![
- WalletAssetDefinition {
- chain,
- evm_network: None,
- symbol: "TRX".to_string(),
- name: "Tron".to_string(),
- native: true,
- decimals: 6,
- contract_address: None,
- },
- WalletAssetDefinition {
- chain,
- evm_network: None,
- symbol: "USDT".to_string(),
- name: "Tether USD (TRC20)".to_string(),
- native: false,
- decimals: 6,
- contract_address: Some("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t".to_string()),
- },
- ],
- }
-}
-
-pub fn evm_asset_catalog(network: EvmNetwork) -> Vec<WalletAssetDefinition> {
- let (native_symbol, native_name) = match network {
- EvmNetwork::PolygonMainnet => ("POL", "Polygon"),
- EvmNetwork::BscMainnet => ("BNB", "BNB"),
- _ => ("ETH", "Ether"),
- };
- let mut assets = vec![WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: native_symbol.to_string(),
- name: native_name.to_string(),
- native: true,
- decimals: 18,
- contract_address: None,
- }];
- // Per-L2 USDC native addresses. BSC is handled below (18-decimal tokens).
- if let Some(usdc) = match network {
- EvmNetwork::EthereumMainnet => Some("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
- EvmNetwork::BaseMainnet => Some("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"),
- EvmNetwork::ArbitrumOne => Some("0xaf88d065e77c8cC2239327C5EDb3A432268e5831"),
- EvmNetwork::OptimismMainnet => Some("0x0b2C639c533813f4Aa9D7837CAf62653d097Ff85"),
- EvmNetwork::PolygonMainnet => Some("0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359"),
- EvmNetwork::BscMainnet => None,
- } {
- assets.push(WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "USDC".to_string(),
- name: "USD Coin".to_string(),
- native: false,
- decimals: 6,
- contract_address: Some(usdc.to_string()),
- });
- }
- // BNB Chain BEP20 stablecoins use 18 decimals (unlike the 6-decimal USDC on
- // other EVM chains), so they are catalogued separately.
- if matches!(network, EvmNetwork::BscMainnet) {
- assets.extend([
- WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "USDT".to_string(),
- name: "Tether USD (BEP20)".to_string(),
- native: false,
- decimals: 18,
- contract_address: Some("0x55d398326f99059fF775485246999027B3197955".to_string()),
- },
- WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "USDC".to_string(),
- name: "USD Coin (BEP20)".to_string(),
- native: false,
- decimals: 18,
- contract_address: Some("0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d".to_string()),
- },
- ]);
- }
- if matches!(network, EvmNetwork::EthereumMainnet) {
- assets.extend([
- WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "USDT".to_string(),
- name: "Tether USD".to_string(),
- native: false,
- decimals: 6,
- contract_address: Some("0xdAC17F958D2ee523a2206206994597C13D831ec7".to_string()),
- },
- WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "DAI".to_string(),
- name: "Dai".to_string(),
- native: false,
- decimals: 18,
- contract_address: Some("0x6B175474E89094C44Da98b954EedeAC495271d0F".to_string()),
- },
- WalletAssetDefinition {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- symbol: "WETH".to_string(),
- name: "Wrapped Ether".to_string(),
- native: false,
- decimals: 18,
- contract_address: Some("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2".to_string()),
- },
- ]);
- }
- assets
-}
-
-pub fn network_defaults() -> Vec<WalletNetworkDefaults> {
- let mut out = Vec::new();
- for network in EvmNetwork::ALL {
- out.push(WalletNetworkDefaults {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- network: network.network_label().to_string(),
- chain_id: Some(network.chain_id()),
- rpc_url: network.rpc_url(),
- rpc_source: network.rpc_source(),
- explorer_tx_url_base: network.explorer_tx_base().to_string(),
- supports_broadcast: true,
- supports_token_transfers: true,
- supports_contract_calls: true,
- assets: evm_asset_catalog(network),
- });
- }
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- out.push(WalletNetworkDefaults {
- chain,
- evm_network: None,
- network: match chain {
- WalletChain::Btc => "bitcoin-mainnet".to_string(),
- WalletChain::Solana => "solana-mainnet-beta".to_string(),
- WalletChain::Tron => "tron-mainnet".to_string(),
- WalletChain::Evm => unreachable!(),
- },
- chain_id: None,
- rpc_url: rpc_url_for_chain(chain),
- rpc_source: rpc_source_for_chain(chain),
- explorer_tx_url_base: match chain {
- WalletChain::Btc => BLOCKSTREAM_TX_BASE,
- WalletChain::Solana => SOLSCAN_TX_BASE,
- WalletChain::Tron => TRONSCAN_TX_BASE,
- WalletChain::Evm => unreachable!(),
- }
- .to_string(),
- supports_broadcast: true,
- supports_token_transfers: !matches!(chain, WalletChain::Btc),
- supports_contract_calls: false,
- assets: asset_catalog(chain),
- });
- }
- out
-}
-
-pub fn find_asset(chain: WalletChain, symbol: &str) -> Option<WalletAssetDefinition> {
- find_asset_for_network(chain, None, symbol)
-}
-
-pub fn find_asset_for_network(
- chain: WalletChain,
- network: Option<EvmNetwork>,
- symbol: &str,
-) -> Option<WalletAssetDefinition> {
- let needle = symbol.trim();
- let catalog = match (chain, network) {
- (WalletChain::Evm, Some(net)) => evm_asset_catalog(net),
- (WalletChain::Evm, None) => evm_asset_catalog(EvmNetwork::EthereumMainnet),
- (other, _) => asset_catalog(other),
- };
- catalog
- .into_iter()
- .find(|asset| asset.symbol.eq_ignore_ascii_case(needle))
-}
-
-#[cfg(test)]
-#[path = "defaults_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/defaults_tests.rs b/crates/openhuman-core/src/web3/wallet/defaults_tests.rs
deleted file mode 100644
index d67bb8c3a0..0000000000
--- a/crates/openhuman-core/src/web3/wallet/defaults_tests.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-use super::*;
-
-#[test]
-fn asset_catalog_includes_default_erc20s() {
- let evm = asset_catalog(WalletChain::Evm);
- assert!(evm.iter().any(|asset| asset.symbol == "USDC"));
- assert!(evm
- .iter()
- .any(|asset| asset.symbol == "ETH" && asset.native));
-}
-
-#[test]
-fn base_network_resolves_chain_id_8453() {
- assert_eq!(EvmNetwork::BaseMainnet.chain_id(), 8453);
- let catalog = evm_asset_catalog(EvmNetwork::BaseMainnet);
- let usdc = catalog
- .iter()
- .find(|asset| asset.symbol == "USDC")
- .expect("Base USDC present");
- assert_eq!(
- usdc.contract_address.as_deref(),
- Some("0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
- );
-}
-
-#[test]
-fn network_defaults_lists_all_evm_networks_and_three_other_chains() {
- let defaults = network_defaults();
- let evm_count = defaults
- .iter()
- .filter(|d| d.chain == WalletChain::Evm)
- .count();
- assert_eq!(evm_count, EvmNetwork::ALL.len());
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- assert!(
- defaults.iter().any(|d| d.chain == chain),
- "missing default entry for {chain:?}"
- );
- }
-}
-
-#[test]
-fn find_asset_for_network_finds_base_usdc() {
- let usdc = find_asset_for_network(WalletChain::Evm, Some(EvmNetwork::BaseMainnet), "usdc")
- .expect("base usdc lookup");
- assert_eq!(usdc.decimals, 6);
- assert_eq!(usdc.evm_network, Some(EvmNetwork::BaseMainnet));
-}
-
-// ── Solana cluster (devnet) ───────────────────────────────────────────────
-//
-// `OPENHUMAN_SOLANA_CLUSTER` is process-global env. Serialise these so they
-// don't race each other (or other env-reading tests) and always restore the
-// prior value afterwards.
-static CLUSTER_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
-
-fn with_cluster_env<T>(value: Option<&str>, f: impl FnOnce() -> T) -> T {
- let _guard = CLUSTER_ENV_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let prev = std::env::var("OPENHUMAN_SOLANA_CLUSTER").ok();
- match value {
- Some(v) => std::env::set_var("OPENHUMAN_SOLANA_CLUSTER", v),
- None => std::env::remove_var("OPENHUMAN_SOLANA_CLUSTER"),
- }
- let out = f();
- match prev {
- Some(v) => std::env::set_var("OPENHUMAN_SOLANA_CLUSTER", v),
- None => std::env::remove_var("OPENHUMAN_SOLANA_CLUSTER"),
- }
- out
-}
-
-#[test]
-fn solana_cluster_defaults_to_mainnet() {
- with_cluster_env(None, || {
- assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
- assert_eq!(solana_cluster().rpc_url(), DEFAULT_SOLANA_RPC_URL);
- assert_eq!(default_rpc_url(WalletChain::Solana), DEFAULT_SOLANA_RPC_URL);
- let usdc = find_asset(WalletChain::Solana, "USDC").expect("solana usdc present");
- assert_eq!(
- usdc.contract_address.as_deref(),
- Some(SOLANA_USDC_MINT_MAINNET)
- );
- });
-}
-
-#[test]
-fn devnet_cluster_uses_devnet_rpc_and_mint() {
- // Case-insensitive parse.
- with_cluster_env(Some("DevNet"), || {
- assert_eq!(solana_cluster(), SolanaCluster::Devnet);
- assert_eq!(solana_cluster().rpc_url(), DEVNET_SOLANA_RPC_URL);
- assert_eq!(default_rpc_url(WalletChain::Solana), DEVNET_SOLANA_RPC_URL);
- let usdc = find_asset(WalletChain::Solana, "USDC").expect("solana usdc present");
- assert_eq!(
- usdc.contract_address.as_deref(),
- Some(SOLANA_USDC_MINT_DEVNET)
- );
- assert_eq!(usdc.decimals, 6);
- });
-}
-
-#[test]
-fn unknown_cluster_value_falls_back_to_mainnet() {
- with_cluster_env(Some("testnet"), || {
- assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
- });
-}
diff --git a/crates/openhuman-core/src/web3/wallet/endpoints.rs b/crates/openhuman-core/src/web3/wallet/endpoints.rs
new file mode 100644
index 0000000000..72981f0496
--- /dev/null
+++ b/crates/openhuman-core/src/web3/wallet/endpoints.rs
@@ -0,0 +1,126 @@
+//! Endpoint and cluster resolution for the wallet: the `OPENHUMAN_WALLET_RPC_*`
+//! and `OPENHUMAN_SOLANA_CLUSTER` environment handling.
+//!
+//! The static half (default URLs, the Solana cluster's RPC and USDC mint) lives
+//! in `tinywallet_web3::crypto::defaults`; what stays here is the part that
+//! depends on this deployment's environment. [`HostEndpoints`] is the
+//! `RpcEndpoints` seam the engine asks, and the free functions are what the
+//! host [`Transport`](super::transport) and the x402 helpers resolve through.
+
+use tinywallet_web3::crypto::defaults::{default_rpc_url, EvmNetwork, RpcSource, SolanaCluster};
+use tinywallet_web3::crypto::seams::RpcEndpoints;
+
+use super::ops::WalletChain;
+
+/// The `OPENHUMAN_WALLET_RPC_<NAME>` variable that overrides `network`.
+pub(crate) fn evm_rpc_env_var(network: EvmNetwork) -> &'static str {
+ match network {
+ EvmNetwork::EthereumMainnet => "OPENHUMAN_WALLET_RPC_EVM",
+ EvmNetwork::BaseMainnet => "OPENHUMAN_WALLET_RPC_BASE",
+ EvmNetwork::ArbitrumOne => "OPENHUMAN_WALLET_RPC_ARBITRUM",
+ EvmNetwork::OptimismMainnet => "OPENHUMAN_WALLET_RPC_OPTIMISM",
+ EvmNetwork::PolygonMainnet => "OPENHUMAN_WALLET_RPC_POLYGON",
+ EvmNetwork::BscMainnet => "OPENHUMAN_WALLET_RPC_BSC",
+ }
+}
+
+/// The `OPENHUMAN_WALLET_RPC_<NAME>` variable that overrides `chain`'s
+/// endpoint (Ethereum mainnet's, for EVM).
+pub(crate) fn env_var_for_chain(chain: WalletChain) -> &'static str {
+ match chain {
+ WalletChain::Evm => evm_rpc_env_var(EvmNetwork::EthereumMainnet),
+ WalletChain::Btc => "OPENHUMAN_WALLET_RPC_BTC",
+ WalletChain::Solana => "OPENHUMAN_WALLET_RPC_SOLANA",
+ WalletChain::Tron => "OPENHUMAN_WALLET_RPC_TRON",
+ }
+}
+
+/// Trimmed value of `env_var`, or `None` when unset or blank.
+fn env_nonempty(env_var: &str) -> Option<String> {
+ std::env::var(env_var)
+ .ok()
+ .map(|value| value.trim().to_string())
+ .filter(|value| !value.is_empty())
+}
+
+/// Resolve the configured Solana cluster from `OPENHUMAN_SOLANA_CLUSTER`
+/// (case-insensitive `devnet` selects [`SolanaCluster::Devnet`]; anything else
+/// or unset selects [`SolanaCluster::Mainnet`], preserving the default).
+pub fn solana_cluster() -> SolanaCluster {
+ let configured = env_nonempty("OPENHUMAN_SOLANA_CLUSTER").map(|v| v.to_ascii_lowercase());
+ match configured.as_deref() {
+ Some("devnet") => {
+ log::debug!("[wallet] Solana cluster = devnet (via OPENHUMAN_SOLANA_CLUSTER)");
+ SolanaCluster::Devnet
+ }
+ _ => SolanaCluster::Mainnet,
+ }
+}
+
+/// The endpoint serving `network`: its env override, else the built-in default.
+pub(crate) fn rpc_url_for_evm_network(network: EvmNetwork) -> String {
+ env_nonempty(evm_rpc_env_var(network)).unwrap_or_else(|| network.default_rpc_url().to_string())
+}
+
+/// Whether `network`'s endpoint is a default or an env override.
+pub(crate) fn rpc_source_for_evm_network(network: EvmNetwork) -> RpcSource {
+ if env_nonempty(evm_rpc_env_var(network)).is_some() {
+ RpcSource::EnvOverride
+ } else {
+ RpcSource::Default
+ }
+}
+
+/// The endpoint serving `chain` (Ethereum mainnet's for EVM): its env override,
+/// else the built-in default (which follows the Solana cluster for Solana).
+pub(crate) fn rpc_url_for_chain(chain: WalletChain) -> String {
+ match chain {
+ WalletChain::Evm => rpc_url_for_evm_network(EvmNetwork::EthereumMainnet),
+ other => env_nonempty(env_var_for_chain(other))
+ .unwrap_or_else(|| default_rpc_url(other, solana_cluster()).to_string()),
+ }
+}
+
+/// Whether `chain`'s endpoint is a default or an env override.
+pub(crate) fn rpc_source_for_chain(chain: WalletChain) -> RpcSource {
+ match chain {
+ WalletChain::Evm => rpc_source_for_evm_network(EvmNetwork::EthereumMainnet),
+ other => {
+ if env_nonempty(env_var_for_chain(other)).is_some() {
+ RpcSource::EnvOverride
+ } else {
+ RpcSource::Default
+ }
+ }
+ }
+}
+
+/// The host's [`RpcEndpoints`]: environment overrides over the built-in
+/// defaults, resolved on every call so an override applied mid-process (as the
+/// e2e harness does) is picked up without rebuilding the engine.
+#[derive(Debug, Clone, Copy, Default)]
+pub struct HostEndpoints;
+
+impl RpcEndpoints for HostEndpoints {
+ fn url(&self, chain: WalletChain, network: Option<EvmNetwork>) -> String {
+ match (chain, network) {
+ (WalletChain::Evm, Some(network)) => rpc_url_for_evm_network(network),
+ (chain, _) => rpc_url_for_chain(chain),
+ }
+ }
+
+ fn source(&self, chain: WalletChain, network: Option<EvmNetwork>) -> RpcSource {
+ match (chain, network) {
+ (WalletChain::Evm, Some(network)) => rpc_source_for_evm_network(network),
+ (chain, _) => rpc_source_for_chain(chain),
+ }
+ }
+
+ fn solana_cluster(&self) -> SolanaCluster {
+ solana_cluster()
+ }
+}
+
+#[cfg(test)]
+#[path = "endpoints_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs b/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs
new file mode 100644
index 0000000000..1467c783ff
--- /dev/null
+++ b/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs
@@ -0,0 +1,151 @@
+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(());
+
+fn with_env<T>(pairs: &[(&str, Option<&str>)], f: impl FnOnce() -> T) -> T {
+ let _guard = ENDPOINT_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ let previous: Vec<_> = pairs
+ .iter()
+ .map(|(name, _)| (*name, std::env::var(name).ok()))
+ .collect();
+ for (name, value) in pairs {
+ match value {
+ Some(v) => std::env::set_var(name, v),
+ None => std::env::remove_var(name),
+ }
+ }
+ let out = f();
+ for (name, value) in previous {
+ match value {
+ Some(v) => std::env::set_var(name, v),
+ None => std::env::remove_var(name),
+ }
+ }
+ out
+}
+
+#[test]
+fn solana_cluster_defaults_to_mainnet() {
+ with_env(&[("OPENHUMAN_SOLANA_CLUSTER", None)], || {
+ assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
+ assert_eq!(
+ rpc_url_for_chain(WalletChain::Solana),
+ SolanaCluster::Mainnet.rpc_url()
+ );
+ });
+}
+
+#[test]
+fn devnet_cluster_is_case_insensitive_and_moves_the_default_endpoint() {
+ with_env(
+ &[
+ ("OPENHUMAN_SOLANA_CLUSTER", Some(" DevNet ")),
+ ("OPENHUMAN_WALLET_RPC_SOLANA", None),
+ ],
+ || {
+ assert_eq!(solana_cluster(), SolanaCluster::Devnet);
+ assert_eq!(
+ rpc_url_for_chain(WalletChain::Solana),
+ SolanaCluster::Devnet.rpc_url()
+ );
+ assert_eq!(HostEndpoints.solana_cluster(), SolanaCluster::Devnet);
+ },
+ );
+}
+
+#[test]
+fn an_unknown_cluster_value_falls_back_to_mainnet() {
+ with_env(&[("OPENHUMAN_SOLANA_CLUSTER", Some("testnet"))], || {
+ assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
+ });
+}
+
+#[test]
+fn an_env_override_wins_and_is_reported_as_one() {
+ with_env(
+ &[
+ ("OPENHUMAN_WALLET_RPC_BTC", Some(" http://btc.test/api ")),
+ ("OPENHUMAN_WALLET_RPC_BASE", Some("http://base.test")),
+ ("OPENHUMAN_WALLET_RPC_TRON", Some(" ")),
+ ],
+ || {
+ assert_eq!(rpc_url_for_chain(WalletChain::Btc), "http://btc.test/api");
+ assert_eq!(
+ rpc_source_for_chain(WalletChain::Btc),
+ RpcSource::EnvOverride
+ );
+ assert_eq!(
+ rpc_url_for_evm_network(EvmNetwork::BaseMainnet),
+ "http://base.test"
+ );
+ assert_eq!(
+ rpc_source_for_evm_network(EvmNetwork::BaseMainnet),
+ RpcSource::EnvOverride
+ );
+ // A blank override is no override.
+ assert_eq!(rpc_source_for_chain(WalletChain::Tron), RpcSource::Default);
+ assert_eq!(
+ rpc_url_for_chain(WalletChain::Tron),
+ default_rpc_url(WalletChain::Tron, SolanaCluster::Mainnet)
+ );
+ },
+ );
+}
+
+#[test]
+fn the_seam_resolves_an_evm_network_or_the_chain() {
+ with_env(
+ &[
+ ("OPENHUMAN_WALLET_RPC_EVM", None),
+ ("OPENHUMAN_WALLET_RPC_ARBITRUM", Some("http://arb.test")),
+ ],
+ || {
+ let endpoints = HostEndpoints;
+ assert_eq!(
+ endpoints.url(WalletChain::Evm, Some(EvmNetwork::ArbitrumOne)),
+ "http://arb.test"
+ );
+ assert_eq!(
+ endpoints.source(WalletChain::Evm, Some(EvmNetwork::ArbitrumOne)),
+ RpcSource::EnvOverride
+ );
+ // No network means Ethereum mainnet.
+ assert_eq!(
+ endpoints.url(WalletChain::Evm, None),
+ EvmNetwork::EthereumMainnet.default_rpc_url()
+ );
+ assert_eq!(endpoints.source(WalletChain::Evm, None), RpcSource::Default);
+ assert_eq!(
+ endpoints.url(WalletChain::Btc, None),
+ rpc_url_for_chain(WalletChain::Btc)
+ );
+ assert_eq!(
+ endpoints.source(WalletChain::Btc, None),
+ rpc_source_for_chain(WalletChain::Btc)
+ );
+ },
+ );
+}
+
+#[test]
+fn every_chain_and_network_has_its_own_env_var() {
+ let mut names: Vec<&str> = EvmNetwork::ALL
+ .iter()
+ .map(|n| evm_rpc_env_var(*n))
+ .collect();
+ for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
+ names.push(env_var_for_chain(chain));
+ }
+ let count = names.len();
+ names.sort_unstable();
+ names.dedup();
+ assert_eq!(names.len(), count, "no two endpoints share an override");
+ assert_eq!(
+ env_var_for_chain(WalletChain::Evm),
+ "OPENHUMAN_WALLET_RPC_EVM"
+ );
+}
diff --git a/crates/openhuman-core/src/web3/wallet/execution.rs b/crates/openhuman-core/src/web3/wallet/execution.rs
index 3f1d274dc6..925c1f0ee6 100644
--- a/crates/openhuman-core/src/web3/wallet/execution.rs
+++ b/crates/openhuman-core/src/web3/wallet/execution.rs
@@ -1,67 +1,114 @@
-//! Wallet execution surface — read tools (balances / supported assets /
-//! network defaults / chain status) and write tools (prepare-then-execute)
-//! for native sends, token transfers, swaps, and contract calls.
+//! Host adapters over the wallet engine: the read and write operations wrapped
+//! in the controller contract's [`Outcome`].
//!
-//! Execution is intentionally narrower than the metadata surface:
-//! - Every write must be prepared first, then explicitly confirmed.
-//! - Secret material stays encrypted at rest in core-owned storage.
-//! - EVM (Ethereum + Base/Arbitrum/Optimism/Polygon L2s), Bitcoin (P2WPKH),
-//! Solana (native + SPL), and Tron (native + TRC20) all sign and broadcast.
-//! Swap broadcast is still quote-only on every chain.
-//!
-//! ## Module layout
-//!
-//! - [`types`] — wire types: chain/asset/balance snapshots, the quote
-//! lifecycle, transaction lookups, and RPC param shapes.
-//! - [`quotes`] — the prepare→execute quote store and its chat-thread
-//! ownership check.
-//! - [`validate`] — address/amount/calldata validation, formatting, and hex
-//! conversions.
-//! - [`accounts`] — resolving a derived wallet account for a chain.
-//! - [`queries`] — the read-only surface: defaults, supported assets, chain
-//! status, balances.
-//! - [`transfer`] — preparing a transfer quote.
-//! - [`tx_lookup`] — transaction status / receipt / raw lookup.
-//! - [`broadcast`] — signing, broadcasting, and `execute_prepared`.
+//! The logic (balances, transfers, lookups, the quote store) lives in
+//! `tinywallet_web3::crypto`. What this file adds is the `Outcome` envelope and
+//! its log lines, and the engine the operations run on
+//! ([`crate::web3::seams::engine`]).
-mod accounts;
-mod broadcast;
-mod queries;
-mod quotes;
-mod transfer;
-mod tx_lookup;
-mod types;
-mod validate;
+use crate::core::Outcome;
+use crate::web3::seams::engine;
-pub(crate) use accounts::require_evm_account;
-pub use broadcast::execute_prepared;
-pub(crate) use broadcast::{sign_and_broadcast_evm, sign_and_broadcast_solana};
-pub use queries::{balances, chain_status, network_defaults, supported_assets};
-pub use quotes::prepared_quotes_for_test;
-#[cfg(test)]
-pub(crate) use quotes::{insert_quote_for_test, now_ms, reset_quote_store_for_tests};
-pub use transfer::prepare_transfer;
-pub use tx_lookup::{lookup_tx, tx_receipt, tx_status};
-pub(crate) use types::RawBroadcastResult;
-pub use types::{
+pub use tinywallet_web3::crypto::execution::{
BalanceInfo, ChainStatus, ExecutePreparedParams, ExecutionResult, PrepareTransferParams,
PreparedKind, PreparedStatus, PreparedTransaction, ProviderStatus, SupportedAsset,
TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,
};
-#[cfg(test)]
-pub(crate) use validate::compressed_public_key;
-pub(crate) use validate::validate_calldata;
-pub use validate::{hex_to_u128, u128_to_hex};
-#[cfg(test)]
-use parking_lot::Mutex;
-#[cfg(test)]
-use quotes::{next_quote_id, store_quote, take_quote_for};
-#[cfg(test)]
-use validate::estimated_fee_raw;
+use tinywallet_web3::crypto::defaults::{EvmNetwork, WalletNetworkDefaults};
+
+use super::ops::WalletChain;
+
+/// Default row for every supported network, with the host's endpoints.
+pub async fn network_defaults() -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {
+ Ok(Outcome::new(
+ engine().network_defaults(),
+ vec!["wallet network defaults listed".to_string()],
+ ))
+}
+
+/// Every asset the wallet catalogues.
+pub async fn supported_assets() -> Result<Outcome<Vec<SupportedAsset>>, String> {
+ Ok(Outcome::new(
+ engine().supported_assets(),
+ vec!["wallet supported_assets listed".to_string()],
+ ))
+}
+
+/// Which chains have an account and a provider.
+pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {
+ Ok(Outcome::new(
+ engine().chain_status().await?,
+ vec!["wallet chain_status listed".to_string()],
+ ))
+}
+
+/// Live native balances.
+pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {
+ Ok(Outcome::new(
+ engine().balances().await?,
+ vec!["wallet balances listed".to_string()],
+ ))
+}
+
+/// Validate a transfer and store a quote for it.
+pub async fn prepare_transfer(
+ params: PrepareTransferParams,
+) -> Result<Outcome<PreparedTransaction>, String> {
+ Ok(Outcome::new(
+ engine().prepare_transfer(params).await?,
+ vec!["wallet transfer prepared".to_string()],
+ ))
+}
+
+/// Confirm and execute a prepared transfer.
+pub async fn execute_prepared(
+ params: ExecutePreparedParams,
+) -> Result<Outcome<ExecutionResult>, String> {
+ Ok(Outcome::new(
+ engine().execute_prepared(params).await?,
+ vec!["wallet transaction broadcast".to_string()],
+ ))
+}
+
+/// Check the on-chain lifecycle state of a broadcast transaction.
+pub async fn tx_status(
+ chain: WalletChain,
+ evm_network: Option<EvmNetwork>,
+ hash: &str,
+) -> Result<Outcome<TxStatusInfo>, String> {
+ Ok(Outcome::new(
+ engine().tx_status(chain, evm_network, hash).await?,
+ vec!["wallet tx status fetched".to_string()],
+ ))
+}
+
+/// Fetch the receipt of a broadcast transaction.
+pub async fn tx_receipt(
+ chain: WalletChain,
+ evm_network: Option<EvmNetwork>,
+ hash: &str,
+) -> Result<Outcome<TxReceiptInfo>, String> {
+ Ok(Outcome::new(
+ engine().tx_receipt(chain, evm_network, hash).await?,
+ vec!["wallet tx receipt fetched".to_string()],
+ ))
+}
-const LOG_PREFIX: &str = "[wallet]";
+/// Look up the raw transaction payload by hash.
+pub async fn lookup_tx(
+ chain: WalletChain,
+ evm_network: Option<EvmNetwork>,
+ hash: &str,
+) -> Result<Outcome<TxLookupInfo>, String> {
+ Ok(Outcome::new(
+ engine().lookup_tx(chain, evm_network, hash).await?,
+ vec!["wallet tx looked up".to_string()],
+ ))
+}
-#[cfg(test)]
-#[path = "execution_tests.rs"]
-mod tests;
+/// The quotes that can still be executed. Test support and the introspection
+/// harness read the engine's store through this.
+pub fn prepared_quotes_for_test() -> Vec<PreparedTransaction> {
+ engine().prepared_quotes()
+}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/accounts.rs b/crates/openhuman-core/src/web3/wallet/execution/accounts.rs
deleted file mode 100644
index 2c436aae95..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/accounts.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-//! Resolving a derived wallet account for a chain, erroring cleanly when the
-//! wallet has not been configured yet.
-
-use super::super::ops::{
- status as wallet_status, WalletAccount, WalletChain, WALLET_NOT_CONFIGURED_MESSAGE,
-};
-use super::validate::chain_str;
-
-/// Resolve the derived EVM account address, erroring if the wallet is not
-/// configured. Used by the `web3` signing primitives that operate on the
-/// single shared EVM address.
-pub(crate) async fn require_evm_account() -> Result<String, String> {
- Ok(require_account(WalletChain::Evm).await?.address)
-}
-
-pub(super) async fn require_account(chain: WalletChain) -> Result<WalletAccount, String> {
- let status = wallet_status().await?.value;
- if !status.configured {
- return Err(WALLET_NOT_CONFIGURED_MESSAGE.to_string());
- }
- status
- .accounts
- .into_iter()
- .find(|account| account.chain == chain)
- .ok_or_else(|| format!("no wallet account derived for chain '{}'", chain_str(chain)))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/broadcast.rs b/crates/openhuman-core/src/web3/wallet/execution/broadcast.rs
deleted file mode 100644
index 4bf6038f44..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/broadcast.rs
+++ /dev/null
@@ -1,91 +0,0 @@
-//! Signing and broadcasting: the crate-internal raw primitives the `web3`
-//! layer uses for externally-built transactions, and `execute_prepared`,
-//! which atomically consumes a quote and dispatches it to the right chain.
-
-use log::warn;
-
-use crate::core::Outcome;
-
-use super::super::chains::{
- btc as chain_btc, evm as chain_evm, solana as chain_sol, tron as chain_tron,
-};
-use super::super::defaults::{explorer_tx_url, EvmNetwork};
-use super::super::ops::WalletChain;
-use super::quotes::{current_owner, now_ms, store_quote, take_quote_for, QUOTE_TTL_MS};
-use super::types::{ExecutePreparedParams, ExecutionResult, RawBroadcastResult};
-use super::validate::chain_str;
-use super::LOG_PREFIX;
-
-/// Crate-internal: sign+broadcast an externally-built unsigned EVM transaction
-/// (deBridge swap/bridge or generic dapp calldata). See [`chain_evm::sign_and_broadcast_evm`].
-pub(crate) async fn sign_and_broadcast_evm(
- network: EvmNetwork,
- to: &str,
- data_hex: Option<String>,
- value_raw: &str,
-) -> Result<RawBroadcastResult, String> {
- chain_evm::sign_and_broadcast_evm(network, to, data_hex, value_raw).await
-}
-
-/// Crate-internal: sign+broadcast an externally-built hex `VersionedTransaction`
-/// (deBridge Solana swap/bridge). See [`chain_sol::sign_and_broadcast_versioned`].
-pub(crate) async fn sign_and_broadcast_solana(
- tx_blob_hex: &str,
-) -> Result<RawBroadcastResult, String> {
- chain_sol::sign_and_broadcast_versioned(tx_blob_hex).await
-}
-
-pub async fn execute_prepared(
- params: ExecutePreparedParams,
-) -> Result<Outcome<ExecutionResult>, String> {
- if !params.confirmed {
- return Err("execute_prepared requires `confirmed: true`".to_string());
- }
- // Bind execute to the chat-thread that prepared the quote.
- // `current_owner()` returns the caller's `APPROVAL_CHAT_CONTEXT` (or `None`
- // for non-chat callers). `take_quote_for` enforces equality with the
- // prepare-time owner and returns the same "not found" error on mismatch
- // — leaked `quote_id`s in a shared channel cannot be hijacked from a
- // different agent session.
- let caller = current_owner();
- // Atomically remove the quote *before* broadcasting so two concurrent
- // confirmations can't both pass get_quote() and double-submit. If signing
- // or broadcast fails we restore the quote to keep it retryable.
- let quote = take_quote_for(&params.quote_id, caller)?;
- let chain = quote.chain;
- let restorable = quote.clone();
- let result = match chain {
- WalletChain::Evm => chain_evm::execute_evm_quote(quote).await,
- WalletChain::Btc => chain_btc::execute_btc_quote(quote).await,
- WalletChain::Solana => chain_sol::execute_solana_quote(quote).await,
- WalletChain::Tron => chain_tron::execute_tron_quote(quote).await,
- };
- let result = match result {
- Ok(value) => value,
- Err(error) => {
- // Restore the quote so the caller can fix the cause and retry.
- // Refresh the TTL window so a slow chain call (network timeouts
- // can chew through the original 5-min budget) doesn't hand back
- // an immediately-expired quote.
- let mut refreshed = restorable;
- let now = now_ms();
- refreshed.expires_at_ms = now + QUOTE_TTL_MS;
- store_quote(refreshed);
- warn!(
- "{LOG_PREFIX} execute chain={} quote_id={} failed (quote restored, ttl refreshed): {error}",
- chain_str(chain),
- params.quote_id
- );
- return Err(error);
- }
- };
- let explorer_fallback = explorer_tx_url(chain, &result.transaction_hash);
- let mut final_result = result;
- if final_result.explorer_url.is_none() {
- final_result.explorer_url = explorer_fallback;
- }
- Ok(Outcome::new(
- final_result,
- vec!["wallet transaction broadcast".to_string()],
- ))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/queries.rs b/crates/openhuman-core/src/web3/wallet/execution/queries.rs
deleted file mode 100644
index 7931cc08dd..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/queries.rs
+++ /dev/null
@@ -1,262 +0,0 @@
-//! Read-only wallet surface: network defaults, the supported-asset catalog,
-//! per-chain provider status, and live balances.
-
-use log::{debug, warn};
-
-use crate::core::Outcome;
-
-use super::super::chains::{
- btc as chain_btc, evm as chain_evm, solana as chain_sol, tron as chain_tron,
-};
-use super::super::defaults::{
- evm_asset_catalog, network_defaults as default_networks, rpc_url_for_chain, EvmNetwork,
- WalletAssetDefinition, WalletNetworkDefaults,
-};
-use super::super::ops::{status as wallet_status, WalletChain, WALLET_NOT_CONFIGURED_MESSAGE};
-use super::types::{BalanceInfo, ChainStatus, ProviderStatus, SupportedAsset};
-use super::validate::{chain_str, format_amount};
-use super::LOG_PREFIX;
-
-pub(super) fn asset_to_supported(asset: WalletAssetDefinition) -> SupportedAsset {
- SupportedAsset {
- chain: asset.chain,
- evm_network: asset.evm_network,
- symbol: asset.symbol,
- name: asset.name,
- native: asset.native,
- decimals: asset.decimals,
- contract_address: asset.contract_address,
- }
-}
-
-pub async fn network_defaults() -> Result<Outcome<Vec<WalletNetworkDefaults>>, String> {
- let rows = default_networks();
- debug!("{LOG_PREFIX} network_defaults count={}", rows.len());
- Ok(Outcome::new(
- rows,
- vec!["wallet network defaults listed".to_string()],
- ))
-}
-
-pub async fn supported_assets() -> Result<Outcome<Vec<SupportedAsset>>, String> {
- let mut assets: Vec<SupportedAsset> = Vec::new();
- for network in EvmNetwork::ALL {
- for asset in evm_asset_catalog(network) {
- assets.push(asset_to_supported(asset));
- }
- }
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- for asset in super::super::defaults::asset_catalog(chain) {
- assets.push(asset_to_supported(asset));
- }
- }
- debug!("{LOG_PREFIX} supported_assets count={}", assets.len());
- Ok(Outcome::new(
- assets,
- vec!["wallet supported_assets listed".to_string()],
- ))
-}
-
-pub async fn chain_status() -> Result<Outcome<Vec<ChainStatus>>, String> {
- let status = wallet_status().await?.value;
- let mut rows = Vec::new();
- for network in EvmNetwork::ALL {
- let has_account = status
- .accounts
- .iter()
- .any(|account| account.chain == WalletChain::Evm);
- rows.push(ChainStatus {
- chain: WalletChain::Evm,
- evm_network: Some(network),
- configured: has_account,
- provider_status: if has_account {
- ProviderStatus::Ready
- } else {
- ProviderStatus::Missing
- },
- rpc_url: network.rpc_url(),
- });
- }
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- let has_account = status.accounts.iter().any(|account| account.chain == chain);
- rows.push(ChainStatus {
- chain,
- evm_network: None,
- configured: has_account,
- provider_status: if has_account {
- ProviderStatus::Ready
- } else {
- ProviderStatus::Missing
- },
- rpc_url: rpc_url_for_chain(chain),
- });
- }
- debug!("{LOG_PREFIX} chain_status reported chains={}", rows.len());
- Ok(Outcome::new(
- rows,
- vec!["wallet chain_status listed".to_string()],
- ))
-}
-
-/// EVM networks surfaced as their own native-balance rows. The single derived
-/// EVM account address is shared across all of them, so `balances()` reads the
-/// native asset (ETH / ETH / BNB) on each network independently.
-pub const EVM_BALANCE_NETWORKS: [EvmNetwork; 3] = [
- EvmNetwork::EthereumMainnet,
- EvmNetwork::BaseMainnet,
- EvmNetwork::BscMainnet,
-];
-
-/// Build a single native-balance row, reading the live on-chain balance and
-/// falling back to a zero/`Missing` row when the provider is unreachable.
-fn balance_row(
- chain: WalletChain,
- evm_network: Option<EvmNetwork>,
- address: &str,
- asset: WalletAssetDefinition,
- raw: String,
- provider_status: ProviderStatus,
-) -> BalanceInfo {
- let raw_u128 = raw.parse::<u128>().unwrap_or(0);
- BalanceInfo {
- chain,
- evm_network,
- address: address.to_string(),
- asset_symbol: asset.symbol,
- decimals: asset.decimals,
- formatted: format_amount(raw_u128, asset.decimals),
- raw,
- provider_status,
- }
-}
-
-fn native_asset_for(chain: WalletChain) -> Result<WalletAssetDefinition, String> {
- super::super::defaults::asset_catalog(chain)
- .into_iter()
- .find(|value| value.native)
- .ok_or_else(|| format!("native asset metadata missing for '{}'", chain_str(chain)))
-}
-
-fn evm_native_asset(network: EvmNetwork) -> Result<WalletAssetDefinition, String> {
- evm_asset_catalog(network)
- .into_iter()
- .find(|value| value.native)
- .ok_or_else(|| {
- format!(
- "native asset metadata missing for evm network '{}'",
- network.as_str()
- )
- })
-}
-
-pub async fn balances() -> Result<Outcome<Vec<BalanceInfo>>, String> {
- let status = wallet_status().await?.value;
- if !status.configured {
- return Err(WALLET_NOT_CONFIGURED_MESSAGE.to_string());
- }
- let mut out = Vec::with_capacity(status.accounts.len() + EVM_BALANCE_NETWORKS.len());
- for account in &status.accounts {
- match account.chain {
- // The EVM account fans out into one native-balance row per displayed
- // network (Ethereum, Base, BNB Chain), all sharing the same address.
- WalletChain::Evm => {
- for network in EVM_BALANCE_NETWORKS {
- let asset = evm_native_asset(network)?;
- let (raw, provider_status) = match chain_evm::evm_balance(
- network,
- &account.address,
- )
- .await
- {
- Ok(balance) => (balance.to_string(), ProviderStatus::Ready),
- Err(error) => {
- warn!(
- "{LOG_PREFIX} balances chain=evm network={} address={} falling back to zero: {error}",
- network.as_str(),
- account.address
- );
- ("0".to_string(), ProviderStatus::Missing)
- }
- };
- out.push(balance_row(
- WalletChain::Evm,
- Some(network),
- &account.address,
- asset,
- raw,
- provider_status,
- ));
- }
- }
- WalletChain::Btc => {
- let (raw, provider_status) = match chain_btc::native_balance(&account.address).await
- {
- Ok(sats) => (sats.to_string(), ProviderStatus::Ready),
- Err(error) => {
- warn!(
- "{LOG_PREFIX} balances chain=btc address={} falling back to zero: {error}",
- account.address
- );
- ("0".to_string(), ProviderStatus::Missing)
- }
- };
- out.push(balance_row(
- WalletChain::Btc,
- None,
- &account.address,
- native_asset_for(WalletChain::Btc)?,
- raw,
- provider_status,
- ));
- }
- WalletChain::Solana => {
- let (raw, provider_status) = match chain_sol::native_balance(&account.address).await
- {
- Ok(lamports) => (lamports.to_string(), ProviderStatus::Ready),
- Err(error) => {
- warn!(
- "{LOG_PREFIX} balances chain=solana address={} falling back to zero: {error}",
- account.address
- );
- ("0".to_string(), ProviderStatus::Missing)
- }
- };
- out.push(balance_row(
- WalletChain::Solana,
- None,
- &account.address,
- native_asset_for(WalletChain::Solana)?,
- raw,
- provider_status,
- ));
- }
- WalletChain::Tron => {
- let (raw, provider_status) = match chain_tron::native_balance(&account.address)
- .await
- {
- Ok(sun) => (sun.to_string(), ProviderStatus::Ready),
- Err(error) => {
- warn!(
- "{LOG_PREFIX} balances chain=tron address={} falling back to zero: {error}",
- account.address
- );
- ("0".to_string(), ProviderStatus::Missing)
- }
- };
- out.push(balance_row(
- WalletChain::Tron,
- None,
- &account.address,
- native_asset_for(WalletChain::Tron)?,
- raw,
- provider_status,
- ));
- }
- }
- }
- debug!("{LOG_PREFIX} balances returned rows={}", out.len());
- Ok(Outcome::new(
- out,
- vec!["wallet balances listed".to_string()],
- ))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/quotes.rs b/crates/openhuman-core/src/web3/wallet/execution/quotes.rs
deleted file mode 100644
index cacffb15b6..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/quotes.rs
+++ /dev/null
@@ -1,150 +0,0 @@
-//! The prepare→execute quote store: a short-lived, capped, in-memory queue
-//! of `PreparedTransaction`s keyed by `quote_id`, plus the chat-thread
-//! ownership check that stops a leaked `quote_id` from being executed by a
-//! different agent session.
-
-use std::sync::atomic::{AtomicU64, Ordering};
-use std::time::{SystemTime, UNIX_EPOCH};
-
-use log::debug;
-use once_cell::sync::Lazy;
-use parking_lot::Mutex;
-
-use super::types::{PreparedStatus, PreparedTransaction, QuoteOwner};
-use super::LOG_PREFIX;
-
-pub(super) const QUOTE_TTL_MS: u64 = 5 * 60 * 1000;
-const QUOTE_STORE_CAP: usize = 64;
-
-static QUOTE_STORE: Lazy<Mutex<Vec<PreparedTransaction>>> = Lazy::new(|| Mutex::new(Vec::new()));
-static QUOTE_COUNTER: AtomicU64 = AtomicU64::new(1);
-
-pub(crate) fn now_ms() -> u64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0)
-}
-
-pub(super) fn next_quote_id() -> String {
- let n = QUOTE_COUNTER.fetch_add(1, Ordering::Relaxed);
- format!("q_{}_{}", now_ms(), n)
-}
-
-/// Read the per-turn chat context that scopes the agent tool loop.
-///
-/// Returns `Some(owner)` when called from inside an interactive chat turn
-/// (the web channel installs `APPROVAL_CHAT_CONTEXT` around `run_chat_task`).
-/// Returns `None` for non-chat callers (CLI, direct JSON-RPC, background
-/// triage / cron / sub-agents) — these keep the pre-binding behavior and
-/// remain executable without an owner gate, since they have no shared
-/// channel from which a `quote_id` could leak.
-///
-// SAFETY: relies on the inline `.await` chain in
-// `web_chat::run_chat_task`. `tokio::task_local!` propagates
-// across `.await` but **not** across `tokio::spawn`. If the chat path ever
-// detaches the tool loop onto a freshly-spawned task without wrapping it in
-// `APPROVAL_CHAT_CONTEXT.scope(...)`, this helper will silently start
-// returning `None` and the owner gate will become a no-op. Keep the
-// prepare/execute calls inline within the scope.
-pub(crate) fn current_owner() -> Option<QuoteOwner> {
- crate::security::approval::APPROVAL_CHAT_CONTEXT
- .try_with(|ctx| QuoteOwner {
- thread_id: ctx.thread_id.clone(),
- client_id: ctx.client_id.clone(),
- })
- .ok()
-}
-
-pub(super) fn store_quote(quote: PreparedTransaction) -> PreparedTransaction {
- let mut store = QUOTE_STORE.lock();
- let cutoff = now_ms();
- store.retain(|q| q.expires_at_ms > cutoff && q.status != PreparedStatus::Consumed);
- if store.len() >= QUOTE_STORE_CAP {
- store.remove(0);
- }
- store.push(quote.clone());
- quote
-}
-
-pub(super) fn get_quote(quote_id: &str) -> Result<PreparedTransaction, String> {
- let store = QUOTE_STORE.lock();
- let now = now_ms();
- let quote = store
- .iter()
- .find(|q| q.quote_id == quote_id)
- .cloned()
- .ok_or_else(|| format!("quote '{quote_id}' not found"))?;
- if quote.status == PreparedStatus::Consumed {
- return Err(format!("quote '{quote_id}' already executed"));
- }
- if quote.expires_at_ms <= now {
- return Err(format!("quote '{quote_id}' expired"));
- }
- Ok(quote)
-}
-
-/// Remove a quote from the store and return it to the caller, if and only if
-/// the caller's chat-thread owner matches the prepare-time owner.
-///
-/// On owner mismatch this returns the **exact same** "quote '…' not found"
-/// error shape that a missing-row lookup would, so cross-thread callers
-/// cannot distinguish "wrong owner" from "no such quote" — i.e. no
-/// enumeration oracle for leaked `quote_id`s.
-///
-/// Callers with no chat context (`caller_owner == None`, e.g. CLI / direct
-/// JSON-RPC / background turns) can only execute quotes that were also
-/// prepared with no chat context. This intentionally prevents privilege-drop
-/// where a background flow could pick up an interactive user's quote.
-pub(super) fn take_quote_for(
- quote_id: &str,
- caller_owner: Option<QuoteOwner>,
-) -> Result<PreparedTransaction, String> {
- let not_found = || format!("quote '{quote_id}' not found");
- let mut store = QUOTE_STORE.lock();
- let now = now_ms();
- let pos = store
- .iter()
- .position(|q| q.quote_id == quote_id)
- .ok_or_else(not_found)?;
- // Owner check happens before status / expiry checks so the error shape on
- // mismatch can be byte-equal to the not-found path. Removing the quote
- // only happens *after* this check passes — a mismatched caller cannot
- // poison the store by consuming someone else's quote.
- if store[pos].owner != caller_owner {
- debug!(
- "{LOG_PREFIX} take_quote_for quote_id={} owner_mismatch (caller_has_ctx={})",
- quote_id,
- caller_owner.is_some()
- );
- return Err(not_found());
- }
- let quote = store.remove(pos);
- if quote.status == PreparedStatus::Consumed {
- return Err(format!("quote '{quote_id}' already executed"));
- }
- if quote.expires_at_ms <= now {
- return Err(format!("quote '{quote_id}' expired"));
- }
- Ok(quote)
-}
-
-pub fn prepared_quotes_for_test() -> Vec<PreparedTransaction> {
- let now = now_ms();
- QUOTE_STORE
- .lock()
- .iter()
- .filter(|q| q.expires_at_ms > now && q.status != PreparedStatus::Consumed)
- .cloned()
- .collect()
-}
-
-#[cfg(test)]
-pub(crate) fn reset_quote_store_for_tests() {
- QUOTE_STORE.lock().clear();
-}
-
-#[cfg(test)]
-pub(crate) fn insert_quote_for_test(quote: PreparedTransaction) -> PreparedTransaction {
- store_quote(quote)
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/transfer.rs b/crates/openhuman-core/src/web3/wallet/execution/transfer.rs
deleted file mode 100644
index 99e04337f0..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/transfer.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-//! Preparing a native/token transfer quote: resolve the network, the asset,
-//! and the source account, then stamp a `PreparedTransaction` the caller
-//! must separately confirm through `execute_prepared`.
-
-use log::debug;
-
-use crate::core::Outcome;
-
-use super::super::defaults::{evm_asset_catalog, find_asset_for_network, EvmNetwork};
-use super::super::ops::WalletChain;
-use super::accounts::require_account;
-use super::quotes::{current_owner, next_quote_id, now_ms, store_quote, QUOTE_TTL_MS};
-use super::types::{PrepareTransferParams, PreparedKind, PreparedStatus, PreparedTransaction};
-use super::validate::{
- chain_str, estimated_fee_raw, format_amount, validate_address, validate_amount,
-};
-use super::LOG_PREFIX;
-
-pub async fn prepare_transfer(
- params: PrepareTransferParams,
-) -> Result<Outcome<PreparedTransaction>, String> {
- let to = validate_address(params.chain, &params.to_address)?;
- let amount = validate_amount(&params.amount_raw)?;
- if amount == 0 {
- return Err("transfer amount must be greater than zero".to_string());
- }
- let network = if params.chain == WalletChain::Evm {
- Some(params.evm_network.unwrap_or(EvmNetwork::EthereumMainnet))
- } else {
- None
- };
- let account = require_account(params.chain).await?;
- let asset = match params.asset_symbol.as_deref().map(str::trim) {
- None | Some("") => {
- // native asset for the chain (or chosen EVM network).
- let catalog = if let Some(net) = network {
- evm_asset_catalog(net)
- } else {
- super::super::defaults::asset_catalog(params.chain)
- };
- catalog
- .into_iter()
- .find(|value| value.native)
- .ok_or_else(|| {
- format!(
- "native asset metadata missing for '{}'",
- chain_str(params.chain)
- )
- })?
- }
- Some(symbol) => find_asset_for_network(params.chain, network, symbol).ok_or_else(|| {
- format!(
- "unsupported asset_symbol '{symbol}' for chain '{}'",
- chain_str(params.chain)
- )
- })?,
- };
- let kind = if asset.native {
- PreparedKind::NativeTransfer
- } else {
- PreparedKind::TokenTransfer
- };
- // BTC has no native token concept; reject TokenTransfer on btc.
- if matches!(params.chain, WalletChain::Btc) && !asset.native {
- return Err("token transfers are not supported on Bitcoin".to_string());
- }
- let now = now_ms();
- let label = if let Some(net) = network {
- format!("{} ({})", chain_str(params.chain), net.network_label())
- } else {
- chain_str(params.chain).to_string()
- };
- let quote = PreparedTransaction {
- quote_id: next_quote_id(),
- kind,
- chain: params.chain,
- evm_network: network,
- from_address: account.address.clone(),
- to_address: to,
- asset_symbol: asset.symbol.clone(),
- amount_raw: amount.to_string(),
- amount_formatted: format_amount(amount, asset.decimals),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: asset.contract_address.clone(),
- estimated_fee_raw: estimated_fee_raw(params.chain, kind),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + QUOTE_TTL_MS,
- notes: vec![format!(
- "Prepared {} transfer on {} using default network settings.",
- asset.symbol, label
- )],
- owner: current_owner(),
- };
- debug!(
- "{LOG_PREFIX} prepare_transfer chain={} kind={:?} quote_id={} amount={} asset={}",
- chain_str(params.chain),
- kind,
- quote.quote_id,
- quote.amount_raw,
- quote.asset_symbol
- );
- Ok(Outcome::new(
- store_quote(quote),
- vec!["wallet transfer prepared".to_string()],
- ))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/tx_lookup.rs b/crates/openhuman-core/src/web3/wallet/execution/tx_lookup.rs
deleted file mode 100644
index a3cdf3e2c4..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/tx_lookup.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-//! Read-only transaction lookups: lifecycle state, receipt, and raw payload,
-//! dispatched to the chain-specific client.
-
-use log::debug;
-
-use crate::core::Outcome;
-
-use super::super::chains::{
- btc as chain_btc, evm as chain_evm, solana as chain_sol, tron as chain_tron,
-};
-use super::super::defaults::EvmNetwork;
-use super::super::ops::WalletChain;
-use super::types::{TxLookupInfo, TxReceiptInfo, TxStatusInfo};
-use super::validate::chain_str;
-use super::LOG_PREFIX;
-
-/// Resolve the EVM network for a tx read, defaulting to Ethereum mainnet.
-fn read_network(chain: WalletChain, evm_network: Option<EvmNetwork>) -> Option<EvmNetwork> {
- if chain == WalletChain::Evm {
- Some(evm_network.unwrap_or(EvmNetwork::EthereumMainnet))
- } else {
- None
- }
-}
-
-/// Check the on-chain lifecycle state of a previously broadcast transaction.
-pub async fn tx_status(
- chain: WalletChain,
- evm_network: Option<EvmNetwork>,
- hash: &str,
-) -> Result<Outcome<TxStatusInfo>, String> {
- let hash = hash.trim();
- if hash.is_empty() {
- return Err("tx hash is empty".to_string());
- }
- let info = match chain {
- WalletChain::Evm => {
- chain_evm::tx_status(read_network(chain, evm_network).unwrap(), hash).await?
- }
- WalletChain::Btc => chain_btc::tx_status(hash).await?,
- WalletChain::Solana => chain_sol::tx_status(hash).await?,
- WalletChain::Tron => chain_tron::tx_status(hash).await?,
- };
- debug!(
- "{LOG_PREFIX} tx_status chain={} hash={} state={:?}",
- chain_str(chain),
- hash,
- info.state
- );
- Ok(Outcome::new(
- info,
- vec!["wallet tx status fetched".to_string()],
- ))
-}
-
-/// Fetch the receipt of a broadcast transaction (success flag, fee, block).
-pub async fn tx_receipt(
- chain: WalletChain,
- evm_network: Option<EvmNetwork>,
- hash: &str,
-) -> Result<Outcome<TxReceiptInfo>, String> {
- let hash = hash.trim();
- if hash.is_empty() {
- return Err("tx hash is empty".to_string());
- }
- let info = match chain {
- WalletChain::Evm => {
- chain_evm::tx_receipt(read_network(chain, evm_network).unwrap(), hash).await?
- }
- WalletChain::Btc => chain_btc::tx_receipt(hash).await?,
- WalletChain::Solana => chain_sol::tx_receipt(hash).await?,
- WalletChain::Tron => chain_tron::tx_receipt(hash).await?,
- };
- debug!(
- "{LOG_PREFIX} tx_receipt chain={} hash={} found={}",
- chain_str(chain),
- hash,
- info.found
- );
- Ok(Outcome::new(
- info,
- vec!["wallet tx receipt fetched".to_string()],
- ))
-}
-
-/// Look up the raw transaction payload by hash.
-pub async fn lookup_tx(
- chain: WalletChain,
- evm_network: Option<EvmNetwork>,
- hash: &str,
-) -> Result<Outcome<TxLookupInfo>, String> {
- let hash = hash.trim();
- if hash.is_empty() {
- return Err("tx hash is empty".to_string());
- }
- let info = match chain {
- WalletChain::Evm => {
- chain_evm::lookup_tx(read_network(chain, evm_network).unwrap(), hash).await?
- }
- WalletChain::Btc => chain_btc::lookup_tx(hash).await?,
- WalletChain::Solana => chain_sol::lookup_tx(hash).await?,
- WalletChain::Tron => chain_tron::lookup_tx(hash).await?,
- };
- debug!(
- "{LOG_PREFIX} lookup_tx chain={} hash={} found={}",
- chain_str(chain),
- hash,
- info.found
- );
- Ok(Outcome::new(info, vec!["wallet tx looked up".to_string()]))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/types.rs b/crates/openhuman-core/src/web3/wallet/execution/types.rs
deleted file mode 100644
index ab24892307..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/types.rs
+++ /dev/null
@@ -1,228 +0,0 @@
-//! Wire types for the wallet execution surface: chain/asset/balance
-//! snapshots, the prepare→execute quote lifecycle, transaction lookups, and
-//! the RPC param shapes.
-
-use serde::{Deserialize, Serialize};
-
-use super::super::defaults::EvmNetwork;
-use super::super::ops::WalletChain;
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ChainStatus {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub configured: bool,
- pub provider_status: ProviderStatus,
- pub rpc_url: String,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum ProviderStatus {
- Ready,
- Missing,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SupportedAsset {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub symbol: String,
- pub name: String,
- pub native: bool,
- pub decimals: u8,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub contract_address: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct BalanceInfo {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub address: String,
- pub asset_symbol: String,
- pub decimals: u8,
- pub raw: String,
- pub formatted: String,
- pub provider_status: ProviderStatus,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum PreparedKind {
- NativeTransfer,
- TokenTransfer,
-}
-
-#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum PreparedStatus {
- AwaitingConfirmation,
- Broadcasted,
- Consumed,
-}
-
-/// Identity of the chat thread that prepared a quote.
-///
-/// The wallet executes prepare/execute as a two-step flow keyed by `quote_id`.
-/// `quote_id`s are visible in the shared chat broadcast (the prepared-tx
-/// summary that gets sent back into the channel), so a co-channel caller can
-/// read another caller's `quote_id` and try to drive its execute from their
-/// own (now per-sender-isolated, post-#2331) agent session. Binding the
-/// quote to the originating chat thread closes that gap: execute is only
-/// allowed when the caller's `current_owner()` equals the prepare-time owner.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub(crate) struct QuoteOwner {
- pub(crate) thread_id: String,
- pub(crate) client_id: String,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PreparedTransaction {
- pub quote_id: String,
- pub kind: PreparedKind,
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub from_address: String,
- pub to_address: String,
- pub asset_symbol: String,
- pub amount_raw: String,
- pub amount_formatted: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub receive_symbol: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub min_receive_raw: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub calldata: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub token_address: Option<String>,
- pub estimated_fee_raw: String,
- pub status: PreparedStatus,
- pub created_at_ms: u64,
- pub expires_at_ms: u64,
- pub notes: Vec<String>,
- /// Chat-thread owner stamped at prepare time. Present when the quote
- /// was prepared from inside an interactive chat turn (web channel sets
- /// `APPROVAL_CHAT_CONTEXT`); `None` for CLI / direct-RPC / background
- /// callers. Internal gate data — never serialized over the wire.
- #[serde(skip_serializing)]
- pub(crate) owner: Option<QuoteOwner>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ExecutionResult {
- pub quote_id: String,
- pub status: PreparedStatus,
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub transaction_hash: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub explorer_url: Option<String>,
- pub transaction: PreparedTransaction,
-}
-
-/// Result of a low-level "sign this unsigned transaction and broadcast it"
-/// primitive. Unlike [`ExecutionResult`], this carries no `PreparedTransaction`
-/// — it is the minimal output the `web3` layer needs after handing the wallet
-/// an externally-built (e.g. deBridge) unsigned transaction to sign+broadcast.
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub(crate) struct RawBroadcastResult {
- pub transaction_hash: String,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub explorer_url: Option<String>,
- /// Simulated fee in the chain's smallest unit. `None` when the fee is not
- /// known at broadcast time (e.g. Solana's dynamic base+priority fee, which
- /// must be read back from the confirmed transaction).
- #[serde(skip_serializing_if = "Option::is_none")]
- pub fee_raw: Option<String>,
-}
-
-/// Normalized lifecycle state of a broadcast transaction.
-#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum TxState {
- /// Seen by the node but not yet included in a block.
- Pending,
- /// Included in a block and succeeded.
- Confirmed,
- /// Included in a block but reverted/failed.
- Failed,
- /// The node has no record of this hash.
- NotFound,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TxStatusInfo {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub hash: String,
- pub state: TxState,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub confirmations: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub block_number: Option<u64>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TxReceiptInfo {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub hash: String,
- pub found: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub success: Option<bool>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub block_number: Option<u64>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub gas_used: Option<String>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub fee_raw: Option<String>,
- /// Raw provider receipt payload, passed through unchanged.
- pub raw: serde_json::Value,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct TxLookupInfo {
- pub chain: WalletChain,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub evm_network: Option<EvmNetwork>,
- pub hash: String,
- pub found: bool,
- /// Raw provider transaction payload, passed through unchanged.
- pub raw: serde_json::Value,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PrepareTransferParams {
- pub chain: WalletChain,
- pub to_address: String,
- pub amount_raw: String,
- #[serde(default)]
- pub asset_symbol: Option<String>,
- #[serde(default)]
- pub evm_network: Option<EvmNetwork>,
-}
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ExecutePreparedParams {
- pub quote_id: String,
- pub confirmed: bool,
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution/validate.rs b/crates/openhuman-core/src/web3/wallet/execution/validate.rs
deleted file mode 100644
index 87d8126ed4..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution/validate.rs
+++ /dev/null
@@ -1,146 +0,0 @@
-//! Address/amount/calldata validation, amount formatting, hex conversions,
-//! and the estimated-fee table used when preparing a quote.
-
-use log::debug;
-
-use super::super::ops::WalletChain;
-use super::types::PreparedKind;
-use super::LOG_PREFIX;
-
-/// Return the compressed SEC1 public key for a secp256k1 secret.
-///
-/// Test-only. Production never holds a secp256k1 secret: the wallet module
-/// derives the key and reports the public half through `DeriveAccount`.
-#[cfg(test)]
-pub(crate) fn compressed_public_key(secret: &[u8]) -> Result<Vec<u8>, String> {
- let key = k256::ecdsa::SigningKey::from_slice(secret)
- .map_err(|_| "derived key is not a valid secp256k1 scalar".to_string())?;
- Ok(key
- .verifying_key()
- .to_encoded_point(true)
- .as_bytes()
- .to_vec())
-}
-
-pub(crate) fn chain_str(chain: WalletChain) -> &'static str {
- match chain {
- WalletChain::Evm => "evm",
- WalletChain::Btc => "btc",
- WalletChain::Solana => "solana",
- WalletChain::Tron => "tron",
- }
-}
-
-pub(crate) fn validate_amount(raw: &str) -> Result<u128, String> {
- let trimmed = raw.trim();
- if trimmed.is_empty() {
- return Err("amount is empty".to_string());
- }
- trimmed
- .parse::<u128>()
- .map_err(|_| format!("amount '{trimmed}' is not a valid non-negative integer"))
-}
-
-/// Validate `addr` for `chain`, returning it trimmed.
-///
-/// Every arm delegates to the vendored [`tinywallet_bus`] crate, which owns the
-/// four address formats. The dispatch stays here rather than calling
-/// `tinywallet_bus::address::validate` directly because [`WalletChain`] is
-/// OpenHuman's enum, and mapping it onto `tinywallet_bus::Chain` here keeps that
-/// translation in one place.
-///
-/// For Bitcoin this is the **recipient** rule — any well-formed mainnet
-/// address. Sender addresses go through `chain_btc::validate_btc_sender_address`,
-/// which additionally requires P2WPKH; the distinction has no equivalent on
-/// the other three chains, so it cannot be expressed through this entry point.
-pub(super) fn validate_address(chain: WalletChain, addr: &str) -> Result<String, String> {
- let tw_chain = match chain {
- WalletChain::Evm => tinywallet_bus::Chain::Evm,
- WalletChain::Btc => tinywallet_bus::Chain::Btc,
- WalletChain::Solana => tinywallet_bus::Chain::Solana,
- WalletChain::Tron => tinywallet_bus::Chain::Tron,
- };
- debug!("{LOG_PREFIX} validate_address chain={chain:?} role=recipient dispatch=tinywallet_bus");
- let result = tinywallet_bus::address::validate(tw_chain, addr).map_err(|e| e.to_string());
- debug!(
- "{LOG_PREFIX} validate_address chain={chain:?} role=recipient result={}",
- if result.is_ok() {
- "accepted"
- } else {
- "rejected"
- }
- );
- result
-}
-
-pub(crate) fn validate_calldata(data: &str) -> Result<String, String> {
- let trimmed = data.trim();
- if !trimmed.starts_with("0x") {
- return Err("calldata must be 0x-prefixed hex".to_string());
- }
- let body = &trimmed[2..];
- if !body.len().is_multiple_of(2) {
- return Err("calldata hex must be byte-aligned".to_string());
- }
- if !body.chars().all(|c| c.is_ascii_hexdigit()) {
- return Err("calldata contains non-hex characters".to_string());
- }
- Ok(trimmed.to_string())
-}
-
-pub(crate) fn format_amount(raw: u128, decimals: u8) -> String {
- if decimals == 0 {
- return raw.to_string();
- }
- let s = raw.to_string();
- let d = decimals as usize;
- if s.len() <= d {
- format!("0.{:0>width$}", s, width = d)
- } else {
- let split = s.len() - d;
- format!("{}.{}", &s[..split], &s[split..])
- }
-}
-
-pub(super) fn estimated_fee_raw(chain: WalletChain, kind: PreparedKind) -> String {
- let base = match (chain, kind) {
- (WalletChain::Evm, PreparedKind::NativeTransfer) => 21_000u128 * 30_000_000_000,
- (WalletChain::Evm, PreparedKind::TokenTransfer) => 65_000u128 * 30_000_000_000,
- (WalletChain::Btc, _) => 5_000,
- (WalletChain::Solana, _) => 5_000,
- (WalletChain::Tron, PreparedKind::NativeTransfer) => 1_000_000,
- (WalletChain::Tron, PreparedKind::TokenTransfer) => 15_000_000,
- };
- base.to_string()
-}
-
-/// Parse an `0x`-prefixed hex quantity, as every EVM JSON-RPC result encodes
-/// integers.
-///
-/// `u128` rather than a 256-bit type. Nothing this wallet reads from a node —
-/// a nonce, a gas price, a gas limit, a wei balance — approaches 2^128, which
-/// is about 3.4e20 ETH, and carrying `ethers-core` for a bignum that is never
-/// exercised past 128 bits is the trade this port exists to stop making. A
-/// value that genuinely did overflow is reported rather than truncated.
-///
-/// # Errors
-///
-/// A message naming the offending value if it is not hex, or does not fit.
-pub fn hex_to_u128(hex_value: &str) -> Result<u128, String> {
- let trimmed = hex_value.trim();
- let normalized = trimmed.strip_prefix("0x").unwrap_or(trimmed);
- u128::from_str_radix(normalized, 16)
- .map_err(|e| format!("invalid hex quantity '{hex_value}': {e}"))
-}
-
-/// Render an integer the way an EVM JSON-RPC parameter expects it.
-#[must_use]
-pub fn u128_to_hex(value: u128) -> String {
- format!("0x{value:x}")
-}
-
-pub fn hex_to_bytes(value: &str) -> Result<Vec<u8>, String> {
- let trimmed = value.trim();
- let normalized = trimmed.strip_prefix("0x").unwrap_or(trimmed);
- hex::decode(normalized).map_err(|e| format!("invalid hex bytes '{value}': {e}"))
-}
diff --git a/crates/openhuman-core/src/web3/wallet/execution_tests.rs b/crates/openhuman-core/src/web3/wallet/execution_tests.rs
deleted file mode 100644
index 6d8879059f..0000000000
--- a/crates/openhuman-core/src/web3/wallet/execution_tests.rs
+++ /dev/null
@@ -1,666 +0,0 @@
-use std::net::SocketAddr;
-use std::sync::Arc;
-
-use axum::{extract::State, routing::post, Json, Router};
-use serde_json::{json, Value};
-use tempfile::TempDir;
-use tokio::net::TcpListener;
-
-use super::*;
-use crate::web3::wallet::execution::types::QuoteOwner;
-use crate::web3::wallet::execution::validate::{format_amount, validate_amount};
-use crate::web3::wallet::test_support::{setup_wallet_in, TEST_LOCK};
-use crate::web3::wallet::{EvmNetwork, WalletChain};
-
-#[derive(Clone)]
-struct MockRpcState {
- estimate_calls: Arc<Mutex<Vec<Value>>>,
- raw_txs: Arc<Mutex<Vec<String>>>,
- chain_id: String,
-}
-
-async fn mock_rpc(State(state): State<MockRpcState>, Json(payload): Json<Value>) -> Json<Value> {
- let method = payload
- .get("method")
- .and_then(Value::as_str)
- .unwrap_or_default();
- let params = payload
- .get("params")
- .and_then(Value::as_array)
- .cloned()
- .unwrap_or_default();
- let result = match method {
- "eth_chainId" => Value::String(state.chain_id.clone()),
- "eth_getTransactionCount" => Value::String("0x7".to_string()),
- "eth_gasPrice" => Value::String("0x3b9aca00".to_string()),
- "eth_estimateGas" => {
- state
- .estimate_calls
- .lock()
- .push(params.first().cloned().unwrap_or(Value::Null));
- Value::String("0x5208".to_string())
- }
- "eth_sendRawTransaction" => {
- if let Some(raw) = params.first().and_then(Value::as_str) {
- state.raw_txs.lock().push(raw.to_string());
- }
- Value::String(
- "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
- )
- }
- "eth_getBalance" => Value::String("0xde0b6b3a7640000".to_string()),
- _ => Value::Null,
- };
- Json(json!({"jsonrpc":"2.0","id":1,"result":result}))
-}
-
-pub(crate) async fn start_mock_rpc_with_chain_id(
- chain_id_hex: &str,
-) -> Result<(SocketAddr, Arc<Mutex<Vec<Value>>>, Arc<Mutex<Vec<String>>>), String> {
- let estimate_calls = Arc::new(Mutex::new(Vec::new()));
- let raw_txs = Arc::new(Mutex::new(Vec::new()));
- let state = MockRpcState {
- estimate_calls: estimate_calls.clone(),
- raw_txs: raw_txs.clone(),
- chain_id: chain_id_hex.to_string(),
- };
- let app = Router::new().route("/", post(mock_rpc)).with_state(state);
- let listener = TcpListener::bind("127.0.0.1:0")
- .await
- .map_err(|e| format!("failed to bind mock rpc: {e}"))?;
- let addr = listener
- .local_addr()
- .map_err(|e| format!("failed to read mock rpc addr: {e}"))?;
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- Ok((addr, estimate_calls, raw_txs))
-}
-
-async fn start_mock_rpc(
-) -> Result<(SocketAddr, Arc<Mutex<Vec<Value>>>, Arc<Mutex<Vec<String>>>), String> {
- start_mock_rpc_with_chain_id("0x1").await
-}
-
-#[test]
-fn validates_amount_rejects_empty_and_non_numeric() {
- assert!(validate_amount("").is_err());
- assert!(validate_amount("abc").is_err());
- assert_eq!(validate_amount("42").unwrap(), 42);
-}
-
-#[test]
-fn validates_calldata_requires_hex() {
- assert!(validate_calldata("deadbeef").is_err());
- assert!(validate_calldata("0xZZ").is_err());
- assert!(validate_calldata("0xabc").is_err());
- assert_eq!(validate_calldata("0xdeadbeef").unwrap(), "0xdeadbeef");
-}
-
-#[test]
-fn formats_amount_with_decimals() {
- assert_eq!(format_amount(0, 18), "0.000000000000000000");
- assert_eq!(format_amount(1, 8), "0.00000001");
- assert_eq!(format_amount(123_456_789, 8), "1.23456789");
- assert_eq!(format_amount(100, 0), "100");
-}
-
-#[test]
-fn next_quote_id_is_unique_and_prefixed() {
- let a = next_quote_id();
- let b = next_quote_id();
- assert_ne!(a, b);
- assert!(a.starts_with("q_"));
-}
-
-#[test]
-fn quote_store_round_trips_and_expires() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let now = now_ms();
- let mut q = PreparedTransaction {
- quote_id: "q_test_1".to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Evm,
- evm_network: Some(EvmNetwork::EthereumMainnet),
- from_address: "0xfrom".to_string(),
- to_address: "0xto".to_string(),
- asset_symbol: "ETH".to_string(),
- amount_raw: "1".to_string(),
- amount_formatted: "0.000000000000000001".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "0".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner: None,
- };
- store_quote(q.clone());
- let taken = take_quote_for("q_test_1", None).expect("quote round-trips");
- assert_eq!(taken.quote_id, "q_test_1");
- assert!(
- take_quote_for("q_test_1", None).is_err(),
- "second take must fail"
- );
-
- q.quote_id = "q_test_2".to_string();
- q.expires_at_ms = now.saturating_sub(1);
- store_quote(q);
- let err = take_quote_for("q_test_2", None).unwrap_err();
- assert!(err.contains("expired"), "got: {err}");
-}
-
-#[tokio::test]
-async fn execute_prepared_requires_confirmed_flag() {
- let err = execute_prepared(ExecutePreparedParams {
- quote_id: "missing".to_string(),
- confirmed: false,
- })
- .await
- .unwrap_err();
- assert!(err.contains("confirmed: true"), "got: {err}");
-}
-
-#[tokio::test]
-async fn supported_assets_lists_default_erc20s_and_l2() {
- let out = supported_assets().await.unwrap();
- assert!(out
- .value
- .iter()
- .any(|asset| asset.symbol == "USDC" && asset.evm_network == Some(EvmNetwork::BaseMainnet)));
- assert!(out
- .value
- .iter()
- .any(|asset| asset.symbol == "ETH" && asset.native));
- assert!(out
- .value
- .iter()
- .any(|asset| asset.symbol == "USDT" && asset.chain == WalletChain::Tron));
-}
-
-#[tokio::test]
-async fn prepare_transfer_rejects_unknown_asset_symbol() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- let err = prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "1".into(),
- asset_symbol: Some("NOPE".into()),
- evm_network: None,
- })
- .await
- .unwrap_err();
- assert!(err.contains("unsupported asset_symbol"), "got: {err}");
-}
-
-#[tokio::test]
-async fn balances_fans_evm_account_into_eth_base_bsc_rows() {
- let _guard = TEST_LOCK.lock();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- // Point all three displayed EVM networks at a mock returning 1e18 wei.
- let (addr, _estimate_calls, _raw_txs) = start_mock_rpc().await.unwrap();
- for var in [
- "OPENHUMAN_WALLET_RPC_EVM",
- "OPENHUMAN_WALLET_RPC_BASE",
- "OPENHUMAN_WALLET_RPC_BSC",
- ] {
- std::env::set_var(var, format!("http://{addr}"));
- }
-
- let rows = balances().await.unwrap().value;
-
- // One row per displayed EVM network plus BTC / Solana / Tron.
- let evm_rows: Vec<_> = rows
- .iter()
- .filter(|row| row.chain == WalletChain::Evm)
- .collect();
- assert_eq!(evm_rows.len(), 3, "expected 3 EVM rows, got {evm_rows:?}");
- let networks: Vec<EvmNetwork> = evm_rows.iter().filter_map(|row| row.evm_network).collect();
- assert!(networks.contains(&EvmNetwork::EthereumMainnet));
- assert!(networks.contains(&EvmNetwork::BaseMainnet));
- assert!(networks.contains(&EvmNetwork::BscMainnet));
- // Native symbols differ by network: ETH on Ethereum/Base, BNB on BNB Chain.
- let bnb = evm_rows
- .iter()
- .find(|row| row.evm_network == Some(EvmNetwork::BscMainnet))
- .expect("bsc row present");
- assert_eq!(bnb.asset_symbol, "BNB");
- // Mock RPC returns 1e18 wei for eth_getBalance on every network.
- assert_eq!(bnb.raw, "1000000000000000000");
- assert!(matches!(bnb.provider_status, ProviderStatus::Ready));
- // The non-EVM chains each still produce exactly one row.
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- assert_eq!(
- rows.iter().filter(|row| row.chain == chain).count(),
- 1,
- "expected one row for {chain:?}"
- );
- }
-
- for var in [
- "OPENHUMAN_WALLET_RPC_EVM",
- "OPENHUMAN_WALLET_RPC_BASE",
- "OPENHUMAN_WALLET_RPC_BSC",
- ] {
- std::env::remove_var(var);
- }
-}
-
-#[tokio::test]
-async fn tx_status_rejects_empty_hash() {
- let err = tx_status(WalletChain::Evm, None, " ").await.unwrap_err();
- assert!(err.contains("tx hash is empty"), "got: {err}");
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_prepared_broadcasts_native_evm_transaction -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_prepared_broadcasts_native_evm_transaction() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- let (addr, estimate_calls, raw_txs) = start_mock_rpc().await.unwrap();
- std::env::set_var("OPENHUMAN_WALLET_RPC_EVM", format!("http://{addr}"));
-
- let prepared = prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "1000".into(),
- asset_symbol: None,
- evm_network: None,
- })
- .await
- .unwrap()
- .value;
- let executed = execute_prepared(ExecutePreparedParams {
- quote_id: prepared.quote_id.clone(),
- confirmed: true,
- })
- .await
- .unwrap()
- .value;
-
- assert_eq!(executed.status, PreparedStatus::Broadcasted);
- assert!(executed.transaction_hash.starts_with("0xaaaa"));
- assert_eq!(raw_txs.lock().len(), 1);
- let estimate = estimate_calls.lock()[0].clone();
- assert_eq!(
- estimate.get("to").and_then(Value::as_str),
- Some("0x1111111111111111111111111111111111111111")
- );
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_prepared_broadcasts_erc20_transfer_using_default_token_catalog -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_prepared_broadcasts_erc20_transfer_using_default_token_catalog() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- let (addr, estimate_calls, raw_txs) = start_mock_rpc().await.unwrap();
- std::env::set_var("OPENHUMAN_WALLET_RPC_EVM", format!("http://{addr}"));
-
- let prepared = prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "5000000".into(),
- asset_symbol: Some("USDC".into()),
- evm_network: None,
- })
- .await
- .unwrap()
- .value;
- let executed = execute_prepared(ExecutePreparedParams {
- quote_id: prepared.quote_id.clone(),
- confirmed: true,
- })
- .await
- .unwrap()
- .value;
-
- assert_eq!(executed.status, PreparedStatus::Broadcasted);
- assert_eq!(raw_txs.lock().len(), 1);
- let estimate = estimate_calls.lock()[0].clone();
- assert_eq!(
- estimate.get("to").and_then(Value::as_str),
- Some("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48")
- );
- let data = estimate
- .get("data")
- .and_then(Value::as_str)
- .expect("token transfer calldata");
- assert!(data.starts_with("0xa9059cbb"));
-}
-
-// Drives the real wallet module, so it must be the only such test in its
-// process: tinybus never unloads a module, and the module bus belongs to
-// whichever tokio runtime created it — a second `#[tokio::test]` finds a
-// broker whose tasks died with the first and the call fails with
-// "connection closed". Verified passing in isolation:
-//
-// cargo test -p openhuman --lib --features "$(bash scripts/ci/product-features.sh)" \
-// execute_prepared_broadcasts_native_evm_on_base_with_chain_id_8453 -- --ignored --test-threads=1
-//
-// Same constraint tinydocs documents for its module-backed tool tests.
-#[ignore = "drives the loaded wallet module; must run alone in its process"]
-#[tokio::test]
-async fn execute_prepared_broadcasts_native_evm_on_base_with_chain_id_8453() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- // Base uses chain_id 8453 = 0x2105.
- let (addr, _estimate_calls, raw_txs) = start_mock_rpc_with_chain_id("0x2105").await.unwrap();
- std::env::set_var("OPENHUMAN_WALLET_RPC_BASE", format!("http://{addr}"));
-
- let prepared = prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "1000".into(),
- asset_symbol: None,
- evm_network: Some(EvmNetwork::BaseMainnet),
- })
- .await
- .unwrap()
- .value;
- let executed = execute_prepared(ExecutePreparedParams {
- quote_id: prepared.quote_id.clone(),
- confirmed: true,
- })
- .await
- .unwrap()
- .value;
- assert_eq!(executed.status, PreparedStatus::Broadcasted);
- assert_eq!(executed.evm_network, Some(EvmNetwork::BaseMainnet));
- assert_eq!(raw_txs.lock().len(), 1);
-}
-
-/// Build a Quote-store fixture pinned to a specific owner.
-/// Bypasses prepare_* (which would need full wallet setup + mock RPC) so
-/// the owner-gate behavior can be exercised in isolation.
-fn insert_owned_quote(quote_id: &str, owner: Option<QuoteOwner>) -> PreparedTransaction {
- let now = now_ms();
- let q = PreparedTransaction {
- quote_id: quote_id.to_string(),
- kind: PreparedKind::NativeTransfer,
- chain: WalletChain::Evm,
- evm_network: Some(EvmNetwork::EthereumMainnet),
- from_address: "0xfrom".to_string(),
- to_address: "0xto".to_string(),
- asset_symbol: "ETH".to_string(),
- amount_raw: "1".to_string(),
- amount_formatted: "0.000000000000000001".to_string(),
- receive_symbol: None,
- min_receive_raw: None,
- calldata: None,
- token_address: None,
- estimated_fee_raw: "0".to_string(),
- status: PreparedStatus::AwaitingConfirmation,
- created_at_ms: now,
- expires_at_ms: now + 60_000,
- notes: vec![],
- owner,
- };
- insert_quote_for_test(q)
-}
-
-fn owner_a() -> QuoteOwner {
- QuoteOwner {
- thread_id: "thread-A".into(),
- client_id: "client-A".into(),
- }
-}
-
-fn owner_b() -> QuoteOwner {
- QuoteOwner {
- thread_id: "thread-B".into(),
- client_id: "client-B".into(),
- }
-}
-
-fn chat_ctx_from(owner: &QuoteOwner) -> crate::security::approval::ApprovalChatContext {
- crate::security::approval::ApprovalChatContext {
- thread_id: owner.thread_id.clone(),
- client_id: owner.client_id.clone(),
- request_id: None,
- }
-}
-
-/// Cross-thread execute must fail. The quote must remain in the store
-/// (mismatched caller cannot poison it by consuming on Alice's behalf).
-#[tokio::test]
-async fn execute_prepared_rejects_cross_owner_execution() {
- use crate::security::approval::APPROVAL_CHAT_CONTEXT;
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let q = insert_owned_quote("q_xowner_1", Some(owner_a()));
-
- // Bob (owner_b) tries to execute Alice's quote. The error string is
- // intentionally identical to a not-found lookup.
- let err = APPROVAL_CHAT_CONTEXT
- .scope(
- chat_ctx_from(&owner_b()),
- execute_prepared(ExecutePreparedParams {
- quote_id: q.quote_id.clone(),
- confirmed: true,
- }),
- )
- .await
- .unwrap_err();
- assert_eq!(err, format!("quote '{}' not found", q.quote_id));
-
- // The quote must still be present and executable by Alice — Bob's
- // failed attempt didn't poison the store.
- let still_present = prepared_quotes_for_test();
- assert!(
- still_present.iter().any(|p| p.quote_id == q.quote_id),
- "quote must survive owner-mismatch attempts"
- );
-}
-
-/// Same-thread execute must pass the owner gate (it will fail later in
-/// the chain code because there's no mock RPC set up, but the failure
-/// must not be the "not found" oracle — that proves we got past the gate).
-#[tokio::test]
-async fn execute_prepared_allows_same_owner_execution() {
- use crate::security::approval::APPROVAL_CHAT_CONTEXT;
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let q = insert_owned_quote("q_same_owner_1", Some(owner_a()));
-
- let result = APPROVAL_CHAT_CONTEXT
- .scope(
- chat_ctx_from(&owner_a()),
- execute_prepared(ExecutePreparedParams {
- quote_id: q.quote_id.clone(),
- confirmed: true,
- }),
- )
- .await;
- // Past the owner gate. Chain code may error (no mock RPC, no wallet
- // setup) — but it must NOT be the "not found" shape we use for the
- // owner-mismatch oracle.
- if let Err(err) = &result {
- assert_ne!(
- err,
- &format!("quote '{}' not found", q.quote_id),
- "same-owner path must not return the owner-mismatch oracle"
- );
- }
-}
-
-/// No-context prepare + no-context execute must work. Keeps CLI / direct
-/// JSON-RPC flows usable.
-#[tokio::test]
-async fn execute_prepared_allows_no_context_flows() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let q = insert_owned_quote("q_no_ctx_1", None);
-
- // No APPROVAL_CHAT_CONTEXT scope — current_owner() returns None on
- // both prepare and execute, so the gate passes.
- let result = execute_prepared(ExecutePreparedParams {
- quote_id: q.quote_id.clone(),
- confirmed: true,
- })
- .await;
- if let Err(err) = &result {
- assert_ne!(
- err,
- &format!("quote '{}' not found", q.quote_id),
- "no-context path must not return the owner-mismatch oracle"
- );
- }
-}
-
-/// A quote prepared inside a chat context must NOT be executable from a
-/// caller with no context. Prevents privilege-drop into background /
-/// triage / cron flows that wouldn't surface UI confirmation.
-#[tokio::test]
-async fn execute_prepared_rejects_chat_quote_from_no_context_caller() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let q = insert_owned_quote("q_chat_to_bg_1", Some(owner_a()));
-
- // No scope around execute → caller_owner = None ≠ Some(owner_a).
- let err = execute_prepared(ExecutePreparedParams {
- quote_id: q.quote_id.clone(),
- confirmed: true,
- })
- .await
- .unwrap_err();
- assert_eq!(err, format!("quote '{}' not found", q.quote_id));
-}
-
-/// Lock the error-shape invariant: cross-owner reject string MUST be
-/// byte-equal to the not-found string. Regressions here would re-open
-/// the enumeration-oracle gap.
-#[tokio::test]
-async fn execute_prepared_owner_mismatch_error_matches_not_found_shape() {
- use crate::security::approval::APPROVAL_CHAT_CONTEXT;
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
-
- // Real (owner-mismatched) quote.
- let real = insert_owned_quote("q_real_1", Some(owner_a()));
- // Reach the mismatched-owner branch.
- let mismatch_err = APPROVAL_CHAT_CONTEXT
- .scope(
- chat_ctx_from(&owner_b()),
- execute_prepared(ExecutePreparedParams {
- quote_id: real.quote_id.clone(),
- confirmed: true,
- }),
- )
- .await
- .unwrap_err();
-
- // Reach the genuine not-found branch (no quote with this id in store).
- let missing_err = APPROVAL_CHAT_CONTEXT
- .scope(
- chat_ctx_from(&owner_b()),
- execute_prepared(ExecutePreparedParams {
- quote_id: "q_does_not_exist".into(),
- confirmed: true,
- }),
- )
- .await
- .unwrap_err();
-
- // Both branches surface the exact same template, parameterised only
- // by quote_id. No enumeration oracle.
- assert_eq!(mismatch_err, format!("quote '{}' not found", real.quote_id));
- assert_eq!(missing_err, "quote 'q_does_not_exist' not found");
-}
-
-/// Verify that `prepare_transfer` inside an `APPROVAL_CHAT_CONTEXT` scope
-/// actually stamps `owner` via the task-local — not just via test helpers.
-#[tokio::test]
-async fn prepare_stamps_owner_via_task_local() {
- use crate::security::approval::APPROVAL_CHAT_CONTEXT;
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
-
- let expected = owner_a();
- let ctx = chat_ctx_from(&expected);
-
- let prepared = APPROVAL_CHAT_CONTEXT
- .scope(
- ctx,
- prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "1000".into(),
- asset_symbol: None,
- evm_network: Some(EvmNetwork::EthereumMainnet),
- }),
- )
- .await
- .unwrap()
- .value;
-
- assert_eq!(
- prepared.owner,
- Some(expected),
- "prepare_transfer must stamp owner from APPROVAL_CHAT_CONTEXT"
- );
-}
-
-#[tokio::test]
-async fn execute_prepared_rejects_evm_chain_id_mismatch() {
- let _guard = TEST_LOCK.lock();
- reset_quote_store_for_tests();
- let temp = TempDir::new().unwrap();
- let _workspace_guard = setup_wallet_in(&temp).await.unwrap();
- // Quote says Base; mock reports Ethereum (0x1) — must fail.
- let (addr, _e, _r) = start_mock_rpc_with_chain_id("0x1").await.unwrap();
- std::env::set_var("OPENHUMAN_WALLET_RPC_BASE", format!("http://{addr}"));
-
- let prepared = prepare_transfer(PrepareTransferParams {
- chain: WalletChain::Evm,
- to_address: "0x1111111111111111111111111111111111111111".into(),
- amount_raw: "1000".into(),
- asset_symbol: None,
- evm_network: Some(EvmNetwork::BaseMainnet),
- })
- .await
- .unwrap()
- .value;
- let err = execute_prepared(ExecutePreparedParams {
- quote_id: prepared.quote_id.clone(),
- confirmed: true,
- })
- .await
- .unwrap_err();
- assert!(err.contains("chain_id mismatch"), "got: {err}");
-}
diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs
index 6d0313a418..fc59a23cbc 100644
--- a/crates/openhuman-core/src/web3/wallet/mod.rs
+++ b/crates/openhuman-core/src/web3/wallet/mod.rs
@@ -1,7 +1,24 @@
//! Core-owned wallet onboarding metadata, derived account visibility, and
-//! the agent-facing execution surface (balances, transfers, swaps,
-//! contract calls). See [`execution`] for the prepare/confirm/execute flow
-//! and [`chains`] for the per-chain signing/broadcast implementations.
+//! the agent-facing execution surface (balances, transfers, transaction
+//! lookups).
+//!
+//! ## Where the logic lives
+//!
+//! The wallet engine — balances, the prepare/confirm/execute flow, the per-chain
+//! signing choreography and the agent tools — lives in
+//! `tinywallet_web3::crypto`. This module is the host adapter over it:
+//!
+//! - [`ops`] — setup, status, recovery-phrase reveal and `secret_material`
+//! (keyring, consent, credentials). Stays here: it is the host's state.
+//! - [`execution`] — the engine's operations wrapped in the controller
+//! contract's `Outcome`.
+//! - [`endpoints`] — the `OPENHUMAN_WALLET_RPC_*` / `OPENHUMAN_SOLANA_CLUSTER`
+//! environment resolution the engine's `RpcEndpoints` seam asks.
+//! - [`transport`] / [`rpc`] — the host `Transport` seam: endpoint resolution,
+//! URL redaction and error classification over the shared `reqwest` client.
+//! - `schemas` — the controllers, with their RPC namespace strings.
+//! - The seam implementations and the process-wide engine are in
+//! [`crate::web3::seams`].
//!
//! ## Compile-time gate (`web3` feature)
//!
@@ -20,11 +37,7 @@
//! the only thing that catches drift.
#[cfg(feature = "web3")]
-mod abi;
-#[cfg(feature = "web3")]
-mod chains;
-#[cfg(feature = "web3")]
-mod defaults;
+pub(crate) mod endpoints;
#[cfg(feature = "web3")]
mod execution;
#[cfg(feature = "web3")]
@@ -34,6 +47,8 @@ pub(crate) mod rpc;
#[cfg(feature = "web3")]
mod schemas;
+/// The wallet agent tools, re-exported from `tinywallet-web3`. The host builds
+/// them over the process-wide engine in `tools/ops.rs`.
#[cfg(feature = "web3")]
pub mod tools;
/// The host side of the wallet primitives' `Transport` seam — endpoint resolution,
@@ -45,14 +60,7 @@ pub(crate) mod transport;
pub(crate) mod test_support;
#[cfg(feature = "web3")]
-pub use abi::encode_erc20_transfer;
-#[cfg(feature = "web3")]
-pub use defaults::{
- asset_catalog, default_rpc_url, env_var_for_chain, evm_asset_catalog, explorer_tx_url,
- find_asset, find_asset_for_network, network_defaults, rpc_source_for_chain, rpc_url_for_chain,
- rpc_url_for_evm_network, solana_cluster, EvmNetwork, RpcSource, SolanaCluster,
- WalletAssetDefinition, WalletNetworkDefaults,
-};
+pub use endpoints::solana_cluster;
#[cfg(feature = "web3")]
pub use execution::{
balances, chain_status, execute_prepared, lookup_tx,
@@ -61,10 +69,6 @@ pub use execution::{
ExecutionResult, PrepareTransferParams, PreparedKind, PreparedStatus, PreparedTransaction,
ProviderStatus, SupportedAsset, TxLookupInfo, TxReceiptInfo, TxState, TxStatusInfo,
};
-/// Crate-internal signing primitives the `web3` layer builds on. Not part of
-/// the agent / RPC surface.
-#[cfg(feature = "web3")]
-pub(crate) use execution::{sign_and_broadcast_evm, sign_and_broadcast_solana};
#[cfg(feature = "web3")]
pub(crate) use ops::secret_material;
#[cfg(feature = "web3")]
@@ -77,6 +81,13 @@ pub use schemas::{
all_controller_schemas, all_registered_controllers, all_wallet_controller_schemas,
all_wallet_registered_controllers, schemas, wallet_schemas,
};
+#[cfg(feature = "web3")]
+pub use tinywallet_web3::crypto::abi::encode_erc20_transfer;
+#[cfg(feature = "web3")]
+pub use tinywallet_web3::crypto::defaults::{
+ evm_asset_catalog, explorer_tx_url, EvmNetwork, RpcSource, SolanaCluster,
+ WalletAssetDefinition, WalletNetworkDefaults,
+};
// ---------------------------------------------------------------------------
// Disabled facade — compiled only when the `web3` feature is OFF.
diff --git a/crates/openhuman-core/src/web3/wallet/ops/types.rs b/crates/openhuman-core/src/web3/wallet/ops/types.rs
index 6cd7fd3350..fc39daf778 100644
--- a/crates/openhuman-core/src/web3/wallet/ops/types.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops/types.rs
@@ -2,51 +2,16 @@
use serde::{Deserialize, Serialize};
-/// Error message returned when the wallet has not been set up yet.
-///
-/// This is an expected user-state (the user simply has not created a wallet),
-/// not an internal failure. Downstream boundaries that surface this condition
-/// match against this constant to
-/// classify it as `expected_user_state` so it stays out of Sentry. Keep it a
-/// shared constant so the producer here and any classifier cannot drift apart.
-pub const WALLET_NOT_CONFIGURED_MESSAGE: &str = "wallet is not configured; run wallet setup first";
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum WalletChain {
- Evm,
- Btc,
- Solana,
- Tron,
-}
-
-impl WalletChain {
- pub(super) const ALL: [Self; 4] = [Self::Evm, Self::Btc, Self::Solana, Self::Tron];
-
- pub(super) fn as_str(self) -> &'static str {
- match self {
- Self::Evm => "evm",
- Self::Btc => "btc",
- Self::Solana => "solana",
- Self::Tron => "tron",
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum WalletSetupSource {
- Generated,
- Imported,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub struct WalletAccount {
- pub chain: WalletChain,
- pub address: String,
- pub derivation_path: String,
-}
+// The wallet's vocabulary lives in `tinywallet-web3`, which the engine and the
+// tools share; the host keeps only the persisted shape and the setup params.
+pub use tinywallet_web3::crypto::wallet::{
+ WalletAccount, WalletChain, WalletSetupSource, WalletStatus,
+};
+/// Error message returned when the wallet has not been set up yet. Downstream
+/// boundaries match against it to classify the condition as an expected user
+/// state, so it stays out of Sentry; it is defined once in `tinywallet-web3`
+/// so the producer and any classifier cannot drift apart.
+pub use tinywallet_web3::quote::WALLET_NOT_CONFIGURED_MESSAGE;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
@@ -83,22 +48,6 @@ pub(crate) struct WalletSecretMaterial {
pub derivation_path: String,
}
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub struct WalletStatus {
- pub configured: bool,
- pub onboarding_completed: bool,
- pub consent_granted: bool,
- pub secret_stored: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub source: Option<WalletSetupSource>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub mnemonic_word_count: Option<u8>,
- pub accounts: Vec<WalletAccount>,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub updated_at_ms: Option<u64>,
-}
-
/// Result returned by `reveal_recovery_phrase`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/openhuman-core/src/web3/wallet/rpc.rs b/crates/openhuman-core/src/web3/wallet/rpc.rs
index f11cadcebc..8c11dbe80f 100644
--- a/crates/openhuman-core/src/web3/wallet/rpc.rs
+++ b/crates/openhuman-core/src/web3/wallet/rpc.rs
@@ -2,7 +2,9 @@
//!
//! JSON-RPC is used for EVM and Solana. REST is used for BTC (Esplora) and
//! Tron (TronGrid). Both honor an `OPENHUMAN_WALLET_RPC_<CHAIN>` env override
-//! so tests can point everything at an axum mock.
+//! so tests can point everything at an axum mock. The wallet engine reaches
+//! these through [`super::transport::OpenHumanTransport`]; `rpc_call` is also
+//! used directly by the x402 payment helpers.
use std::time::Duration;
@@ -10,7 +12,7 @@ use once_cell::sync::Lazy;
use serde::de::DeserializeOwned;
use serde_json::{json, Value};
-use super::defaults::{rpc_url_for_chain, rpc_url_for_evm_network, EvmNetwork};
+use super::endpoints::rpc_url_for_chain;
use super::ops::WalletChain;
const LOG_PREFIX: &str = "[wallet::rpc]";
@@ -58,15 +60,6 @@ pub async fn rpc_call<T: DeserializeOwned>(
rpc_call_to(&rpc_url_for_chain(chain), method, params).await
}
-/// JSON-RPC POST against a specific EVM network's RPC URL.
-pub async fn evm_rpc_call<T: DeserializeOwned>(
- network: EvmNetwork,
- method: &str,
- params: Value,
-) -> Result<T, String> {
- rpc_call_to(&rpc_url_for_evm_network(network), method, params).await
-}
-
pub async fn rpc_call_to<T: DeserializeOwned>(
url: &str,
method: &str,
@@ -153,12 +146,6 @@ pub async fn rest_get_text(url: &str) -> Result<String, String> {
Ok(body)
}
-pub async fn rest_get_json<T: DeserializeOwned>(url: &str) -> Result<T, String> {
- let body = rest_get_text(url).await?;
- serde_json::from_str(&body)
- .map_err(|e| format!("wallet REST GET decode failed: {e}; body={body}"))
-}
-
/// Plain REST POST with a raw text body (e.g. Esplora /tx accepts hex).
pub async fn rest_post_text(url: &str, body: &str, content_type: &str) -> Result<String, String> {
log::debug!(
@@ -186,29 +173,6 @@ pub async fn rest_post_text(url: &str, body: &str, content_type: &str) -> Result
Ok(text)
}
-/// REST POST with a JSON body.
-pub async fn rest_post_json<T: DeserializeOwned>(url: &str, body: &Value) -> Result<T, String> {
- log::debug!("{LOG_PREFIX} rest_post_json url={}", redact_rpc_url(url));
- let response = client()
- .post(url)
- .json(body)
- .send()
- .await
- .map_err(|e| format!("wallet REST POST transport failed: {e}"))?;
- let status = response.status();
- let text = response
- .text()
- .await
- .map_err(|e| format!("wallet REST POST read body failed: {e}"))?;
- if !status.is_success() {
- return Err(format!(
- "wallet REST POST HTTP failure: status={status} body={text}"
- ));
- }
- serde_json::from_str(&text)
- .map_err(|e| format!("wallet REST POST decode failed: {e}; body={text}"))
-}
-
#[cfg(test)]
#[path = "rpc_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/tools.rs b/crates/openhuman-core/src/web3/wallet/tools.rs
index c5af571016..b3bb311c08 100644
--- a/crates/openhuman-core/src/web3/wallet/tools.rs
+++ b/crates/openhuman-core/src/web3/wallet/tools.rs
@@ -1,9 +1,8 @@
-mod chain_status;
-mod prepare_transfer;
-mod status;
-mod tx_query;
+//! The wallet agent tools.
+//!
+//! The tools live in `tinywallet_web3::tools::wallet`; they are re-exported here
+//! so `tools/mod.rs` keeps exposing them under their historical path. Each is
+//! built over the process-wide wallet engine
+//! ([`crate::web3::seams::engine`]) at registration in `tools/ops.rs`.
-pub use chain_status::WalletChainStatusTool;
-pub use prepare_transfer::WalletPrepareTransferTool;
-pub use status::WalletStatusTool;
-pub use tx_query::{WalletLookupTxTool, WalletTxReceiptTool, WalletTxStatusTool};
+pub use tinywallet_web3::tools::wallet::*;
diff --git a/crates/openhuman-core/src/web3/wallet/tools/chain_status.rs b/crates/openhuman-core/src/web3/wallet/tools/chain_status.rs
deleted file mode 100644
index cef975d997..0000000000
--- a/crates/openhuman-core/src/web3/wallet/tools/chain_status.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use crate::web3::wallet;
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct WalletChainStatusTool;
-
-impl Default for WalletChainStatusTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletChainStatusTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletChainStatusTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_chain_status"
- }
-
- fn description(&self) -> &str {
- "List blockchain chain readiness — which chains have a configured account and RPC provider."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {},
- "additionalProperties": false
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- _args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- match wallet::chain_status().await {
- Ok(outcome) => {
- let json_str = serde_json::to_string_pretty(&outcome.value)?;
- Ok(ToolResult::success(json_str))
- }
- Err(e) => Ok(ToolResult::error(e)),
- }
- }
-}
diff --git a/crates/openhuman-core/src/web3/wallet/tools/prepare_transfer.rs b/crates/openhuman-core/src/web3/wallet/tools/prepare_transfer.rs
deleted file mode 100644
index 67285ed87c..0000000000
--- a/crates/openhuman-core/src/web3/wallet/tools/prepare_transfer.rs
+++ /dev/null
@@ -1,104 +0,0 @@
-use crate::web3::wallet::{self, PrepareTransferParams};
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct WalletPrepareTransferTool;
-
-impl Default for WalletPrepareTransferTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletPrepareTransferTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletPrepareTransferTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_prepare_transfer"
- }
-
- fn description(&self) -> &str {
- "Prepare a cryptocurrency transfer. Returns a quote that must be confirmed before execution."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "chain": {
- "type": "string",
- "enum": ["evm", "btc", "solana", "tron"],
- "description": "Blockchain network to use"
- },
- "toAddress": {
- "type": "string",
- "description": "Destination wallet address"
- },
- "amountRaw": {
- "type": "string",
- "description": "Transfer amount in the chain's smallest unit (e.g. wei for EVM)"
- },
- "assetSymbol": {
- "type": "string",
- "description": "Asset symbol (e.g. ETH, USDC). Defaults to the native asset."
- },
- "evmNetwork": {
- "type": "string",
- "enum": ["ethereum_mainnet", "base_mainnet", "arbitrum_one", "optimism_mainnet", "polygon_mainnet", "bsc_mainnet"],
- "description": "Optional EVM network when chain='evm'. Defaults to ethereum_mainnet."
- }
- },
- "required": ["chain", "toAddress", "amountRaw"],
- "additionalProperties": false
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let params: PrepareTransferParams = match serde_json::from_value(args) {
- Ok(p) => p,
- Err(e) => {
- log::debug!("[wallet_prepare_transfer] invalid arguments: {e}");
- return Ok(ToolResult::error(format!("invalid arguments: {e}")));
- }
- };
-
- log::debug!(
- "[wallet_prepare_transfer] chain={:?} to={}…{} amount_len={}",
- params.chain,
- &params.to_address[..params.to_address.len().min(6)],
- &params.to_address[params.to_address.len().saturating_sub(4)..],
- params.amount_raw.len()
- );
-
- match wallet::prepare_transfer(params).await {
- Ok(outcome) => {
- let json_str = serde_json::to_string_pretty(&outcome.value)?;
- log::debug!("[wallet_prepare_transfer] success");
- Ok(ToolResult::success(json_str))
- }
- Err(e) => {
- log::warn!("[wallet_prepare_transfer] failed: {e}");
- Ok(ToolResult::error(e))
- }
- }
- }
-}
diff --git a/crates/openhuman-core/src/web3/wallet/tools/status.rs b/crates/openhuman-core/src/web3/wallet/tools/status.rs
deleted file mode 100644
index 8d20ab9bcc..0000000000
--- a/crates/openhuman-core/src/web3/wallet/tools/status.rs
+++ /dev/null
@@ -1,60 +0,0 @@
-use crate::web3::wallet;
-use async_trait::async_trait;
-use serde_json::json;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-pub struct WalletStatusTool;
-
-impl Default for WalletStatusTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletStatusTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletStatusTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_status"
- }
-
- fn description(&self) -> &str {
- "Check wallet configuration status — whether the wallet is set up, which chains are configured, and available accounts."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {},
- "additionalProperties": false
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- _args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- match wallet::status().await {
- Ok(outcome) => {
- let json_str = serde_json::to_string_pretty(&outcome.value)?;
- Ok(ToolResult::success(json_str))
- }
- Err(e) => Ok(ToolResult::error(e)),
- }
- }
-}
diff --git a/crates/openhuman-core/src/web3/wallet/tools/tx_query.rs b/crates/openhuman-core/src/web3/wallet/tools/tx_query.rs
deleted file mode 100644
index 6eee7cc604..0000000000
--- a/crates/openhuman-core/src/web3/wallet/tools/tx_query.rs
+++ /dev/null
@@ -1,212 +0,0 @@
-//! Read-only agent tools for inspecting on-chain transactions by hash:
-//! `wallet_tx_status`, `wallet_tx_receipt`, `wallet_lookup_tx`. Each shares the
-//! same `{chain, hash, evmNetwork?}` input and delegates to the matching
-//! `wallet::*` dispatcher.
-
-use crate::web3::wallet::{self, EvmNetwork, WalletChain};
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-#[derive(Debug, Deserialize)]
-#[serde(rename_all = "camelCase")]
-struct TxQueryArgs {
- chain: WalletChain,
- #[serde(default)]
- evm_network: Option<EvmNetwork>,
- hash: String,
-}
-
-fn tx_query_schema(verb: &str) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "chain": {
- "type": "string",
- "enum": ["evm", "btc", "solana", "tron"],
- "description": format!("Blockchain network whose transaction to {verb}")
- },
- "hash": {
- "type": "string",
- "description": "Transaction hash / signature / txid to query"
- },
- "evmNetwork": {
- "type": "string",
- "enum": ["ethereum_mainnet", "base_mainnet", "arbitrum_one", "optimism_mainnet", "polygon_mainnet", "bsc_mainnet"],
- "description": "Optional EVM network when chain='evm'. Defaults to ethereum_mainnet."
- }
- },
- "required": ["chain", "hash"],
- "additionalProperties": false
- })
-}
-
-fn parse_args(args: serde_json::Value) -> Result<TxQueryArgs, ToolResult> {
- serde_json::from_value(args).map_err(|e| ToolResult::error(format!("invalid arguments: {e}")))
-}
-
-pub struct WalletTxStatusTool;
-
-impl Default for WalletTxStatusTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletTxStatusTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletTxStatusTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_tx_status"
- }
-
- fn description(&self) -> &str {
- "Check the on-chain lifecycle state (pending / confirmed / failed / not_found) of a transaction by hash."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- tx_query_schema("check")
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let args = match parse_args(args) {
- Ok(a) => a,
- Err(err) => return Ok(err),
- };
- match wallet::tx_status(args.chain, args.evm_network, &args.hash).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(e)),
- }
- }
-}
-
-pub struct WalletTxReceiptTool;
-
-impl Default for WalletTxReceiptTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletTxReceiptTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletTxReceiptTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_tx_receipt"
- }
-
- fn description(&self) -> &str {
- "Fetch the receipt of a broadcast transaction (success flag, fee, block, gas used) by hash."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- tx_query_schema("fetch the receipt for")
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let args = match parse_args(args) {
- Ok(a) => a,
- Err(err) => return Ok(err),
- };
- match wallet::tx_receipt(args.chain, args.evm_network, &args.hash).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(e)),
- }
- }
-}
-
-pub struct WalletLookupTxTool;
-
-impl Default for WalletLookupTxTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl WalletLookupTxTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for WalletLookupTxTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "wallet_lookup_tx"
- }
-
- fn description(&self) -> &str {
- "Look up the raw transaction payload by hash on the target chain."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- tx_query_schema("look up")
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let args = match parse_args(args) {
- Ok(a) => a,
- Err(err) => return Ok(err),
- };
- match wallet::lookup_tx(args.chain, args.evm_network, &args.hash).await {
- Ok(outcome) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &outcome.value,
- )?)),
- Err(e) => Ok(ToolResult::error(e)),
- }
- }
-}
diff --git a/crates/openhuman-core/src/web3/wallet/transport.rs b/crates/openhuman-core/src/web3/wallet/transport.rs
index b799e1903d..642339ff07 100644
--- a/crates/openhuman-core/src/web3/wallet/transport.rs
+++ b/crates/openhuman-core/src/web3/wallet/transport.rs
@@ -33,7 +33,9 @@ use log::debug;
use serde_json::Value;
use tinywallet_bus::rpc::{NetworkId, Transport, TransportError, TransportResult};
-use super::defaults::{rpc_url_for_chain, rpc_url_for_evm_network, EvmNetwork};
+use tinywallet_web3::crypto::defaults::EvmNetwork;
+
+use super::endpoints::{rpc_url_for_chain, rpc_url_for_evm_network};
use super::ops::WalletChain;
use super::rpc::{redact_rpc_url, rest_get_text, rest_post_text, rpc_call_to};
diff --git a/crates/openhuman-core/src/web3/web3_tests.rs b/crates/openhuman-core/src/web3/web3_tests.rs
deleted file mode 100644
index 9ff9d2962c..0000000000
--- a/crates/openhuman-core/src/web3/web3_tests.rs
+++ /dev/null
@@ -1,84 +0,0 @@
-use super::store::{self, execute_quote};
-use super::types::{chain_family, ChainFamily, ExecuteQuoteParams, UnsignedTx, Web3QuoteKind};
-use crate::web3::wallet::EvmNetwork;
-use once_cell::sync::Lazy;
-use parking_lot::Mutex;
-
-/// Serializes tests that touch the process-global web3 quote store so parallel
-/// `cargo test` runs can't interleave `reset_store_for_tests` /
-/// `stored_quote_count` and make count assertions flaky.
-static STORE_TEST_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));
-
-#[test]
-fn chain_family_maps_known_ids() {
- assert_eq!(
- chain_family(1),
- Some(ChainFamily::Evm(EvmNetwork::EthereumMainnet))
- );
- assert_eq!(
- chain_family(56),
- Some(ChainFamily::Evm(EvmNetwork::BscMainnet))
- );
- assert_eq!(
- chain_family(8453),
- Some(ChainFamily::Evm(EvmNetwork::BaseMainnet))
- );
- assert_eq!(chain_family(7_565_164), Some(ChainFamily::Solana));
-}
-
-#[test]
-fn chain_family_rejects_unsignable_chain() {
- // 999999 is not an EVM chain we sign for, nor the deBridge Solana id.
- assert_eq!(chain_family(999_999), None);
-}
-
-#[tokio::test]
-async fn execute_requires_confirmation() {
- let _g = STORE_TEST_LOCK.lock();
- store::reset_store_for_tests();
- let quote = store::store_quote(
- Web3QuoteKind::DappCall,
- UnsignedTx::Evm {
- network: EvmNetwork::EthereumMainnet,
- to: "0x0000000000000000000000000000000000000001".to_string(),
- data: Some("0x".to_string()),
- value: "0".to_string(),
- },
- serde_json::json!({"type": "dapp_call"}),
- );
- let err = execute_quote(ExecuteQuoteParams {
- quote_id: quote.quote_id,
- confirmed: false,
- })
- .await
- .unwrap_err();
- assert!(err.contains("confirmed"), "got: {err}");
-}
-
-#[tokio::test]
-async fn execute_unknown_quote_is_not_found() {
- let _g = STORE_TEST_LOCK.lock();
- store::reset_store_for_tests();
- let err = execute_quote(ExecuteQuoteParams {
- quote_id: "w3_missing".to_string(),
- confirmed: true,
- })
- .await
- .unwrap_err();
- assert!(err.contains("not found"), "got: {err}");
-}
-
-#[test]
-fn store_quote_is_retained_and_counted() {
- let _g = STORE_TEST_LOCK.lock();
- store::reset_store_for_tests();
- assert_eq!(store::stored_quote_count(), 0);
- let _ = store::store_quote(
- Web3QuoteKind::Swap,
- UnsignedTx::Solana {
- tx_blob_hex: "00".to_string(),
- },
- serde_json::json!({}),
- );
- assert_eq!(store::stored_quote_count(), 1);
-}
diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md
index dbe2169edc..54140f6f88 100644
--- a/crates/openhuman-core/src/web3/x402/README.md
+++ b/crates/openhuman-core/src/web3/x402/README.md
@@ -12,16 +12,24 @@ Sibling of the [`wallet`](../wallet/README.md) module in the
dedicated `x402_request` agent tool or as a 402 fallback inside the generic
`http_request` tool.
+The implementation lives in the **`tinywallet-x402`** crate
+(`vendor/tinywallet/crates/tinywallet-x402`, features `wire`, `pay`, `ledger`,
+`tools`): the 402 client, the EVM and Solana payment builders, the spending
+ledger and the `x402_request` agent tool. This directory is the host side and
+nothing else: the seams the crate is handed, the RPC controllers, the spending
+limits, and the disabled-build stub. A behavior change to the protocol, the
+payment construction, the ledger or the tool belongs in `tinywallet`, not here.
+
## Compile-time gate (`web3` feature)
`pub mod x402;` (declared in `web3/mod.rs`) is always compiled: it is a
-facade. The real payment machinery (`ops`, `schemas`, `store`, `tools`,
-`types`) is gated behind the default-ON `web3` Cargo feature (shared with
+facade. The real payment surface (`seams`, `schemas`, `budget` and the
+`tinywallet_x402` re-exports) is gated behind the default-ON `web3` Cargo feature (shared with
`web3` and `web3::wallet`). When the feature is off, `stub.rs` takes its
place and exposes only the three entry points with always-on callers:
`init_ledger` (a no-op; the boot call site in `core/runtime/bootstrap.rs` is itself
runtime-gated on `DomainGroup::Web3`), `all_x402_registered_controllers`, and
-`all_x402_controller_schemas` (both empty). `X402RequestTool`'s registration
+`all_x402_controller_schemas` (both empty). The `x402_request` tool's registration
and the `http_request` 402-retry path are `#[cfg(feature = "web3")]` at their
own call sites, so the rest of the payment surface (`PaymentRecord`, `store`,
`SettlementResponse`, and so on) is never referenced when the feature is off
@@ -32,18 +40,20 @@ and does not need a stub. Signatures must match the real ones exactly;
| File | Role |
| --- | --- |
-| `mod.rs` | Facade root: feature gate, re-exports (`handle_402`, `handle_402_and_pay`, `try_paid_request`, `X402Client`, `X402Error`, `X402PaymentResult`, `init_ledger`, the controller pair, wire types). |
-| `ops.rs` | Facade over submodules under `ops/` (`client.rs`, `errors.rs`, `headers.rs`, `evm_payment.rs`, `solana_payment.rs`) of the client logic: parse a 402 challenge, build the Solana (`exact` scheme: ComputeBudget limit/price, SPL `TransferChecked`, optional Memo) or EVM (`exact` scheme: EIP-3009 `transferWithAuthorization`) payment, sign, and retry with the proof. |
-| `ops/client.rs` / `ops/errors.rs` | `X402Client`/`try_paid_request`, `X402PaymentResult`, `X402Error`, `handle_402`/`handle_402_and_pay`, `wallet_signer` (Solana signer resolution through the wallet module), calling into `build_solana_payment` (`solana_payment.rs`) and `build_evm_payment` (`evm_payment.rs`). |
-| `ops/headers.rs` | `PAYMENT-REQUIRED`/`PAYMENT-RESPONSE` header parsing. |
-| `ops/evm_payment.rs` | EVM EIP-712 authorization/payload construction (`evm_payment_authorization`, `evm_payment_payload`), `evm_signer` (EVM signer resolution), `build_evm_payment` (signs via `modules::wallet::sign_message`), and a `cfg(test)`-only local `k256` signer used to check the construction against a fixed vector. |
-| `ops/solana_payment.rs` | The Solana instruction builders (ComputeBudget, `TransferChecked`, Memo) and `build_solana_payment`. |
-| `store.rs` | Append-only JSONL payment ledger (`PaymentLedger`) with per-request/daily/monthly budget enforcement and session/daily/monthly spend summaries; `PaymentRecord`, `PaymentStatus`, `SpendingSummary`, `SpendingBudget`, `BudgetCheck`, the process-global `GLOBAL_LEDGER`, `init_global` (re-exported as `init_ledger`), and `with_ledger`/`with_ledger_mut` accessors. |
+| `mod.rs` | Facade root: feature gate; re-exports from `tinywallet_x402` (`X402Client`, `X402Error`, `X402PaymentResult`, `handle_402`, the ledger and wire types); `init_ledger`, `handle_402_and_pay`, `try_paid_request` and `request_tool`, which supply the seams; the `store` accessors used by `http_request`. |
+| `seams.rs` | `WalletPaymentSigner` (the crate's `PaymentSigner`: keyring secret, decrypt, `modules::wallet::{derive_account, sign_message}`), `RuntimeProxyPolicy` (`ProxyPolicy` over `config::apply_runtime_proxy_to_builder`), and the `payments()` / `request_tool()` constructors that pair them with the wallet's `OpenHumanTransport`. |
+| `budget.rs` | The spending limits: the crate's defaults plus the `OPENHUMAN_X402_*` overrides. |
| `schemas.rs` | RPC controller schemas and handlers for the `x402` namespace: `get_summary`, `list_payments`, `update_budget`. |
-| `tools.rs` | `X402RequestTool` (`x402_request`), a purpose-built agent tool for x402 endpoints, as opposed to the generic `http_request` tool's opportunistic 402 fallback. |
-| `types.rs` | Wire types for the v2 protocol: header names, CAIP-2 network/asset constants (Solana mainnet/devnet, Base/Ethereum, USDC mints/contracts), `PaymentRequired`/`PaymentRequirements`/`PaymentPayload`/`PaymentProof` (Evm/Solana variants), `SettlementResponse`, `ResourceInfo`. |
| `stub.rs` | Disabled facade compiled when `web3` is off. See Compile-time gate above. |
-| `x402_tests.rs`, `store_tests.rs`, `stub_tests.rs` | Behavior tests, `#[cfg(all(test, feature = "web3"))]` except `stub_tests.rs` which runs only in the disabled build. |
+| `seams_tests.rs`, `budget_tests.rs`, `stub_tests.rs` | Behavior tests. `stub_tests.rs` runs only in the disabled build. The protocol, builder, ledger and tool tests live in the crate. |
+
+## The seams
+
+| Trait (in `tinywallet-x402`) | Host implementation | Notes |
+| --- | --- | --- |
+| `PaymentSigner` (`account`, `sign`) | `WalletPaymentSigner` | The mnemonic is decrypted here for one confidential module call and never enters the crate; it sees an address and finished signatures. Errors keep their historical prefixes (`wallet secret:`, `load config:`, `decrypt mnemonic:`, `derive account:`). |
+| `rpc::Transport` (from `tinywallet-crypto`) | `wallet::transport::OpenHumanTransport` | Reads the Solana blockhash through the wallet's failover-aware RPC layer. |
+| `ProxyPolicy` (`apply`) | `RuntimeProxyPolicy` | Applies the runtime proxy configuration to the tool's HTTP client. |
## RPC / controllers
@@ -58,61 +68,55 @@ Namespace `x402` (method form `openhuman.x402_<function>`), registered via
## Agent tool
-`X402RequestTool` (`x402_request`, `PermissionLevel::Write`) makes an HTTP
-request to an x402-payable endpoint, always expecting a payment challenge: it
-sends the initial request, requires a `PAYMENT-REQUIRED`/`X-PAYMENT-REQUIRED`
-header on a 402, builds and signs the payment via `handle_402_and_pay`,
-records a `Pending` ledger entry, retries with `PAYMENT-SIGNATURE`, and
-updates the ledger to `Settled`/`Failed` based on the retry's outcome and the
-decoded `PAYMENT-RESPONSE` settlement header. This differs from the generic
-`http_request` tool (`crates/openhuman-core/src/tools/impl/network/http_request.rs`),
-which handles a 402 only as a silent fallback for any endpoint.
+`x402_request` is `tinywallet_x402::tools::X402RequestTool`, built by
+`request_tool()` and registered in `tools/ops.rs`. See the crate for its
+behavior: it sends the initial request, requires a `PAYMENT-REQUIRED` /
+`X-PAYMENT-REQUIRED` header on a 402, pays via `handle_402_and_pay`, records a
+`Pending` ledger entry, retries with `PAYMENT-SIGNATURE`, and settles the entry
+from the retry's outcome and the `PAYMENT-RESPONSE` header. It differs from the
+generic `http_request` tool (`tools/impl/network/http_request.rs`), which
+handles a 402 only as a silent fallback.
## Persistence
-- `{workspace_dir}/x402/payments.jsonl`: one JSON `PaymentRecord` per
- line, appended on every pending/settled/failed payment. Loaded into memory
- at `PaymentLedger::new` (via `init_ledger`) and held in the process-global
- `GLOBAL_LEDGER`, guarded by a `parking_lot::Mutex`.
-- Budget enforcement (`SpendingBudget`, defaults: 1 USDC per request, 10
- USDC per day, 100 USDC per month, in atomic units) is checked against the
- in-memory ledger before a payment is built. Daily and monthly totals sum
- the `Settled` records for the current UTC day / calendar month. The session
- total reported by `get_summary` counts records whose `session_id` equals the
- ledger's `x402-<uuid>` boot id; it is not a cap, and both writers currently
- store an empty `session_id`, so it reads as zero. `init_ledger` seeds the limits
- from `OPENHUMAN_X402_PER_REQUEST_MAX` / `OPENHUMAN_X402_DAILY_MAX` /
- `OPENHUMAN_X402_MONTHLY_MAX` when set; `update_budget` changes them for the
- running process only and does not rewrite historical records.
+- `{workspace_dir}/x402/payments.jsonl`: one JSON `PaymentRecord` per line,
+ appended on every pending/settled/failed payment (`tinywallet_x402::ledger`).
+ Loaded into memory by `init_ledger` and held in the crate's process-wide
+ ledger.
+- Budget enforcement (defaults: 1 USDC per request, 10 USDC per day, 100 USDC
+ per month, in atomic units) is checked against the in-memory ledger before a
+ payment is built. Daily and monthly totals sum the `Settled` records for the
+ current UTC day / calendar month. The session total reported by `get_summary`
+ counts records whose `session_id` equals the ledger's `x402-<uuid>` boot id; it
+ is not a cap, and both writers currently store an empty `session_id`, so it
+ reads as zero. `init_ledger` seeds the limits from
+ `OPENHUMAN_X402_PER_REQUEST_MAX` / `OPENHUMAN_X402_DAILY_MAX` /
+ `OPENHUMAN_X402_MONTHLY_MAX` when set (`budget.rs`); `update_budget` changes
+ them for the running process only and does not rewrite historical records.
## Dependencies
-- `crate::web3::wallet::secret_material`: fetches the encrypted mnemonic and
- derivation path for the chain being paid on (`WalletChain::Evm` /
- `WalletChain::Solana`).
-- `crate::security::encryption::rpc::decrypt_secret`: decrypts the mnemonic
- in this process just long enough to hand it to the signer.
-- `crate::modules::wallet::{derive_account, sign_message}`: the actual
- derivation and signing happen inside the loaded `tinywallet` native module
- over a confidential bus call; this binary never derives a private key or
- holds one. Only the decrypted mnemonic passes through this process, in
- the `tinywallet_bus::wire::SecretMaterial` handed to those calls.
-- `tinywallet_bus::wire::SecretMaterial`, `tinywallet_bus::Chain`: the wire
- types crossing that seam.
-- `crate::config::rpc::load_config_with_timeout`: config needed to reach the
- wallet module and decrypt the mnemonic.
+- `tinywallet-x402` (features `wire`, `pay`, `ledger`, `tools`): everything above.
+- `crate::web3::wallet::secret_material`: the encrypted mnemonic and derivation
+ path for the chain being paid on.
+- `crate::security::encryption::rpc::decrypt_secret`: decrypts the mnemonic in
+ this process just long enough to hand it to the module.
+- `crate::modules::wallet::{derive_account, sign_message}`: derivation and
+ signing happen inside the loaded `tinywallet` native module over a
+ confidential bus call; this binary never derives a private key.
+- `crate::config::rpc::load_config_with_timeout` and
+ `config::apply_runtime_proxy_to_builder`.
## Used by
-- `crates/openhuman-core/src/tools/impl/network/http_request.rs`: `handle_x402_payment`, gated `#[cfg(feature = "web3")]`, is the
- 402 fallback path any HTTP tool call can hit. It calls
- `x402::handle_402_and_pay` and records to the same ledger via
- `x402::store::with_ledger_mut`.
-- `crates/openhuman-core/src/tools/ops.rs`: registers `X402RequestTool` as an
- agent tool.
-- `crates/openhuman-core/src/core/all.rs` (around line 710): wires
- `all_x402_registered_controllers` into the controller registry under
- `DomainGroup::Web3`.
+- `crates/openhuman-core/src/tools/impl/network/http_request.rs`:
+ `handle_x402_payment`, gated `#[cfg(feature = "web3")]`, is the 402 fallback
+ path any HTTP tool call can hit. It calls `x402::handle_402_and_pay` and
+ records to the same ledger via `x402::store::with_ledger_mut`.
+- `crates/openhuman-core/src/tools/ops.rs`: registers `x402::request_tool()` as
+ an agent tool.
+- `crates/openhuman-core/src/core/all.rs`: wires `all_x402_registered_controllers`
+ into the controller registry under `DomainGroup::Web3`.
- `crates/openhuman-core/src/core/runtime/bootstrap.rs`: calls
`init_ledger(&workspace_dir, &x402_session)` at boot, itself runtime-gated on
`DomainGroup::Web3`.
diff --git a/crates/openhuman-core/src/web3/x402/budget.rs b/crates/openhuman-core/src/web3/x402/budget.rs
new file mode 100644
index 0000000000..a7555c38a3
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/budget.rs
@@ -0,0 +1,52 @@
+//! Where the x402 spending limits come from.
+//!
+//! The crate owns the budget type and its defaults (1 / 10 / 100 USDC per
+//! request / day / month); which limits a process runs with is host policy, so
+//! the `OPENHUMAN_X402_*` environment overrides are read here.
+
+use log::debug;
+use tinywallet_x402::ledger::SpendingBudget;
+
+const LOG_PREFIX: &str = "[x402::budget]";
+
+/// Override for [`SpendingBudget::per_request_max_atomic`].
+const ENV_PER_REQUEST_MAX: &str = "OPENHUMAN_X402_PER_REQUEST_MAX";
+/// Override for [`SpendingBudget::daily_max_atomic`].
+const ENV_DAILY_MAX: &str = "OPENHUMAN_X402_DAILY_MAX";
+/// Override for [`SpendingBudget::monthly_max_atomic`].
+const ENV_MONTHLY_MAX: &str = "OPENHUMAN_X402_MONTHLY_MAX";
+
+/// The crate's default budget with the process environment's overrides applied.
+pub(crate) fn budget_from_env() -> SpendingBudget {
+ budget_from(|name| std::env::var(name).ok())
+}
+
+/// [`budget_from_env`] over an arbitrary variable lookup, so the override rules
+/// are testable without touching the process environment.
+///
+/// A value that is not a base-10 `u64` is ignored and the default stays.
+pub(crate) fn budget_from(get: impl Fn(&str) -> Option<String>) -> SpendingBudget {
+ let mut budget = SpendingBudget::default();
+ let apply = |name: &str, label: &str, slot: &mut u64| {
+ if let Some(n) = get(name).and_then(|v| v.parse::<u64>().ok()) {
+ debug!("{LOG_PREFIX} env override {label}={n}");
+ *slot = n;
+ }
+ };
+ apply(
+ ENV_PER_REQUEST_MAX,
+ "per_request_max",
+ &mut budget.per_request_max_atomic,
+ );
+ apply(ENV_DAILY_MAX, "daily_max", &mut budget.daily_max_atomic);
+ apply(
+ ENV_MONTHLY_MAX,
+ "monthly_max",
+ &mut budget.monthly_max_atomic,
+ );
+ budget
+}
+
+#[cfg(test)]
+#[path = "budget_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/budget_tests.rs b/crates/openhuman-core/src/web3/x402/budget_tests.rs
new file mode 100644
index 0000000000..8b8046cf26
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/budget_tests.rs
@@ -0,0 +1,42 @@
+use super::*;
+
+fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
+ move |name| {
+ pairs
+ .iter()
+ .find(|(k, _)| *k == name)
+ .map(|(_, v)| (*v).to_string())
+ }
+}
+
+#[test]
+fn no_overrides_gives_the_crate_defaults() {
+ assert_eq!(budget_from(env(&[])), SpendingBudget::default());
+}
+
+#[test]
+fn each_variable_overrides_only_its_own_limit() {
+ let budget = budget_from(env(&[
+ ("OPENHUMAN_X402_PER_REQUEST_MAX", "111"),
+ ("OPENHUMAN_X402_MONTHLY_MAX", "333"),
+ ]));
+ assert_eq!(budget.per_request_max_atomic, 111);
+ assert_eq!(
+ budget.daily_max_atomic,
+ SpendingBudget::default().daily_max_atomic
+ );
+ assert_eq!(budget.monthly_max_atomic, 333);
+
+ let budget = budget_from(env(&[("OPENHUMAN_X402_DAILY_MAX", "222")]));
+ assert_eq!(budget.daily_max_atomic, 222);
+}
+
+#[test]
+fn a_value_that_is_not_a_u64_is_ignored() {
+ let budget = budget_from(env(&[
+ ("OPENHUMAN_X402_PER_REQUEST_MAX", "one usdc"),
+ ("OPENHUMAN_X402_DAILY_MAX", "-5"),
+ ("OPENHUMAN_X402_MONTHLY_MAX", ""),
+ ]));
+ assert_eq!(budget, SpendingBudget::default());
+}
diff --git a/crates/openhuman-core/src/web3/x402/mod.rs b/crates/openhuman-core/src/web3/x402/mod.rs
index 45d2b2f1c5..c4efb9921f 100644
--- a/crates/openhuman-core/src/web3/x402/mod.rs
+++ b/crates/openhuman-core/src/web3/x402/mod.rs
@@ -1,13 +1,23 @@
//! x402 — HTTP 402 payment protocol for machine-payable APIs.
//!
-//! Intercepts HTTP 402 responses carrying a `PAYMENT-REQUIRED` header,
-//! constructs a Solana SPL token payment (typically USDC), signs it with the
-//! wallet's ed25519 key, and retries the request with the payment proof in a
-//! `PAYMENT-SIGNATURE` header. The facilitator co-signs as fee payer and
-//! broadcasts, so the client never needs SOL for gas.
+//! The protocol lives in the `tinywallet-x402` crate (`vendor/tinywallet`): the
+//! 402 client, the EVM EIP-3009 and Solana SPL payment builders, the spending
+//! ledger and the `x402_request` agent tool. This module is the host side of
+//! it — what OpenHuman adds and nothing more:
+//!
+//! - [`seams`] — the wallet ([`seams::WalletPaymentSigner`]: keyring secret,
+//! decrypt, the wallet module) and outbound-proxy policy
+//! ([`seams::RuntimeProxyPolicy`]) the crate is handed. The mnemonic never
+//! enters the crate.
+//! - `schemas` — the `x402_*` RPC controllers (namespace strings are wire
+//! contracts).
+//! - [`budget`] — where the spending limits come from (defaults plus the
+//! `OPENHUMAN_X402_*` environment overrides).
+//! - this file — a facade re-exporting the crate so existing callers
+//! (`http_request`, boot, the tool registry) keep their paths.
//!
//! Protocol spec: <https://x402.org> / coinbase/x402 (v2).
-
+//!
//! ## Compile-time gate (`web3` feature)
//!
//! `pub mod x402;` is ALWAYS compiled — it is a facade. The real payment
@@ -21,35 +31,70 @@
//! referenced when off and need not be stubbed.
#[cfg(feature = "web3")]
-mod ops;
+pub(crate) mod budget;
#[cfg(feature = "web3")]
mod schemas;
#[cfg(feature = "web3")]
-pub(crate) mod store;
-#[cfg(feature = "web3")]
-pub mod tools;
-#[cfg(feature = "web3")]
-mod types;
+pub(crate) mod seams;
-#[cfg(all(test, feature = "web3"))]
-mod x402_tests;
-
-#[cfg(feature = "web3")]
-pub use ops::{
- handle_402, handle_402_and_pay, try_paid_request, X402Client, X402Error, X402PaymentResult,
-};
#[cfg(feature = "web3")]
pub use schemas::all_controller_schemas as all_x402_controller_schemas;
#[cfg(feature = "web3")]
pub use schemas::all_registered_controllers as all_x402_registered_controllers;
#[cfg(feature = "web3")]
-pub use store::{init_global as init_ledger, PaymentRecord, PaymentStatus, SpendingBudget};
+pub use tinywallet_x402::ledger::{PaymentRecord, PaymentStatus, SpendingBudget};
#[cfg(feature = "web3")]
-pub use types::{
+pub use tinywallet_x402::protocol::{handle_402, X402Client, X402Error, X402PaymentResult};
+#[cfg(feature = "web3")]
+pub use tinywallet_x402::wire::{
EvmAuthorization, EvmPaymentProof, PaymentChain, PaymentPayload, PaymentProof, PaymentRequired,
PaymentRequirements, ResourceInfo, SettlementResponse, SolanaPaymentProof,
};
+/// The process-wide spending ledger, as the crate exposes it.
+#[cfg(feature = "web3")]
+pub(crate) mod store {
+ pub use tinywallet_x402::ledger::{with_ledger, with_ledger_mut};
+}
+
+/// Open the spending ledger under `workspace_dir` for this process.
+///
+/// The limits are [`budget::budget_from_env`]: the crate's defaults with any
+/// `OPENHUMAN_X402_*` override applied.
+#[cfg(feature = "web3")]
+pub fn init_ledger(workspace_dir: &std::path::Path, session_id: &str) {
+ tinywallet_x402::ledger::init_global(workspace_dir, session_id, budget::budget_from_env());
+}
+
+/// End-to-end 402 handler for the HTTP tool layer: parse the challenge, check
+/// the budget, and have the wallet build and sign the payment.
+#[cfg(feature = "web3")]
+pub async fn handle_402_and_pay(
+ response_headers: &reqwest::header::HeaderMap,
+ request_url: &str,
+) -> Result<X402PaymentResult, X402Error> {
+ tinywallet_x402::protocol::handle_402_and_pay(&seams::payments(), response_headers, request_url)
+ .await
+}
+
+/// Build a payment for `requirement` and return the encoded header value, for
+/// callers that manage their own HTTP layer.
+#[cfg(feature = "web3")]
+pub async fn try_paid_request(
+ challenge: &PaymentRequired,
+ requirement: &PaymentRequirements,
+) -> Result<String, X402Error> {
+ tinywallet_x402::protocol::pay_challenge_header(&seams::payments(), challenge, requirement)
+ .await
+}
+
+/// The `x402_request` agent tool, wired to OpenHuman's wallet, chain
+/// transport and proxy policy.
+#[cfg(feature = "web3")]
+pub fn request_tool() -> tinywallet_x402::tools::X402RequestTool {
+ seams::request_tool()
+}
+
// ---------------------------------------------------------------------------
// Disabled facade — compiled only when the `web3` feature is OFF.
// ---------------------------------------------------------------------------
diff --git a/crates/openhuman-core/src/web3/x402/ops.rs b/crates/openhuman-core/src/web3/x402/ops.rs
deleted file mode 100644
index 822d99fece..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops.rs
+++ /dev/null
@@ -1,34 +0,0 @@
-//! x402 client operations — parse 402 challenges, build payment transactions
-//! (Solana SPL or EVM ERC-20), sign, and retry with proof.
-//!
-//! Solana `exact` scheme layout:
-//! 1. ComputeBudget::SetComputeUnitLimit
-//! 2. ComputeBudget::SetComputeUnitPrice
-//! 3. SPL Token `TransferChecked`
-//! 4. (optional) SPL Memo with `extra.memo` or random nonce
-//!
-//! EVM `exact` scheme:
-//! EIP-3009 `transferWithAuthorization` signed by the wallet's EVM key.
-//! The facilitator submits the signed authorization on-chain.
-//!
-//! ## Module layout
-//!
-//! - [`errors`] — the client's error type.
-//! - [`headers`] — parsing the challenge / settlement headers.
-//! - [`solana_payment`] — Solana `exact` scheme transaction construction.
-//! - [`evm_payment`] — EVM EIP-3009 payment construction.
-//! - [`client`] — the high-level client and the `handle_402*` entry points.
-
-mod client;
-mod errors;
-mod evm_payment;
-mod headers;
-mod solana_payment;
-
-pub use client::{handle_402, handle_402_and_pay, try_paid_request, X402Client, X402PaymentResult};
-pub use errors::X402Error;
-
-#[cfg(test)]
-pub(crate) use evm_payment::build_evm_payment_with_signer;
-
-const LOG_PREFIX: &str = "[x402]";
diff --git a/crates/openhuman-core/src/web3/x402/ops/client.rs b/crates/openhuman-core/src/web3/x402/ops/client.rs
deleted file mode 100644
index 0f18bb5eee..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops/client.rs
+++ /dev/null
@@ -1,326 +0,0 @@
-//! The high-level x402 client (intercept 402, pay, retry) and the
-//! lower-level `handle_402` / `handle_402_and_pay` entry points the HTTP
-//! tool layer drives directly.
-
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-use log::{debug, warn};
-use reqwest::header::HeaderMap;
-
-use super::super::types::*;
-use super::errors::X402Error;
-use super::evm_payment::build_evm_payment;
-use super::headers::{parse_402_headers, parse_settlement_response};
-use super::solana_payment::{b58_to_32, build_solana_payment};
-use super::LOG_PREFIX;
-
-/// High-level x402 client. Wraps a `reqwest::Client` and knows how to
-/// intercept 402 responses, build Solana payments, and retry transparently.
-pub struct X402Client {
- http: reqwest::Client,
-}
-
-impl X402Client {
- pub fn new(http: reqwest::Client) -> Self {
- Self { http }
- }
-
- /// Send a request. If the server returns 402 with a `PAYMENT-REQUIRED`
- /// header, attempt to pay using the wallet's Solana key and retry.
- ///
- /// The signing key is no longer a parameter: derivation and signing both
- /// happen inside the loaded wallet module, so there is no key for a caller
- /// to hold or pass. The wallet's phrase is resolved here and handed over on
- /// a confidential call.
- ///
- /// `max_amount` — optional ceiling in atomic units; rejects challenges above
- /// this to prevent runaway spending.
- pub async fn try_paid_request(
- &self,
- request: reqwest::Request,
- max_amount: Option<u64>,
- ) -> Result<reqwest::Response, X402Error> {
- let method = request.method().clone();
- let url = request.url().clone();
- let headers = request.headers().clone();
- let body_bytes = request
- .body()
- .and_then(|b| b.as_bytes())
- .map(|b| b.to_vec());
-
- debug!("{LOG_PREFIX} initial request {} {}", method, url);
- let response = self
- .http
- .execute(request)
- .await
- .map_err(X402Error::Transport)?;
-
- if response.status() != reqwest::StatusCode::PAYMENT_REQUIRED {
- return Ok(response);
- }
-
- let challenge = parse_402_headers(response.headers())?;
- debug!(
- "{LOG_PREFIX} got 402 challenge version={} accepts={}",
- challenge.x402_version,
- challenge.accepts.len()
- );
-
- let (requirement, chain) = challenge
- .best_exact_requirement()
- .ok_or_else(|| X402Error::NoPaymentOption)?;
-
- let amount: u64 = requirement.amount.parse().map_err(|e| {
- X402Error::Protocol(format!("invalid amount '{}': {e}", requirement.amount))
- })?;
-
- if let Some(cap) = max_amount {
- if amount > cap {
- return Err(X402Error::AmountExceedsCap {
- requested: amount,
- cap,
- });
- }
- }
-
- debug!(
- "{LOG_PREFIX} paying {} atomic units of {} to {} chain={:?} (fee_payer={:?})",
- amount,
- requirement.asset,
- requirement.pay_to,
- chain,
- requirement.fee_payer_pubkey(),
- );
-
- let payment = match chain {
- PaymentChain::Solana => {
- let (config, signing_secret, our_pubkey) = wallet_signer().await?;
- build_solana_payment(
- &config,
- &signing_secret,
- our_pubkey,
- &challenge,
- requirement,
- )
- .await?
- }
- PaymentChain::Evm => build_evm_payment(&challenge, requirement).await?,
- };
- let encoded = B64.encode(serde_json::to_string(&payment).unwrap());
-
- let mut retry_req = self.http.request(method, url);
- for (key, value) in headers.iter() {
- retry_req = retry_req.header(key, value);
- }
- retry_req = retry_req.header(HEADER_PAYMENT_SIGNATURE, &encoded);
- if let Some(body) = body_bytes {
- retry_req = retry_req.body(body);
- }
-
- debug!("{LOG_PREFIX} retrying with payment proof");
- let paid_response = retry_req.send().await.map_err(X402Error::Transport)?;
-
- if let Some(receipt_header) = paid_response.headers().get(HEADER_PAYMENT_RESPONSE) {
- match parse_settlement_response(receipt_header.to_str().unwrap_or("")) {
- Ok(receipt) => {
- if receipt.success {
- debug!(
- "{LOG_PREFIX} payment settled tx={} network={}",
- receipt.transaction, receipt.network
- );
- } else {
- warn!(
- "{LOG_PREFIX} payment settlement failed reason={:?}",
- receipt.error_reason
- );
- }
- }
- Err(e) => warn!("{LOG_PREFIX} could not parse settlement response: {e}"),
- }
- }
-
- Ok(paid_response)
- }
-}
-
-/// Standalone entry point — parse a 402 response's headers and return the
-/// challenge with the index of the best payment option and its chain family.
-pub fn handle_402(
- headers: &HeaderMap,
-) -> Result<(PaymentRequired, usize, PaymentChain), X402Error> {
- let challenge = parse_402_headers(headers)?;
- // Prefer Solana (lower fees, faster finality), fall back to EVM
- let (idx, chain) = challenge
- .accepts
- .iter()
- .enumerate()
- .find(|(_, r)| r.scheme == "exact" && r.network.starts_with("solana:"))
- .map(|(i, _)| (i, PaymentChain::Solana))
- .or_else(|| {
- challenge
- .accepts
- .iter()
- .enumerate()
- .find(|(_, r)| r.scheme == "exact" && r.network.starts_with("eip155:"))
- .map(|(i, _)| (i, PaymentChain::Evm))
- })
- .ok_or(X402Error::NoPaymentOption)?;
- Ok((challenge, idx, chain))
-}
-
-/// Build a payment and return the encoded header value ready to attach.
-/// Separated from `try_paid_request` so callers that manage their own HTTP
-/// layer can still use the payment construction.
-pub async fn try_paid_request(
- challenge: &PaymentRequired,
- requirement: &PaymentRequirements,
-) -> Result<String, X402Error> {
- let chain = if requirement.network.starts_with("eip155:") {
- PaymentChain::Evm
- } else {
- PaymentChain::Solana
- };
- let payment = match chain {
- PaymentChain::Solana => {
- let (config, signing_secret, our_pubkey) = wallet_signer().await?;
- build_solana_payment(&config, &signing_secret, our_pubkey, challenge, requirement)
- .await?
- }
- PaymentChain::Evm => build_evm_payment(challenge, requirement).await?,
- };
- let json = serde_json::to_string(&payment)
- .map_err(|e| X402Error::Protocol(format!("serialize payment: {e}")))?;
- Ok(B64.encode(json))
-}
-
-/// Result of a successful x402 payment retry — the payment header value and
-/// metadata for the ledger.
-pub struct X402PaymentResult {
- pub header_value: String,
- pub amount_atomic: u64,
- pub asset: String,
- pub recipient: String,
- pub network: String,
- pub url: String,
-}
-
-/// End-to-end 402 handler for the HTTP tool layer. Given a 402 response's
-/// headers and the original URL:
-///
-/// 1. Parses the PAYMENT-REQUIRED challenge
-/// 2. Checks the spending budget
-/// 3. Derives the wallet's signing key (Solana preferred, EVM fallback)
-/// 4. Builds a partially-signed payment transaction
-/// 5. Returns the encoded PAYMENT-SIGNATURE header value
-///
-/// The caller retries the original request with this header attached and
-/// records the payment outcome in the ledger.
-pub async fn handle_402_and_pay(
- response_headers: &HeaderMap,
- request_url: &str,
-) -> Result<X402PaymentResult, X402Error> {
- let (challenge, idx, chain) = handle_402(response_headers)?;
- let requirement = &challenge.accepts[idx];
-
- let amount: u64 = requirement.amount.parse().map_err(|e| {
- X402Error::Protocol(format!("invalid amount '{}': {e}", requirement.amount))
- })?;
-
- let budget_check =
- super::super::store::with_ledger(|l| l.check_budget(amount)).map_err(X402Error::Wallet)?;
-
- match budget_check {
- super::super::store::BudgetCheck::Allowed => {}
- super::super::store::BudgetCheck::ExceedsPerRequest { requested, cap } => {
- return Err(X402Error::AmountExceedsCap { requested, cap });
- }
- super::super::store::BudgetCheck::ExceedsDailyBudget { current, cap } => {
- return Err(X402Error::BudgetExceeded {
- period: "daily",
- current,
- cap,
- });
- }
- super::super::store::BudgetCheck::ExceedsMonthlyBudget { current, cap } => {
- return Err(X402Error::BudgetExceeded {
- period: "monthly",
- current,
- cap,
- });
- }
- }
-
- debug!(
- "{LOG_PREFIX} paying {} atomic {} to {} for {} chain={:?}",
- amount, requirement.asset, requirement.pay_to, request_url, chain
- );
-
- let payment = match chain {
- PaymentChain::Solana => {
- let (config, signing_secret, our_pubkey) = wallet_signer().await?;
- build_solana_payment(
- &config,
- &signing_secret,
- our_pubkey,
- &challenge,
- requirement,
- )
- .await?
- }
- PaymentChain::Evm => build_evm_payment(&challenge, requirement).await?,
- };
-
- let header_value = serde_json::to_string(&payment)
- .map(|json| B64.encode(json))
- .map_err(|e| X402Error::Protocol(format!("serialize payment: {e}")))?;
-
- Ok(X402PaymentResult {
- header_value,
- amount_atomic: amount,
- asset: requirement.asset.clone(),
- recipient: requirement.pay_to.clone(),
- network: requirement.network.clone(),
- url: request_url.to_string(),
- })
-}
-
-/// Derive the wallet's Solana ed25519 signing key from the encrypted mnemonic.
-/// The phrase to sign a payment with, its config, and the wallet's public key.
-///
-/// Derivation happens in the loaded wallet module; this process never holds the
-/// private key. The phrase is handed over on a confidential call, and only to a
-/// module that has proved it is an artifact this build pinned.
-async fn wallet_signer() -> Result<
- (
- crate::config::Config,
- tinywallet_bus::wire::SecretMaterial,
- [u8; 32],
- ),
- X402Error,
-> {
- use crate::web3::wallet::WalletChain;
-
- let secret = crate::web3::wallet::secret_material(WalletChain::Solana)
- .await
- .map_err(|e| X402Error::Wallet(format!("wallet secret: {e}")))?;
-
- let config = crate::config::rpc::load_config_with_timeout()
- .await
- .map_err(|e| X402Error::Wallet(format!("load config: {e}")))?;
-
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
- .await
- .map_err(|e| X402Error::Wallet(format!("decrypt mnemonic: {e}")))?
- .value;
-
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Solana,
- };
- let account = crate::modules::wallet::derive_account(&config, &signing_secret)
- .await
- .map_err(|e| X402Error::Wallet(format!("derive account: {e}")))?;
- let pubkey = b58_to_32(&account.address)?;
- Ok((config, signing_secret, pubkey))
-}
diff --git a/crates/openhuman-core/src/web3/x402/ops/errors.rs b/crates/openhuman-core/src/web3/x402/ops/errors.rs
deleted file mode 100644
index 9a710be237..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops/errors.rs
+++ /dev/null
@@ -1,51 +0,0 @@
-//! The x402 client's error type.
-
-#[derive(Debug)]
-pub enum X402Error {
- Transport(reqwest::Error),
- NoPaymentHeader,
- NoPaymentOption,
- AmountExceedsCap {
- requested: u64,
- cap: u64,
- },
- BudgetExceeded {
- period: &'static str,
- current: u64,
- cap: u64,
- },
- Protocol(String),
- Wallet(String),
-}
-
-impl std::fmt::Display for X402Error {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- match self {
- Self::Transport(e) => write!(f, "x402 transport: {e}"),
- Self::NoPaymentHeader => write!(f, "402 response missing PAYMENT-REQUIRED header"),
- Self::NoPaymentOption => {
- write!(
- f,
- "no supported payment option (Solana exact or EVM exact) in 402 challenge"
- )
- }
- Self::AmountExceedsCap { requested, cap } => {
- write!(f, "x402 amount {requested} exceeds per-request cap {cap}")
- }
- Self::BudgetExceeded {
- period,
- current,
- cap,
- } => {
- write!(
- f,
- "x402 {period} budget exceeded: {current}/{cap} atomic units"
- )
- }
- Self::Protocol(msg) => write!(f, "x402 protocol: {msg}"),
- Self::Wallet(msg) => write!(f, "x402 wallet: {msg}"),
- }
- }
-}
-
-impl std::error::Error for X402Error {}
diff --git a/crates/openhuman-core/src/web3/x402/ops/evm_payment.rs b/crates/openhuman-core/src/web3/x402/ops/evm_payment.rs
deleted file mode 100644
index 0a287d82a7..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops/evm_payment.rs
+++ /dev/null
@@ -1,292 +0,0 @@
-//! EVM `exact` scheme payment construction: EIP-3009
-//! `transferWithAuthorization`, signed over its EIP-712 digest by the
-//! wallet's EVM key. The facilitator submits the signed authorization
-//! on-chain.
-
-use log::debug;
-use sha2::{Digest, Sha256};
-
-use super::super::types::*;
-use super::errors::X402Error;
-use super::LOG_PREFIX;
-
-/// Build an EVM payment using EIP-3009 `transferWithAuthorization`.
-/// Signs the typed data with the wallet's EVM key and returns the proof
-/// for the facilitator to submit on-chain.
-pub(super) async fn build_evm_payment(
- challenge: &PaymentRequired,
- req: &PaymentRequirements,
-) -> Result<PaymentPayload, X402Error> {
- let (config, signing_secret, from_address) = evm_signer().await?;
- let authorization = evm_payment_authorization(&from_address, req)?;
-
- // Signed in the wallet module over the prehashed EIP-712 digest. This
- // process never holds the EVM key.
- let signature = crate::modules::wallet::sign_message(
- &config,
- &signing_secret,
- &authorization.digest,
- tinywallet_bus::wire::Scheme::Secp256k1Prehash,
- )
- .await
- .map_err(|e| X402Error::Wallet(format!("sign EIP-3009: {e}")))?;
- let tinywallet_bus::wire::Signature::Secp256k1 {
- rs_hex,
- recovery_id,
- } = signature
- else {
- return Err(X402Error::Wallet(
- "the wallet module returned a non-secp256k1 signature".to_string(),
- ));
- };
- let rs = hex::decode(&rs_hex)
- .map_err(|e| X402Error::Wallet(format!("invalid signature hex: {e}")))?;
- if rs.len() != 64 {
- return Err(X402Error::Wallet(
- "the wallet module returned a malformed signature".to_string(),
- ));
- }
- let mut sig_bytes = [0u8; 65];
- sig_bytes[..64].copy_from_slice(&rs);
- sig_bytes[64] = recovery_id
- .checked_add(27)
- .ok_or_else(|| X402Error::Wallet("recovery id out of range".to_string()))?;
-
- evm_payment_payload(&authorization, sig_bytes, &from_address, challenge, req)
-}
-
-/// The EIP-712 digest to sign, and the fields the payload needs alongside it.
-///
-/// Split out from signing so that production (which signs in the wallet module)
-/// and the tests (which sign locally, to check the construction against a fixed
-/// vector) share one implementation of the part that can be wrong. Only *who
-/// holds the key* differs between them.
-pub(crate) struct EvmPaymentAuthorization {
- /// The 32-byte EIP-712 digest.
- pub digest: [u8; 32],
- /// The EIP-3009 nonce, echoed into the payload.
- pub nonce: [u8; 32],
- valid_after_secs: u64,
- valid_before_secs: u64,
-}
-
-/// Compute the EIP-3009 authorization and its EIP-712 digest.
-pub(crate) fn evm_payment_authorization(
- from_address: &str,
- req: &PaymentRequirements,
-) -> Result<EvmPaymentAuthorization, X402Error> {
- use tinywallet_bus::eip712;
-
- let chain_id = req
- .evm_chain_id()
- .ok_or_else(|| X402Error::Protocol(format!("not an EVM network: {}", req.network)))?;
-
- let amount = eip712::u256_from_decimal(&req.amount)
- .map_err(|e| X402Error::Protocol(format!("invalid amount '{}': {e}", req.amount)))?;
-
- let from_bytes = evm_address_bytes(from_address)?;
- let pay_to = evm_address_bytes(&req.pay_to)?;
- let token_address = evm_address_bytes(&req.asset)?;
-
- // EIP-3009 parameters
- let valid_after = eip712::u256_from_u64(0);
- let valid_before_secs = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_secs()
- .saturating_add(req.max_timeout_seconds);
- let valid_before = eip712::u256_from_u64(valid_before_secs);
-
- // Random nonce for EIP-3009
- let nonce = {
- let mut hasher = Sha256::new();
- let ts = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- hasher.update(ts.to_le_bytes());
- hasher.update(std::process::id().to_le_bytes());
- let hash: [u8; 32] = hasher.finalize().into();
- hash
- };
-
- // EIP-712 typed data for `transferWithAuthorization`
- let domain_name = req
- .extra
- .as_ref()
- .and_then(|e| e.name.as_deref())
- .unwrap_or("USD Coin");
- let domain_version = req
- .extra
- .as_ref()
- .and_then(|e| e.version.as_deref())
- .unwrap_or("2");
- let domain_separator =
- eip712::domain_separator(token_address, chain_id, domain_name, domain_version);
- let struct_hash = eip712::transfer_with_authorization_hash(
- from_bytes,
- pay_to,
- amount,
- valid_after,
- valid_before,
- nonce,
- );
- let digest = eip712::signing_digest(domain_separator, struct_hash);
-
- Ok(EvmPaymentAuthorization {
- digest,
- nonce,
- valid_after_secs: 0,
- valid_before_secs,
- })
-}
-
-/// Assemble the payload from an authorization and its signature.
-///
-/// An EIP-712 signature is `r ‖ s ‖ v` where `v` is the recovery id offset by
-/// 27 — not EIP-155's chain-mixed `v`, because typed data is not a transaction.
-pub(crate) fn evm_payment_payload(
- authorization: &EvmPaymentAuthorization,
- sig_bytes: [u8; 65],
- from_address: &str,
- challenge: &PaymentRequired,
- req: &PaymentRequirements,
-) -> Result<PaymentPayload, X402Error> {
- let chain_id = req
- .evm_chain_id()
- .ok_or_else(|| X402Error::Protocol(format!("not an EVM network: {}", req.network)))?;
- let valid_after = authorization.valid_after_secs;
- let valid_before = authorization.valid_before_secs;
- let nonce = authorization.nonce;
-
- let sig_hex = format!("0x{}", hex::encode(sig_bytes));
- let nonce_hex = format!("0x{}", hex::encode(nonce));
-
- debug!(
- "{LOG_PREFIX} built EVM payment chain_id={chain_id} amount={} asset={} from={} to={}",
- req.amount, req.asset, from_address, req.pay_to
- );
-
- Ok(PaymentPayload {
- x402_version: X402_VERSION,
- resource: Some(challenge.resource.clone()),
- accepted: req.clone(),
- payload: PaymentProof::Evm(EvmPaymentProof {
- signature: sig_hex,
- authorization: EvmAuthorization {
- from: from_address.to_string(),
- to: req.pay_to.clone(),
- value: req.amount.clone(),
- valid_after: valid_after.to_string(),
- valid_before: valid_before.to_string(),
- nonce: nonce_hex,
- },
- }),
- extensions: serde_json::Map::new(),
- })
-}
-
-/// Resolve the EVM account an x402 payment will be signed as.
-///
-/// Returns the config, the [`SecretMaterial`](tinywallet_bus::wire::SecretMaterial)
-/// the signing calls take, and the checksummed address that material controls.
-///
-/// # Where the key is, and where it is not
-///
-/// **No private key is derived in this process.** The address comes back from
-/// `modules::wallet::derive_account` — a confidential call into the loaded
-/// `tinywallet` module, which derives, answers with public data only, and wipes
-/// its copy of the phrase before returning. The signature is produced the same
-/// way, by `modules::wallet::sign_message`. This binary links no derivation
-/// stack at all: it takes `tinywallet-bus`, the wire contract, and `key` is one
-/// of the gates that deliberately stayed in the root crate.
-///
-/// What *does* live in this process is the decrypted **mnemonic**, held in the
-/// returned `SecretMaterial` for as long as a caller holds it and sent across
-/// the bus on each confidential call. That is the exposure to reason about
-/// here; a derived private key is not.
-///
-/// Deriving the address rather than assuming one is what makes an x402 payment
-/// signed by exactly the account the wallet reports.
-pub(super) async fn evm_signer() -> Result<
- (
- crate::config::Config,
- tinywallet_bus::wire::SecretMaterial,
- String,
- ),
- X402Error,
-> {
- use crate::web3::wallet::WalletChain;
-
- let secret = crate::web3::wallet::secret_material(WalletChain::Evm)
- .await
- .map_err(|e| X402Error::Wallet(format!("wallet secret: {e}")))?;
-
- let config = crate::config::rpc::load_config_with_timeout()
- .await
- .map_err(|e| X402Error::Wallet(format!("load config: {e}")))?;
-
- let mnemonic =
- crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
- .await
- .map_err(|e| X402Error::Wallet(format!("decrypt mnemonic: {e}")))?
- .value;
-
- let signing_secret = tinywallet_bus::wire::SecretMaterial {
- mnemonic,
- derivation_path: secret.derivation_path.clone(),
- chain: tinywallet_bus::Chain::Evm,
- };
- let account = crate::modules::wallet::derive_account(&config, &signing_secret)
- .await
- .map_err(|e| X402Error::Wallet(format!("derive EVM signer: {e}")))?;
-
- Ok((config, signing_secret, account.address))
-}
-
-/// Sign an EIP-712 digest locally. Test-only.
-///
-/// Production signs in the wallet module; this exists so the payment
-/// construction can be checked against a fixed vector without a broker. It is
-/// the only remaining local use of a private key in this domain, and it is
-/// compiled out of the shipped binary.
-#[cfg(test)]
-pub(crate) fn sign_evm_digest_locally(
- secret: &[u8],
- digest: &[u8; 32],
-) -> Result<[u8; 65], X402Error> {
- let key = k256::ecdsa::SigningKey::from_slice(secret)
- .map_err(|_| X402Error::Wallet("derived EVM key is unusable".to_string()))?;
- let (signature, recovery_id) = key
- .sign_prehash_recoverable(digest)
- .map_err(|e| X402Error::Wallet(format!("EVM sign EIP-3009: {e}")))?;
- let mut sig_bytes = [0u8; 65];
- sig_bytes[..64].copy_from_slice(&signature.to_bytes());
- sig_bytes[64] = recovery_id.to_byte() + 27;
- Ok(sig_bytes)
-}
-
-/// The construction the tests drive: authorize, sign locally, assemble.
-#[cfg(test)]
-pub(crate) fn build_evm_payment_with_signer(
- secret: &[u8],
- from_address: &str,
- challenge: &PaymentRequired,
- req: &PaymentRequirements,
-) -> Result<PaymentPayload, X402Error> {
- let authorization = evm_payment_authorization(from_address, req)?;
- let sig_bytes = sign_evm_digest_locally(secret, &authorization.digest)?;
- evm_payment_payload(&authorization, sig_bytes, from_address, challenge, req)
-}
-
-/// The 20 raw bytes of an EVM address.
-fn evm_address_bytes(address: &str) -> Result<[u8; 20], X402Error> {
- let validated = tinywallet_bus::address::evm::validate(address)
- .map_err(|e| X402Error::Protocol(format!("invalid EVM address '{address}': {e}")))?;
- let body = validated.strip_prefix("0x").unwrap_or(&validated);
- let decoded = hex::decode(body)
- .map_err(|_| X402Error::Protocol(format!("non-hex EVM address '{address}'")))?;
- decoded
- .try_into()
- .map_err(|_| X402Error::Protocol(format!("truncated EVM address '{address}'")))
-}
diff --git a/crates/openhuman-core/src/web3/x402/ops/headers.rs b/crates/openhuman-core/src/web3/x402/ops/headers.rs
deleted file mode 100644
index 658888b574..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops/headers.rs
+++ /dev/null
@@ -1,39 +0,0 @@
-//! Parsing the `PAYMENT-REQUIRED` challenge and `PAYMENT-RESPONSE` settlement
-//! headers, both base64-encoded JSON.
-
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-use log::warn;
-use reqwest::header::HeaderMap;
-
-use super::super::types::*;
-use super::errors::X402Error;
-use super::LOG_PREFIX;
-
-pub(super) fn parse_402_headers(headers: &HeaderMap) -> Result<PaymentRequired, X402Error> {
- let raw = headers
- .get(HEADER_PAYMENT_REQUIRED)
- .or_else(|| headers.get(HEADER_PAYMENT_REQUIRED_V1))
- .ok_or(X402Error::NoPaymentHeader)?;
- let b64_str = raw.to_str().map_err(|e| {
- X402Error::Protocol(format!("PAYMENT-REQUIRED header not valid UTF-8: {e}"))
- })?;
- let json_bytes = B64
- .decode(b64_str.trim())
- .map_err(|e| X402Error::Protocol(format!("PAYMENT-REQUIRED base64 decode: {e}")))?;
- let challenge: PaymentRequired = serde_json::from_slice(&json_bytes)
- .map_err(|e| X402Error::Protocol(format!("PAYMENT-REQUIRED JSON parse: {e}")))?;
- if challenge.x402_version != X402_VERSION {
- warn!(
- "{LOG_PREFIX} unexpected x402 version {} (expected {X402_VERSION})",
- challenge.x402_version
- );
- }
- Ok(challenge)
-}
-
-pub(super) fn parse_settlement_response(b64_str: &str) -> Result<SettlementResponse, String> {
- let json_bytes = B64
- .decode(b64_str.trim())
- .map_err(|e| format!("PAYMENT-RESPONSE base64 decode: {e}"))?;
- serde_json::from_slice(&json_bytes).map_err(|e| format!("PAYMENT-RESPONSE JSON parse: {e}"))
-}
diff --git a/crates/openhuman-core/src/web3/x402/ops/solana_payment.rs b/crates/openhuman-core/src/web3/x402/ops/solana_payment.rs
deleted file mode 100644
index f0e5abe725..0000000000
--- a/crates/openhuman-core/src/web3/x402/ops/solana_payment.rs
+++ /dev/null
@@ -1,336 +0,0 @@
-//! Solana `exact` scheme payment construction: a partially-signed legacy
-//! transaction carrying ComputeBudget + SPL `TransferChecked` (+ optional
-//! Memo) instructions, encoded by hand — no `solana-sdk` dependency.
-//!
-//! Layout:
-//! account_keys[0] = fee_payer (facilitator) — signer, writable
-//! account_keys[1] = our_pubkey (transfer authority) — signer, writable
-//! account_keys[2] = src_ata — writable
-//! account_keys[3] = dst_ata — writable
-//! account_keys[4] = mint — readonly
-//! account_keys[5] = token_program — readonly
-//! account_keys[6] = compute_budget_program — readonly
-//! account_keys[7] = memo_program — readonly (if memo present)
-//!
-//! Instructions:
-//! 0. SetComputeUnitLimit(DEFAULT_COMPUTE_UNITS)
-//! 1. SetComputeUnitPrice(DEFAULT_COMPUTE_UNIT_PRICE)
-//! 2. TransferChecked { amount, decimals=6 }
-//! 3. Memo (if extra.memo set, otherwise random 16-byte hex nonce)
-
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-use log::debug;
-use sha2::{Digest, Sha256};
-
-use super::super::types::*;
-use super::errors::X402Error;
-use super::LOG_PREFIX;
-
-/// Reasonable compute budget defaults for a single SPL TransferChecked.
-const DEFAULT_COMPUTE_UNITS: u32 = 50_000;
-const DEFAULT_COMPUTE_UNIT_PRICE: u64 = 1000; // micro-lamports per CU
-
-/// Build a partially-signed Solana transaction for the `exact` scheme.
-pub(super) async fn build_solana_payment(
- config: &crate::config::Config,
- signing_secret: &tinywallet_bus::wire::SecretMaterial,
- our_pubkey: [u8; 32],
- challenge: &PaymentRequired,
- req: &PaymentRequirements,
-) -> Result<PaymentPayload, X402Error> {
- let amount: u64 = req
- .amount
- .parse()
- .map_err(|e| X402Error::Protocol(format!("invalid amount '{}': {e}", req.amount)))?;
-
- let fee_payer = req
- .fee_payer_pubkey()
- .ok_or_else(|| X402Error::Protocol("no fee_payer in payment requirements".into()))?;
- let fee_payer_bytes = b58_to_32(fee_payer)?;
- let pay_to_bytes = b58_to_32(&req.pay_to)?;
- let mint_bytes = b58_to_32(&req.asset)?;
-
- let token_program = b58_to_32(SPL_TOKEN_PROGRAM)?;
- let compute_budget = b58_to_32(COMPUTE_BUDGET_PROGRAM)?;
- let memo_program = b58_to_32(SPL_MEMO_PROGRAM)?;
-
- let src_ata = derive_ata(&our_pubkey, &mint_bytes, &token_program)?;
- let dst_ata = derive_ata(&pay_to_bytes, &mint_bytes, &token_program)?;
-
- let memo_data = req
- .memo_value()
- .map(|m| m.as_bytes().to_vec())
- .unwrap_or_else(random_memo_nonce);
-
- // -- account keys (order matters) --
- let account_keys: Vec<[u8; 32]> = vec![
- fee_payer_bytes, // 0: fee payer (signer, writable)
- our_pubkey, // 1: transfer authority (signer, writable)
- src_ata, // 2: source ATA (writable)
- dst_ata, // 3: destination ATA (writable)
- mint_bytes, // 4: mint (readonly)
- token_program, // 5: SPL Token program (readonly)
- compute_budget, // 6: Compute Budget program (readonly)
- memo_program, // 7: SPL Memo program (readonly)
- ];
-
- // header: [num_required_sigs, num_readonly_signed, num_readonly_unsigned]
- // 2 signers (fee_payer + us), 0 readonly signed, 4 readonly unsigned
- // (mint, token_program, compute_budget, memo_program)
- let header = [2u8, 0u8, 4u8];
-
- // -- instructions --
- let set_cu_limit = build_set_compute_unit_limit(6, DEFAULT_COMPUTE_UNITS);
- let set_cu_price = build_set_compute_unit_price(6, DEFAULT_COMPUTE_UNIT_PRICE);
- let transfer_checked = build_transfer_checked(
- 5, // token_program index
- 2, // src_ata index
- 4, // mint index
- 3, // dst_ata index
- 1, // authority (our_pubkey) index
- amount, 6, // USDC decimals
- );
- let memo = build_memo(7, &memo_data);
-
- let instructions = vec![set_cu_limit, set_cu_price, transfer_checked, memo];
-
- // -- fetch recent blockhash --
- let blockhash = fetch_recent_blockhash_for_x402().await?;
-
- // -- encode message --
- let message = encode_legacy_message(&header, &account_keys, &blockhash, &instructions);
-
- // -- build wire: 2 signature slots, sign only ours (index 1) --
- let mut wire = Vec::with_capacity(1 + 128 + message.len());
- wire.extend(encode_shortvec(2)); // 2 required signatures
- wire.extend([0u8; 64]); // slot 0: fee_payer (left zeroed for facilitator)
-
- // Signed in the module: the phrase goes over a confidential call and the
- // private key is never assembled in this process.
- let signature = crate::modules::wallet::sign_message(
- config,
- signing_secret,
- &message,
- tinywallet_bus::wire::Scheme::Ed25519,
- )
- .await
- .map_err(|e| X402Error::Wallet(format!("sign payment: {e}")))?;
- let tinywallet_bus::wire::Signature::Ed25519 { signature_hex } = signature else {
- return Err(X402Error::Wallet(
- "the wallet module returned a non-ed25519 signature".to_string(),
- ));
- };
- let sig_bytes = hex_to_32_bytes_64(&signature_hex)?;
- wire.extend(sig_bytes); // slot 1: our signature
- wire.extend(&message);
-
- let tx_b64 = B64.encode(&wire);
- debug!(
- "{LOG_PREFIX} built payment tx {} bytes, amount={amount} asset={}",
- wire.len(),
- req.asset
- );
-
- Ok(PaymentPayload {
- x402_version: X402_VERSION,
- resource: Some(challenge.resource.clone()),
- accepted: req.clone(),
- payload: PaymentProof::Solana(SolanaPaymentProof {
- transaction: tx_b64,
- }),
- extensions: serde_json::Map::new(),
- })
-}
-
-// ---------------------------------------------------------------------------
-// Solana wire-format helpers (mirrors wallet/chains/solana.rs primitives)
-// ---------------------------------------------------------------------------
-
-pub(super) fn b58_to_32(addr: &str) -> Result<[u8; 32], X402Error> {
- let v = bs58::decode(addr.trim())
- .into_vec()
- .map_err(|e| X402Error::Protocol(format!("invalid base58 '{addr}': {e}")))?;
- if v.len() != 32 {
- return Err(X402Error::Protocol(format!(
- "expected 32-byte key, got {} for '{addr}'",
- v.len()
- )));
- }
- let mut out = [0u8; 32];
- out.copy_from_slice(&v);
- Ok(out)
-}
-
-fn derive_ata(
- owner: &[u8; 32],
- mint: &[u8; 32],
- token_program: &[u8; 32],
-) -> Result<[u8; 32], X402Error> {
- let ata_program = b58_to_32("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL")?;
- for bump in (0u8..=255).rev() {
- let mut hasher = Sha256::new();
- hasher.update(owner);
- hasher.update(token_program);
- hasher.update(mint);
- hasher.update([bump]);
- hasher.update(ata_program);
- hasher.update(b"ProgramDerivedAddress");
- let candidate: [u8; 32] = hasher.finalize().into();
- if curve25519_dalek::edwards::CompressedEdwardsY(candidate)
- .decompress()
- .is_none()
- {
- return Ok(candidate);
- }
- }
- Err(X402Error::Protocol("ATA PDA derivation failed".into()))
-}
-
-fn encode_shortvec(value: u16) -> Vec<u8> {
- let mut out = Vec::new();
- let mut v = value as u32;
- loop {
- let mut byte = (v & 0x7f) as u8;
- v >>= 7;
- if v == 0 {
- out.push(byte);
- return out;
- }
- byte |= 0x80;
- out.push(byte);
- }
-}
-
-struct Instruction {
- program_id_index: u8,
- accounts: Vec<u8>,
- data: Vec<u8>,
-}
-
-fn build_set_compute_unit_limit(program_idx: u8, units: u32) -> Instruction {
- let mut data = vec![2u8]; // discriminator
- data.extend(units.to_le_bytes());
- Instruction {
- program_id_index: program_idx,
- accounts: vec![],
- data,
- }
-}
-
-fn build_set_compute_unit_price(program_idx: u8, micro_lamports: u64) -> Instruction {
- let mut data = vec![3u8]; // discriminator
- data.extend(micro_lamports.to_le_bytes());
- Instruction {
- program_id_index: program_idx,
- accounts: vec![],
- data,
- }
-}
-
-fn build_transfer_checked(
- token_program_idx: u8,
- src_idx: u8,
- mint_idx: u8,
- dst_idx: u8,
- authority_idx: u8,
- amount: u64,
- decimals: u8,
-) -> Instruction {
- let mut data = vec![12u8]; // SPL Token: TransferChecked = 12
- data.extend(amount.to_le_bytes());
- data.push(decimals);
- Instruction {
- program_id_index: token_program_idx,
- accounts: vec![src_idx, mint_idx, dst_idx, authority_idx],
- data,
- }
-}
-
-fn build_memo(program_idx: u8, memo_data: &[u8]) -> Instruction {
- Instruction {
- program_id_index: program_idx,
- accounts: vec![],
- data: memo_data.to_vec(),
- }
-}
-
-fn encode_instruction(ins: &Instruction) -> Vec<u8> {
- let mut out = Vec::new();
- out.push(ins.program_id_index);
- out.extend(encode_shortvec(ins.accounts.len() as u16));
- out.extend(&ins.accounts);
- out.extend(encode_shortvec(ins.data.len() as u16));
- out.extend(&ins.data);
- out
-}
-
-fn encode_legacy_message(
- header: &[u8; 3],
- account_keys: &[[u8; 32]],
- recent_blockhash: &[u8; 32],
- instructions: &[Instruction],
-) -> Vec<u8> {
- let mut out = Vec::new();
- out.extend(header);
- out.extend(encode_shortvec(account_keys.len() as u16));
- for key in account_keys {
- out.extend(key);
- }
- out.extend(recent_blockhash);
- out.extend(encode_shortvec(instructions.len() as u16));
- for ins in instructions {
- out.extend(encode_instruction(ins));
- }
- out
-}
-
-fn random_memo_nonce() -> Vec<u8> {
- use std::time::{SystemTime, UNIX_EPOCH};
- let ts = SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .unwrap_or_default()
- .as_nanos();
- let mut hasher = Sha256::new();
- hasher.update(ts.to_le_bytes());
- hasher.update(std::process::id().to_le_bytes());
- let hash: [u8; 32] = hasher.finalize().into();
- hex::encode(&hash[..16]).into_bytes()
-}
-
-async fn fetch_recent_blockhash_for_x402() -> Result<[u8; 32], X402Error> {
- use crate::web3::wallet::WalletChain;
-
- #[derive(serde::Deserialize)]
- struct BlockhashResponse {
- value: BlockhashValue,
- }
- #[derive(serde::Deserialize)]
- struct BlockhashValue {
- blockhash: String,
- }
-
- let result: BlockhashResponse = crate::web3::wallet::rpc::rpc_call(
- WalletChain::Solana,
- "getLatestBlockhash",
- serde_json::json!([{"commitment": "finalized"}]),
- )
- .await
- .map_err(|e| X402Error::Wallet(format!("fetch blockhash: {e}")))?;
-
- b58_to_32(&result.value.blockhash)
-}
-
-/// Decode a 64-byte signature returned as lowercase hex by the wallet module.
-fn hex_to_32_bytes_64(value: &str) -> Result<[u8; 64], X402Error> {
- if value.len() != 128 {
- return Err(X402Error::Wallet(
- "the wallet module returned a malformed signature".to_string(),
- ));
- }
- let mut out = [0u8; 64];
- for (index, slot) in out.iter_mut().enumerate() {
- *slot = u8::from_str_radix(&value[index * 2..index * 2 + 2], 16)
- .map_err(|e| X402Error::Wallet(format!("invalid signature hex: {e}")))?;
- }
- Ok(out)
-}
diff --git a/crates/openhuman-core/src/web3/x402/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rs
new file mode 100644
index 0000000000..85e0c94cb8
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/seams.rs
@@ -0,0 +1,185 @@
+//! The host side of the `tinywallet-x402` seams.
+//!
+//! The crate never sees a mnemonic, a config or a proxy setting. It is handed:
+//!
+//! - a [`PaymentSigner`]: [`WalletPaymentSigner`] resolves the wallet's
+//! encrypted secret from the keyring state, decrypts it with the configured
+//! key, and asks the loaded `tinywallet` module to derive the account and sign.
+//! The decrypted phrase lives only for the length of one confidential call;
+//! what crosses back to the crate is an address and finished signatures.
+//! - a `Transport`: [`OpenHumanTransport`](crate::web3::wallet::transport::OpenHumanTransport),
+//! the failover-aware RPC adapter the wallet already uses, for the Solana
+//! blockhash.
+//! - a [`ProxyPolicy`]: [`RuntimeProxyPolicy`] applies the runtime proxy
+//! configuration to the tool's HTTP client.
+//!
+//! Every `Err(String)` these return is the text a user sees, prefixed exactly as
+//! the payment flow did before it moved into the crate (`wallet secret: …`,
+//! `load config: …`, `decrypt mnemonic: …`, `derive account: …`).
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use log::debug;
+use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme};
+use tinywallet_x402::protocol::ProxyPolicy;
+use tinywallet_x402::tools::X402RequestTool;
+use tinywallet_x402::wire::PaymentChain;
+
+use crate::web3::wallet::transport::OpenHumanTransport;
+use crate::web3::wallet::WalletChain;
+
+const LOG_PREFIX: &str = "[x402::seams]";
+
+/// The wallet as x402 signs with it: keyring secret, decrypt, wallet module.
+#[derive(Debug, Clone, Copy, Default)]
+pub(crate) struct WalletPaymentSigner;
+
+/// The runtime proxy configuration, applied to x402's outbound HTTP.
+#[derive(Debug, Clone, Copy, Default)]
+pub(crate) struct RuntimeProxyPolicy;
+
+/// The wallet chain a payment chain is signed as.
+fn wallet_chain(chain: PaymentChain) -> WalletChain {
+ match chain {
+ PaymentChain::Solana => WalletChain::Solana,
+ PaymentChain::Evm => WalletChain::Evm,
+ }
+}
+
+/// The bus chain the wallet module derives for.
+fn bus_chain(chain: PaymentChain) -> tinywallet_bus::Chain {
+ match chain {
+ PaymentChain::Solana => tinywallet_bus::Chain::Solana,
+ PaymentChain::Evm => tinywallet_bus::Chain::Evm,
+ }
+}
+
+/// Resolve the phrase to sign with: the config, and the wallet's decrypted
+/// mnemonic packaged for a confidential call.
+///
+/// Derivation and signing both happen inside the loaded wallet module, so this
+/// process never holds a private key. The phrase is handed over on a
+/// confidential call, and only to a module that has proved it is an artifact this
+/// build pinned.
+async fn signing_secret(
+ chain: PaymentChain,
+) -> Result<(crate::config::Config, tinywallet_bus::wire::SecretMaterial), String> {
+ let secret = crate::web3::wallet::secret_material(wallet_chain(chain))
+ .await
+ .map_err(|e| format!("wallet secret: {e}"))?;
+
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|e| format!("load config: {e}"))?;
+
+ let mnemonic =
+ crate::security::encryption::rpc::decrypt_secret(&config, &secret.encrypted_mnemonic)
+ .await
+ .map_err(|e| format!("decrypt mnemonic: {e}"))?
+ .value;
+
+ Ok((
+ config,
+ tinywallet_bus::wire::SecretMaterial {
+ mnemonic,
+ derivation_path: secret.derivation_path.clone(),
+ chain: bus_chain(chain),
+ },
+ ))
+}
+
+#[async_trait]
+impl PaymentSigner for WalletPaymentSigner {
+ async fn account(&self, chain: PaymentChain) -> Result<PaymentAccount, String> {
+ debug!("{LOG_PREFIX} account chain={chain:?}");
+ let (config, secret) = signing_secret(chain).await?;
+ let account = crate::modules::wallet::derive_account(&config, &secret)
+ .await
+ .map_err(|e| match chain {
+ PaymentChain::Solana => format!("derive account: {e}"),
+ PaymentChain::Evm => format!("derive EVM signer: {e}"),
+ })?;
+ // The module answers with the address only; the crate decodes a Solana
+ // public key from it.
+ Ok(PaymentAccount {
+ address: account.address,
+ pubkey: None,
+ })
+ }
+
+ async fn sign(
+ &self,
+ chain: PaymentChain,
+ message: &[u8],
+ scheme: SignScheme,
+ ) -> Result<Vec<u8>, String> {
+ debug!(
+ "{LOG_PREFIX} sign chain={chain:?} scheme={scheme:?} bytes={}",
+ message.len()
+ );
+ let (config, secret) = signing_secret(chain).await?;
+ let wire_scheme = match scheme {
+ SignScheme::Ed25519 => tinywallet_bus::wire::Scheme::Ed25519,
+ SignScheme::Secp256k1Digest => tinywallet_bus::wire::Scheme::Secp256k1Prehash,
+ };
+ // Signed in the module; the private key is never assembled here.
+ let signature =
+ crate::modules::wallet::sign_message(&config, &secret, message, wire_scheme)
+ .await
+ .map_err(|e| e.to_string())?;
+ signature_bytes(signature)
+ }
+}
+
+/// The raw bytes the crate expects from the module's signature: 64 for ed25519,
+/// `r ‖ s ‖ recovery_id` (65) for secp256k1.
+fn signature_bytes(signature: tinywallet_bus::wire::Signature) -> Result<Vec<u8>, String> {
+ match signature {
+ tinywallet_bus::wire::Signature::Ed25519 { signature_hex } => {
+ hex::decode(&signature_hex).map_err(|e| format!("invalid signature hex: {e}"))
+ }
+ tinywallet_bus::wire::Signature::Secp256k1 {
+ rs_hex,
+ recovery_id,
+ } => {
+ let mut bytes =
+ hex::decode(&rs_hex).map_err(|e| format!("invalid signature hex: {e}"))?;
+ if bytes.len() != 64 {
+ return Err("the wallet module returned a malformed signature".to_string());
+ }
+ bytes.push(recovery_id);
+ Ok(bytes)
+ }
+ // `Signature` is non-exhaustive; a scheme this build has never heard of
+ // cannot be paid with.
+ _ => Err("the wallet module returned an unsupported signature".to_string()),
+ }
+}
+
+impl ProxyPolicy for RuntimeProxyPolicy {
+ fn apply(&self, builder: reqwest::ClientBuilder, service: &str) -> reqwest::ClientBuilder {
+ crate::config::apply_runtime_proxy_to_builder(builder, service)
+ }
+}
+
+/// The crypto rail's payment builder, over OpenHuman's wallet and transport.
+pub(crate) fn payments() -> CryptoPayments {
+ CryptoPayments::new(
+ Arc::new(WalletPaymentSigner),
+ Arc::new(OpenHumanTransport::new()),
+ )
+}
+
+/// The `x402_request` tool, over the same seams.
+pub(crate) fn request_tool() -> X402RequestTool {
+ X402RequestTool::new(
+ Arc::new(WalletPaymentSigner),
+ Arc::new(OpenHumanTransport::new()),
+ Arc::new(RuntimeProxyPolicy),
+ )
+}
+
+#[cfg(test)]
+#[path = "seams_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/seams_tests.rs b/crates/openhuman-core/src/web3/x402/seams_tests.rs
new file mode 100644
index 0000000000..b727412d23
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/seams_tests.rs
@@ -0,0 +1,178 @@
+use super::*;
+
+use base64::Engine as _;
+use reqwest::header::{HeaderMap, HeaderValue};
+use tinywallet_bus::wire::Signature;
+use tinywallet_x402::protocol::{PaymentBuilder, X402Error};
+use tinywallet_x402::wire::{
+ PaymentExtra, PaymentRequired, PaymentRequirements, ResourceInfo, SOLANA_MAINNET_CAIP2,
+ USDC_MINT_MAINNET, X402_VERSION,
+};
+
+// ---------------------------------------------------------------------------
+// Signature decoding: what the wallet module returns, as bytes the crate takes
+// ---------------------------------------------------------------------------
+
+#[test]
+fn an_ed25519_signature_becomes_its_64_bytes() {
+ let bytes = signature_bytes(Signature::Ed25519 {
+ signature_hex: "ab".repeat(64),
+ })
+ .unwrap();
+ assert_eq!(bytes, vec![0xab; 64]);
+}
+
+#[test]
+fn a_secp256k1_signature_is_r_s_then_the_recovery_id() {
+ let bytes = signature_bytes(Signature::Secp256k1 {
+ rs_hex: "cd".repeat(64),
+ recovery_id: 1,
+ })
+ .unwrap();
+ assert_eq!(bytes.len(), 65);
+ assert_eq!(&bytes[..64], &[0xcd; 64][..]);
+ assert_eq!(bytes[64], 1);
+}
+
+#[test]
+fn a_signature_that_is_not_hex_is_rejected() {
+ let err = signature_bytes(Signature::Ed25519 {
+ signature_hex: "zz".into(),
+ })
+ .unwrap_err();
+ assert!(err.starts_with("invalid signature hex: "), "{err}");
+ let err = signature_bytes(Signature::Secp256k1 {
+ rs_hex: "zz".into(),
+ recovery_id: 0,
+ })
+ .unwrap_err();
+ assert!(err.starts_with("invalid signature hex: "), "{err}");
+}
+
+#[test]
+fn a_secp256k1_signature_of_the_wrong_length_is_malformed() {
+ let err = signature_bytes(Signature::Secp256k1 {
+ rs_hex: "cd".repeat(63),
+ recovery_id: 0,
+ })
+ .unwrap_err();
+ assert_eq!(err, "the wallet module returned a malformed signature");
+}
+
+#[test]
+fn payment_chains_map_onto_the_wallets_chains() {
+ assert!(matches!(
+ wallet_chain(PaymentChain::Solana),
+ WalletChain::Solana
+ ));
+ assert!(matches!(wallet_chain(PaymentChain::Evm), WalletChain::Evm));
+ assert_eq!(
+ bus_chain(PaymentChain::Solana),
+ tinywallet_bus::Chain::Solana
+ );
+ assert_eq!(bus_chain(PaymentChain::Evm), tinywallet_bus::Chain::Evm);
+}
+
+// ---------------------------------------------------------------------------
+// The seams compose into the crate's payment flow
+// ---------------------------------------------------------------------------
+
+#[test]
+fn the_proxy_policy_yields_a_buildable_client() {
+ let builder = RuntimeProxyPolicy.apply(reqwest::Client::builder(), "tool.x402_request");
+ assert!(builder.build().is_ok());
+}
+
+#[test]
+fn the_tool_is_built_from_the_host_seams() {
+ use tinytools::Tool;
+ assert_eq!(request_tool().name(), "x402_request");
+ assert_eq!(super::super::request_tool().name(), "x402_request");
+}
+
+fn solana_challenge_headers() -> HeaderMap {
+ let challenge = PaymentRequired {
+ x402_version: X402_VERSION,
+ error: None,
+ resource: ResourceInfo {
+ url: "https://x402.example.test/thing".into(),
+ description: None,
+ mime_type: None,
+ },
+ accepts: vec![PaymentRequirements {
+ scheme: "exact".into(),
+ network: SOLANA_MAINNET_CAIP2.into(),
+ amount: "10000".into(),
+ asset: USDC_MINT_MAINNET.into(),
+ pay_to: "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4".into(),
+ max_timeout_seconds: 60,
+ extra: Some(PaymentExtra {
+ fee_payer: Some("EwWqGE4ZFKLofuestmU4LDdK7XM1N4ALgdZccwYugwGd".into()),
+ memo: None,
+ name: None,
+ version: None,
+ }),
+ }],
+ extensions: serde_json::Map::new(),
+ };
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ "PAYMENT-REQUIRED",
+ HeaderValue::from_str(
+ &base64::engine::general_purpose::STANDARD
+ .encode(serde_json::to_vec(&challenge).unwrap()),
+ )
+ .unwrap(),
+ );
+ headers
+}
+
+/// With no wallet set up, the failure must surface from the *wallet seam* —
+/// proving the facade reached the crate's budget check, the crate reached its
+/// payment builder, and the builder reached the host signer — and read exactly
+/// as it did before the flow moved into the crate.
+#[tokio::test]
+async fn a_payment_reaches_the_host_wallet_through_the_crate() {
+ let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock();
+ let temp = tempfile::tempdir().unwrap();
+ let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp);
+ super::super::init_ledger(temp.path(), "seam-test");
+
+ let err =
+ super::super::handle_402_and_pay(&solana_challenge_headers(), "https://x402.example.test")
+ .await
+ .unwrap_err();
+
+ match err {
+ X402Error::Wallet(message) => {
+ assert!(message.starts_with("wallet secret: "), "{message}");
+ assert!(
+ message.contains(crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE),
+ "{message}"
+ );
+ }
+ other => panic!("expected a wallet error, got {other}"),
+ }
+}
+
+#[tokio::test]
+async fn the_signer_reports_a_missing_wallet_for_either_chain() {
+ let _wallet_lock = crate::web3::wallet::test_support::TEST_LOCK.lock();
+ let temp = tempfile::tempdir().unwrap();
+ let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp);
+
+ for chain in [PaymentChain::Solana, PaymentChain::Evm] {
+ let err = WalletPaymentSigner.account(chain).await.unwrap_err();
+ assert!(err.starts_with("wallet secret: "), "{err}");
+ let err = WalletPaymentSigner
+ .sign(chain, b"message", SignScheme::Ed25519)
+ .await
+ .unwrap_err();
+ assert!(err.starts_with("wallet secret: "), "{err}");
+ }
+}
+
+#[tokio::test]
+async fn the_payment_builder_is_object_safe_for_the_facade() {
+ let _builder: Box<dyn PaymentBuilder> = Box::new(payments());
+}
diff --git a/crates/openhuman-core/src/web3/x402/store.rs b/crates/openhuman-core/src/web3/x402/store.rs
deleted file mode 100644
index b7e20262a0..0000000000
--- a/crates/openhuman-core/src/web3/x402/store.rs
+++ /dev/null
@@ -1,325 +0,0 @@
-//! x402 payment ledger — append-only JSONL persistence for payment records
-//! with session/daily/monthly budget enforcement.
-
-use std::fs::{self, OpenOptions};
-use std::io::{BufRead, BufReader, Write};
-use std::path::{Path, PathBuf};
-
-use chrono::{DateTime, Datelike, Utc};
-use log::{debug, warn};
-use once_cell::sync::Lazy;
-use parking_lot::Mutex;
-use serde::{Deserialize, Serialize};
-
-const LOG_PREFIX: &str = "[x402::store]";
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentRecord {
- pub id: String,
- pub url: String,
- pub asset: String,
- pub amount_atomic: u64,
- pub amount_display: String,
- pub recipient: String,
- pub network: String,
- pub tx_signature: Option<String>,
- pub status: PaymentStatus,
- pub timestamp: DateTime<Utc>,
- pub session_id: String,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum PaymentStatus {
- Pending,
- Settled,
- Failed,
- Denied,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-#[derive(Default)]
-pub struct SpendingSummary {
- pub session_total_atomic: u64,
- pub daily_total_atomic: u64,
- pub monthly_total_atomic: u64,
- pub session_count: usize,
- pub daily_count: usize,
- pub monthly_count: usize,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SpendingBudget {
- pub per_request_max_atomic: u64,
- pub daily_max_atomic: u64,
- pub monthly_max_atomic: u64,
-}
-
-impl Default for SpendingBudget {
- fn default() -> Self {
- Self {
- // 1 USDC per request
- per_request_max_atomic: 1_000_000,
- // 10 USDC per day
- daily_max_atomic: 10_000_000,
- // 100 USDC per month
- monthly_max_atomic: 100_000_000,
- }
- }
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum BudgetCheck {
- Allowed,
- ExceedsPerRequest { requested: u64, cap: u64 },
- ExceedsDailyBudget { current: u64, cap: u64 },
- ExceedsMonthlyBudget { current: u64, cap: u64 },
-}
-
-pub struct PaymentLedger {
- records: Vec<PaymentRecord>,
- file_path: PathBuf,
- budget: SpendingBudget,
- session_id: String,
-}
-
-static GLOBAL_LEDGER: Lazy<Mutex<Option<PaymentLedger>>> = Lazy::new(|| Mutex::new(None));
-
-impl PaymentLedger {
- pub fn new(workspace_dir: &Path, session_id: &str, budget: SpendingBudget) -> Self {
- let file_path = workspace_dir.join("x402").join("payments.jsonl");
- let records = Self::load_from_disk(&file_path);
- debug!(
- "{LOG_PREFIX} loaded {} existing payment records from {}",
- records.len(),
- file_path.display()
- );
- Self {
- records,
- file_path,
- budget,
- session_id: session_id.to_string(),
- }
- }
-
- fn load_from_disk(path: &Path) -> Vec<PaymentRecord> {
- let file = match fs::File::open(path) {
- Ok(f) => f,
- Err(_) => return Vec::new(),
- };
- let reader = BufReader::new(file);
- let mut records = Vec::new();
- for line in reader.lines() {
- let line = match line {
- Ok(l) => l,
- Err(e) => {
- warn!("{LOG_PREFIX} read error: {e}");
- continue;
- }
- };
- if line.trim().is_empty() {
- continue;
- }
- match serde_json::from_str::<PaymentRecord>(&line) {
- Ok(r) => records.push(r),
- Err(e) => warn!("{LOG_PREFIX} corrupt record: {e}"),
- }
- }
- records
- }
-
- fn append_to_disk(&self, record: &PaymentRecord) {
- if let Some(parent) = self.file_path.parent() {
- if let Err(e) = fs::create_dir_all(parent) {
- warn!("{LOG_PREFIX} mkdir failed: {e}");
- return;
- }
- }
- let mut file = match OpenOptions::new()
- .create(true)
- .append(true)
- .open(&self.file_path)
- {
- Ok(f) => f,
- Err(e) => {
- warn!("{LOG_PREFIX} open failed: {e}");
- return;
- }
- };
- match serde_json::to_string(record) {
- Ok(json) => {
- if let Err(e) = writeln!(file, "{json}") {
- warn!("{LOG_PREFIX} write failed: {e}");
- }
- }
- Err(e) => warn!("{LOG_PREFIX} serialize failed: {e}"),
- }
- }
-
- pub fn check_budget(&self, amount: u64) -> BudgetCheck {
- if amount > self.budget.per_request_max_atomic {
- return BudgetCheck::ExceedsPerRequest {
- requested: amount,
- cap: self.budget.per_request_max_atomic,
- };
- }
-
- let now = Utc::now();
- let today = now.date_naive();
- let this_month = (now.year(), now.month());
-
- let daily: u64 = self
- .records
- .iter()
- .filter(|r| r.status == PaymentStatus::Settled && r.timestamp.date_naive() == today)
- .map(|r| r.amount_atomic)
- .sum();
-
- if daily.saturating_add(amount) > self.budget.daily_max_atomic {
- return BudgetCheck::ExceedsDailyBudget {
- current: daily,
- cap: self.budget.daily_max_atomic,
- };
- }
-
- let monthly: u64 = self
- .records
- .iter()
- .filter(|r| {
- r.status == PaymentStatus::Settled && {
- let ts = r.timestamp;
- (ts.year(), ts.month()) == this_month
- }
- })
- .map(|r| r.amount_atomic)
- .sum();
-
- if monthly.saturating_add(amount) > self.budget.monthly_max_atomic {
- return BudgetCheck::ExceedsMonthlyBudget {
- current: monthly,
- cap: self.budget.monthly_max_atomic,
- };
- }
-
- BudgetCheck::Allowed
- }
-
- pub fn record_payment(&mut self, record: PaymentRecord) {
- self.append_to_disk(&record);
- self.records.push(record);
- }
-
- pub fn summary(&self) -> SpendingSummary {
- let now = Utc::now();
- let today = now.date_naive();
- let this_month = (now.year(), now.month());
-
- let settled: Vec<&PaymentRecord> = self
- .records
- .iter()
- .filter(|r| r.status == PaymentStatus::Settled)
- .collect();
-
- let session: Vec<&&PaymentRecord> = settled
- .iter()
- .filter(|r| r.session_id == self.session_id)
- .collect();
-
- let daily: Vec<&&PaymentRecord> = settled
- .iter()
- .filter(|r| r.timestamp.date_naive() == today)
- .collect();
-
- let monthly: Vec<&&PaymentRecord> = settled
- .iter()
- .filter(|r| {
- let ts = r.timestamp;
- (ts.year(), ts.month()) == this_month
- })
- .collect();
-
- SpendingSummary {
- session_total_atomic: session.iter().map(|r| r.amount_atomic).sum(),
- daily_total_atomic: daily.iter().map(|r| r.amount_atomic).sum(),
- monthly_total_atomic: monthly.iter().map(|r| r.amount_atomic).sum(),
- session_count: session.len(),
- daily_count: daily.len(),
- monthly_count: monthly.len(),
- }
- }
-
- pub fn recent_payments(&self, limit: usize) -> Vec<PaymentRecord> {
- self.records.iter().rev().take(limit).cloned().collect()
- }
-
- pub fn budget(&self) -> &SpendingBudget {
- &self.budget
- }
-
- pub fn update_budget(&mut self, budget: SpendingBudget) {
- debug!(
- "{LOG_PREFIX} budget updated per_request={} daily={} monthly={}",
- budget.per_request_max_atomic, budget.daily_max_atomic, budget.monthly_max_atomic
- );
- self.budget = budget;
- }
-}
-
-pub fn init_global(workspace_dir: &Path, session_id: &str) {
- let budget = budget_from_env();
- let ledger = PaymentLedger::new(workspace_dir, session_id, budget);
- *GLOBAL_LEDGER.lock() = Some(ledger);
- debug!("{LOG_PREFIX} global ledger initialized");
-}
-
-fn budget_from_env() -> SpendingBudget {
- let mut budget = SpendingBudget::default();
- if let Ok(v) = std::env::var("OPENHUMAN_X402_PER_REQUEST_MAX") {
- if let Ok(n) = v.parse::<u64>() {
- debug!("{LOG_PREFIX} env override per_request_max={n}");
- budget.per_request_max_atomic = n;
- }
- }
- if let Ok(v) = std::env::var("OPENHUMAN_X402_DAILY_MAX") {
- if let Ok(n) = v.parse::<u64>() {
- debug!("{LOG_PREFIX} env override daily_max={n}");
- budget.daily_max_atomic = n;
- }
- }
- if let Ok(v) = std::env::var("OPENHUMAN_X402_MONTHLY_MAX") {
- if let Ok(n) = v.parse::<u64>() {
- debug!("{LOG_PREFIX} env override monthly_max={n}");
- budget.monthly_max_atomic = n;
- }
- }
- budget
-}
-
-pub fn with_ledger<F, R>(f: F) -> Result<R, String>
-where
- F: FnOnce(&PaymentLedger) -> R,
-{
- let guard = GLOBAL_LEDGER.lock();
- let ledger = guard
- .as_ref()
- .ok_or_else(|| "x402 payment ledger not initialized".to_string())?;
- Ok(f(ledger))
-}
-
-pub fn with_ledger_mut<F, R>(f: F) -> Result<R, String>
-where
- F: FnOnce(&mut PaymentLedger) -> R,
-{
- let mut guard = GLOBAL_LEDGER.lock();
- let ledger = guard
- .as_mut()
- .ok_or_else(|| "x402 payment ledger not initialized".to_string())?;
- Ok(f(ledger))
-}
-
-#[cfg(test)]
-#[path = "store_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/store_tests.rs b/crates/openhuman-core/src/web3/x402/store_tests.rs
deleted file mode 100644
index bc03c9b209..0000000000
--- a/crates/openhuman-core/src/web3/x402/store_tests.rs
+++ /dev/null
@@ -1,112 +0,0 @@
-use super::*;
-
-fn test_budget() -> SpendingBudget {
- SpendingBudget {
- per_request_max_atomic: 500_000,
- daily_max_atomic: 2_000_000,
- monthly_max_atomic: 10_000_000,
- }
-}
-
-const TEST_SESSION: &str = "test";
-
-fn make_record(amount: u64, status: PaymentStatus) -> PaymentRecord {
- PaymentRecord {
- id: uuid::Uuid::new_v4().to_string(),
- url: "https://api.example.com/data".into(),
- asset: "USDC".into(),
- amount_atomic: amount,
- amount_display: format!("{:.6} USDC", amount as f64 / 1_000_000.0),
- recipient: "RecipientPubkey".into(),
- network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into(),
- tx_signature: Some("sig123".into()),
- status,
- timestamp: Utc::now(),
- session_id: TEST_SESSION.into(),
- }
-}
-
-#[test]
-fn budget_check_allows_within_limits() {
- let ledger = PaymentLedger {
- records: vec![],
- file_path: PathBuf::from("/tmp/test-x402.jsonl"),
- budget: test_budget(),
- session_id: "test".into(),
- };
- assert_eq!(ledger.check_budget(100_000), BudgetCheck::Allowed);
-}
-
-#[test]
-fn budget_check_rejects_over_per_request() {
- let ledger = PaymentLedger {
- records: vec![],
- file_path: PathBuf::from("/tmp/test-x402.jsonl"),
- budget: test_budget(),
- session_id: "test".into(),
- };
- assert_eq!(
- ledger.check_budget(600_000),
- BudgetCheck::ExceedsPerRequest {
- requested: 600_000,
- cap: 500_000
- }
- );
-}
-
-#[test]
-fn budget_check_rejects_over_daily() {
- let mut ledger = PaymentLedger {
- records: vec![],
- file_path: PathBuf::from("/tmp/test-x402.jsonl"),
- budget: test_budget(),
- session_id: "test".into(),
- };
- ledger
- .records
- .push(make_record(1_800_000, PaymentStatus::Settled));
- assert_eq!(
- ledger.check_budget(400_000),
- BudgetCheck::ExceedsDailyBudget {
- current: 1_800_000,
- cap: 2_000_000
- }
- );
-}
-
-#[test]
-fn budget_check_ignores_failed_payments() {
- let mut ledger = PaymentLedger {
- records: vec![],
- file_path: PathBuf::from("/tmp/test-x402.jsonl"),
- budget: test_budget(),
- session_id: "test".into(),
- };
- ledger
- .records
- .push(make_record(1_800_000, PaymentStatus::Failed));
- assert_eq!(ledger.check_budget(400_000), BudgetCheck::Allowed);
-}
-
-#[test]
-fn summary_aggregates_correctly() {
- let mut ledger = PaymentLedger {
- records: vec![],
- file_path: PathBuf::from("/tmp/test-x402.jsonl"),
- budget: test_budget(),
- session_id: "test".into(),
- };
- ledger
- .records
- .push(make_record(100_000, PaymentStatus::Settled));
- ledger
- .records
- .push(make_record(200_000, PaymentStatus::Settled));
- ledger
- .records
- .push(make_record(50_000, PaymentStatus::Failed));
-
- let summary = ledger.summary();
- assert_eq!(summary.session_total_atomic, 300_000);
- assert_eq!(summary.session_count, 2);
-}
diff --git a/crates/openhuman-core/src/web3/x402/tools.rs b/crates/openhuman-core/src/web3/x402/tools.rs
deleted file mode 100644
index 8f84950fce..0000000000
--- a/crates/openhuman-core/src/web3/x402/tools.rs
+++ /dev/null
@@ -1,367 +0,0 @@
-//! Agent tool for making x402-paid HTTP requests.
-//!
-//! Unlike the general `http_request` tool (which silently handles 402s as a
-//! fallback), this tool is purpose-built for x402 endpoints: it always expects
-//! a payment challenge, surfaces pricing to the agent, and records the payment
-//! in the ledger.
-
-use async_trait::async_trait;
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-use log::debug;
-use serde_json::json;
-use std::time::Duration;
-
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-use super::store;
-use super::types::*;
-
-const LOG_PREFIX: &str = "[tool.x402_request]";
-const DEFAULT_TIMEOUT_SECS: u64 = 30;
-
-pub struct X402RequestTool;
-
-impl Default for X402RequestTool {
- fn default() -> Self {
- Self::new()
- }
-}
-
-impl X402RequestTool {
- pub fn new() -> Self {
- Self
- }
-}
-
-#[async_trait]
-impl Tool for X402RequestTool {
- fn exposure(&self) -> tinytools::ToolExposure {
- tinytools::ToolExposure::Deferred
- }
-
- fn name(&self) -> &str {
- "x402_request"
- }
-
- fn description(&self) -> &str {
- "Make an HTTP request to an x402-payable API endpoint. Automatically handles the \
- HTTP 402 payment challenge by signing a payment (EVM EIP-3009 on Base/Ethereum, or \
- Solana SPL transfer) with the wallet and retrying with the payment proof. \
- Returns the API response after payment. Use this for x402-enabled APIs like twit.sh. \
- The wallet must be set up with USDC on the target chain."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "url": {
- "type": "string",
- "description": "URL of the x402-payable API endpoint (e.g. https://x402.twit.sh/tweets/by/id?id=1110302988)"
- },
- "method": {
- "type": "string",
- "description": "HTTP method (default: GET)",
- "default": "GET",
- "enum": ["GET", "POST", "PUT", "DELETE", "PATCH"]
- },
- "headers": {
- "type": "object",
- "description": "Optional HTTP headers as key-value pairs",
- "default": {}
- },
- "body": {
- "type": "string",
- "description": "Optional request body (for POST/PUT/PATCH)"
- }
- },
- "required": ["url"]
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let url = match args.get("url").and_then(|v| v.as_str()) {
- Some(u) => u.to_string(),
- None => return Ok(ToolResult::error("Missing required 'url' parameter")),
- };
-
- let method_str = args.get("method").and_then(|v| v.as_str()).unwrap_or("GET");
- let method: reqwest::Method = match method_str.parse() {
- Ok(m) => m,
- Err(_) => {
- return Ok(ToolResult::error(format!(
- "Unsupported HTTP method: {method_str}"
- )))
- }
- };
-
- let headers = parse_header_args(args.get("headers"));
- let body = args.get("body").and_then(|v| v.as_str()).map(String::from);
-
- debug!("{LOG_PREFIX} requesting {method} {url}");
-
- // Step 1: Initial request to get the 402 challenge
- let client = match build_client() {
- Ok(c) => c,
- Err(e) => {
- return Ok(ToolResult::error(format!(
- "Failed to build HTTP client: {e}"
- )))
- }
- };
-
- let initial_response =
- match send_request(&client, &method, &url, &headers, body.as_deref()).await {
- Ok(r) => r,
- Err(e) => return Ok(ToolResult::error(format!("Initial request failed: {e}"))),
- };
-
- // If the response is not 402, return it directly
- if initial_response.status() != reqwest::StatusCode::PAYMENT_REQUIRED {
- let status = initial_response.status().as_u16();
- debug!("{LOG_PREFIX} got {status} (not 402), returning directly");
- return format_response(initial_response, &url).await;
- }
-
- // Step 2: Parse the 402 challenge
- let initial_headers = initial_response.headers().clone();
- if initial_headers.get(HEADER_PAYMENT_REQUIRED).is_none()
- && initial_headers.get(HEADER_PAYMENT_REQUIRED_V1).is_none()
- {
- return Ok(ToolResult::error(
- "Server returned 402 but without a PAYMENT-REQUIRED header — not an x402 endpoint",
- ));
- }
-
- debug!("{LOG_PREFIX} got 402 with PAYMENT-REQUIRED header, processing payment");
-
- // Step 3: Build and sign the payment
- let payment_result = match super::handle_402_and_pay(&initial_headers, &url).await {
- Ok(r) => r,
- Err(e) => {
- return Ok(ToolResult::error(format!("x402 payment failed: {e}")));
- }
- };
-
- let amount_display = format!(
- "{:.6} USDC",
- payment_result.amount_atomic as f64 / 1_000_000.0
- );
-
- debug!(
- "{LOG_PREFIX} payment built: {} to {} on {} for {}",
- amount_display, payment_result.recipient, payment_result.network, url
- );
-
- // Record the pending payment
- let record = store::PaymentRecord {
- id: uuid::Uuid::new_v4().to_string(),
- url: payment_result.url.clone(),
- asset: payment_result.asset.clone(),
- amount_atomic: payment_result.amount_atomic,
- amount_display: amount_display.clone(),
- recipient: payment_result.recipient.clone(),
- network: payment_result.network.clone(),
- tx_signature: None,
- status: store::PaymentStatus::Pending,
- timestamp: chrono::Utc::now(),
- session_id: String::new(),
- };
- let record_id = record.id.clone();
- let _ = store::with_ledger_mut(|l| l.record_payment(record));
-
- // Step 4: Retry with the payment signature
- let mut retry_headers = headers.clone();
- retry_headers.push((
- HEADER_PAYMENT_SIGNATURE.to_string(),
- payment_result.header_value,
- ));
-
- let paid_response =
- match send_request(&client, &method, &url, &retry_headers, body.as_deref()).await {
- Ok(r) => r,
- Err(e) => {
- let _ = store::with_ledger_mut(|l| {
- let updated = store::PaymentRecord {
- id: record_id,
- url: url.clone(),
- asset: payment_result.asset.clone(),
- amount_atomic: payment_result.amount_atomic,
- amount_display: amount_display.clone(),
- recipient: payment_result.recipient.clone(),
- network: payment_result.network.clone(),
- tx_signature: None,
- status: store::PaymentStatus::Failed,
- timestamp: chrono::Utc::now(),
- session_id: String::new(),
- };
- l.record_payment(updated);
- });
- return Ok(ToolResult::error(format!("x402 retry request failed: {e}")));
- }
- };
-
- // Step 5: Parse settlement response and update ledger
- let settled_status = if paid_response.status().is_success() {
- store::PaymentStatus::Settled
- } else {
- store::PaymentStatus::Failed
- };
-
- let tx_sig = paid_response
- .headers()
- .get(HEADER_PAYMENT_RESPONSE)
- .and_then(|v| v.to_str().ok())
- .and_then(|b64| B64.decode(b64).ok())
- .and_then(|bytes| serde_json::from_slice::<SettlementResponse>(&bytes).ok())
- .and_then(|r| {
- if r.success && !r.transaction.is_empty() {
- Some(r.transaction)
- } else {
- None
- }
- });
-
- let _ = store::with_ledger_mut(|l| {
- let updated = store::PaymentRecord {
- id: record_id.clone(),
- url: url.clone(),
- asset: payment_result.asset.clone(),
- amount_atomic: payment_result.amount_atomic,
- amount_display: amount_display.clone(),
- recipient: payment_result.recipient.clone(),
- network: payment_result.network.clone(),
- tx_signature: tx_sig.clone(),
- status: settled_status,
- timestamp: chrono::Utc::now(),
- session_id: String::new(),
- };
- l.record_payment(updated);
- });
-
- if settled_status == store::PaymentStatus::Settled {
- debug!(
- "{LOG_PREFIX} payment settled for {url} tx={:?} amount={}",
- tx_sig, amount_display
- );
- } else {
- log::warn!(
- "{LOG_PREFIX} payment failed for {url} status={}",
- paid_response.status()
- );
- }
-
- // Step 6: Format and return the response with payment metadata
- format_response_with_payment(
- paid_response,
- &url,
- &amount_display,
- &payment_result.network,
- tx_sig.as_deref(),
- )
- .await
- }
-}
-
-fn build_client() -> Result<reqwest::Client, reqwest::Error> {
- let builder = reqwest::Client::builder()
- .timeout(Duration::from_secs(DEFAULT_TIMEOUT_SECS))
- .connect_timeout(Duration::from_secs(10))
- .redirect(reqwest::redirect::Policy::limited(5));
- let builder = crate::config::apply_runtime_proxy_to_builder(builder, "tool.x402_request");
- builder.build()
-}
-
-fn parse_header_args(headers_val: Option<&serde_json::Value>) -> Vec<(String, String)> {
- let mut result = Vec::new();
- if let Some(obj) = headers_val.and_then(|v| v.as_object()) {
- for (key, value) in obj {
- if let Some(str_val) = value.as_str() {
- result.push((key.clone(), str_val.to_string()));
- }
- }
- }
- result
-}
-
-async fn send_request(
- client: &reqwest::Client,
- method: &reqwest::Method,
- url: &str,
- headers: &[(String, String)],
- body: Option<&str>,
-) -> Result<reqwest::Response, reqwest::Error> {
- let mut request = client.request(method.clone(), url);
- for (key, value) in headers {
- request = request.header(key, value);
- }
- if let Some(body_str) = body {
- request = request.body(body_str.to_string());
- }
- request.send().await
-}
-
-async fn format_response(response: reqwest::Response, url: &str) -> anyhow::Result<ToolResult> {
- let status = response.status().as_u16();
- let body = response.text().await.unwrap_or_default();
- let truncated = if body.len() > 50_000 {
- format!("{}…(truncated)", &body[..50_000])
- } else {
- body
- };
-
- Ok(ToolResult::success(format!(
- "HTTP {status} from {url}\n\n{truncated}"
- )))
-}
-
-async fn format_response_with_payment(
- response: reqwest::Response,
- url: &str,
- amount_display: &str,
- network: &str,
- tx_sig: Option<&str>,
-) -> anyhow::Result<ToolResult> {
- let status = response.status().as_u16();
- let body = response.text().await.unwrap_or_default();
- let truncated = if body.len() > 50_000 {
- format!("{}…(truncated)", &body[..50_000])
- } else {
- body
- };
-
- let chain_label = if network.starts_with("eip155:8453") {
- "Base"
- } else if network.starts_with("eip155:1") {
- "Ethereum"
- } else if network.starts_with("eip155:") {
- "EVM"
- } else if network.starts_with("solana:") {
- "Solana"
- } else {
- network
- };
-
- let tx_line = tx_sig
- .map(|sig| format!("\nTransaction: {sig}"))
- .unwrap_or_default();
-
- Ok(ToolResult::success(format!(
- "HTTP {status} from {url}\n\
- x402 payment: {amount_display} on {chain_label}{tx_line}\n\n\
- {truncated}"
- )))
-}
diff --git a/crates/openhuman-core/src/web3/x402/types.rs b/crates/openhuman-core/src/web3/x402/types.rs
deleted file mode 100644
index 0ee688d766..0000000000
--- a/crates/openhuman-core/src/web3/x402/types.rs
+++ /dev/null
@@ -1,237 +0,0 @@
-//! Wire types for the x402 protocol (v2).
-//!
-//! All header payloads are standard-base64-encoded JSON. Network identifiers
-//! use CAIP-2 format (e.g. `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`).
-
-use serde::{Deserialize, Serialize};
-
-// ---------------------------------------------------------------------------
-// Constants
-// ---------------------------------------------------------------------------
-
-pub const X402_VERSION: u8 = 2;
-
-pub const HEADER_PAYMENT_REQUIRED: &str = "PAYMENT-REQUIRED";
-pub const HEADER_PAYMENT_REQUIRED_V1: &str = "X-PAYMENT-REQUIRED";
-pub const HEADER_PAYMENT_SIGNATURE: &str = "PAYMENT-SIGNATURE";
-pub const HEADER_PAYMENT_SIGNATURE_V1: &str = "X-PAYMENT";
-pub const HEADER_PAYMENT_RESPONSE: &str = "PAYMENT-RESPONSE";
-
-pub const SOLANA_MAINNET_CAIP2: &str = "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp";
-pub const SOLANA_DEVNET_CAIP2: &str = "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1";
-
-pub const USDC_MINT_MAINNET: &str = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
-pub const USDC_MINT_DEVNET: &str = "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU";
-
-pub const SPL_TOKEN_PROGRAM: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
-pub const SPL_MEMO_PROGRAM: &str = "MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr";
-pub const COMPUTE_BUDGET_PROGRAM: &str = "ComputeBudget111111111111111111111111111111";
-
-// EVM / Base chain constants (CAIP-2 format: eip155:<chain_id>)
-pub const BASE_MAINNET_CAIP2: &str = "eip155:8453";
-pub const BASE_SEPOLIA_CAIP2: &str = "eip155:84532";
-pub const ETHEREUM_MAINNET_CAIP2: &str = "eip155:1";
-
-pub const USDC_BASE_MAINNET: &str = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
-pub const USDC_BASE_SEPOLIA: &str = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
-pub const USDC_ETHEREUM_MAINNET: &str = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
-
-// ---------------------------------------------------------------------------
-// 402 challenge — server → client (PAYMENT-REQUIRED header)
-// ---------------------------------------------------------------------------
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentRequired {
- pub x402_version: u8,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
- pub resource: ResourceInfo,
- pub accepts: Vec<PaymentRequirements>,
- #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
- pub extensions: serde_json::Map<String, serde_json::Value>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ResourceInfo {
- pub url: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub description: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub mime_type: Option<String>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentRequirements {
- pub scheme: String,
- pub network: String,
- /// Amount in atomic token units (e.g. 1 USDC = 1_000_000).
- pub amount: String,
- /// Token mint address (Solana) or contract address (EVM).
- pub asset: String,
- /// Recipient wallet address.
- pub pay_to: String,
- pub max_timeout_seconds: u64,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub extra: Option<PaymentExtra>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentExtra {
- /// Facilitator pubkey that will co-sign as fee payer (Solana).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub fee_payer: Option<String>,
- /// Required memo value for transaction uniqueness (Solana).
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub memo: Option<String>,
- /// EIP-712 domain name for the token contract (EVM, e.g. "USD Coin").
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub name: Option<String>,
- /// EIP-712 domain version for the token contract (EVM, e.g. "2").
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub version: Option<String>,
-}
-
-// ---------------------------------------------------------------------------
-// Payment proof — client → server (PAYMENT-SIGNATURE header)
-// ---------------------------------------------------------------------------
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct PaymentPayload {
- pub x402_version: u8,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub resource: Option<ResourceInfo>,
- pub accepted: PaymentRequirements,
- pub payload: PaymentProof,
- #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
- pub extensions: serde_json::Map<String, serde_json::Value>,
-}
-
-/// Chain-specific payment proof. Serializes flat (untagged) so the facilitator
-/// sees either `{ "transaction": "..." }` (Solana) or
-/// `{ "signature": "0x...", "authorization": {...} }` (EVM).
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(untagged)]
-pub enum PaymentProof {
- Solana(SolanaPaymentProof),
- Evm(EvmPaymentProof),
-}
-
-/// Solana `exact` scheme payload — a partially-signed `VersionedTransaction`
-/// serialized as standard base64. The facilitator adds its fee-payer signature
-/// and broadcasts.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct SolanaPaymentProof {
- pub transaction: String,
-}
-
-/// EVM `exact` scheme payload — a signed EIP-3009 `transferWithAuthorization`
-/// or plain ERC-20 transfer authorization for the facilitator to submit.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EvmPaymentProof {
- pub signature: String,
- pub authorization: EvmAuthorization,
-}
-
-/// EIP-3009 `transferWithAuthorization` parameters signed by the token holder.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct EvmAuthorization {
- pub from: String,
- pub to: String,
- pub value: String,
- pub valid_after: String,
- pub valid_before: String,
- pub nonce: String,
-}
-
-// ---------------------------------------------------------------------------
-// Settlement response — server → client (PAYMENT-RESPONSE header)
-// ---------------------------------------------------------------------------
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SettlementResponse {
- pub success: bool,
- /// Base58 transaction signature (Solana) or hex tx hash (EVM).
- pub transaction: String,
- pub network: String,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub payer: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub error_reason: Option<String>,
- #[serde(default, skip_serializing_if = "Option::is_none")]
- pub amount: Option<String>,
- #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")]
- pub extensions: serde_json::Map<String, serde_json::Value>,
-}
-
-// ---------------------------------------------------------------------------
-// Internal helpers
-// ---------------------------------------------------------------------------
-
-impl PaymentRequired {
- /// Find the first `accepts` entry whose network starts with `"solana:"` and
- /// whose scheme is `"exact"`.
- pub fn solana_exact_requirement(&self) -> Option<&PaymentRequirements> {
- self.accepts
- .iter()
- .find(|r| r.scheme == "exact" && r.network.starts_with("solana:"))
- }
-
- /// Find the first `accepts` entry whose network starts with `"eip155:"` and
- /// whose scheme is `"exact"`.
- pub fn evm_exact_requirement(&self) -> Option<&PaymentRequirements> {
- self.accepts
- .iter()
- .find(|r| r.scheme == "exact" && r.network.starts_with("eip155:"))
- }
-
- /// Find the best payment option — prefer EVM (Base), fall back to Solana.
- pub fn best_exact_requirement(&self) -> Option<(&PaymentRequirements, PaymentChain)> {
- if let Some(sol) = self.solana_exact_requirement() {
- Some((sol, PaymentChain::Solana))
- } else if let Some(evm) = self.evm_exact_requirement() {
- Some((evm, PaymentChain::Evm))
- } else {
- None
- }
- }
-}
-
-/// Which chain family a payment requirement targets.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum PaymentChain {
- Solana,
- Evm,
-}
-
-impl PaymentRequirements {
- pub fn is_solana_mainnet(&self) -> bool {
- self.network == SOLANA_MAINNET_CAIP2
- }
-
- pub fn is_base_mainnet(&self) -> bool {
- self.network == BASE_MAINNET_CAIP2
- }
-
- /// Parse the EVM chain ID from an `eip155:<chain_id>` network string.
- pub fn evm_chain_id(&self) -> Option<u64> {
- self.network
- .strip_prefix("eip155:")
- .and_then(|s| s.parse().ok())
- }
-
- pub fn fee_payer_pubkey(&self) -> Option<&str> {
- self.extra.as_ref()?.fee_payer.as_deref()
- }
-
- pub fn memo_value(&self) -> Option<&str> {
- self.extra.as_ref()?.memo.as_deref()
- }
-}
diff --git a/crates/openhuman-core/src/web3/x402/x402_tests.rs b/crates/openhuman-core/src/web3/x402/x402_tests.rs
deleted file mode 100644
index 7c1c59e564..0000000000
--- a/crates/openhuman-core/src/web3/x402/x402_tests.rs
+++ /dev/null
@@ -1,626 +0,0 @@
-use super::ops::build_evm_payment_with_signer;
-use super::types::*;
-use base64::engine::{general_purpose::STANDARD as B64, Engine as _};
-
-#[test]
-fn parse_payment_required_round_trips() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: Some("PAYMENT-SIGNATURE header is required".into()),
- resource: ResourceInfo {
- url: "https://api.example.com/data".into(),
- description: Some("Premium data".into()),
- mime_type: Some("application/json".into()),
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "10000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4".into(),
- max_timeout_seconds: 60,
- extra: Some(PaymentExtra {
- fee_payer: Some("EwWqGE4ZFKLofuestmU4LDdK7XM1N4ALgdZccwYugwGd".into()),
- memo: Some("pi_3abc123".into()),
- name: None,
- version: None,
- }),
- }],
- extensions: serde_json::Map::new(),
- };
- let json_str = serde_json::to_string(&challenge).unwrap();
- let parsed: PaymentRequired = serde_json::from_str(&json_str).unwrap();
- assert_eq!(parsed.x402_version, 2);
- assert_eq!(parsed.accepts.len(), 1);
- assert_eq!(parsed.accepts[0].amount, "10000");
- assert_eq!(
- parsed.accepts[0].pay_to,
- "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4"
- );
-}
-
-#[test]
-fn solana_exact_requirement_finds_match() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![
- PaymentRequirements {
- scheme: "exact".into(),
- network: "eip155:84532".into(),
- amount: "100".into(),
- asset: "0xUsdc".into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- },
- PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "5000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "SomeRecipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- },
- ],
- extensions: serde_json::Map::new(),
- };
- let sol = challenge.solana_exact_requirement().unwrap();
- assert_eq!(sol.amount, "5000");
- assert!(sol.is_solana_mainnet());
-}
-
-#[test]
-fn solana_exact_requirement_returns_none_when_absent() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: "eip155:1".into(),
- amount: "100".into(),
- asset: "0xUsdc".into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- }],
- extensions: serde_json::Map::new(),
- };
- assert!(challenge.solana_exact_requirement().is_none());
-}
-
-#[test]
-fn payment_extra_accessors() {
- let req = PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "1000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "Recipient".into(),
- max_timeout_seconds: 60,
- extra: Some(PaymentExtra {
- fee_payer: Some("FeePayer123".into()),
- memo: Some("order_456".into()),
- name: None,
- version: None,
- }),
- };
- assert_eq!(req.fee_payer_pubkey(), Some("FeePayer123"));
- assert_eq!(req.memo_value(), Some("order_456"));
-}
-
-#[test]
-fn payment_extra_accessors_none() {
- let req = PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "1000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "Recipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- };
- assert_eq!(req.fee_payer_pubkey(), None);
- assert_eq!(req.memo_value(), None);
-}
-
-#[test]
-fn settlement_response_deserializes_success() {
- let json_str = r#"{
- "success": true,
- "transaction": "4vJ9YFuPzUgdLkWYJf3Kqf",
- "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
- "payer": "EwWqGE4ZFKLofuestmU4LDdK7XM1N4ALgdZccwYugwGd"
- }"#;
- let resp: SettlementResponse = serde_json::from_str(json_str).unwrap();
- assert!(resp.success);
- assert_eq!(resp.transaction, "4vJ9YFuPzUgdLkWYJf3Kqf");
- assert!(resp.error_reason.is_none());
-}
-
-#[test]
-fn settlement_response_deserializes_failure() {
- let json_str = r#"{
- "success": false,
- "transaction": "",
- "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
- "payer": "EwWqGE4ZFKLofuestmU4LDdK7XM1N4ALgdZccwYugwGd",
- "errorReason": "insufficient_funds"
- }"#;
- let resp: SettlementResponse = serde_json::from_str(json_str).unwrap();
- assert!(!resp.success);
- assert_eq!(resp.error_reason.as_deref(), Some("insufficient_funds"));
-}
-
-#[test]
-fn base64_header_round_trip() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com/api".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "1000000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "RecipientPubkey".into(),
- max_timeout_seconds: 60,
- extra: None,
- }],
- extensions: serde_json::Map::new(),
- };
- let json_bytes = serde_json::to_vec(&challenge).unwrap();
- let encoded = B64.encode(&json_bytes);
- let decoded = B64.decode(&encoded).unwrap();
- let parsed: PaymentRequired = serde_json::from_slice(&decoded).unwrap();
- assert_eq!(parsed.accepts[0].amount, "1000000");
-}
-
-// ---------------------------------------------------------------------------
-// EVM tests
-// ---------------------------------------------------------------------------
-
-#[test]
-fn evm_exact_requirement_finds_match() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://twit.sh/post".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![
- PaymentRequirements {
- scheme: "exact".into(),
- network: BASE_MAINNET_CAIP2.into(),
- amount: "100".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0x1234567890abcdef1234567890abcdef12345678".into(),
- max_timeout_seconds: 30,
- extra: None,
- },
- PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "5000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "SomeRecipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- },
- ],
- extensions: serde_json::Map::new(),
- };
- let evm = challenge.evm_exact_requirement().unwrap();
- assert_eq!(evm.amount, "100");
- assert!(evm.is_base_mainnet());
- assert_eq!(evm.evm_chain_id(), Some(8453));
-}
-
-#[test]
-fn best_exact_requirement_prefers_solana() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![
- PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "5000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "SolRecipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- },
- PaymentRequirements {
- scheme: "exact".into(),
- network: BASE_MAINNET_CAIP2.into(),
- amount: "100".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- },
- ],
- extensions: serde_json::Map::new(),
- };
- let (req, chain) = challenge.best_exact_requirement().unwrap();
- assert_eq!(chain, PaymentChain::Solana);
- assert_eq!(req.amount, "5000");
-}
-
-#[test]
-fn best_exact_requirement_falls_back_to_evm() {
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: BASE_MAINNET_CAIP2.into(),
- amount: "100".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- }],
- extensions: serde_json::Map::new(),
- };
- let (req, chain) = challenge.best_exact_requirement().unwrap();
- assert_eq!(chain, PaymentChain::Evm);
- assert_eq!(req.amount, "100");
-}
-
-#[test]
-fn evm_chain_id_parsing() {
- let req = PaymentRequirements {
- scheme: "exact".into(),
- network: "eip155:8453".into(),
- amount: "100".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- };
- assert_eq!(req.evm_chain_id(), Some(8453));
- assert!(req.is_base_mainnet());
-
- let eth_req = PaymentRequirements {
- scheme: "exact".into(),
- network: "eip155:1".into(),
- amount: "100".into(),
- asset: USDC_ETHEREUM_MAINNET.into(),
- pay_to: "0xRecipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- };
- assert_eq!(eth_req.evm_chain_id(), Some(1));
- assert!(!eth_req.is_base_mainnet());
-
- let sol_req = PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "100".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "Recipient".into(),
- max_timeout_seconds: 30,
- extra: None,
- };
- assert_eq!(sol_req.evm_chain_id(), None);
-}
-
-#[test]
-fn evm_payment_proof_serializes_correctly() {
- let proof = EvmPaymentProof {
- signature: "0xdeadbeef".into(),
- authorization: EvmAuthorization {
- from: "0xaaaa".into(),
- to: "0xbbbb".into(),
- value: "1000000".into(),
- valid_after: "0".into(),
- valid_before: "99999999".into(),
- nonce: "0xabcd".into(),
- },
- };
- let payload = PaymentPayload {
- x402_version: 2,
- resource: None,
- accepted: PaymentRequirements {
- scheme: "exact".into(),
- network: BASE_MAINNET_CAIP2.into(),
- amount: "1000000".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0xbbbb".into(),
- max_timeout_seconds: 60,
- extra: None,
- },
- payload: PaymentProof::Evm(proof),
- extensions: serde_json::Map::new(),
- };
- let json = serde_json::to_string(&payload).unwrap();
- assert!(json.contains("\"signature\":\"0xdeadbeef\""));
- assert!(json.contains("\"authorization\""));
- assert!(!json.contains("\"transaction\""));
-}
-
-#[test]
-fn solana_payment_proof_serializes_correctly() {
- let payload = PaymentPayload {
- x402_version: 2,
- resource: None,
- accepted: PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "5000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "Recipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- },
- payload: PaymentProof::Solana(SolanaPaymentProof {
- transaction: "base64tx".into(),
- }),
- extensions: serde_json::Map::new(),
- };
- let json = serde_json::to_string(&payload).unwrap();
- assert!(json.contains("\"transaction\":\"base64tx\""));
- assert!(!json.contains("\"signature\""));
-}
-
-#[test]
-fn eip712_domain_separator_is_deterministic() {
- // Now `tinywallet_bus::eip712`; the crate's own suite pins its hashes against
- // the published EIP-712/EIP-3009 vectors. What this test checks is the
- // property that matters at this layer: the separator is deterministic and
- // binds the chain, so an authorization cannot be replayed on another one.
- use tinywallet_bus::eip712::domain_separator;
-
- let contract = base_usdc();
- let sep1 = domain_separator(contract, 8453, "USD Coin", "2");
- let sep2 = domain_separator(contract, 8453, "USD Coin", "2");
- assert_eq!(sep1, sep2);
-
- let sep_eth = domain_separator(contract, 1, "USD Coin", "2");
- assert_ne!(sep1, sep_eth);
-}
-
-/// The BIP-39 vector mnemonic's EVM account: raw secret and its address.
-///
-/// Derived through the **root** `tinywallet` crate's `key` gate, taken here as a
-/// dev-dependency. Production does not derive in this process at all — it calls
-/// `modules::wallet::derive_account` — so this reproduces the same BIP-32 walk
-/// locally, which is what lets the test sign as exactly the account the wallet
-/// would without standing up a broker.
-fn test_signer() -> (Vec<u8>, String) {
- let test_mnemonic = "abandon abandon abandon abandon abandon abandon \
- abandon abandon abandon abandon abandon about";
- let derived =
- tinywallet::key::derive(tinywallet::Chain::Evm, test_mnemonic, "m/44'/60'/0'/0/0").unwrap();
- (
- derived.secret_bytes().to_vec(),
- derived.address().to_string(),
- )
-}
-
-/// Base mainnet USDC, as raw address bytes.
-fn base_usdc() -> [u8; 20] {
- address_bytes("833589fCD6eDb6E08f4c7C32D4f71b54bdA02913")
-}
-
-/// Decode an unprefixed 20-byte hex address.
-fn address_bytes(hex: &str) -> [u8; 20] {
- hex::decode(hex).unwrap().try_into().unwrap()
-}
-
-#[test]
-fn eip3009_struct_hash_is_deterministic() {
- use tinywallet_bus::eip712::{transfer_with_authorization_hash, u256_from_u64};
-
- let from = address_bytes(&"aa".repeat(20));
- let to = address_bytes(&"bb".repeat(20));
- let value = u256_from_u64(1_000_000);
- let valid_after = u256_from_u64(0);
- let valid_before = u256_from_u64(99_999);
- let nonce = [42u8; 32];
-
- let h1 = transfer_with_authorization_hash(from, to, value, valid_after, valid_before, nonce);
- let h2 = transfer_with_authorization_hash(from, to, value, valid_after, valid_before, nonce);
- assert_eq!(h1, h2);
-
- // Different nonce produces different hash
- let h3 =
- transfer_with_authorization_hash(from, to, value, valid_after, valid_before, [43u8; 32]);
- assert_ne!(h1, h3);
-}
-
-#[test]
-fn parse_twit_sh_402_challenge() {
- let b64 = "eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIiwicmVzb3VyY2UiOnsidXJsIjoiaHR0cHM6Ly94NDAyLnR3aXQuc2gvdHdlZXRzL2J5L2lkIiwiZGVzY3JpcHRpb24iOiJMb29rIHVwIGEgc2luZ2xlIFR3aXR0ZXIvWCB0d2VldCBieSBpdHMgbnVtZXJpYyB0d2VldCBJRC4iLCJtaW1lVHlwZSI6ImFwcGxpY2F0aW9uL2pzb24ifSwiYWNjZXB0cyI6W3sic2NoZW1lIjoiZXhhY3QiLCJuZXR3b3JrIjoiZWlwMTU1Ojg0NTMiLCJhbW91bnQiOiIyNTAwIiwiYXNzZXQiOiIweDgzMzU4OWZDRDZlRGI2RTA4ZjRjN0MzMkQ0ZjcxYjU0YmRBMDI5MTMiLCJwYXlUbyI6IjB4OURCQTQxNDYzN2M2MTFhMTZCRWE2ZjA3OTZCRmNiY0JkYzQxMGRmOCIsIm1heFRpbWVvdXRTZWNvbmRzIjozMDAsImV4dHJhIjp7Im5hbWUiOiJVU0QgQ29pbiIsInZlcnNpb24iOiIyIn19XX0=";
- let json_bytes = B64.decode(b64).unwrap();
- let challenge: PaymentRequired = serde_json::from_slice(&json_bytes).unwrap();
-
- assert_eq!(challenge.x402_version, 2);
- assert_eq!(challenge.error.as_deref(), Some("Payment required"));
- assert_eq!(challenge.resource.url, "https://x402.twit.sh/tweets/by/id");
- assert_eq!(challenge.accepts.len(), 1);
-
- let req = &challenge.accepts[0];
- assert_eq!(req.scheme, "exact");
- assert_eq!(req.network, BASE_MAINNET_CAIP2);
- assert_eq!(req.amount, "2500");
- assert_eq!(req.asset, USDC_BASE_MAINNET);
- assert_eq!(req.pay_to, "0x9DBA414637c611a16BEa6f0796BFcbcBdc410df8");
- assert_eq!(req.max_timeout_seconds, 300);
- assert!(req.is_base_mainnet());
- assert_eq!(req.evm_chain_id(), Some(8453));
-
- let extra = req.extra.as_ref().unwrap();
- assert_eq!(extra.name.as_deref(), Some("USD Coin"));
- assert_eq!(extra.version.as_deref(), Some("2"));
-
- // Should select EVM path
- let (best, chain) = challenge.best_exact_requirement().unwrap();
- assert_eq!(chain, PaymentChain::Evm);
- assert_eq!(best.amount, "2500");
- assert!(challenge.solana_exact_requirement().is_none());
-}
-
-#[test]
-fn build_evm_payment_with_test_key_produces_valid_payload() {
- let (wallet, from_address) = test_signer();
- assert_eq!(from_address, "0x9858EfFD232B4033E47d90003D41EC34EcaEda94");
-
- let challenge = PaymentRequired {
- x402_version: 2,
- error: Some("Payment required".into()),
- resource: ResourceInfo {
- url: "https://x402.twit.sh/tweets/by/id".into(),
- description: Some("Look up a tweet".into()),
- mime_type: Some("application/json".into()),
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: BASE_MAINNET_CAIP2.into(),
- amount: "2500".into(),
- asset: USDC_BASE_MAINNET.into(),
- pay_to: "0x9DBA414637c611a16BEa6f0796BFcbcBdc410df8".into(),
- max_timeout_seconds: 300,
- extra: Some(PaymentExtra {
- fee_payer: None,
- memo: None,
- name: Some("USD Coin".into()),
- version: Some("2".into()),
- }),
- }],
- extensions: serde_json::Map::new(),
- };
-
- let req = &challenge.accepts[0];
- let payload = build_evm_payment_with_signer(&wallet, &from_address, &challenge, req).unwrap();
-
- assert_eq!(payload.x402_version, 2);
- assert_eq!(payload.accepted.network, BASE_MAINNET_CAIP2);
- assert_eq!(payload.accepted.amount, "2500");
-
- match &payload.payload {
- PaymentProof::Evm(evm) => {
- assert!(evm.signature.starts_with("0x"));
- // 0x prefix + 65 bytes (r=32 + s=32 + v=1) as hex = 130 chars + 2 = 132
- assert_eq!(evm.signature.len(), 132);
- assert_eq!(evm.authorization.value, "2500");
- assert_eq!(evm.authorization.valid_after, "0");
- assert!(evm.authorization.nonce.starts_with("0x"));
- // Checksummed, as `tinywallet_bus::address::evm` renders it, and as
- // the requirement itself carried it.
- assert_eq!(
- evm.authorization.to,
- "0x9DBA414637c611a16BEa6f0796BFcbcBdc410df8"
- );
- assert_eq!(evm.authorization.from, from_address);
-
- use k256::ecdsa::{RecoveryId, Signature, VerifyingKey};
- use tinywallet_bus::eip712;
-
- let raw = hex::decode(evm.signature.trim_start_matches("0x")).unwrap();
- assert!(matches!(raw[64], 27 | 28), "invalid recovery byte");
- let signature = Signature::from_slice(&raw[..64]).unwrap();
- let recovery_id = RecoveryId::try_from(raw[64] - 27).unwrap();
- let nonce: [u8; 32] = hex::decode(evm.authorization.nonce.trim_start_matches("0x"))
- .unwrap()
- .try_into()
- .unwrap();
- let domain = eip712::domain_separator(
- base_usdc(),
- 8453,
- req.extra.as_ref().unwrap().name.as_deref().unwrap(),
- req.extra.as_ref().unwrap().version.as_deref().unwrap(),
- );
- let structure = eip712::transfer_with_authorization_hash(
- address_bytes(evm.authorization.from.trim_start_matches("0x")),
- address_bytes(evm.authorization.to.trim_start_matches("0x")),
- eip712::u256_from_decimal(&evm.authorization.value).unwrap(),
- eip712::u256_from_u64(evm.authorization.valid_after.parse().unwrap()),
- eip712::u256_from_u64(evm.authorization.valid_before.parse().unwrap()),
- nonce,
- );
- let digest = eip712::signing_digest(domain, structure);
- let recovered =
- VerifyingKey::recover_from_prehash(&digest, &signature, recovery_id).unwrap();
- assert_eq!(
- recovered,
- *k256::ecdsa::SigningKey::from_slice(&wallet)
- .unwrap()
- .verifying_key(),
- "the recovered signer must control the pinned from_address"
- );
- }
- PaymentProof::Solana(_) => panic!("expected EVM proof, got Solana"),
- }
-
- // Verify the payload round-trips through base64 (as PAYMENT-SIGNATURE header)
- let json = serde_json::to_string(&payload).unwrap();
- let b64_header = B64.encode(&json);
- let decoded = B64.decode(&b64_header).unwrap();
- let parsed: PaymentPayload = serde_json::from_slice(&decoded).unwrap();
- assert_eq!(parsed.x402_version, 2);
- match &parsed.payload {
- PaymentProof::Evm(evm) => assert_eq!(evm.authorization.value, "2500"),
- _ => panic!("round-trip lost EVM proof"),
- }
-}
-
-#[test]
-fn build_evm_payment_rejects_solana_network() {
- let (wallet, from_address) = test_signer();
-
- let challenge = PaymentRequired {
- x402_version: 2,
- error: None,
- resource: ResourceInfo {
- url: "https://example.com".into(),
- description: None,
- mime_type: None,
- },
- accepts: vec![PaymentRequirements {
- scheme: "exact".into(),
- network: SOLANA_MAINNET_CAIP2.into(),
- amount: "5000".into(),
- asset: USDC_MINT_MAINNET.into(),
- pay_to: "SomeRecipient".into(),
- max_timeout_seconds: 60,
- extra: None,
- }],
- extensions: serde_json::Map::new(),
- };
-
- let req = &challenge.accepts[0];
- let result = build_evm_payment_with_signer(&wallet, &from_address, &challenge, req);
- assert!(result.is_err());
- let err_msg = format!("{}", result.unwrap_err());
- assert!(err_msg.contains("not an EVM network"));
-}
diff --git a/vendor/tinywallet b/vendor/tinywallet
index cc94d96b51..9a922c0c48 160000
--- a/vendor/tinywallet
+++ b/vendor/tinywallet
@@ -1 +1 @@
-Subproject commit cc94d96b51f34d7faaf0c7b86a42221043385d9a
+Subproject commit 9a922c0c4885ea722d516d7f235076b13029e065