Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
a68e4cf
feat(wallet): add secondary account index and label to wallet types
senamakel Nov 15, 2026
e7a4bbd
feat(wallet): split primary and additional accounts in wallet status
senamakel Nov 15, 2026
4a1b659
fix(web3): annotate partition result types in wallet status
senamakel Nov 15, 2026
9f7db83
feat(wallet): derive secondary accounts alongside primary ones
senamakel Nov 15, 2026
7361c86
feat(config): add per-account wallet program policy
senamakel Nov 15, 2026
bd161c1
feat(wallet): track ledger record kind and account index
senamakel Nov 15, 2026
992ede2
test(wallet): update test fixtures for new ledger and policy fields
senamakel Nov 15, 2026
b4f17ef
chore(web3): add bs58 dependency for transaction decoding
senamakel Nov 15, 2026
0cc43d0
refactor(web3): expose execution origin label and class to crate
senamakel Nov 15, 2026
ce48fca
feat(web3): add wallet program module
senamakel Nov 15, 2026
57543fa
feat(wallet): add account index to secret material lookup
senamakel Nov 15, 2026
3edb0e1
feat(wallet): add account and Solana program transaction controllers
senamakel Nov 15, 2026
17455dc
feat(web3): add tests for wallet program instructions
senamakel Nov 15, 2026
fbb1e6a
test(wallet): cover per-account policy and secondary account derivation
senamakel Nov 15, 2026
446a13f
test(wallet): pass recipient to spent helper in policy tests
senamakel Nov 15, 2026
2732a77
test(wallet): seed legacy wallet state directly in secondary path test
senamakel Nov 15, 2026
cc93f0d
feat(wallet): add secondary Solana account and program transaction si…
senamakel Nov 15, 2026
16730b8
refactor(wallet): split program transaction module into submodules
senamakel Nov 15, 2026
dfdb5db
refactor(wallet): split program wallet module into focused submodules
senamakel Nov 15, 2026
aeaef5a
refactor(web3): use match guard for associated token program check
senamakel Nov 15, 2026
a648b83
refactor(wallet): move program controller schemas into program module
senamakel Nov 15, 2026
9f05362
feat(wallet): validate declared token debits against transaction tran…
senamakel Nov 15, 2026
e8cfa49
feat(web3): add program simulation for wallet transactions
senamakel Nov 15, 2026
96140f3
feat(wallet): simulate program transactions before quoting and executing
senamakel Nov 15, 2026
209d0c2
test(web3): update wallet program tests for token-2022 and simulation
senamakel Nov 15, 2026
d22a5fc
test(web3): add simulation tests for wallet program
senamakel Nov 15, 2026
1b0491c
feat(wallet): require declared token debits confirmed by simulation
senamakel Nov 15, 2026
97d87f8
test(wallet): remove unused simulation report import
senamakel Nov 15, 2026
1ebf9b1
feat(web3): verify co-signer signatures before signing solana transac…
senamakel Nov 15, 2026
ef64446
docs(wallet): document co-signer support in program transactions
senamakel Nov 15, 2026
5243836
test(web3): cover co-signed rewards distributions and signature attac…
senamakel Nov 15, 2026
dacda38
refactor(web3): use as_chunks for signature parsing and share test he…
senamakel Nov 15, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions app/src/services/walletApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ export interface WalletAccount {
chain: WalletChain;
address: string;
derivationPath: string;
/** Account index on the chain; absent for the primary (index 0) account. */
index?: number;
/** Label of a secondary account (`giveaway`). */
label?: string;
}

