Skip to content

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

docs(web3): rewrite wallet and x402 readmes around module ownership

Steven Enamakel55bb8d679746
diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md
index 8d14501b64..a56c9363b7 100644
--- a/crates/openhuman-core/src/web3/wallet/README.md
+++ b/crates/openhuman-core/src/web3/wallet/README.md
@@ -1,166 +1,84 @@
-# wallet
-
-Core-owned local multi-chain crypto wallet, deliberately basic: key/account
-management plus the primitive on-chain operations. Owns onboarding metadata
-(consent + derived per-chain account addresses), secret material at rest (an
-encrypted recovery phrase stored in the OS keychain or workspace JSON), and
-the agent-facing surface: address and balance reads, network/asset catalogs,
-chain readiness, a prepare-then-confirm-then-execute flow for native sends and
-token transfers (ERC20 / SPL / TRC20 / BEP20), transaction broadcast, and
-read-only transaction inspection (status, receipt, lookup) across EVM
-(Ethereum plus Base/Arbitrum/Optimism/Polygon/BNB Chain), Bitcoin (P2WPKH),
-Solana (native + SPL), and Tron (native + TRC20). This process decrypts the
-recovery phrase and hands it, as a `tinywallet_bus::wire::SecretMaterial`, to
-the loaded `tinywallet` native module (`crate::modules::wallet`), which
-derives the key, signs, and returns the raw signed bytes; the core then
-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
-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`](./ops)), the `Outcome`
-adapters ([`execution.rs`](./execution.rs)), endpoint resolution from the environment
-([`endpoints.rs`](./endpoints.rs)), the host `Transport` ([`transport.rs`](./transport.rs), [`rpc.rs`](./rpc.rs)) and the RPC
-controllers ([`schemas.rs`](./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`](./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`,
-`status`, `secret_material`, `WalletChain`, `prepare_transfer`,
-`execute_prepared`, the prepare/execute param and result types,
-`solana_cluster` / `SolanaCluster`, `prepared_quotes_for_test`, and the
-controller-registration entry points (`all_wallet_registered_controllers`,
-`all_wallet_controller_schemas`), with no-op or disabled-error bodies.
-Signatures must match the real ones exactly; `cargo check
---no-default-features` is the only thing that catches drift.
-
-## Responsibilities
-
-- Persist wallet onboarding state (consent flag, mnemonic word count, setup source, exactly one derived account per supported chain) and the encrypted recovery phrase.
-- Prefer the OS keychain for the encrypted mnemonic; transparently migrate the secret out of `wallet-state.json` into the keychain on load/save, and back to JSON when the keychain is unavailable (headless).
-- Expose read-only wallet info: status, per-account native balances (EVM live, others provider-gated), supported-asset catalog, per-network defaults (RPC/explorer/capability flags), and per-chain readiness.
-- Build prepared-transaction quotes (validated, fee-estimated, TTL'd) that must be explicitly confirmed before execution.
-- 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.
-- 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: `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`](./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_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`](./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 `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 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`](./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`, `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
-
-Namespace `wallet` (method form `openhuman.wallet_<function>`), 13 controllers registered via `all_wallet_registered_controllers`:
+# Wallet
+
+OpenHuman owns wallet onboarding, consent, encrypted mnemonic custody, and the
+product RPC surface. The compiled TinyWallet module owns account derivation,
+address validation, chain defaults and reference data, transaction building,
+signing, ERC-20 encoding, provider access, and user-scoped quote state.
+
+The host decrypts a mnemonic only for confidential calls to the attested module
+and stores only the encrypted phrase. It applies explicit user approval to the
+exact prepared transaction before the module signer runs. Missing or
+incompatible module operations fail closed; there is no host implementation
+fallback.
+
+## Compile-time gate
+
+`wallet` remains an always-available facade. The real implementation is gated
+by the `web3` Cargo feature; `stub.rs` provides the disabled surface for
+always-on callers. The product enables `web3` through
+`scripts/ci/product-features.txt`. Run both enabled and disabled builds after
+changing the facade.
+
+## Host responsibilities
+
+- `ops/` persists consent, setup source, word count, derived public accounts,
+ and encrypted mnemonic state. It prefers the OS keychain and retains the
+ workspace JSON fallback for headless operation.
+- `execution.rs` maps typed TinyWallet calls into controller results.
+- `endpoints.rs` reads host endpoint overrides and the Solana cluster. The
+ module chooses defaults and returns only opaque references for host-provided
+ endpoints.
+- `rpc.rs` is the generic host HTTP/RPC transport used by guarded module
+ callbacks; it redacts endpoint details in logs.
+- `schemas.rs` preserves the `openhuman.wallet_*` RPC names and response
+ shapes.
+- `tools.rs` adapts the static tool declarations from `tinywallet-bus` to
+ OpenHuman's `tinytools::Tool` interface.
+- `modules::wallet_service` manages the native wallet service handle and
+ closes it on replacement, sign-out, and shutdown.
+
+## RPC surface
| Function | Purpose |
| --- | --- |
-| `status` | Onboarding status + safe account metadata (addresses). |
-| `setup` | Persist consent + derived accounts + encrypted mnemonic (all inputs required); refuses to overwrite a configured wallet unless `force: true`. |
-| `balances` | Native-asset balances per account (EVM live; others provider-gated). |
-| `network_defaults` | RPC/explorer/capability flags + asset catalogs per chain. |
-| `supported_assets` | Built-in asset catalog including default EVM ERC-20s / BEP20s. |
-| `encode_erc20_transfer` | Encode `transfer(address,uint256)` calldata (EVM only). |
-| `chain_status` | Per-chain readiness + active RPC URL. An account's endpoint is probed (chain tip) through the transport; a failure reports `missing` with `error`. |
-| `prepare_transfer` | Quote a native/token transfer (all four chains). |
-| `execute_prepared` | Confirm (`confirmed: true`) and execute a quote by `quoteId` (tx send). |
-| `tx_status` | Check a transaction's lifecycle state (pending/confirmed/failed/not_found) by hash. |
-| `tx_receipt` | Fetch a transaction receipt (success, fee, block) by hash. |
-| `lookup_tx` | Look up the raw transaction payload by hash. |
-| `reveal_recovery_phrase` | Decrypt and return the stored BIP-39 phrase (`{phrase, wordCount}`); read-only, for transient display in the UI. |
-
-Wired into the registry in `crates/openhuman-core/src/core/all.rs` (controllers + schemas + capability description).
+| `status`, `setup`, `reveal_recovery_phrase` | Onboarding, public account metadata, encrypted phrase custody, and explicit reveal. |
+| `balances`, `chain_status`, `network_defaults`, `supported_assets` | Read module-owned provider and network data. |
+| `encode_erc20_transfer` | Request standard EVM transfer calldata from the module. |
+| `prepare_transfer`, `execute_prepared` | Prepare a module-owned quote, then explicitly confirm and execute it. |
+| `tx_status`, `tx_receipt`, `lookup_tx` | Read transaction lifecycle and raw transaction data through the module. |
+
+The four chain families are EVM, Bitcoin, Solana, and Tron. EVM network
+selection, asset catalogs, explorers, mint metadata, transaction encoding, and
+provider-specific behavior remain module-owned. OpenHuman supplies only
+explicit endpoint overrides, authenticated host transport, custody, and
+approval policy.
## Agent tools
-Defined in `tinywallet_web3::tools::wallet`, re-exported via [`tools.rs`](./tools.rs), built over the process-wide engine in `tools/ops.rs`:
-
-- `WalletStatusTool`, tool name `wallet_status`
-- `WalletChainStatusTool`, tool name `wallet_chain_status`
-- `WalletPrepareTransferTool`, tool name `wallet_prepare_transfer`
-- `WalletTxStatusTool`, tool name `wallet_tx_status`
-- `WalletTxReceiptTool`, tool name `wallet_tx_receipt`
-- `WalletLookupTxTool`, tool name `wallet_lookup_tx`
-
-All implement `tinytools::Tool` and delegate to the matching `wallet::*` functions. There is no agent tool for `execute_prepared` here; execution is reached via RPC.
-
-## Events
-
-None. The module publishes or subscribes no `DomainEvent`s and has no `bus.rs`. Chat-context coupling is via the task-local `approval::APPROVAL_CHAT_CONTEXT`, not the event bus.
-
-## Persistence
-
-- `{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::secret_storage`), 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 (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::secret_storage` (`is_available`/`get`/`set`): OS keychain storage for the encrypted mnemonic.
-- `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`), 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: `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
+The six wallet tools are declared in `tinywallet-bus` and adapted locally:
+`wallet_status`, `wallet_chain_status`, `wallet_prepare_transfer`,
+`wallet_tx_status`, `wallet_tx_receipt`, and `wallet_lookup_tx`. Transfer
+execution remains behind the controller confirmation flow.
-- `crates/openhuman-core/src/tools/mod.rs` re-exports `wallet::tools::*`; `crates/openhuman-core/src/tools/ops.rs` registers the six wallet agent tools (gated on the `web3` feature) and reserves the `wallet_`/`web3_`/`x402_` name prefixes as Web3-exclusive.
-- `crates/openhuman-core/src/core/all.rs` wires controllers/schemas/capability description.
-- `crates/openhuman-core/src/test_support/introspect.rs`: `wallet_prepared_quotes` introspection helper used in tests, backed by `wallet::prepared_quotes_for_test`.
+## Persistence and lifecycle
-## Notes / gotchas
+- `{workspace_dir}/state/wallet-state.json` stores consent and public setup
+ metadata, with the encrypted mnemonic only when the OS keychain is
+ unavailable. Writes remain atomic and corrupt state is quarantined.
+- The OS keychain is preferred for the encrypted mnemonic when policy and
+ platform support permit it.
+- Prepared transactions and one-shot approval state live in the module service
+ and are not persisted across sign-out or process restart. Closing the service
+ invalidates quotes and endpoint aliases before the host discards its config.
-- `rpc.rs` here is network transport, not RPC controllers. RPC controllers live in [`schemas.rs`](./schemas.rs). This is an exception to the canonical "`rpc.rs` = domain API" convention.
-- 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.
-- `balances`: only EVM reads live (Ethereum mainnet); BTC/Solana/Tron call their providers but fall back to zero with `ProviderStatus::Missing` on error.
+## Tests and further reading
-## Further reading
+Wallet behavior and cryptographic execution are tested in the owning TinyWallet
+repository and against its compiled module artifact. OpenHuman tests cover
+onboarding persistence, host approval, adapter behavior, and controller/tool
+compatibility.
-- [Parent module (`web3`)](../README.md)
-- [Wallet](../../../../../gitbooks/features/wallet.md)
-- [tinywallet submodule](../../../../../vendor/tinywallet/README.md)
+- [Parent Web3 module](../README.md)
+- [Wallet product guide](../../../../../gitbooks/features/wallet.md)
+- [TinyWallet source](../../../../../vendor/tinywallet/README.md)
- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)
diff --git a/crates/openhuman-core/src/web3/x402/README.md b/crates/openhuman-core/src/web3/x402/README.md
index 5cb43a98eb..6ef86ef2f3 100644
--- a/crates/openhuman-core/src/web3/x402/README.md
+++ b/crates/openhuman-core/src/web3/x402/README.md
@@ -1,156 +1,63 @@
# x402
-HTTP 402 machine-payment protocol (x402.org / coinbase/x402 v2). Intercepts an
-HTTP 402 response carrying a `PAYMENT-REQUIRED` header, builds a payment (a
-Solana SPL/USDC transfer, or an EVM EIP-3009 `transferWithAuthorization`),
-signs it with the wallet's key, and retries the request with the proof in a
-`PAYMENT-SIGNATURE` header. A facilitator co-signs as fee payer and broadcasts,
-so the client never needs native gas currency (SOL/ETH) to pay.
+OpenHuman exposes x402 payment history and budget RPCs and connects payment
+handling to its generic HTTP tool. TinyWallet owns challenge parsing, chain and
+asset selection, payment encoding and signing, budget reservation, settlement
+parsing, and ledger persistence.
-Sibling of the [`wallet`](../wallet/README.md) module in the
-[`web3`](../README.md) family. Payments are reached either through the
-dedicated `x402_request` agent tool or as a 402 fallback inside the generic
-`http_request` tool.
+The host keeps generic HTTP policy: allowed destinations, request authorization,
+network execution, and explicit approval. It retrieves encrypted wallet secrets
+from host custody and sends them only through the confidential TinyWallet
+module call. The module returns the payment header; after the retry, the host
+passes the raw response status and settlement header back to the module. The
+host does not parse x402 payloads or keep a parallel ledger.
-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.
+Payments are available through both the `x402_request` tool and the generic
+`http_request` tool's HTTP 402 payment hook. Both use the same module-owned
+budget and ledger.
-## Compile-time gate (`web3` feature)
+## Compile-time gate
-`pub mod x402;` (declared in `web3/mod.rs`) is always compiled: it is a
-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`](./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). 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
-and does not need a stub. Signatures must match the real ones exactly;
-`cargo check --no-default-features` is the only thing that catches drift.
+`x402` is an always-available facade. Its real controllers require the `web3`
+feature, while `stub.rs` provides empty controller lists when disabled. The
+product enables `web3` through `scripts/ci/product-features.txt`.
-## Key files
+## Host files
-| File | Role |
+| File | Responsibility |
| --- | --- |
-| [`mod.rs`](./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` and `request_tool`, which supply the seams; the `store` accessors used by `http_request`. |
-| [`seams.rs`](./seams.rs) | `WalletPaymentSigner` (the crate's `PaymentSigner`: keyring secret, decrypt, `modules::wallet::{derive_account, sign_message}`), `HostRequestGuard` (action, privacy and destination policy), `RuntimeProxyPolicy` (direct-egress permission from runtime and environment proxy settings), and the `payments()` / `request_tool()` constructors that pair them with the wallet's `OpenHumanTransport`. |
-| [`budget.rs`](./budget.rs) | The spending limits: the crate's defaults plus the `OPENHUMAN_X402_*` overrides. |
-| [`records.rs`](./records.rs) | `pending_record`: the `Pending` ledger record for the `http_request` fallback (ledger session + chat thread). |
-| [`schemas.rs`](./schemas.rs) | RPC controller schemas and handlers for the `x402` namespace: `get_summary`, `list_payments`, `update_budget`. |
-| [`stub.rs`](./stub.rs) | Disabled facade compiled when `web3` is off. See Compile-time gate above. |
-| [`seams_tests.rs`](./seams_tests.rs), [`budget_tests.rs`](./budget_tests.rs), [`stub_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. |
+| [`mod.rs`](./mod.rs) | Facade, payment record vocabulary re-exports, and disabled stub. |
+| [`schemas.rs`](./schemas.rs) | Stable `openhuman.x402_*` controller names and RPC projections. |
+| [`schemas_tests.rs`](./schemas_tests.rs) | Pins payment history output, amount display, and UTC timestamp representation. |
+| [`../../modules/x402_service.rs`](../../modules/x402_service.rs) | User-scoped module configuration, confidential payment calls, history and budget calls, and close/reconfigure cleanup. |
+| [`../../tools/impl/network/host.rs`](../../tools/impl/network/host.rs) | Generic HTTP payment hook; sends the challenge and returns the module-produced payment header. |
-## 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. |
-| `RequestGuard` (`authorize`) | `HostRequestGuard` | Checks action and privacy policy, vets DNS, and returns the complete request with pinned socket addresses. |
-| `ProxyPolicy` (`apply`, `allows_direct_connection`) | `RuntimeProxyPolicy` | Applies runtime proxy settings and refuses direct address-pinned requests while a runtime or environment proxy is required. |
-
-## RPC / controllers
-
-Namespace `x402` (method form `openhuman.x402_<function>`), registered via
-`all_x402_registered_controllers`:
+## RPC surface
| Function | Purpose |
| --- | --- |
-| `get_summary` | Spending totals for session/day/month plus the current budget limits. |
-| `list_payments` | Recent payment records, newest first (`limit`, default 50, max 500). |
-| `update_budget` | Update `per_request_max` / `daily_max` / `monthly_max` (atomic USDC units; 1 USDC = 1,000,000). |
-
-## Agent tool
-
-`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 (`tinytools_std::network::HttpRequestTool`, with its payment hook in `tools/impl/network/host.rs`), which
-handles a 402 only as a silent fallback.
-
-The tool is built with `TaskLocalThread` ([`seams.rs`](./seams.rs)), the host's
-`tinywallet_x402::thread::ThreadScope`: it reads the chat thread id from the
-`APPROVAL_CHAT_CONTEXT` task-local and the crate records it as
-`PaymentRecord.thread_id` (absent outside a chat turn). `session_id` is always
-the ledger's own `x402-<uuid>` boot id. The `http_request` 402 fallback builds
-its record with `pending_record` ([`records.rs`](./records.rs)), which applies the same rule.
-
-## Persistence
-
-- `{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) checks and reserves the amount atomically against
- the in-memory ledger before a payment is signed, so concurrent payments cannot
- exceed a cap. Daily and monthly totals sum the `Settled` records for the
- current UTC day / calendar month plus the amounts held by in-flight payments.
- The session total reported by `get_summary` counts records whose `session_id`
- equals the ledger's `x402-<uuid>` boot id, which every payment of this process
- carries (both writers), so it is the process's total; it is not a cap. The chat
- thread is recorded separately in `thread_id`. `init_ledger` seeds the limits from
- `OPENHUMAN_X402_PER_REQUEST_MAX` / `OPENHUMAN_X402_DAILY_MAX` /
- `OPENHUMAN_X402_MONTHLY_MAX` when set ([`budget.rs`](./budget.rs)); `update_budget` changes
- them for the running process only and does not rewrite historical records.
-
-## Dependencies
-
-- `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
+| `get_summary` | Project module-owned spending totals and configured limits. |
+| `list_payments` | Project recent module-owned payment records using the existing RPC shape. |
+| `update_budget` | Ask the module to update per-request, daily, and monthly limits. |
-- `crates/openhuman-core/src/tools/impl/network/host.rs`:
- `X402PaymentHook`, gated `#[cfg(feature = "web3")]` and installed on
- `http_request` as its `PaymentHook`, 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`.
+Payment history keeps the established fields and formatting, including
+`amount_display` and UTC timestamps. These are host projections of module DTOs,
+not host-side accounting or protocol interpretation.
-## Notes / gotchas
+## Safety and lifecycle
-- The paying account never needs SOL (or ETH/native gas) for the payment
- transaction itself; the facilitator is the fee payer and on-chain submitter.
- The wallet does still need the payment asset (typically USDC) on the target
- chain.
-- Budget limits live in the process (defaults or env at boot, then
- `update_budget`); spend totals are recomputed from the on-disk ledger on
- every boot, so restarting does not reset what was spent today or this
- month. None of this substitutes for on-chain spending limits.
-- Two distinct paths reach a payment: the purpose-built `x402_request` agent
- tool (always expects a 402) and the generic `http_request` tool's
- opportunistic 402 fallback. Both funnel through `handle_402_and_pay` and the
- same ledger, so spending is tracked consistently regardless of entry point.
+- The host rejects a request before secret access if user approval is absent.
+- The module parses the challenge, selects the payment rail, reserves budget,
+ and verifies the exact owner and payment facts before signing.
+- The module service is closed on sign-out, configuration replacement, and
+ shutdown. Pending reservations are released by the module before its ledger
+ is replaced or discarded.
+- If the module or required capability is unavailable, payment fails closed;
+ the host does not fall back to a local payment implementation.
## Further reading
-- [Parent module (`web3`)](../README.md)
-- [Wallet](../../../../../gitbooks/features/wallet.md)
-- [tinywallet submodule](../../../../../vendor/tinywallet/README.md)
+- [Parent Web3 module](../README.md)
+- [Wallet host adapter](../wallet/README.md)
+- [TinyWallet source](../../../../../vendor/tinywallet/README.md)
- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)