export interface WalletRecoveryMaterial {
Expand All @@ -48,6 +52,8 @@ export interface WalletStatus {
source: WalletSetupSource | null;
mnemonicWordCount: number | null;
accounts: WalletAccount[];
/** Secondary accounts (index 1 and up), absent when there are none. */
additionalAccounts?: WalletAccount[];
updatedAtMs: number | null;
}

Expand Down
9 changes: 9 additions & 0 deletions crates/openhuman-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -452,6 +452,13 @@ tinyhosts-bus = { path = "../../vendor/tinyhosts/crates/tinyhosts-bus", optional
# 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 = ["wire"], optional = true }
# Base58 for Solana public keys and signatures in `web3::wallet::program`,
# which decodes a host-built transaction to check it against the account's
# policy before the module signs it. A codec only; no key material.
bs58 = { version = "0.5", optional = true }
# Verifies (never makes) the co-signers' ed25519 signatures on a partially
# signed host-built Solana transaction before the module adds the account's.
ed25519-dalek = { version = "2.2", optional = true }


[target.'cfg(windows)'.dependencies]
Expand Down Expand Up @@ -721,6 +728,8 @@ voice = [
# feature carries only the lightweight bus contract and generic HTTP client.
web3 = [
"dep:tinywallet-bus",
"dep:bs58",
"dep:ed25519-dalek",
"modules",
]

Expand Down
2 changes: 1 addition & 1 deletion crates/openhuman-core/src/config/schema/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub use hosting::HostingConfig;
pub mod storage;
pub use storage::StorageConfig;
pub mod wallet_policy;
pub use wallet_policy::{WalletAssetCap, WalletPolicyConfig};
pub use wallet_policy::{WalletAccountPolicy, WalletAssetCap, WalletMintCap, WalletPolicyConfig};
pub mod profile_layout;
pub use profile_layout::{users_dir, ProfileLayout};
mod identity_cost;
Expand Down
73 changes: 73 additions & 0 deletions crates/openhuman-core/src/config/schema/wallet_policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,38 @@
//! recipient_weekly_max_raw = 50000000 # 50 USDC per recipient per rolling 7d
//! ```
//!
//! ## Per-account program policy
//!
//! `assets` above governs the primary account of each chain, which signs the
//! module's transfers. A secondary account (Solana index 1, `m/44'/501'/1'/0'`)
//! and any account used to sign a host-built transaction through
//! `wallet.prepare_program` / `wallet.execute_prepared_program` is governed
//! only by its own section, keyed `<chain>_<index>`. An account with no
//! section is refused for every program execute; the section never affects
//! `assets` or the primary account's transfers.
//!
//! ```toml
//! [wallet_policy.accounts.solana_1]
//! allowed_programs = [
//! "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb", # Token-2022
//! "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL", # Associated Token Account
//! "<distributor program id>", # the program being called
//! ]
//!
//! [[wallet_policy.accounts.solana_1.mints]]
//! mint = "<mint address>"
//! per_tx_max_raw = 1000000000 # atomic units of the mint
//! daily_max_raw = 2000000000 # rolling 24h
//! ```
//!
//! Environment overrides (applied at config load, like every other section):
//! `OPENHUMAN_WALLET_POLICY_AUTOMATION_ENABLED`,
//! `OPENHUMAN_WALLET_POLICY_APPLY_TO_INTERACTIVE` (booleans) and
//! `OPENHUMAN_WALLET_POLICY_ASSETS` (a JSON array of asset caps, replacing the
//! `assets` list).

use std::collections::BTreeMap;

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

Expand All @@ -57,6 +83,53 @@ pub struct WalletPolicyConfig {
/// The assets a capped execute may move, each with its caps. An asset that
/// is not listed is refused for every capped execute.
pub assets: Vec<WalletAssetCap>,

/// Per-account policy for host-built program transactions, keyed
/// `<chain>_<index>` (`solana_1`). An account with no entry cannot sign a
/// program transaction. Independent of `assets`.
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
pub accounts: BTreeMap<String, WalletAccountPolicy>,
}

impl WalletPolicyConfig {
/// The key of `chain`'s account `index` in [`Self::accounts`].
#[must_use]
pub fn account_key(chain: &str, index: u32) -> String {
format!("{}_{index}", chain.to_ascii_lowercase())
}

/// The program policy of `chain`'s account `index`, if it has one.
#[must_use]
pub fn account_policy(&self, chain: &str, index: u32) -> Option<&WalletAccountPolicy> {
self.accounts.get(&Self::account_key(chain, index))
}
}

/// What one account may sign through `wallet.execute_prepared_program`.
///
/// Every instruction of the transaction must invoke a listed program, and the
/// token debits the caller declares (and simulation confirms) must be of a
/// listed mint within its caps.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct WalletAccountPolicy {
/// Program ids (base58) the transaction's instructions may invoke.
pub allowed_programs: Vec<String>,
/// The mints the account may move, each with its caps.
pub mints: Vec<WalletMintCap>,
}

/// Caps for one SPL mint. Both caps are required: a program account has no
/// uncapped mode.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct WalletMintCap {
/// Mint address (base58).
pub mint: String,
/// Largest total of this mint one transaction may move, atomic units.
pub per_tx_max_raw: u64,
/// Largest total over the last 24 hours, atomic units.
pub daily_max_raw: u64,
}

/// The caps for one asset. A cap that is absent does not limit that dimension;
Expand Down
48 changes: 48 additions & 0 deletions crates/openhuman-core/src/config/schema/wallet_policy_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,3 +92,51 @@ fn a_misspelled_asset_cap_field_is_rejected_instead_of_leaving_the_cap_off() {
.unwrap_err();
assert!(error.to_string().contains("daily_max_raww"), "{error}");
}

#[test]
fn per_account_program_sections_parse_and_round_trip() {
let config: crate::config::schema::Config = toml::from_str(
r#"
[wallet_policy.accounts.solana_1]
allowed_programs = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"]

[[wallet_policy.accounts.solana_1.mints]]
mint = "Mint1111111111111111111111111111111111111111"
per_tx_max_raw = 1000
daily_max_raw = 2000
"#,
)
.unwrap();
let policy = config.wallet_policy;
assert!(policy.assets.is_empty());
let section = policy.account_policy("solana", 1).expect("section");
assert_eq!(section.allowed_programs.len(), 1);
assert_eq!(section.mints[0].per_tx_max_raw, 1000);
assert_eq!(section.mints[0].daily_max_raw, 2000);
assert!(policy.account_policy("solana", 0).is_none());
assert_eq!(WalletPolicyConfig::account_key("Solana", 1), "solana_1");

let text = toml::to_string(&policy).unwrap();
let back: WalletPolicyConfig = toml::from_str(&text).unwrap();
assert_eq!(back, policy);
}

#[test]
fn an_empty_accounts_map_is_not_serialized() {
let text = toml::to_string(&WalletPolicyConfig::default()).unwrap();
assert!(!text.contains("accounts"), "{text}");
}

#[test]
fn a_mint_cap_without_both_caps_or_with_a_typo_fails_to_parse() {
for body in [
"mint = \"m\"\nper_tx_max_raw = 1\n",
"mint = \"m\"\nper_tx_max_raw = 1\ndaily_max_raw = 1\ndaily_max_raww = 1\n",
] {
let text = format!("[[wallet_policy.accounts.solana_1.mints]]\n{body}");
assert!(
toml::from_str::<crate::config::schema::Config>(&text).is_err(),
"{body}"
);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::*;
use crate::config::Config;
use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds};
use crate::config::Config;
use crate::inference::provider::factory::resolves_to_managed_backend;

fn byok_openai_compatible_entry() -> CloudProviderCreds {
Expand Down
2 changes: 1 addition & 1 deletion crates/openhuman-core/src/modules/wallet_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ async fn signing_secret(
tinywallet_bus::wire::WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,
tinywallet_bus::wire::WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,
};
let stored = crate::web3::wallet::secret_material(ctx, local_chain)
let stored = crate::web3::wallet::secret_material(ctx, local_chain, 0)
.await
.map_err(WalletCallError::Failed)?;
let mnemonic = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic)
Expand Down
2 changes: 1 addition & 1 deletion crates/openhuman-core/src/modules/web3_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ pub(crate) async fn execute(
WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,
WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,
};
let stored = crate::web3::wallet::secret_material(ctx, chain)
let stored = crate::web3::wallet::secret_material(ctx, chain, 0)
.await
.map_err(|error| wallet::WalletCallError::Failed(error.to_string()))?;
let mnemonic = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic)
Expand Down
2 changes: 1 addition & 1 deletion crates/openhuman-core/src/modules/x402_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ async fn signing_secret(
config: &Config,
chain: crate::web3::wallet::WalletChain,
) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {
let stored = crate::web3::wallet::secret_material(ctx, chain)
let stored = crate::web3::wallet::secret_material(ctx, chain, 0)
.await
.map_err(WalletCallError::Failed)?;
let phrase = crate::credentials::ops::decrypt_secret(config, &stored.encrypted_mnemonic)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,8 @@ Capability {
name: "Wallet Execution Tools",
domain: "wallet",
category: CapabilityCategory::Workflows,
description: "Read addresses, native balances and token balances (USDC on Solana, via wallet.token_balances), prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local. Agent and automated executes run inside the [wallet_policy] spend policy (asset allowlist, per-transaction, rolling-day and per-recipient weekly caps) and are recorded in a persistent ledger. Switched off by [components] wallet = false, which answers COMPONENT_DISABLED:wallet and leaves keychain material, spending limits and RPC endpoints untouched.",
how_to: "Use wallet.* RPC methods (balances, token_balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx, policy_get, policy_update, ledger_list) via the agent or core_rpc_relay. Settings > Crypto > Wallet Balances shows native balances only; token balances come from wallet.token_balances or the agent's wallet_balances tool.",
description: "Read addresses, native balances and token balances (USDC on Solana, via wallet.token_balances), prepare/confirm/execute native + token transfers (ERC20/SPL/TRC20/BEP20), and inspect transactions (status, receipt, lookup) across the connected wallet (EVM, BTC, Solana, Tron). Quote-first; signing stays local. Agent and automated executes run inside the [wallet_policy] spend policy (asset allowlist, per-transaction, rolling-day and per-recipient weekly caps) and are recorded in a persistent ledger. A secondary Solana account (index 1) can sign host-built program transactions only, under its own [wallet_policy.accounts.solana_1] program and mint allowlist with per-transaction and rolling-day caps. Switched off by [components] wallet = false, which answers COMPONENT_DISABLED:wallet and leaves keychain material, spending limits and RPC endpoints untouched.",
how_to: "Use wallet.* RPC methods (balances, token_balances, prepare_transfer, execute_prepared, tx_status, tx_receipt, lookup_tx, policy_get, policy_update, ledger_list, account, prepare_program, execute_prepared_program) via the agent or core_rpc_relay. Settings > Crypto > Wallet Balances shows native balances only; token balances come from wallet.token_balances or the agent's wallet_balances tool.",
status: CapabilityStatus::Beta,
privacy: LOCAL_CREDENTIALS,
},
Expand Down
33 changes: 33 additions & 0 deletions crates/openhuman-core/src/web3/wallet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ changing the facade.
| `prepare_transfer`, `execute_prepared` | Prepare a module-owned quote, then explicitly confirm and execute it (through the spend policy, as an interactive execute). |
| `policy_get`, `policy_update` | Read and persist the `[wallet_policy]` spend policy. |
| `ledger_list` | Recent execute records from the persistent spend ledger (`{limit}`, default 50, max 500). |
| `account` | One account by `{chain, accountIndex}`; derives and stores a known secondary account (Solana index 1, `giveaway`) that the stored state predates. |
| `prepare_program`, `execute_prepared_program` | Check a host-built unsigned Solana transaction against `[wallet_policy.accounts.solana_<index>]`, then sign it in the module with that account's key and send it (`program.rs`). |
| `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
Expand Down Expand Up @@ -95,6 +97,37 @@ harness gate and is refused by the policy; a cron job whose agent opted into
sub-agents stay read-only). x402 payments from the same origin are approved
within the per-request budget.

## Secondary accounts and program transactions

Each chain has one primary account (index 0), the only one the module's
transfers, swaps and x402 payments use. `ops::SECONDARY_ACCOUNTS` lists the
extra accounts derived from the same phrase: today Solana index 1 at
`m/44'/501'/1'/0'`, labelled `giveaway`. Recovery derives it with the others;
`setup` stores it; `status` reports it under `additionalAccounts` so callers
that expect one account per chain (and the module's `WalletAccounts`
callback) see only the primaries. A wallet set up before an entry existed
signs with its canonical path anyway, and `ensure_account` (`wallet.account`)
derives and stores its address on first use.

`program.rs` lets such an account sign a transaction the caller built,
under its own `[wallet_policy.accounts.<chain>_<index>]` section
(`allowed_programs`, `mints` with `per_tx_max_raw` and `daily_max_raw`). The
host decodes the transaction and refuses it unless the account is the fee
payer, every other required signer has already signed validly, every program is listed, token instructions (SPL
Token or Token-2022) are `TransferChecked`, ATA instructions are creates, and
there is no System instruction or lookup table. The caller declares what the
transaction debits from the account's token balances (`expectedDebits`); the
caps apply to that, it must cover every visible transfer, and
`simulateTransaction` must lower the account's token balances by exactly that
much (`program/simulate.rs`), which is what pins a program that moves tokens
by CPI. The quote holds the exact bytes for 60 seconds; execute simulates
again, re-checks and reserves in the ledger
(`kind = program`, `accountIndex`), signs the message bytes with a
confidential `SignMessage`, and sends the transaction to the Solana RPC (the
host override, else the module's default for the cluster). Program records
never count against the primary account's caps, and transfer records never
count against a program account's.

## Persistence and lifecycle

- `{workspace_dir}/state/wallet-state.json` stores consent and public setup
Expand Down
31 changes: 31 additions & 0 deletions crates/openhuman-core/src/web3/wallet/ledger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,30 @@ impl LedgerStatus {
}
}

/// What an execute signed.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LedgerKind {
/// A module-prepared transfer from a chain's primary account
/// (`wallet.execute_prepared`). Records written before kinds existed.
#[default]
Transfer,
/// A host-built transaction (`wallet.execute_prepared_program`), capped by
/// its account's `[wallet_policy.accounts]` section only.
Program,
}

impl LedgerKind {
fn is_transfer(&self) -> bool {
*self == Self::Transfer
}
}

#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(value: &u32) -> bool {
*value == 0
}

/// One execute attempt.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -105,6 +129,13 @@ pub struct LedgerRecord {
/// Why the execute was refused or failed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
/// What was signed. Transfer and program records never count against
/// each other's caps.
#[serde(default, skip_serializing_if = "LedgerKind::is_transfer")]
pub kind: LedgerKind,
/// The signing account's index on its chain (0 for the primary account).
#[serde(default, skip_serializing_if = "is_zero")]
pub account_index: u32,
}

impl LedgerRecord {
Expand Down
2 changes: 2 additions & 0 deletions crates/openhuman-core/src/web3/wallet/ledger_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ pub(super) fn record(quote_id: &str, created_at_ms: u64, status: LedgerStatus) -
status,
transaction_hash: None,
error: None,
kind: LedgerKind::Transfer,
account_index: 0,
}
}

Expand Down
8 changes: 6 additions & 2 deletions crates/openhuman-core/src/web3/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ mod ops;
pub mod policy;
#[cfg(feature = "web3")]
pub mod policy_ops;
/// Host-built program transactions signed by one account under its own
/// policy (`prepare_program` / `execute_prepared_program`).
#[cfg(feature = "web3")]
pub mod program;
#[cfg(feature = "web3")]
pub(crate) mod rpc;

Expand All @@ -72,8 +76,8 @@ pub use execution::{
};
#[cfg(feature = "web3")]
pub use ops::{
derive_recovery_material, generate_recovery_phrase, reveal_recovery_phrase, setup, status,
validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation,
derive_recovery_material, ensure_account, generate_recovery_phrase, reveal_recovery_phrase,
setup, status, validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation,
RevealRecoveryPhraseResult, WalletAccount, WalletChain, WalletRecoveryMaterial,
WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE,
};
Expand Down
Loading
Loading