Skip to content

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

chore: files changed Cargo.lock,app/package.json,app/src/components/settings/panels/RecoveryPhrasePa

Steven Enamakel050f34c56073
diff --git a/Cargo.lock b/Cargo.lock
index a5b69af994..c3532798c9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3984,9 +3984,6 @@ dependencies = [
"tinyvoice-bus",
"tinywallet",
"tinywallet-bus",
- "tinywallet-crypto",
- "tinywallet-web3",
- "tinywallet-x402",
"tokio",
"tokio-tungstenite 0.29.0",
"tokio-util",
@@ -4093,6 +4090,7 @@ dependencies = [
"tinyagents-harness",
"tinyagents-session",
"tinybus",
+ "tinyflows-schedule",
"tinyinference-embeddings",
"tinyinference-llm",
"tinymcp-bus",
@@ -7305,12 +7303,13 @@ dependencies = [
[[package]]
name = "tinywallet"
-version = "0.13.0"
+version = "0.19.0"
dependencies = [
"coins-bip32",
"coins-bip39",
"ed25519-dalek",
"hmac 0.13.0",
+ "rand 0.9.5",
"ripemd 0.2.0",
"sha2 0.11.0",
"sha3 0.12.0",
@@ -7323,7 +7322,7 @@ dependencies = [
[[package]]
name = "tinywallet-bus"
-version = "0.13.0"
+version = "0.19.0"
dependencies = [
"serde",
"serde_json",
@@ -7332,64 +7331,20 @@ dependencies = [
[[package]]
name = "tinywallet-crypto"
-version = "0.13.0"
+version = "0.19.0"
dependencies = [
- "async-trait",
"bech32 0.12.0",
"bs58",
"hex",
- "serde",
- "serde_json",
"sha2 0.11.0",
"sha3 0.12.0",
"thiserror 2.0.20",
"tinywallet-bus",
]
-[[package]]
-name = "tinywallet-web3"
-version = "0.13.0"
-dependencies = [
- "anyhow",
- "async-trait",
- "base64 0.23.1",
- "bs58",
- "curve25519-dalek 5.0.0",
- "hex",
- "log",
- "parking_lot",
- "serde",
- "serde_json",
- "sha2 0.11.0",
- "tinytools",
- "tinywallet-bus",
- "tinywallet-crypto",
- "tinywallet-x402",
-]
-
[[package]]
name = "tinywallet-x402"
-version = "0.13.0"
-dependencies = [
- "anyhow",
- "async-trait",
- "base64 0.23.1",
- "bs58",
- "chrono",
- "curve25519-dalek 5.0.0",
- "hex",
- "log",
- "reqwest 0.13.5",
- "serde",
- "serde_json",
- "sha2 0.11.0",
- "sha3 0.12.0",
- "thiserror 2.0.20",
- "tinytools",
- "tinywallet-bus",
- "tinywallet-crypto",
- "uuid",
-]
+version = "0.19.0"
[[package]]
name = "tokio"
diff --git a/app/package.json b/app/package.json
index af7da43c91..64d5400b95 100644
--- a/app/package.json
+++ b/app/package.json
@@ -82,13 +82,9 @@
"@noble/ciphers": "^1.2.1",
"@noble/curves": "^2.2.0",
"@noble/hashes": "^2.0.1",
- "@noble/secp256k1": "^3.0.0",
"@radix-ui/react-collapsible": "^1.1.20",
"@reduxjs/toolkit": "^2.11.2",
"@rive-app/react-webgl2": "^4.28.6",
- "@scure/base": "^2.2.0",
- "@scure/bip32": "^2.0.1",
- "@scure/bip39": "^2.0.1",
"@sentry/react": "^10.38.0",
"@tauri-apps/api": "^2.11.0",
"@tauri-apps/plugin-barcode-scanner": "^2.4.4",
diff --git a/app/src/components/settings/panels/RecoveryPhrasePanel.tsx b/app/src/components/settings/panels/RecoveryPhrasePanel.tsx
index 1a3519f862..e48bb1428b 100644
--- a/app/src/components/settings/panels/RecoveryPhrasePanel.tsx
+++ b/app/src/components/settings/panels/RecoveryPhrasePanel.tsx
@@ -4,12 +4,13 @@ import { useNavigate } from 'react-router-dom';
import { persistLocalWalletFromMnemonic } from '../../../features/wallet/setupLocalWalletFromMnemonic';
import { useT } from '../../../lib/i18n/I18nContext';
import { useCoreState } from '../../../providers/CoreStateProvider';
-import { fetchWalletStatus, type WalletStatus } from '../../../services/walletApi';
import {
- generateMnemonicPhrase,
- MNEMONIC_GENERATE_WORD_COUNT,
- validateMnemonicPhrase,
-} from '../../../utils/cryptoKeys';
+ fetchWalletStatus,
+ generateRecoveryPhrase,
+ validateRecoveryPhrase,
+ type WalletStatus,
+} from '../../../services/walletApi';
+import { MNEMONIC_GENERATE_WORD_COUNT } from '../../../utils/cryptoKeys';
import { Alert } from '../../ui/Alert';
import Button from '../../ui/Button';
import { CheckIcon, Spinner } from '../../ui/icons';
@@ -78,8 +79,8 @@ const RecoveryPhrasePanel = () => {
setMode('view');
} else {
// No configured wallet — generate mode. Generate phrase now.
- const phrase = generateMnemonicPhrase();
- setMnemonic(phrase);
+ const generated = await generateRecoveryPhrase();
+ setMnemonic(generated.phrase);
setMode('generate');
}
} catch (e) {
@@ -99,15 +100,19 @@ const RecoveryPhrasePanel = () => {
}, []);
// ── Transition into generate mode after replace confirmation ─────────────
- const handleConfirmReplace = useCallback(() => {
- const phrase = generateMnemonicPhrase();
- setMnemonic(phrase);
- setIsReplace(true);
- setConfirmed(false);
- setRevealed(false);
- setError(null);
- setMode('generate');
- }, []);
+ const handleConfirmReplace = useCallback(async () => {
+ try {
+ const generated = await generateRecoveryPhrase();
+ setMnemonic(generated.phrase);
+ setIsReplace(true);
+ setConfirmed(false);
+ setRevealed(false);
+ setError(null);
+ setMode('generate');
+ } catch (e) {
+ setError(e instanceof Error ? e.message : t('mnemonic.somethingWentWrong'));
+ }
+ }, [t]);
// ── Transition into import mode after replace confirmation ────────────────
const handleImportReplace = useCallback(() => {
@@ -219,7 +224,7 @@ const RecoveryPhrasePanel = () => {
[importWords]
);
- const handleValidateImport = useCallback(() => {
+ const handleValidateImport = useCallback(async () => {
const phrase = importWords.join(' ').trim();
const filledWords = importWords.filter(w => w.trim());
const n = filledWords.length;
@@ -230,7 +235,7 @@ const RecoveryPhrasePanel = () => {
return false;
}
- const isValid = validateMnemonicPhrase(phrase);
+ const isValid = await validateRecoveryPhrase(phrase);
setImportValid(isValid);
if (!isValid) {
@@ -250,7 +255,7 @@ const RecoveryPhrasePanel = () => {
let phraseToUse: string;
if (mode === 'import') {
- if (!handleValidateImport()) {
+ if (!(await handleValidateImport())) {
setLoading(false);
return;
}
@@ -395,14 +400,7 @@ const RecoveryPhrasePanel = () => {
<Button
type="button"
variant="tertiary"
- onClick={() => {
- const phrase = generateMnemonicPhrase();
- setMnemonic(phrase);
- setConfirmed(false);
- setRevealed(false);
- setError(null);
- setMode('generate');
- }}
+ onClick={() => void handleConfirmReplace()}
className="w-full mb-3">
{t('mnemonic.createANewWallet')}
</Button>
diff --git a/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.custody.test.tsx b/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.custody.test.tsx
index dc8ed492ad..194bfd922f 100644
--- a/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.custody.test.tsx
+++ b/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.custody.test.tsx
@@ -43,20 +43,20 @@ const PHRASE_12 = 'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10
const {
mockGenerateMnemonicPhrase,
mockFetchWalletStatus,
+ mockValidateRecoveryPhrase,
mockPersistLocalWalletFromMnemonic,
mockRevealRecoveryPhrase,
} = vi.hoisted(() => ({
- mockGenerateMnemonicPhrase: vi.fn(() => ''),
+ mockGenerateMnemonicPhrase: vi.fn<() => string | { phrase: string; wordCount: number }>(() => ({
+ phrase: '',
+ wordCount: 12,
+ })),
+ mockValidateRecoveryPhrase: vi.fn(async () => true),
mockFetchWalletStatus: vi.fn(async () => ({}) as WalletStatus),
mockPersistLocalWalletFromMnemonic: vi.fn(async (_args: unknown) => undefined),
mockRevealRecoveryPhrase: vi.fn(async () => ({ phrase: '', wordCount: 12 })),
}));
-vi.mock('../../../../utils/cryptoKeys', async importOriginal => {
- const original = await importOriginal<typeof import('../../../../utils/cryptoKeys')>();
- return { ...original, generateMnemonicPhrase: mockGenerateMnemonicPhrase };
-});
-
vi.mock('../../../../providers/CoreStateProvider', () => ({
useCoreState: () => ({
snapshot: { currentUser: { _id: 'test-user-id' } },
@@ -66,6 +66,11 @@ vi.mock('../../../../providers/CoreStateProvider', () => ({
vi.mock('../../../../services/walletApi', () => ({
fetchWalletStatus: mockFetchWalletStatus,
+ generateRecoveryPhrase: async () => {
+ const generated = await mockGenerateMnemonicPhrase();
+ return typeof generated === 'string' ? { phrase: generated, wordCount: 12 } : generated;
+ },
+ validateRecoveryPhrase: mockValidateRecoveryPhrase,
setupLocalWallet: vi.fn(async () => ({}) as WalletStatus),
revealRecoveryPhrase: mockRevealRecoveryPhrase,
}));
diff --git a/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.test.tsx b/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.test.tsx
index 6e32b74cfb..a8c3a37b39 100644
--- a/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.test.tsx
+++ b/app/src/components/settings/panels/__tests__/RecoveryPhrasePanel.test.tsx
@@ -9,12 +9,15 @@ import RecoveryPhrasePanel from '../RecoveryPhrasePanel';
const {
mockGenerateMnemonicPhrase,
mockFetchWalletStatus,
+ mockValidateRecoveryPhrase,
mockPersistLocalWalletFromMnemonic,
mockRevealRecoveryPhrase,
} = vi.hoisted(() => ({
- mockGenerateMnemonicPhrase: vi.fn(
- () => 'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12'
- ),
+ mockGenerateMnemonicPhrase: vi.fn<() => string | { phrase: string; wordCount: number }>(() => ({
+ phrase: 'word1 word2 word3 word4 word5 word6 word7 word8 word9 word10 word11 word12',
+ wordCount: 12,
+ })),
+ mockValidateRecoveryPhrase: vi.fn(async () => true),
mockFetchWalletStatus: vi.fn(
async (): Promise<WalletStatus> => ({
configured: false,
@@ -36,11 +39,6 @@ const {
})),
}));
-vi.mock('../../../../utils/cryptoKeys', async importOriginal => {
- const original = await importOriginal<typeof import('../../../../utils/cryptoKeys')>();
- return { ...original, generateMnemonicPhrase: mockGenerateMnemonicPhrase };
-});
-
vi.mock('../../../../providers/CoreStateProvider', () => ({
useCoreState: () => ({
snapshot: { currentUser: { _id: 'test-user-id' } },
@@ -51,6 +49,11 @@ vi.mock('../../../../providers/CoreStateProvider', () => ({
// Default: no existing wallet. Individual describe blocks override in beforeEach.
vi.mock('../../../../services/walletApi', () => ({
fetchWalletStatus: mockFetchWalletStatus,
+ generateRecoveryPhrase: async () => {
+ const generated = await mockGenerateMnemonicPhrase();
+ return typeof generated === 'string' ? { phrase: generated, wordCount: 12 } : generated;
+ },
+ validateRecoveryPhrase: mockValidateRecoveryPhrase,
setupLocalWallet: vi.fn(async () => ({
configured: true,
onboardingCompleted: true,
@@ -160,7 +163,7 @@ describe('RecoveryPhrasePanel — mode-switch state reset', () => {
expect(screen.queryByRole('checkbox')).toBeNull();
fireEvent.click(screen.getByText(/Create a New Wallet/i));
- const regeneratedCheckbox = screen.getByRole('checkbox');
+ const regeneratedCheckbox = await screen.findByRole('checkbox');
expect(regeneratedCheckbox).not.toBeChecked();
});
@@ -171,7 +174,7 @@ describe('RecoveryPhrasePanel — mode-switch state reset', () => {
expect(screen.getByText(/Enter your recovery phrase below/i)).toBeTruthy();
fireEvent.click(screen.getByText(/Create a New Wallet/i));
- expect(screen.getByText(/can never be recovered if lost/i)).toBeTruthy();
+ expect(await screen.findByText(/can never be recovered if lost/i)).toBeTruthy();
});
});
@@ -603,6 +606,7 @@ describe('RecoveryPhrasePanel — import mode word inputs and valid/invalid styl
// Covers lines 640 (importValid===false invalid border), 638, and 707 (error alert).
it('clicking Save with an invalid phrase shows the error alert (line 707)', async () => {
+ mockValidateRecoveryPhrase.mockResolvedValueOnce(false);
renderWithProviders(<RecoveryPhrasePanel />);
await waitFor(() => screen.getByText(/I already have a recovery phrase/i));
@@ -627,6 +631,14 @@ describe('RecoveryPhrasePanel — import mode word inputs and valid/invalid styl
// Covers line 650 (importValid===true banner), line 640 (sage border on valid inputs).
it('filling a valid BIP39 phrase and saving shows the valid-phrase banner then persists', async () => {
+ let finishPersist!: () => void;
+ mockPersistLocalWalletFromMnemonic.mockImplementationOnce(
+ () =>
+ new Promise<undefined>(resolve => {
+ finishPersist = () => resolve(undefined);
+ })
+ );
+
renderWithProviders(<RecoveryPhrasePanel />);
await waitFor(() => screen.getByText(/I already have a recovery phrase/i));
@@ -651,6 +663,8 @@ describe('RecoveryPhrasePanel — import mode word inputs and valid/invalid styl
const callArgs = mockPersistLocalWalletFromMnemonic.mock.calls[0][0];
expect(callArgs.mnemonic).toBe(VALID_12_WORDS.join(' '));
expect(callArgs.source).toBe('imported');
+ finishPersist();
+ await waitFor(() => expect(screen.queryByText(/Recovery phrase saved/i)).toBeTruthy());
});
// Covers line 608 (handleWordCountChange via the word-count toggle buttons).
diff --git a/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts b/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts
index 30eb80642a..2f2dd97396 100644
--- a/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts
+++ b/app/src/features/wallet/setupLocalWalletFromMnemonic.test.ts
@@ -4,8 +4,39 @@ import { persistLocalWalletFromMnemonic } from './setupLocalWalletFromMnemonic';
const mockSetupLocalWallet = vi.fn();
const mockEncryptSecret = vi.fn();
+const mockDeriveRecoveryMaterial = vi.fn();
+
+const canonicalSeed = Uint8Array.from(
+ '5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4'.match(
+ /.{2}/g
+ ) ?? [],
+ byte => Number.parseInt(byte, 16)
+);
+const canonicalAccounts = [
+ {
+ chain: 'evm' as const,
+ address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
+ derivationPath: "m/44'/60'/0'/0/0",
+ },
+ {
+ chain: 'btc' as const,
+ address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',
+ derivationPath: "m/44'/0'/0'/0/0",
+ },
+ {
+ chain: 'solana' as const,
+ address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',
+ derivationPath: "m/44'/501'/0'/0'",
+ },
+ {
+ chain: 'tron' as const,
+ address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',
+ derivationPath: "m/44'/195'/0'/0/0",
+ },
+];
vi.mock('../../services/walletApi', () => ({
+ deriveRecoveryMaterial: (...args: unknown[]) => mockDeriveRecoveryMaterial(...args),
setupLocalWallet: (...args: unknown[]) => mockSetupLocalWallet(...args),
}));
@@ -14,8 +45,12 @@ vi.mock('../../utils/tauriCommands/auth', () => ({
}));
describe('persistLocalWalletFromMnemonic', () => {
- it('derives multi-chain wallet metadata and persists it after storing the AES key', async () => {
+ it('uses module-derived seed and accounts before persisting the wallet', async () => {
const setEncryptionKey = vi.fn(async () => undefined);
+ mockDeriveRecoveryMaterial.mockResolvedValueOnce({
+ seed: new Uint8Array(canonicalSeed),
+ accounts: canonicalAccounts,
+ });
mockSetupLocalWallet.mockResolvedValueOnce({
configured: true,
onboardingCompleted: true,
@@ -33,6 +68,10 @@ describe('persistLocalWalletFromMnemonic', () => {
await persistLocalWalletFromMnemonic({ mnemonic, source: 'generated', setEncryptionKey });
+ expect(mockDeriveRecoveryMaterial).toHaveBeenCalledWith(
+ 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
+ );
+
expect(setEncryptionKey).toHaveBeenCalledWith(
'dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1'
);
@@ -41,28 +80,7 @@ describe('persistLocalWalletFromMnemonic', () => {
source: 'generated',
mnemonicWordCount: 12,
encryptedMnemonic: 'enc2:wallet-secret',
- accounts: [
- {
- chain: 'evm',
- address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
- derivationPath: "m/44'/60'/0'/0/0",
- },
- {
- chain: 'btc',
- address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',
- derivationPath: "m/44'/0'/0'/0/0",
- },
- {
- chain: 'solana',
- address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',
- derivationPath: "m/44'/501'/0'/0'",
- },
- {
- chain: 'tron',
- address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',
- derivationPath: "m/44'/195'/0'/0/0",
- },
- ],
+ accounts: canonicalAccounts,
});
});
@@ -77,12 +95,18 @@ describe('persistLocalWalletFromMnemonic', () => {
expect(setEncryptionKey).not.toHaveBeenCalled();
expect(mockEncryptSecret).not.toHaveBeenCalled();
expect(mockSetupLocalWallet).not.toHaveBeenCalled();
+ expect(mockDeriveRecoveryMaterial).not.toHaveBeenCalled();
});
it('rejects empty encrypted mnemonic output before persisting wallet state', async () => {
const setEncryptionKey = vi.fn(async () => undefined);
mockSetupLocalWallet.mockReset();
mockEncryptSecret.mockReset();
+ mockDeriveRecoveryMaterial.mockReset();
+ mockDeriveRecoveryMaterial.mockResolvedValueOnce({
+ seed: new Uint8Array(canonicalSeed),
+ accounts: canonicalAccounts,
+ });
mockEncryptSecret.mockResolvedValueOnce({ result: ' ' });
await expect(
diff --git a/app/src/features/wallet/setupLocalWalletFromMnemonic.ts b/app/src/features/wallet/setupLocalWalletFromMnemonic.ts
index 9d36a8c628..9609030b53 100644
--- a/app/src/features/wallet/setupLocalWalletFromMnemonic.ts
+++ b/app/src/features/wallet/setupLocalWalletFromMnemonic.ts
@@ -1,9 +1,9 @@
-import { setupLocalWallet } from '../../services/walletApi';
import {
- deriveAesKeyFromMnemonic,
- deriveWalletAccountsFromMnemonic,
+ deriveRecoveryMaterial,
+ setupLocalWallet,
type WalletSetupSource,
-} from '../../utils/cryptoKeys';
+} from '../../services/walletApi';
+import { deriveAesKeyFromSeed } from '../../utils/cryptoKeys';
import { openhumanEncryptSecret } from '../../utils/tauriCommands/auth';
export async function persistLocalWalletFromMnemonic(args: {
@@ -22,7 +22,8 @@ export async function persistLocalWalletFromMnemonic(args: {
throw new Error('Recovery phrase is required.');
}
const normalizedMnemonic = words.join(' ');
- const aesKey = deriveAesKeyFromMnemonic(normalizedMnemonic);
+ const recoveryMaterial = await deriveRecoveryMaterial(normalizedMnemonic);
+ const aesKey = deriveAesKeyFromSeed(recoveryMaterial.seed);
const encryptedMnemonic = (await openhumanEncryptSecret(normalizedMnemonic)).result?.trim();
if (!encryptedMnemonic) {
throw new Error('Failed to secure recovery phrase. Please try again.');
@@ -34,7 +35,7 @@ export async function persistLocalWalletFromMnemonic(args: {
source,
mnemonicWordCount: words.length,
encryptedMnemonic,
- accounts: deriveWalletAccountsFromMnemonic(normalizedMnemonic),
+ accounts: recoveryMaterial.accounts,
force,
});
}
diff --git a/app/src/services/walletApi.test.ts b/app/src/services/walletApi.test.ts
index 626de24576..0018d12a83 100644
--- a/app/src/services/walletApi.test.ts
+++ b/app/src/services/walletApi.test.ts
@@ -32,6 +32,53 @@ describe('walletApi', () => {
expect(result.configured).toBe(true);
});
+ it('generateRecoveryPhrase requests the module-owned 12-word phrase', async () => {
+ mockCallCoreRpc.mockResolvedValueOnce({
+ result: { phrase: 'word1 ... word12', wordCount: 12 },
+ });
+
+ const { generateRecoveryPhrase } = await import('./walletApi');
+ const result = await generateRecoveryPhrase();
+
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.wallet_generate_mnemonic',
+ params: { wordCount: 12 },
+ });
+ expect(result).toEqual({ phrase: 'word1 ... word12', wordCount: 12 });
+ });
+
+ it('validateRecoveryPhrase asks the module to validate an imported phrase', async () => {
+ mockCallCoreRpc.mockResolvedValueOnce({ result: { valid: false } });
+
+ const { validateRecoveryPhrase } = await import('./walletApi');
+ const result = await validateRecoveryPhrase('abandon abandon');
+
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.wallet_validate_mnemonic',
+ params: { phrase: 'abandon abandon' },
+ });
+ expect(result).toBe(false);
+ });
+
+ it('deriveRecoveryMaterial requests module-owned seed and account derivation', async () => {
+ const seed = Array.from({ length: 64 }, (_, index) => index);
+ const accounts = [
+ { chain: 'evm' as const, address: '0xabc', derivationPath: "m/44'/60'/0'/0/0" },
+ ];
+ mockCallCoreRpc.mockResolvedValueOnce({ result: { seed, accounts } });
+
+ const { deriveRecoveryMaterial } = await import('./walletApi');
+ const result = await deriveRecoveryMaterial('secret phrase');
+
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.wallet_derive_recovery_material',
+ params: { phrase: 'secret phrase' },
+ });
+ expect(result.seed).toEqual(Uint8Array.from({ length: 64 }, (_, index) => index));
+ expect(seed).toEqual(new Array(64).fill(0));
+ expect(result.accounts).toEqual(accounts);
+ });
+
it('setupLocalWallet calls the wallet setup RPC with params', async () => {
const payload = {
consentGranted: true,
diff --git a/app/src/services/walletApi.ts b/app/src/services/walletApi.ts
index 57eb580b56..ce559d568b 100644
--- a/app/src/services/walletApi.ts
+++ b/app/src/services/walletApi.ts
@@ -29,6 +29,17 @@ export interface WalletAccount {
derivationPath: string;
}
+export interface WalletRecoveryMaterial {
+ /** Standard BIP-39 seed; consumed and cleared by the storage-key KDF. */
+ seed: Uint8Array;
+ accounts: WalletAccount[];
+}
+
+export interface GeneratedRecoveryPhrase {
+ phrase: string;
+ wordCount: number;
+}
+
export interface WalletStatus {
configured: boolean;
onboardingCompleted: boolean;
@@ -62,6 +73,35 @@ export const fetchWalletStatus = async (): Promise<WalletStatus> => {
return response.result;
};
+/** Generate recovery material through the confidentially called TinyWallet module. */
+export const generateRecoveryPhrase = async (): Promise<GeneratedRecoveryPhrase> => {
+ const response = await callCoreRpc<{ result: GeneratedRecoveryPhrase }>({
+ method: 'openhuman.wallet_generate_mnemonic',
+ params: { wordCount: 12 },
+ });
+ return response.result;
+};
+
+/** Validate an imported phrase in the TinyWallet module without local derivation. */
+export const validateRecoveryPhrase = async (phrase: string): Promise<boolean> => {
+ const response = await callCoreRpc<{ result: { valid: boolean } }>({
+ method: 'openhuman.wallet_validate_mnemonic',
+ params: { phrase },
+ });
+ return response.result.valid;
+};
+
+/** Derive the generic storage-key seed and public accounts through TinyWallet. */
+export const deriveRecoveryMaterial = async (phrase: string): Promise<WalletRecoveryMaterial> => {
+ const response = await callCoreRpc<{ result: { seed: number[]; accounts: WalletAccount[] } }>({
+ method: 'openhuman.wallet_derive_recovery_material',
+ params: { phrase },
+ });
+ const seed = Uint8Array.from(response.result.seed);
+ response.result.seed.fill(0);
+ return { seed, accounts: response.result.accounts };
+};
+
export const setupLocalWallet = async (params: SetupWalletParams): Promise<WalletStatus> => {
const response = await callCoreRpc<{ result: WalletStatus }>({
method: 'openhuman.wallet_setup',
diff --git a/app/src/utils/cryptoKeys.test.ts b/app/src/utils/cryptoKeys.test.ts
index 1bd4707b8a..40b9429969 100644
--- a/app/src/utils/cryptoKeys.test.ts
+++ b/app/src/utils/cryptoKeys.test.ts
@@ -1,182 +1,29 @@
import { describe, expect, it } from 'vitest';
-import {
- deriveAesKeyFromMnemonic,
- deriveBtcAddressFromMnemonic,
- deriveEvmAddressFromMnemonic,
- deriveSolanaAddressFromMnemonic,
- deriveTronAddressFromMnemonic,
- deriveWalletAccountsFromMnemonic,
- generateMnemonicPhrase,
- MNEMONIC_GENERATE_WORD_COUNT,
- validateMnemonicPhrase,
-} from './cryptoKeys';
+import { deriveAesKeyFromSeed } from './cryptoKeys';
-// Known-good 12-word BIP39 mnemonic for deterministic assertions.
-const KNOWN_MNEMONIC =
- 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about';
+// BIP-39's published empty-passphrase seed for `abandon` x11 + `about`.
+const CANONICAL_SEED_HEX =
+ '5eb00bbddcf069084889a8ab9155568165f5c453ccb85e70811aaed6f6da5fc19a5ac40b389cd370d086206dec8aa6c43daea6690f20ad3d8d48b2d2ce9e38e4';
-describe('MNEMONIC_GENERATE_WORD_COUNT', () => {
- it('is 12', () => {
- expect(MNEMONIC_GENERATE_WORD_COUNT).toBe(12);
- });
-});
-
-describe('generateMnemonicPhrase', () => {
- it('returns a 12-word phrase', () => {
- const phrase = generateMnemonicPhrase();
- expect(phrase.trim().split(/\s+/)).toHaveLength(12);
- });
-
- it('returns a valid BIP39 mnemonic', () => {
- const phrase = generateMnemonicPhrase();
- expect(validateMnemonicPhrase(phrase)).toBe(true);
- });
-
- it('produces a different phrase each call', () => {
- const a = generateMnemonicPhrase();
- const b = generateMnemonicPhrase();
- // Astronomically unlikely to collide; guards against a no-op implementation.
- expect(a).not.toBe(b);
- });
-});
-
-describe('validateMnemonicPhrase', () => {
- it('returns true for the known valid mnemonic', () => {
- expect(validateMnemonicPhrase(KNOWN_MNEMONIC)).toBe(true);
- });
-
- it('returns false for an empty string', () => {
- expect(validateMnemonicPhrase('')).toBe(false);
- });
-
- it('returns false for a single random word', () => {
- expect(validateMnemonicPhrase('abandon')).toBe(false);
- });
-
- it('returns false for 12 non-BIP39 words', () => {
- expect(
- validateMnemonicPhrase('foo bar baz qux quux corge grault garply waldo fred plugh xyzzy')
- ).toBe(false);
- });
-
- it('returns false for an otherwise valid phrase with one word replaced by a non-wordlist word', () => {
- const tampered = KNOWN_MNEMONIC.replace('abandon', 'xxxxxxxx');
- expect(validateMnemonicPhrase(tampered)).toBe(false);
- });
-});
-
-describe('deriveAesKeyFromMnemonic', () => {
- it('returns a 64-character hex string (256-bit key)', () => {
- const key = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);
- expect(key).toMatch(/^[0-9a-f]{64}$/);
- });
-
- it('is deterministic for the same mnemonic', () => {
- const key1 = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);
- const key2 = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);
- expect(key1).toBe(key2);
- });
-
- it('produces a different key for a different mnemonic', () => {
- const other = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong';
- expect(validateMnemonicPhrase(other)).toBe(true);
- const keyA = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);
- const keyB = deriveAesKeyFromMnemonic(other);
- expect(keyA).not.toBe(keyB);
- });
-
- it('returns a fixed known value for the all-abandon mnemonic', () => {
- // Pinned output for salt='openhuman-aes-key-v1', PBKDF2-SHA256, c=100000, dkLen=32.
- // If this assertion fails, the KDF parameters or salt have changed — update intentionally.
- const key = deriveAesKeyFromMnemonic(KNOWN_MNEMONIC);
- expect(key).toBe('dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1');
- });
-});
+function bytesFromHex(hex: string): Uint8Array {
+ return Uint8Array.from(hex.match(/.{2}/g) ?? [], byte => Number.parseInt(byte, 16));
+}
-describe('deriveEvmAddressFromMnemonic', () => {
- it('returns a 0x-prefixed 42-character string', () => {
- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- expect(address).toMatch(/^0x[0-9a-fA-F]{40}$/);
- });
-
- it('is deterministic for the same mnemonic', () => {
- const addr1 = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- const addr2 = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- expect(addr1).toBe(addr2);
- });
+describe('deriveAesKeyFromSeed', () => {
+ it('preserves the existing storage-key result for the canonical BIP-39 seed', () => {
+ const seed = bytesFromHex(CANONICAL_SEED_HEX);
- it('returns the well-known address for the all-abandon mnemonic', () => {
- // MetaMask / BIP44 m/44'/60'/0'/0/0 for all-abandon is a stable known address.
- // Pinned in EIP-55 checksummed form — validates both identity and checksum casing.
- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- expect(address).toBe('0x9858EfFD232B4033E47d90003D41EC34EcaEda94');
- });
-
- it('returns a different address for a different mnemonic', () => {
- const other = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong';
- const addrA = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- const addrB = deriveEvmAddressFromMnemonic(other);
- expect(addrA).not.toBe(addrB);
- });
-
- it('produces a checksummed address (EIP-55)', () => {
- const address = deriveEvmAddressFromMnemonic(KNOWN_MNEMONIC);
- // At least some characters must be uppercase (otherwise it would just be lowercase hex).
- // EIP-55 checksummed addresses contain mixed case by design.
- const hex = address.slice(2);
- // Not all-lowercase and not all-uppercase → mixed casing applied.
- const hasUpper = hex !== hex.toLowerCase();
- const hasLower = hex !== hex.toUpperCase();
- expect(hasUpper && hasLower).toBe(true);
- });
-});
-
-describe('deriveBtcAddressFromMnemonic', () => {
- it('returns the well-known address for the all-abandon mnemonic', () => {
- expect(deriveBtcAddressFromMnemonic(KNOWN_MNEMONIC)).toBe('1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA');
- });
-});
-
-describe('deriveSolanaAddressFromMnemonic', () => {
- it('returns the well-known address for the all-abandon mnemonic', () => {
- expect(deriveSolanaAddressFromMnemonic(KNOWN_MNEMONIC)).toBe(
- 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk'
+ expect(deriveAesKeyFromSeed(seed)).toBe(
+ 'dce707ee483afb0a70cb2e076295f9f914e0c62cc097895eabda1c0c1f2f0cb1'
);
+ expect(seed).toEqual(new Uint8Array(64));
});
-});
-describe('deriveTronAddressFromMnemonic', () => {
- it('returns the well-known address for the all-abandon mnemonic', () => {
- expect(deriveTronAddressFromMnemonic(KNOWN_MNEMONIC)).toBe(
- 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH'
- );
- });
-});
+ it('rejects a non-BIP-39-sized seed and clears it', () => {
+ const seed = new Uint8Array([1, 2, 3]);
-describe('deriveWalletAccountsFromMnemonic', () => {
- it('returns one derived identity per supported chain in a stable order', () => {
- expect(deriveWalletAccountsFromMnemonic(KNOWN_MNEMONIC)).toEqual([
- {
- chain: 'evm',
- address: '0x9858EfFD232B4033E47d90003D41EC34EcaEda94',
- derivationPath: "m/44'/60'/0'/0/0",
- },
- {
- chain: 'btc',
- address: '1LqBGSKuX5yYUonjxT5qGfpUsXKYYWeabA',
- derivationPath: "m/44'/0'/0'/0/0",
- },
- {
- chain: 'solana',
- address: 'HAgk14JpMQLgt6rVgv7cBQFJWFto5Dqxi472uT3DKpqk',
- derivationPath: "m/44'/501'/0'/0'",
- },
- {
- chain: 'tron',
- address: 'TUEZSdKsoDHQMeZwihtdoBiN46zxhGWYdH',
- derivationPath: "m/44'/195'/0'/0/0",
- },
- ]);
+ expect(() => deriveAesKeyFromSeed(seed)).toThrow(/exactly 64 bytes/i);
+ expect(seed).toEqual(new Uint8Array(3));
});
});
diff --git a/app/src/utils/cryptoKeys.ts b/app/src/utils/cryptoKeys.ts
index 991ecfee76..72908ea75f 100644
--- a/app/src/utils/cryptoKeys.ts
+++ b/app/src/utils/cryptoKeys.ts
@@ -1,177 +1,24 @@
-import { ed25519 } from '@noble/curves/ed25519.js';
-import { hmac } from '@noble/hashes/hmac.js';
-import { ripemd160 } from '@noble/hashes/legacy.js';
import { pbkdf2 } from '@noble/hashes/pbkdf2.js';
-import { sha256, sha512 } from '@noble/hashes/sha2.js';
-import { keccak_256 } from '@noble/hashes/sha3.js';
+import { sha256 } from '@noble/hashes/sha2.js';
import { bytesToHex } from '@noble/hashes/utils.js';
-import { getPublicKey } from '@noble/secp256k1';
-import { base58 } from '@scure/base';
-import { HDKey } from '@scure/bip32';
-import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
-import { wordlist } from '@scure/bip39/wordlists/english.js';
-/** Word count for newly generated recovery phrases (128-bit entropy, BIP39). */
+/** Word count used when the wallet module generates a new recovery phrase. */
export const MNEMONIC_GENERATE_WORD_COUNT = 12;
-type WalletChain = 'evm' | 'btc' | 'solana' | 'tron';
-export type WalletSetupSource = 'generated' | 'imported';
-
-interface WalletAccountIdentity {
- chain: WalletChain;
- address: string;
- derivationPath: string;
-}
-
-/**
- * Generate a 12-word BIP39 mnemonic phrase (128-bit entropy).
- */
-export function generateMnemonicPhrase(): string {
- return generateMnemonic(wordlist, 128);
-}
-
-/**
- * Validate a BIP39 mnemonic phrase.
- */
-export function validateMnemonicPhrase(mnemonic: string): boolean {
- return validateMnemonic(mnemonic, wordlist);
-}
/**
- * Derive a 256-bit AES encryption key from a mnemonic phrase.
- * Uses BIP39 seed derivation followed by PBKDF2-SHA256.
- * Returns the key as a hex string.
+ * Derive the existing 256-bit OpenHuman storage key from a module-derived
+ * BIP-39 seed. The seed buffer is cleared after the generic storage KDF runs.
*/
-export function deriveAesKeyFromMnemonic(mnemonic: string): string {
- // Get the BIP39 seed (512-bit) from the mnemonic
- const seed = mnemonicToSeedSync(mnemonic);
-
- // Derive a 256-bit AES key using PBKDF2 with the seed
- const salt = new TextEncoder().encode('openhuman-aes-key-v1');
- const derivedKey = pbkdf2(sha256, seed, salt, { c: 100000, dkLen: 32 });
-
- return bytesToHex(derivedKey);
-}
-
-/** BIP44 path for first Ethereum account: m/44'/60'/0'/0/0 */
-const EVM_DERIVATION_PATH = "m/44'/60'/0'/0/0";
-const BTC_DERIVATION_PATH = "m/44'/0'/0'/0/0";
-const SOLANA_DERIVATION_PATH = "m/44'/501'/0'/0'";
-const TRON_DERIVATION_PATH = "m/44'/195'/0'/0/0";
-
-/**
- * Derive the first EVM wallet address (Ethereum BIP44) from a mnemonic phrase.
- * Uses path m/44'/60'/0'/0/0. Returns a checksummed 0x-prefixed address.
- */
-export function deriveEvmAddressFromMnemonic(mnemonic: string): string {
- const privateKey = deriveSecp256k1PrivateKey(mnemonic, EVM_DERIVATION_PATH);
- // Ethereum address = keccak256(uncompressed public key without 0x04)[12:]
- const pubKey = getPublicKey(privateKey, false); // uncompressed, 65 bytes
- const hash = keccak_256(pubKey.slice(1));
- const addressBytes = hash.slice(-20);
- const hex = bytesToHex(addressBytes);
- return toChecksumAddress('0x' + hex);
-}
-
-export function deriveBtcAddressFromMnemonic(mnemonic: string): string {
- const privateKey = deriveSecp256k1PrivateKey(mnemonic, BTC_DERIVATION_PATH);
- const compressedPublicKey = getPublicKey(privateKey, true);
- const payload = new Uint8Array(21);
- payload[0] = 0x00;
- payload.set(ripemd160(sha256(compressedPublicKey)), 1);
- return base58CheckEncode(payload);
-}
-
-export function deriveSolanaAddressFromMnemonic(mnemonic: string): string {
- const seed = mnemonicToSeedSync(mnemonic);
- const privateKey = deriveSlip10Ed25519PrivateKey(seed, SOLANA_DERIVATION_PATH);
- return base58.encode(ed25519.getPublicKey(privateKey));
-}
-
-export function deriveTronAddressFromMnemonic(mnemonic: string): string {
- const privateKey = deriveSecp256k1PrivateKey(mnemonic, TRON_DERIVATION_PATH);
- const publicKey = getPublicKey(privateKey, false);
- const payload = new Uint8Array(21);
- payload[0] = 0x41;
- payload.set(keccak_256(publicKey.slice(1)).slice(-20), 1);
- return base58CheckEncode(payload);
-}
-
-export function deriveWalletAccountsFromMnemonic(mnemonic: string): WalletAccountIdentity[] {
- return [
- {
- chain: 'evm',
- address: deriveEvmAddressFromMnemonic(mnemonic),
- derivationPath: EVM_DERIVATION_PATH,
- },
- {
- chain: 'btc',
- address: deriveBtcAddressFromMnemonic(mnemonic),
- derivationPath: BTC_DERIVATION_PATH,
- },
- {
- chain: 'solana',
- address: deriveSolanaAddressFromMnemonic(mnemonic),
- derivationPath: SOLANA_DERIVATION_PATH,
- },
- {
- chain: 'tron',
- address: deriveTronAddressFromMnemonic(mnemonic),
- derivationPath: TRON_DERIVATION_PATH,
- },
- ];
-}
-
-/** Simple checksum: lowercase with 0x, then capitalize by hash. */
-function toChecksumAddress(address: string): string {
- const a = address.replace(/^0x/i, '').toLowerCase();
- const hash = bytesToHex(keccak_256(new TextEncoder().encode(a)));
- let result = '0x';
- for (let i = 0; i < 40; i++) {
- result += parseInt(hash[i], 16) >= 8 ? a[i].toUpperCase() : a[i];
+export function deriveAesKeyFromSeed(seed: Uint8Array): string {
+ if (seed.length !== 64) {
+ seed.fill(0);
+ throw new Error('Recovery seed must be exactly 64 bytes.');
}
- return result;
-}
-
-function deriveSecp256k1PrivateKey(mnemonic: string, derivationPath: string): Uint8Array {
- const seed = mnemonicToSeedSync(mnemonic);
- const hdkey = HDKey.fromMasterSeed(seed);
- const derived = hdkey.derive(derivationPath);
- if (!derived.privateKey) {
- throw new Error(`Failed to derive private key for path ${derivationPath}`);
- }
- return derived.privateKey;
-}
-
-function deriveSlip10Ed25519PrivateKey(seed: Uint8Array, derivationPath: string): Uint8Array {
- let key = hmac(sha512, new TextEncoder().encode('ed25519 seed'), seed);
- let privateKey = key.slice(0, 32);
- let chainCode = key.slice(32);
-
- for (const segment of derivationPath.split('/').slice(1)) {
- if (!segment.endsWith("'")) {
- throw new Error(`Ed25519 derivation path must be fully hardened: ${derivationPath}`);
- }
- const index = Number.parseInt(segment.slice(0, -1), 10);
- const hardened = (index + 0x80000000) >>> 0;
- const data = new Uint8Array(37);
- data[0] = 0;
- data.set(privateKey, 1);
- data[33] = (hardened >>> 24) & 0xff;
- data[34] = (hardened >>> 16) & 0xff;
- data[35] = (hardened >>> 8) & 0xff;
- data[36] = hardened & 0xff;
- key = hmac(sha512, chainCode, data);
- privateKey = key.slice(0, 32);
- chainCode = key.slice(32);
+ const salt = new TextEncoder().encode('openhuman-aes-key-v1');
+ try {
+ const derivedKey = pbkdf2(sha256, seed, salt, { c: 100000, dkLen: 32 });
+ return bytesToHex(derivedKey);
+ } finally {
+ seed.fill(0);
}
-
- return privateKey;
-}
-
-function base58CheckEncode(payload: Uint8Array): string {
- const checksum = sha256(sha256(payload)).slice(0, 4);
- const bytes = new Uint8Array(payload.length + checksum.length);
- bytes.set(payload, 0);
- bytes.set(checksum, payload.length);
- return base58.encode(bytes);
}
diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lock
index 2924d19016..8cb9a221fd 100644
--- a/crates/openhuman-app/Cargo.lock
+++ b/crates/openhuman-app/Cargo.lock
@@ -460,12 +460,6 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
-[[package]]
-name = "bech32"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "efbd3e1070bbdf4cd88a75264e18e8a26f7cb5c6949eadf0ceb85fb159cf08f8"
-
[[package]]
name = "bit-set"
version = "0.8.0"
@@ -557,7 +551,6 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
- "sha2 0.10.9",
"tinyvec",
]
@@ -1106,22 +1099,7 @@ dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"curve25519-dalek-derive",
- "fiat-crypto 0.2.9",
- "rustc_version",
- "subtle",
- "zeroize",
-]
-
-[[package]]
-name = "curve25519-dalek"
-version = "5.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
-dependencies = [
- "cfg-if",
- "cpufeatures 0.3.1",
- "curve25519-dalek-derive",
- "fiat-crypto 0.3.0",
+ "fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
@@ -1678,12 +1656,6 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
-[[package]]
-name = "fiat-crypto"
-version = "0.3.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
-
[[package]]
name = "field-offset"
version = "0.3.6"
@@ -3094,16 +3066,6 @@ dependencies = [
"zmij",
]
-[[package]]
-name = "keccak"
-version = "0.2.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"
-dependencies = [
- "cfg-if",
- "cpufeatures 0.3.1",
-]
-
[[package]]
name = "keyboard-types"
version = "0.7.0"
@@ -4054,9 +4016,6 @@ dependencies = [
"tinytools-std",
"tinyvoice-bus",
"tinywallet-bus",
- "tinywallet-crypto",
- "tinywallet-web3",
- "tinywallet-x402",
"tokio",
"tokio-tungstenite 0.29.0",
"tokio-util",
@@ -5856,17 +5815,6 @@ dependencies = [
"digest 0.11.3",
]
-[[package]]
-name = "sha3"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
-dependencies = [
- "digest 0.11.3",
- "keccak",
- "sponge-cursor",
-]
-
[[package]]
name = "sharded-slab"
version = "0.1.7"
@@ -6040,12 +5988,6 @@ dependencies = [
"system-deps",
]
-[[package]]
-name = "sponge-cursor"
-version = "0.1.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
-
[[package]]
name = "sqlite-wasm-rs"
version = "0.5.5"
@@ -7651,72 +7593,11 @@ dependencies = [
[[package]]
name = "tinywallet-bus"
-version = "0.13.0"
-dependencies = [
- "serde",
- "serde_json",
- "thiserror 2.0.20",
-]
-
-[[package]]
-name = "tinywallet-crypto"
-version = "0.13.0"
-dependencies = [
- "async-trait",
- "bech32",
- "bs58",
- "hex",
- "serde",
- "serde_json",
- "sha2 0.11.0",
- "sha3",
- "thiserror 2.0.20",
- "tinywallet-bus",
-]
-
-[[package]]
-name = "tinywallet-web3"
-version = "0.13.0"
-dependencies = [
- "anyhow",
- "async-trait",
- "base64 0.23.1",
- "bs58",
- "curve25519-dalek 5.0.0",
- "hex",
- "log",
- "parking_lot",
- "serde",
- "serde_json",
- "sha2 0.11.0",
- "tinytools",
- "tinywallet-bus",
- "tinywallet-crypto",
- "tinywallet-x402",
-]
-
-[[package]]
-name = "tinywallet-x402"
-version = "0.13.0"
+version = "0.19.0"
dependencies = [
- "anyhow",
- "async-trait",
- "base64 0.23.1",
- "bs58",
- "chrono",
- "curve25519-dalek 5.0.0",
- "hex",
- "log",
- "reqwest 0.13.5",
"serde",
"serde_json",
- "sha2 0.11.0",
- "sha3",
"thiserror 2.0.20",
- "tinytools",
- "tinywallet-bus",
- "tinywallet-crypto",
- "uuid",
]
[[package]]
@@ -9426,7 +9307,7 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277"
dependencies = [
- "curve25519-dalek 4.1.3",
+ "curve25519-dalek",
"rand_core 0.6.4",
"serde",
"zeroize",
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 8758f91c75..b2f661c497 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -455,32 +455,14 @@ tinyhosts-bus = { path = "../../vendor/tinyhosts/crates/tinyhosts-bus", optional
# not pay for it. See the two-set note above `default`.
#
# Taken as `tinywallet-bus`, the contract crate, and NOT the root `tinywallet`
-# crate. The root crate is where key derivation, transaction building, signing
-# and the chain clients live, and those are the gates that pull the `bitcoin`
-# crate and its native secp256k1 build; all of it happens inside the loaded
-# `tinywallet` module now, so this binary links none of it. What the contract
-# crate carries is exactly what a host still runs itself: the wire types that
-# cross the bus, the bus member names, address validation, the EIP-712 and ERC-20
-# encoders the x402 payment path builds with, the `Transport` seam this crate
-# implements, and the Tron verifier that checks what a node handed back before
-# a transaction is sent for signing.
+# crate. The host carries transport-neutral wire vocabulary only; wallet,
+# Web3, x402 parsing, payment construction, signing, ABI encoding and ledger
+# behavior execute inside the loaded TinyWallet module.
#
# The root crate is still taken under [dev-dependencies], where test fixtures
# 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 }
-# Transitional adapter dependency: the pre-cutover host WalletEngine still
-# consumes this leaf transport trait. It is removed with the direct engine path
-# once every Wallet/Web3/x402 caller uses the module contract.
-tinywallet-crypto = { path = "../../vendor/tinywallet/crates/tinywallet-crypto", default-features = false, features = ["net", "serde"], 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 }
+tinywallet-bus = { path = "../../vendor/tinywallet/crates/tinywallet-bus", default-features = false, features = ["wire"], optional = true }
[target.'cfg(windows)'.dependencies]
@@ -707,31 +689,14 @@ voice = [
# `voice::live`: live voice agent sessions over tinyagents-live.
"dep:tinyagents-live",
]
-# Web3 family: openhuman::web3 + web3::wallet + web3::x402 — the
-# crypto wallet (multi-chain sign/broadcast), the high-level swap/bridge/dapp
-# 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) + `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
-# binary derives a key or signs with secp256k1 any more — the wallet module
-# does both. `k256` is gone entirely; `coins-bip39` is gone entirely
-# (the fixtures derive through `tinywallet`'s own copy).
-#
-# `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 family: product RPC/controllers, module adapters, and host-configured
+# transport/custody/approval callbacks for Wallet, swaps, bridges, dapps, and
+# x402. The algorithms and provider-specific state live in TinyWallet; this
+# feature carries only the lightweight bus contract and generic HTTP client.
web3 = [
"dep:reqwest13",
"dep:webpki-roots",
"dep:tinywallet-bus",
- "dep:tinywallet-crypto",
- "dep:tinywallet-x402",
- "dep:tinywallet-web3",
"modules",
]
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
index ca8d63cb9f..22788af04d 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder.rs
@@ -21,6 +21,15 @@ use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::agent::tinyagents::model::TurnChatModel;
use crate::agent::tinyagents::turn_outcome::ToolOutcomeSink;
+/// Window assumed for sizing microcompact when the model's context window is
+/// unknown (not in any static table, no `context_length` from `/v1/models`).
+/// Deliberately conservative: small enough that a runaway transcript is still
+/// blanked well before any real model overflows, large enough that a short run
+/// stays append-only and prompt-cache eligible. Used only for microcompact;
+/// compression and trim still treat an unknown window as "nothing to size
+/// against", and known-window behaviour is unchanged.
+pub(super) const UNKNOWN_WINDOW_FALLBACK_TOKENS: u64 = 64_000;
+
/// Fractions of a capped turn's model-call budget at which the model is told
/// how many calls are left (#6958; `FinalCallWrapUpMiddleware::with_budget_notice`).
const BUDGET_NOTICE_THRESHOLDS: [f64; 2] = [0.5, 0.8];
@@ -154,16 +163,8 @@ pub(super) fn install_context_ladder(
// answered from the last five results while well inside a window with
// room for all ten. Not a capped-turn problem: every turn. The budget
// matches the trim's allowance, putting microcompact strictly behind
- // compression. With no window there is nothing to size against and
- // nothing else bounding growth, so always-blank stays as the backstop.
- let microcompact = tinyagents_harness::middleware::MicrocompactMiddleware::new(
- microcompact_keep_recent,
- crate::agent::context::CLEARED_PLACEHOLDER,
- );
- let microcompact = match context_window.filter(|w| *w > 0) {
- Some(window) => microcompact.with_token_budget(legacy_max_input_tokens(window).max(1)),
- None => microcompact,
- };
+ // compression. See `microcompact_middleware` for the unknown-window case.
+ let microcompact = microcompact_middleware(microcompact_keep_recent, context_window);
// Emit `AgentEvent::Compressed` when a body is cleared. Off by default —
// the middleware was built as "a silent transcript rewrite" — which is
// why blanking was, until now, the one reduction step nobody could see
@@ -354,6 +355,33 @@ pub(super) fn compression_policy(
.map(|policy| with_turn_aware_tail(policy, window))
}
+/// Build the microcompact step of the context ladder.
+///
+/// With a known window the token budget is the trim's allowance
+/// (`legacy_max_input_tokens(window)`). Without one, the budget is sized
+/// against [`UNKNOWN_WINDOW_FALLBACK_TOKENS`] instead of being left unset:
+/// a bare microcompact blanks every tool result older than `keep_recent` on
+/// every turn, and each blanking rewrites an already-sent prefix position, so
+/// the provider's prompt (KV) cache misses from that point on. Observed on a
+/// router whose model id had no static window: 77 of 80 turns emitted
+/// `compressed` events, only 48-67% of input tokens were cached (99% when the
+/// same prompts were sent append-only) and cold calls took ~6-7 s vs ~3 s
+/// warm. The finite fallback keeps a short run append-only while still
+/// blanking once the transcript outgrows it, so growth stays bounded.
+pub(super) fn microcompact_middleware(
+ keep_recent: usize,
+ context_window: Option<u64>,
+) -> tinyagents_harness::middleware::MicrocompactMiddleware {
+ let window = context_window
+ .filter(|w| *w > 0)
+ .unwrap_or(UNKNOWN_WINDOW_FALLBACK_TOKENS);
+ tinyagents_harness::middleware::MicrocompactMiddleware::new(
+ keep_recent,
+ crate::agent::context::CLEARED_PLACEHOLDER,
+ )
+ .with_token_budget(legacy_max_input_tokens(window).max(1))
+}
+
/// Share of the context window a compaction keeps verbatim as its tail.
const COMPACTION_TAIL_WINDOW_FRACTION: f64 = 0.30;
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs
index 83d8e43df6..ffd5ed57bc 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_context_ladder_tests.rs
@@ -60,3 +60,33 @@ fn an_override_without_a_window_still_pins_with_a_token_tail() {
assert!(policy.pin_turn_user_message);
assert_eq!(policy.keep_recent_tokens, Some(19_200));
}
+
+// ── microcompact budget (prompt-cache churn when the window is unknown) ──────
+
+#[test]
+fn an_unknown_window_still_gives_microcompact_a_budget_so_short_runs_stay_append_only() {
+ // Unbudgeted microcompact blanks every old tool body on every turn, which
+ // rewrites the sent prefix and misses the provider's prompt cache.
+ for window in [None, Some(0)] {
+ let mw = microcompact_middleware(5, window);
+ assert_eq!(
+ mw.token_budget(),
+ Some(legacy_max_input_tokens(UNKNOWN_WINDOW_FALLBACK_TOKENS)),
+ "window {window:?}"
+ );
+ }
+}
+
+#[test]
+fn the_unknown_window_budget_is_finite_so_blanking_still_backstops_growth() {
+ let budget = microcompact_middleware(5, None).token_budget().unwrap();
+ assert!(budget < UNKNOWN_WINDOW_FALLBACK_TOKENS);
+ assert!(budget > 0);
+}
+
+#[test]
+fn a_known_window_keeps_the_trim_allowance_as_the_microcompact_budget() {
+ let mw = microcompact_middleware(5, Some(200_000));
+ assert_eq!(mw.token_budget(), Some(legacy_max_input_tokens(200_000)));
+ assert_eq!(mw.keep_recent(), 5);
+}
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index 43d5a83279..32f295b8ba 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -87,6 +87,8 @@ pub(crate) async fn run_relay_turn(
thread_id: String,
request_id: String,
) -> Vec<String> {
+ // One turn at a time per profile: wait behind its chat and cron turns.
+ let _turn = crate::profiles::turn_gate::acquire().await;
let workspace_dir = config.workspace_dir.clone();
// The thread is busy for the whole turn, so a background result due on it
// waits instead of landing mid-turn. The pipeline's session id does not
diff --git a/crates/openhuman-core/src/core/runtime/bootstrap.rs b/crates/openhuman-core/src/core/runtime/bootstrap.rs
index 53c6166c8e..f431f37948 100644
--- a/crates/openhuman-core/src/core/runtime/bootstrap.rs
+++ b/crates/openhuman-core/src/core/runtime/bootstrap.rs
@@ -166,19 +166,6 @@ pub(crate) async fn bootstrap_core_runtime(
// share one JSONL-backed store. Idempotent.
crate::platform::cost::init_global(cfg.cost.clone(), &workspace_dir);
- // --- x402 payment ledger ---
- // Initializes the JSONL-backed spending ledger for machine-payable API
- // payments (x402 protocol). Budget defaults can be overridden via
- // the `openhuman.x402_update_budget` RPC. Gated on the Web3 domain (#4808
- // review): under `harness()`/`none()` the x402 controllers are absent, so
- // their ledger must not initialize either.
- if domains.allows(crate::core::all::DomainGroup::Web3) {
- let x402_session = format!("x402-{}", uuid::Uuid::new_v4());
- crate::web3::x402::init_ledger(&workspace_dir, &x402_session);
- } else {
- log::debug!("[boot] x402 payment ledger SKIPPED — Web3 domain disabled");
- }
-
// --- Sub-agent definition registry bootstrap ---
// Loads built-in archetype definitions plus any custom TOML files
// under `<workspace>/agents/*.toml`. Idempotent — safe to call
diff --git a/crates/openhuman-core/src/modules/README.md b/crates/openhuman-core/src/modules/README.md
index a9c70d5ee2..0ddd507320 100644
--- a/crates/openhuman-core/src/modules/README.md
+++ b/crates/openhuman-core/src/modules/README.md
@@ -211,7 +211,7 @@ download, its `dlopen`, or its resident memory.
| Path | Module | What it does |
| --- | --- | --- |
| [`documents.rs`](documents.rs) | `tinydocs` | `generate_docx`, `generate_pptx`, `extract_text`, bounded `extract_document`, complete `convert_markdown`, `inspect_image`, and `render_pdf`. Inbound bytes ride a TinyBus stream; held results are pulled with `ReadOutput` and released. Feature `documents`. |
-| [`wallet.rs`](wallet.rs) | `tinywallet` | `derive_account`, `sign_transaction_in_module`, `sign_message`, `export_key`. Key material goes only to an attested module whose attested digest is one the registry pinned (`attested_proxy`). Feature `web3`. |
+| [`wallet.rs`](wallet.rs) | `tinywallet` | Typed wallet, Web3, ERC-20 encoding, and x402 calls. Key material goes only to confidential calls to an attested module whose digest is pinned by the registry (`attested_proxy`). Feature `web3`. |
| [`voice.rs`](voice.rs) | `tinyvoice` | Intent routing, command extraction, wake-word and hallucination checks, capture preparation, WAV encoding, frame energies, and a `VadSession` driven from the always-on capture loop. Every call returns a `VoiceCallError` the caller falls back from. Feature `voice`. |
| [`desktop.rs`](desktop.rs) | `tinycomputer` | The shared proxy for TinyComputer: loads it with an 8 second bound, reinitializes it when its configuration fingerprint changes, and exposes `call`, `permissions`, `state`, `jev_ready`. |
| [`computer_config.rs`](computer_config.rs) | `tinycomputer` | The private configuration: `jev` (decision model), `planner` (planner, rescue and output models), `browser` (Chrome path), `trace_path`. Rebuilt from `[computer]` and stored credentials on every call; `OPENHUMAN_COMPUTER_TRACE` turns tracing on. |
@@ -322,7 +322,7 @@ loadable:
| `tinydocs-bus` | `documents` |
| `tinyvoice-bus` | `voice` |
| `tinyjuice-bus` | inference kernel |
- | `tinywallet-bus` | `web3` (the chain primitives are in `tinywallet-crypto`) |
+ | `tinywallet-bus` | `web3` (transport-neutral module contract vocabulary) |
| `tinymcp-bus` | `mcp` |
| `tinysearch-bus` | search provider declarations and bus payloads |
| `tinycomputer-bus` | desktop, browser and task members |
@@ -343,8 +343,8 @@ loadable:
budgets, and approval of irreversible steps.
- Callers outside this folder: `runtime::client` re-exports `execute`,
`resolve` and `RuntimeCallError` from `modules::runtime` so `runtime/`
- compiles without the gate; `web3/seams.rs` and `web3/x402/seams.rs` use
- `wallet.rs`; `tools/impl/document`, `tools/impl/presentation`,
+ compiles without the gate; wallet, Web3, and x402 adapters use `wallet.rs`;
+ `tools/impl/document`, `tools/impl/presentation`,
`agent/multimodal.rs` and `agent/attachments/` use `documents.rs`;
`voice/always_on` and `voice/streaming.rs` use `voice.rs`;
`tools/impl/browser/` and `desktop/control/` use the TinyComputer files;
diff --git a/crates/openhuman-core/src/modules/host_tests.rs b/crates/openhuman-core/src/modules/host_tests.rs
index a2d8500c36..e7681b075b 100644
--- a/crates/openhuman-core/src/modules/host_tests.rs
+++ b/crates/openhuman-core/src/modules/host_tests.rs
@@ -30,6 +30,9 @@ async fn the_module_bus_is_a_singleton_and_serves_proxies() {
#[cfg(feature = "web3")]
#[tokio::test]
async fn wallet_host_callback_is_served_before_the_module_is_loaded() {
+ let workspace = tempfile::tempdir().expect("isolated wallet workspace");
+ let _workspace_env =
+ crate::web3::wallet::test_support::set_workspace_env_for_test(&workspace).await;
let runtime = runtime().await.expect("runtime should start");
let proxy = runtime
.proxy(
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index cb7d147e19..ac524919db 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -89,6 +89,10 @@ pub mod wallet;
mod wallet_host;
#[cfg(feature = "web3")]
pub(crate) mod wallet_service;
+#[cfg(feature = "web3")]
+pub(crate) mod web3_service;
+#[cfg(feature = "web3")]
+pub(crate) mod x402_service;
#[cfg(feature = "modules")]
pub use ops::{ensure_loaded, ensure_loaded_within, state_of, LoadError};
diff --git a/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs b/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs
index fd825aa5d2..700129c544 100644
--- a/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs
+++ b/crates/openhuman-core/src/modules/registry/records_docs_wallet.rs
@@ -95,101 +95,102 @@ pub(crate) const TINYDOCS: ModuleRecord = ModuleRecord {
/// The contract also exposes `ExportKey` for downstream hosts that must drive
/// a signer locally; OpenHuman itself does not call it.
///
-/// The pinned v0.13.0 release carries the native wallet, Web3, and x402 bus
-/// operations. Secret-bearing operations remain confidential and require both
-/// attestation and a matching pinned digest.
+/// The pinned v0.19.0 release carries the native wallet, Web3, and x402 bus
+/// operations, including typed configured-endpoint references. Secret-bearing
+/// operations remain confidential and require both attestation and a matching
+/// pinned digest.
pub(crate) const TINYWALLET: ModuleRecord = ModuleRecord {
id: "tinywallet",
description: "Transaction building and assembly for Bitcoin, EVM, Solana and Tron",
bus_name: "ai.tinyhumans.tinywallet.Wallet",
object_path: "/ai/tinyhumans/tinywallet/Wallet",
- version: "0.13.0",
- release_url: "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.13.0",
+ version: "0.19.0",
+ release_url: "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.19.0",
assets: &[
PlatformAsset {
host_key: "ubuntu-24.04-x86_64",
- archive: "tinywallet-module-0.13.0-ubuntu-24.04-x86_64.tar.gz",
- sha256: "284983d01c548109b3e9d5bbca1951787912f713b4a98920b9b45cfd034b6760",
+ archive: "tinywallet-module-0.19.0-ubuntu-24.04-x86_64.tar.gz",
+ sha256: "55c27a4c85631aee0509e9c74ae1eceb5f3fb3aa43540294bdd4991eac5500af",
},
PlatformAsset {
host_key: "ubuntu-24.04-arm64",
- archive: "tinywallet-module-0.13.0-ubuntu-24.04-arm64.tar.gz",
- sha256: "18ef8ffe518f731dc594d1606554ca12c840219e54f230382937061c395ab860",
+ archive: "tinywallet-module-0.19.0-ubuntu-24.04-arm64.tar.gz",
+ sha256: "aa79e84f60892f2ff624f42619f928b2699bdbea613f7bc2a0595f769c7f1d68",
},
PlatformAsset {
host_key: "ubuntu-22.04-x86_64",
- archive: "tinywallet-module-0.13.0-ubuntu-22.04-x86_64.tar.gz",
- sha256: "92d0d0fe9ab20fdf4c44aa58d762b7e28b6a08876899a5b2d368df3feabcd2d5",
+ archive: "tinywallet-module-0.19.0-ubuntu-22.04-x86_64.tar.gz",
+ sha256: "4511bf4a03f9163f5493472c1b294eccd8087e44efbde6b7e50c2ee4867b707c",
},
PlatformAsset {
host_key: "ubuntu-22.04-arm64",
- archive: "tinywallet-module-0.13.0-ubuntu-22.04-arm64.tar.gz",
- sha256: "4d0e17d778c0c84df17e4c5b7fa60aa9296efecc5726902008946409b3a3c9e1",
+ archive: "tinywallet-module-0.19.0-ubuntu-22.04-arm64.tar.gz",
+ sha256: "d981e334615d4a4d2ea003a4c3d59ee8f631d6f52532cfa70dc97143e97a6fe8",
},
PlatformAsset {
host_key: "macos-26-arm64",
- archive: "tinywallet-module-0.13.0-macos-26-arm64.tar.gz",
- sha256: "e01a70efbcece8e134abfa84c70181425802415525303d7ba2a7798afbab1041",
+ archive: "tinywallet-module-0.19.0-macos-26-arm64.tar.gz",
+ sha256: "bff93e7c33fcf663c0b69117add0e249c461233a58eb5ba2f1b753a9a8944350",
},
PlatformAsset {
host_key: "macos-26-x86_64",
- archive: "tinywallet-module-0.13.0-macos-26-x86_64.tar.gz",
- sha256: "c48f1f7807d0b25c2b54dca97237f6e64d02ec3a9396370cd8e3b1857419296a",
+ archive: "tinywallet-module-0.19.0-macos-26-x86_64.tar.gz",
+ sha256: "72e1ef5c1047c0ac848abb9cd1cf69e6639ac4e8527496979406922852a4d2d3",
},
PlatformAsset {
host_key: "macos-15-arm64",
- archive: "tinywallet-module-0.13.0-macos-15-arm64.tar.gz",
- sha256: "95f69f2e17ff1785d032f6e1017e12de5c6dc09af9633e67fc9c225dfcef9ce6",
+ archive: "tinywallet-module-0.19.0-macos-15-arm64.tar.gz",
+ sha256: "15397175e39dffbfe372bb40a4dccd6e03440ed5925043d41df058a335e1427d",
},
PlatformAsset {
host_key: "macos-15-x86_64",
- archive: "tinywallet-module-0.13.0-macos-15-x86_64.tar.gz",
- sha256: "f3114694e2d666ea1b030db952c589f08d79c60ab79aadb844327e273c5faaf5",
+ archive: "tinywallet-module-0.19.0-macos-15-x86_64.tar.gz",
+ sha256: "389e68114a4d1243afe04e8143e7f6ebd321c1cc24b54be2d768c7ee8643c7b1",
},
PlatformAsset {
host_key: "windows-2025-x86_64",
- archive: "tinywallet-module-0.13.0-windows-2025-x86_64.zip",
- sha256: "7b79a25a1fccef17a4c6e0d400f49646c3a5f321821bb03ddc23e76d6030717a",
+ archive: "tinywallet-module-0.19.0-windows-2025-x86_64.zip",
+ sha256: "17856ed57fb14840c3a4c5cde9167a68d9a8d578ee63728852b894d3d1e8fec1",
},
PlatformAsset {
host_key: "windows-2022-x86_64",
- archive: "tinywallet-module-0.13.0-windows-2022-x86_64.zip",
- sha256: "0b7126be04b23dd5fad883d7f1dd33dd65c1042af68f93593590ea07c5daa95e",
+ archive: "tinywallet-module-0.19.0-windows-2022-x86_64.zip",
+ sha256: "398bce97e33fa44faa3e92eb20cdd448089882233858a952b7710ad4d1806546",
},
PlatformAsset {
host_key: "windows-11-arm64",
- archive: "tinywallet-module-0.13.0-windows-11-arm64.zip",
- sha256: "483d3fda2c46de71c8efd5dfa4ec828c0b6c86bb164c8362c1356f85cb8ec231",
+ archive: "tinywallet-module-0.19.0-windows-11-arm64.zip",
+ sha256: "f91ef12a88c324a4c890be0ff8114239d835770541ce8cfd6059f015d3720764",
},
PlatformAsset {
host_key: "archlinux-arm64",
- archive: "tinywallet-module-0.13.0-archlinux-arm64.tar.gz",
- sha256: "ad2222bd1d2dd680568f486e40389c0b963cf5ba2d170f9d658985f31cabb511",
+ archive: "tinywallet-module-0.19.0-archlinux-arm64.tar.gz",
+ sha256: "59863d52205fabe486a16dfbf573a007d19c3237236cee3a8ff236281cdf6ba9",
},
PlatformAsset {
host_key: "archlinux-x86_64",
- archive: "tinywallet-module-0.13.0-archlinux-x86_64.tar.gz",
- sha256: "d67f541330f7712106238b90d993550d2e2e55f33d3c8c9f50669a1a51c1e981",
+ archive: "tinywallet-module-0.19.0-archlinux-x86_64.tar.gz",
+ sha256: "645679737effe617f566af7349dc7153f29dac21fa7a377a610ccf72054e7454",
},
PlatformAsset {
host_key: "fedora-43-arm64",
- archive: "tinywallet-module-0.13.0-fedora-43-arm64.tar.gz",
- sha256: "a2d62b03f2e99008ee3fe7ea84290fd050e12016ce36e89fda24d5449e795261",
+ archive: "tinywallet-module-0.19.0-fedora-43-arm64.tar.gz",
+ sha256: "c05ff2da4101246b7a50a37a44632a8502a5747f5e7cc416258fb728782d91b6",
},
PlatformAsset {
host_key: "fedora-43-x86_64",
- archive: "tinywallet-module-0.13.0-fedora-43-x86_64.tar.gz",
- sha256: "0c8c5dbf2aa7b7caa371aa6366c7cfdd232fda41e2dbd894d2ef344c7c2cfa0a",
+ archive: "tinywallet-module-0.19.0-fedora-43-x86_64.tar.gz",
+ sha256: "c4399bbb1c9d3c42545fb78474f548337cfc4a96ebb49ce50912ca4c85dd3aa4",
},
PlatformAsset {
host_key: "fedora-44-arm64",
- archive: "tinywallet-module-0.13.0-fedora-44-arm64.tar.gz",
- sha256: "272b535910fc4bc84099887b7ccfbdd9d41a6d187616086c174f86cb77f21757",
+ archive: "tinywallet-module-0.19.0-fedora-44-arm64.tar.gz",
+ sha256: "d17075dd175d0bd3bebe31350a3bcc58320c698f4c54f69691f85dd54297fdb9",
},
PlatformAsset {
host_key: "fedora-44-x86_64",
- archive: "tinywallet-module-0.13.0-fedora-44-x86_64.tar.gz",
- sha256: "3dcad60a65d4f0bbb1af838468a2f52d648d22b2fbc849ae0548a30ed9806646",
+ archive: "tinywallet-module-0.19.0-fedora-44-x86_64.tar.gz",
+ sha256: "ef64e56e536a2661ae0ddcd799632819c02f391a5e7f98431adc184f7df45adb",
},
],
load: LoadPolicy::Lazy,
diff --git a/crates/openhuman-core/src/modules/registry_tests.rs b/crates/openhuman-core/src/modules/registry_tests.rs
index a4421d21d9..3692685fa5 100644
--- a/crates/openhuman-core/src/modules/registry_tests.rs
+++ b/crates/openhuman-core/src/modules/registry_tests.rs
@@ -20,106 +20,110 @@ fn tinycomputer_registry_matches_bus_contract_and_published_release() {
}
#[test]
-fn tinywallet_registry_matches_the_verified_v013_release_manifest() {
+fn tinywallet_registry_matches_the_verified_v019_release_manifest() {
let wallet = find("tinywallet").expect("compiled TinyWallet module");
- assert_eq!(wallet.version, "0.13.0");
+ assert_eq!(wallet.version, "0.19.0");
+ assert_eq!(tinywallet_bus::CONTRACT_VERSION, (1, 13));
assert_eq!(
wallet.release_url,
- "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.13.0"
+ "https://github.com/tinyhumansai/tinywallet/releases/tag/v0.19.0"
);
- let actual = wallet
+ let mut actual = wallet
.assets
.iter()
.map(|asset| (asset.host_key, asset.archive, asset.sha256))
.collect::<Vec<_>>();
- let published = [
+ assert_eq!(wallet.assets.len(), 17);
+ let mut published = [
(
- "ubuntu-24.04-x86_64",
- "tinywallet-module-0.13.0-ubuntu-24.04-x86_64.tar.gz",
- "284983d01c548109b3e9d5bbca1951787912f713b4a98920b9b45cfd034b6760",
+ "archlinux-arm64",
+ "tinywallet-module-0.19.0-archlinux-arm64.tar.gz",
+ "59863d52205fabe486a16dfbf573a007d19c3237236cee3a8ff236281cdf6ba9",
),
(
- "ubuntu-24.04-arm64",
- "tinywallet-module-0.13.0-ubuntu-24.04-arm64.tar.gz",
- "18ef8ffe518f731dc594d1606554ca12c840219e54f230382937061c395ab860",
+ "archlinux-x86_64",
+ "tinywallet-module-0.19.0-archlinux-x86_64.tar.gz",
+ "645679737effe617f566af7349dc7153f29dac21fa7a377a610ccf72054e7454",
),
(
- "ubuntu-22.04-x86_64",
- "tinywallet-module-0.13.0-ubuntu-22.04-x86_64.tar.gz",
- "92d0d0fe9ab20fdf4c44aa58d762b7e28b6a08876899a5b2d368df3feabcd2d5",
+ "fedora-43-arm64",
+ "tinywallet-module-0.19.0-fedora-43-arm64.tar.gz",
+ "c05ff2da4101246b7a50a37a44632a8502a5747f5e7cc416258fb728782d91b6",
),
(
- "ubuntu-22.04-arm64",
- "tinywallet-module-0.13.0-ubuntu-22.04-arm64.tar.gz",
- "4d0e17d778c0c84df17e4c5b7fa60aa9296efecc5726902008946409b3a3c9e1",
+ "fedora-43-x86_64",
+ "tinywallet-module-0.19.0-fedora-43-x86_64.tar.gz",
+ "c4399bbb1c9d3c42545fb78474f548337cfc4a96ebb49ce50912ca4c85dd3aa4",
),
(
- "macos-26-arm64",
- "tinywallet-module-0.13.0-macos-26-arm64.tar.gz",
- "e01a70efbcece8e134abfa84c70181425802415525303d7ba2a7798afbab1041",
+ "fedora-44-arm64",
+ "tinywallet-module-0.19.0-fedora-44-arm64.tar.gz",
+ "d17075dd175d0bd3bebe31350a3bcc58320c698f4c54f69691f85dd54297fdb9",
),
(
- "macos-26-x86_64",
- "tinywallet-module-0.13.0-macos-26-x86_64.tar.gz",
- "c48f1f7807d0b25c2b54dca97237f6e64d02ec3a9396370cd8e3b1857419296a",
+ "fedora-44-x86_64",
+ "tinywallet-module-0.19.0-fedora-44-x86_64.tar.gz",
+ "ef64e56e536a2661ae0ddcd799632819c02f391a5e7f98431adc184f7df45adb",
),
(
"macos-15-arm64",
- "tinywallet-module-0.13.0-macos-15-arm64.tar.gz",
- "95f69f2e17ff1785d032f6e1017e12de5c6dc09af9633e67fc9c225dfcef9ce6",
+ "tinywallet-module-0.19.0-macos-15-arm64.tar.gz",
+ "15397175e39dffbfe372bb40a4dccd6e03440ed5925043d41df058a335e1427d",
),
(
"macos-15-x86_64",
- "tinywallet-module-0.13.0-macos-15-x86_64.tar.gz",
- "f3114694e2d666ea1b030db952c589f08d79c60ab79aadb844327e273c5faaf5",
+ "tinywallet-module-0.19.0-macos-15-x86_64.tar.gz",
+ "389e68114a4d1243afe04e8143e7f6ebd321c1cc24b54be2d768c7ee8643c7b1",
),
(
- "windows-2025-x86_64",
- "tinywallet-module-0.13.0-windows-2025-x86_64.zip",
- "7b79a25a1fccef17a4c6e0d400f49646c3a5f321821bb03ddc23e76d6030717a",
+ "macos-26-arm64",
+ "tinywallet-module-0.19.0-macos-26-arm64.tar.gz",
+ "bff93e7c33fcf663c0b69117add0e249c461233a58eb5ba2f1b753a9a8944350",
),
(
- "windows-2022-x86_64",
- "tinywallet-module-0.13.0-windows-2022-x86_64.zip",
- "0b7126be04b23dd5fad883d7f1dd33dd65c1042af68f93593590ea07c5daa95e",
+ "macos-26-x86_64",
+ "tinywallet-module-0.19.0-macos-26-x86_64.tar.gz",
+ "72e1ef5c1047c0ac848abb9cd1cf69e6639ac4e8527496979406922852a4d2d3",
),
(
- "windows-11-arm64",
- "tinywallet-module-0.13.0-windows-11-arm64.zip",
- "483d3fda2c46de71c8efd5dfa4ec828c0b6c86bb164c8362c1356f85cb8ec231",
+ "ubuntu-22.04-arm64",
+ "tinywallet-module-0.19.0-ubuntu-22.04-arm64.tar.gz",
+ "d981e334615d4a4d2ea003a4c3d59ee8f631d6f52532cfa70dc97143e97a6fe8",
),
(
- "archlinux-arm64",
- "tinywallet-module-0.13.0-archlinux-arm64.tar.gz",
- "ad2222bd1d2dd680568f486e40389c0b963cf5ba2d170f9d658985f31cabb511",
+ "ubuntu-22.04-x86_64",
+ "tinywallet-module-0.19.0-ubuntu-22.04-x86_64.tar.gz",
+ "4511bf4a03f9163f5493472c1b294eccd8087e44efbde6b7e50c2ee4867b707c",
),
(
- "archlinux-x86_64",
- "tinywallet-module-0.13.0-archlinux-x86_64.tar.gz",
- "d67f541330f7712106238b90d993550d2e2e55f33d3c8c9f50669a1a51c1e981",
+ "ubuntu-24.04-arm64",
+ "tinywallet-module-0.19.0-ubuntu-24.04-arm64.tar.gz",
+ "aa79e84f60892f2ff624f42619f928b2699bdbea613f7bc2a0595f769c7f1d68",
),
(
- "fedora-43-arm64",
- "tinywallet-module-0.13.0-fedora-43-arm64.tar.gz",
- "a2d62b03f2e99008ee3fe7ea84290fd050e12016ce36e89fda24d5449e795261",
+ "ubuntu-24.04-x86_64",
+ "tinywallet-module-0.19.0-ubuntu-24.04-x86_64.tar.gz",
+ "55c27a4c85631aee0509e9c74ae1eceb5f3fb3aa43540294bdd4991eac5500af",
),
(
- "fedora-43-x86_64",
- "tinywallet-module-0.13.0-fedora-43-x86_64.tar.gz",
- "0c8c5dbf2aa7b7caa371aa6366c7cfdd232fda41e2dbd894d2ef344c7c2cfa0a",
+ "windows-11-arm64",
+ "tinywallet-module-0.19.0-windows-11-arm64.zip",
+ "f91ef12a88c324a4c890be0ff8114239d835770541ce8cfd6059f015d3720764",
),
(
- "fedora-44-arm64",
- "tinywallet-module-0.13.0-fedora-44-arm64.tar.gz",
- "272b535910fc4bc84099887b7ccfbdd9d41a6d187616086c174f86cb77f21757",
+ "windows-2022-x86_64",
+ "tinywallet-module-0.19.0-windows-2022-x86_64.zip",
+ "398bce97e33fa44faa3e92eb20cdd448089882233858a952b7710ad4d1806546",
),
(
- "fedora-44-x86_64",
- "tinywallet-module-0.13.0-fedora-44-x86_64.tar.gz",
- "3dcad60a65d4f0bbb1af838468a2f52d648d22b2fbc849ae0548a30ed9806646",
+ "windows-2025-x86_64",
+ "tinywallet-module-0.19.0-windows-2025-x86_64.zip",
+ "17856ed57fb14840c3a4c5cde9167a68d9a8d578ee63728852b894d3d1e8fec1",
),
];
+ actual.sort_unstable();
+ published.sort_unstable();
assert_eq!(actual, published);
}
diff --git a/crates/openhuman-core/src/modules/wallet.rs b/crates/openhuman-core/src/modules/wallet.rs
index 091ff1ff79..1b384fc52d 100644
--- a/crates/openhuman-core/src/modules/wallet.rs
+++ b/crates/openhuman-core/src/modules/wallet.rs
@@ -70,9 +70,12 @@ use serde::de::DeserializeOwned;
use serde::Serialize;
use tinywallet_bus::names::methods;
use tinywallet_bus::wire::{
- DerivedAccount, ExportRequest, ExportedKey, Scheme, SecretMaterial, SignMessageRequest,
+ DeriveMnemonicSeedRequest, DeriveMnemonicSeedResponse, DerivedAccount,
+ EncodeErc20TransferRequest, EncodeErc20TransferResponse, ExportRequest, ExportedKey,
+ GenerateMnemonicRequest, GenerateMnemonicResponse, Scheme, SecretMaterial, SignMessageRequest,
SignRequest, Signature, SignedTransaction, TransactionSpec,
};
+use zeroize::Zeroize;
use super::{host, ops, registry};
use crate::config::Config;
@@ -147,15 +150,73 @@ pub async fn derive_account(
config: &Config,
secret: &SecretMaterial,
) -> Result<DerivedAccount, WalletCallError> {
- let proxy = attested_proxy(config).await?;
log::debug!(
"[modules:wallet] derive_account chain={:?} module={MODULE_ID} (confidential)",
secret.chain
);
- proxy
- .call_confidential(methods::DERIVE_ACCOUNT, (secret.clone(),))
- .await
- .map_err(|error| classify(&error))
+ let mut request = secret.clone();
+ let result = call_confidential(config, methods::DERIVE_ACCOUNT, &request).await;
+ request.mnemonic.zeroize();
+ result
+}
+
+/// Generate a recovery phrase inside the attested TinyWallet module.
+///
+/// # Errors
+///
+/// [`WalletCallError`]. The phrase is returned to the host for encryption and
+/// custody, but generation and BIP-39 vocabulary remain module-owned.
+pub async fn generate_mnemonic(
+ config: &Config,
+ word_count: u8,
+) -> Result<GenerateMnemonicResponse, WalletCallError> {
+ call_confidential(
+ config,
+ methods::GENERATE_MNEMONIC,
+ &GenerateMnemonicRequest { word_count },
+ )
+ .await
+}
+
+/// Derive a standard BIP-39 seed inside the attested module.
+///
+/// The caller uses the seed only for OpenHuman's generic storage-key KDF.
+///
+/// # Errors
+///
+/// [`WalletCallError`]. Invalid or unsupported phrases are classified as
+/// [`WalletCallError::InvalidInput`].
+pub async fn derive_mnemonic_seed(
+ config: &Config,
+ mnemonic: String,
+) -> Result<DeriveMnemonicSeedResponse, WalletCallError> {
+ let mut request = DeriveMnemonicSeedRequest { mnemonic };
+ let result = call_confidential(config, methods::DERIVE_MNEMONIC_SEED, &request).await;
+ request.mnemonic.zeroize();
+ result
+}
+
+/// Encode ERC-20 transfer calldata with the module-owned ABI implementation.
+///
+/// # Errors
+///
+/// Returns [`WalletCallError`] if the module is unavailable or rejects the
+/// recipient or base-unit amount.
+pub async fn encode_erc20_transfer(
+ config: &Config,
+ to_address: &str,
+ amount_raw: &str,
+) -> Result<String, WalletCallError> {
+ let response: EncodeErc20TransferResponse = call(
+ config,
+ methods::ENCODE_ERC20_TRANSFER,
+ &EncodeErc20TransferRequest {
+ to_address: to_address.to_owned(),
+ amount_raw: amount_raw.to_owned(),
+ },
+ )
+ .await?;
+ Ok(response.calldata)
}
/// Sign opaque bytes with the key derived from `secret`.
@@ -316,94 +377,94 @@ async fn attested_proxy(config: &Config) -> Result<tinybus::Proxy, WalletCallErr
Ok(proxy)
}
-// Library checksums verified against modules.toml and the library bytes in each
-// registry-pinned TinyWallet v0.13.0 archive. A library is trusted only while
-// its corresponding archive remains pinned in the supplied ModuleRecord.
+// Embedded library checksums verified from all 17 archives in the
+// registry-pinned TinyWallet v0.19.0 release. Each library is trusted only
+// while its archive checksum remains pinned in the supplied ModuleRecord.
const PINNED_WALLET_LIBRARIES: &[(&str, &str)] = &[
- // ubuntu-24.04-x86_64
+ // archlinux-arm64
(
- "284983d01c548109b3e9d5bbca1951787912f713b4a98920b9b45cfd034b6760",
- "f9a13c65e14b7cf9de57beeb40e8753a212234795a75fe8d8d11564a4ccabb67",
+ "59863d52205fabe486a16dfbf573a007d19c3237236cee3a8ff236281cdf6ba9",
+ "33929ad0096de1ea9e7a2cb03eeecba27ff35e44f8d10bc74941c65481c03683",
),
- // ubuntu-24.04-arm64
+ // archlinux-x86_64
(
- "18ef8ffe518f731dc594d1606554ca12c840219e54f230382937061c395ab860",
- "66961c39b0e2ebcb3c69ab1f6c1aa7cb59a830d787565b7fbb91339ca594d644",
+ "645679737effe617f566af7349dc7153f29dac21fa7a377a610ccf72054e7454",
+ "7770801d0ddc7c659391b3d1f06b3aa757cc086094c9bd9b40306de77e8b28c2",
),
- // ubuntu-22.04-x86_64
+ // fedora-43-arm64
(
- "92d0d0fe9ab20fdf4c44aa58d762b7e28b6a08876899a5b2d368df3feabcd2d5",
- "7b6fdd843622a29b610633e0f5cabf6f48c8aa7566a466696916e99d1221eb08",
+ "c05ff2da4101246b7a50a37a44632a8502a5747f5e7cc416258fb728782d91b6",
+ "3d23139debe5d9d0d69c9feefcbe2372449cda547f81eae590dfb82f7842e2e3",
),
- // ubuntu-22.04-arm64
+ // fedora-43-x86_64
(
- "4d0e17d778c0c84df17e4c5b7fa60aa9296efecc5726902008946409b3a3c9e1",
- "6f91352fbf5bdf69b7c76ae33f100b67320e3239573d4bb5402ba21ed51e7680",
+ "c4399bbb1c9d3c42545fb78474f548337cfc4a96ebb49ce50912ca4c85dd3aa4",
+ "2ddd77bf0645ad8dce6b8e4ab6554ac913d5f0e9ee21ab6b234c8d572d0d763e",
),
- // macos-26-arm64
+ // fedora-44-arm64
(
- "e01a70efbcece8e134abfa84c70181425802415525303d7ba2a7798afbab1041",
- "a8181f4a927f86182fadc4c65f12854cf7f719dc57b00ac1ff7da2e0a1ecc5b4",
+ "d17075dd175d0bd3bebe31350a3bcc58320c698f4c54f69691f85dd54297fdb9",
+ "d00d9630dff068c0980e9b81c6184eba0af11fd3168ea2bcdc57ebad713eb91a",
),
- // macos-26-x86_64
+ // fedora-44-x86_64
(
- "c48f1f7807d0b25c2b54dca97237f6e64d02ec3a9396370cd8e3b1857419296a",
- "684f2d74d3abaca8712eddafa0e7dd67ddfa9fa64ca03427959a03d20e31e3c0",
+ "ef64e56e536a2661ae0ddcd799632819c02f391a5e7f98431adc184f7df45adb",
+ "71df95081c6b0da69e52bb4ae461c841763436332eae5e19b269730a5bf1688e",
),
// macos-15-arm64
(
- "95f69f2e17ff1785d032f6e1017e12de5c6dc09af9633e67fc9c225dfcef9ce6",
- "39f3674672bfaef485838eba98a60fb21c173d5f161449abc0dacc4c2a8aa8ff",
+ "15397175e39dffbfe372bb40a4dccd6e03440ed5925043d41df058a335e1427d",
+ "e1e95043354060e98a604ef7a2c4ec0407bf22c906f4240b1438e303c4283bbd",
),
// macos-15-x86_64
(
- "f3114694e2d666ea1b030db952c589f08d79c60ab79aadb844327e273c5faaf5",
- "3ed1c36990a6fde7710d6616f7ddc2d68d0ed029c73f93aef859a0a023ed5e4b",
+ "389e68114a4d1243afe04e8143e7f6ebd321c1cc24b54be2d768c7ee8643c7b1",
+ "deb320a1e0214105e1621f83fbb43c3e884ed7923d5303ae56b113b4f31eef2e",
),
- // windows-2025-x86_64
+ // macos-26-arm64
(
- "7b79a25a1fccef17a4c6e0d400f49646c3a5f321821bb03ddc23e76d6030717a",
- "66278854fe0843d46f3029baa9e5deccaf9fa20d757eea20ceae321f3ee72310",
+ "bff93e7c33fcf663c0b69117add0e249c461233a58eb5ba2f1b753a9a8944350",
+ "4aaaec17daa9c3aca68c02342761138aa100a10886a3845a1e3068c755665091",
),
- // windows-2022-x86_64
+ // macos-26-x86_64
(
- "0b7126be04b23dd5fad883d7f1dd33dd65c1042af68f93593590ea07c5daa95e",
- "b547c227e56400f92ffd21829d510f455e4be446d049106e7490039919acb267",
+ "72e1ef5c1047c0ac848abb9cd1cf69e6639ac4e8527496979406922852a4d2d3",
+ "3655a3efb340c1959704b71e67056499e47b0dde719b9139e8d3a4d5608c7d57",
),
- // windows-11-arm64
+ // ubuntu-22.04-arm64
(
- "483d3fda2c46de71c8efd5dfa4ec828c0b6c86bb164c8362c1356f85cb8ec231",
- "ee10089c09b5e3b5f178484816fc90f297ad7c23e209d3281a10e0668d0aeaca",
+ "d981e334615d4a4d2ea003a4c3d59ee8f631d6f52532cfa70dc97143e97a6fe8",
+ "6a30e85422cfeb919efcf70ece5e503ba9fd6145eac1e6229caff326d7c438e7",
),
- // archlinux-arm64
+ // ubuntu-22.04-x86_64
(
- "ad2222bd1d2dd680568f486e40389c0b963cf5ba2d170f9d658985f31cabb511",
- "66766056becbb6d55078952989ae542c88758075bae58ce5e9c9294b7712701e",
+ "4511bf4a03f9163f5493472c1b294eccd8087e44efbde6b7e50c2ee4867b707c",
+ "04ed808e5c32234b9879a1468da6034c8bdc214beaf6da4f6303b1a9efb83f9b",
),
- // archlinux-x86_64
+ // ubuntu-24.04-arm64
(
- "d67f541330f7712106238b90d993550d2e2e55f33d3c8c9f50669a1a51c1e981",
- "725a256ded1ee0f2bc0f6360f1dac84f94423b8816162c4202b6c71d2194f1b1",
+ "aa79e84f60892f2ff624f42619f928b2699bdbea613f7bc2a0595f769c7f1d68",
+ "27ec59b039fff01ebf01ba065a061fa84c67552f3486e1e9757a1210a52304fd",
),
- // fedora-43-arm64
+ // ubuntu-24.04-x86_64
(
- "a2d62b03f2e99008ee3fe7ea84290fd050e12016ce36e89fda24d5449e795261",
- "3fb82b1ae8dbce52999be065b8e64bcc3668d056a2fba90a5f6f067343ea6161",
+ "55c27a4c85631aee0509e9c74ae1eceb5f3fb3aa43540294bdd4991eac5500af",
+ "5d0a3ae5881f91966249858cd155e5b9c244bd419d06698d808f972a8d23afc9",
),
- // fedora-43-x86_64
+ // windows-11-arm64
(
- "0c8c5dbf2aa7b7caa371aa6366c7cfdd232fda41e2dbd894d2ef344c7c2cfa0a",
- "7be79421594597b6fc8b9c15a16a7df3218f8d78651a3ac85153f6cb88d6532e",
+ "f91ef12a88c324a4c890be0ff8114239d835770541ce8cfd6059f015d3720764",
+ "0b702e879f7514f0204bc867c3c6e01e429fcba993ef1817be65110097c6b0bd",
),
- // fedora-44-arm64
+ // windows-2022-x86_64
(
- "272b535910fc4bc84099887b7ccfbdd9d41a6d187616086c174f86cb77f21757",
- "09226fb7f644746cd9ed12523ffc08962be035d5a2f1d5004f5e1bc70d74cb0d",
+ "398bce97e33fa44faa3e92eb20cdd448089882233858a952b7710ad4d1806546",
+ "83aaed32e29ead292066e123efb91f1ebd21545ea0d8a3b3ca20fdd7cd99e644",
),
- // fedora-44-x86_64
+ // windows-2025-x86_64
(
- "3dcad60a65d4f0bbb1af838468a2f52d648d22b2fbc849ae0548a30ed9806646",
- "b6eab1fc5076a55764cb44a04e500cc52928604a8c1b42ed9426e4ba9966ba4b",
+ "17856ed57fb14840c3a4c5cde9167a68d9a8d578ee63728852b894d3d1e8fec1",
+ "34d33e8534cb36acaf771cfd8a73a2dc6149ecdd4d143cc1af76088457795d8b",
),
];
diff --git a/crates/openhuman-core/src/modules/wallet_host.rs b/crates/openhuman-core/src/modules/wallet_host.rs
index b98bfe2cf1..bb90314120 100644
--- a/crates/openhuman-core/src/modules/wallet_host.rs
+++ b/crates/openhuman-core/src/modules/wallet_host.rs
@@ -10,12 +10,12 @@ use std::future::Future;
use std::sync::{Mutex, OnceLock};
use tinybus::ObjectPath;
+use tinywallet_bus::wire::HostEndpointReference;
use tinywallet_bus::wire::{
AuthorizationResult, AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest,
AuthorizeX402PaymentRequest, ChainTransportRequest, ChainTransportResult, HostResponse,
WalletAccountInfo, WalletAccountsResponse, WalletBackendRequest, WalletBackendResponse,
};
-use tinywallet_crypto::rpc::{NetworkId, Transport, TransportError};
const HOST_ERROR_NAME: &str = "ai.tinyhumans.tinywallet.Host.Error.CallbackFailed";
@@ -35,9 +35,17 @@ static APPROVALS: OnceLock<Mutex<HashSet<ApprovalKey>>> = OnceLock::new();
static NATIVE_APPROVAL_QUOTES: OnceLock<
Mutex<HashMap<String, tinywallet_bus::wire::PreparedTransaction>>,
> = OnceLock::new();
-static ENDPOINT_REFERENCES: OnceLock<
- Mutex<HashMap<String, (tinywallet_bus::wire::RpcEndpointKey, String)>>,
+static WEB3_APPROVAL_QUOTES: OnceLock<
+ Mutex<HashMap<String, tinywallet_bus::wire::Web3QuoteResponse>>,
> = OnceLock::new();
+static ENDPOINT_REFERENCES: OnceLock<Mutex<HashMap<String, EndpointReference>>> = OnceLock::new();
+
+#[derive(Debug, Clone)]
+struct EndpointReference {
+ service: String,
+ key: tinywallet_bus::wire::RpcEndpointKey,
+ url: String,
+}
fn approvals() -> &'static Mutex<HashSet<ApprovalKey>> {
APPROVALS.get_or_init(|| Mutex::new(HashSet::new()))
@@ -48,51 +56,70 @@ fn native_approval_quotes(
NATIVE_APPROVAL_QUOTES.get_or_init(|| Mutex::new(HashMap::new()))
}
-fn endpoint_references(
-) -> &'static Mutex<HashMap<String, (tinywallet_bus::wire::RpcEndpointKey, String)>> {
+fn web3_approval_quotes() -> &'static Mutex<HashMap<String, tinywallet_bus::wire::Web3QuoteResponse>>
+{
+ WEB3_APPROVAL_QUOTES.get_or_init(|| Mutex::new(HashMap::new()))
+}
+
+fn endpoint_references() -> &'static Mutex<HashMap<String, EndpointReference>> {
ENDPOINT_REFERENCES.get_or_init(|| Mutex::new(HashMap::new()))
}
+fn x402_request_owner_matches(
+ request: &AuthorizeX402PaymentRequest,
+ context: &crate::security::approval::ApprovalChatContext,
+) -> bool {
+ request.owner.as_ref().is_some_and(|owner| {
+ owner.thread_id == context.thread_id && owner.client_id == context.client_id
+ })
+}
+
+fn x402_approval_facts(request: &AuthorizeX402PaymentRequest) -> serde_json::Value {
+ serde_json::json!({
+ "url": request.url,
+ "network": request.network,
+ "asset": request.asset,
+ "recipient": request.recipient,
+ "amount_atomic": request.amount_atomic,
+ })
+}
+
/// Bind module-issued opaque endpoint aliases to the current host configuration.
/// Actual URLs remain in this process and are never serialized onto TinyBus.
pub(crate) fn bind_endpoint_references(
- configured: &tinywallet_bus::wire::NativeWalletConfigResponse,
+ service: &str,
+ references: &[HostEndpointReference],
) -> Result<(), String> {
- use tinywallet_bus::wire::RpcEndpointKey;
-
let mut resolved = HashMap::new();
- for endpoint in &configured.endpoint_references {
- let url = match endpoint.key {
- RpcEndpointKey::Evm { network } => {
- crate::web3::wallet::endpoints::rpc_url_for_evm_network(network)
- }
- RpcEndpointKey::Btc => crate::web3::wallet::endpoints::rpc_url_for_chain(
- tinywallet_web3::crypto::wallet::WalletChain::Btc,
- ),
- RpcEndpointKey::Solana => crate::web3::wallet::endpoints::rpc_url_for_chain(
- tinywallet_web3::crypto::wallet::WalletChain::Solana,
- ),
- RpcEndpointKey::Tron => crate::web3::wallet::endpoints::rpc_url_for_chain(
- tinywallet_web3::crypto::wallet::WalletChain::Tron,
- ),
- };
+ for endpoint in references {
+ let url = crate::web3::wallet::endpoints::override_for_endpoint(endpoint.key).ok_or_else(
+ || "wallet module referenced an endpoint without a host override".to_string(),
+ )?;
if endpoint.reference.trim().is_empty()
|| resolved
- .insert(endpoint.reference.clone(), (endpoint.key, url))
+ .insert(
+ endpoint.reference.clone(),
+ EndpointReference {
+ service: service.to_owned(),
+ key: endpoint.key,
+ url,
+ },
+ )
.is_some()
{
return Err("wallet module returned an invalid endpoint reference".into());
}
}
- *endpoint_references()
+ endpoint_references()
.lock()
- .map_err(|_| "wallet endpoint reference store is unavailable".to_string())? = resolved;
+ .map_err(|_| "wallet endpoint reference store is unavailable".to_string())?
+ .extend(resolved);
Ok(())
}
-pub(crate) fn clear_endpoint_references() {
+pub(crate) fn clear_endpoint_references(service: &str) {
if let Ok(mut references) = endpoint_references().lock() {
- references.clear();
+ references.retain(|_, endpoint| endpoint.service != service);
}
}
@@ -133,6 +160,7 @@ impl ApprovalPermit {
kind: ApprovalKind,
quote_id: &str,
expected_native_quote: Option<tinywallet_bus::wire::PreparedTransaction>,
+ expected_web3_quote: Option<tinywallet_bus::wire::Web3QuoteResponse>,
) -> Self {
let key = ApprovalKey {
kind,
@@ -148,6 +176,13 @@ impl ApprovalPermit {
active.insert(quote_id.to_owned(), quote);
}
}
+ if kind == ApprovalKind::Web3 {
+ if let (Some(quote), Ok(mut active)) =
+ (expected_web3_quote, web3_approval_quotes().lock())
+ {
+ active.insert(quote_id.to_owned(), quote);
+ }
+ }
Self(key)
}
}
@@ -162,6 +197,11 @@ impl Drop for ApprovalPermit {
active.remove(&self.0.quote_id);
}
}
+ if self.0.kind == ApprovalKind::Web3 {
+ if let Ok(mut active) = web3_approval_quotes().lock() {
+ active.remove(&self.0.quote_id);
+ }
+ }
}
}
@@ -186,6 +226,103 @@ pub(super) fn native_approval_matches_request(
&& native_intent_matches_quote(expected_quote, &request.intent)
}
+fn web3_approval_matches_request(
+ quote: &tinywallet_bus::wire::Web3QuoteResponse,
+ request: &AuthorizeWeb3ExecutionRequest,
+) -> bool {
+ use tinywallet_bus::wire::{WalletChain, Web3ExecutionIntent, Web3QuoteKind};
+
+ let operation_matches = matches!(
+ (quote.kind, request.operation.as_str()),
+ (Web3QuoteKind::Swap, "swap")
+ | (Web3QuoteKind::Bridge, "bridge")
+ | (Web3QuoteKind::DappCall, "dapp_call")
+ );
+ if quote.quote_id != request.quote_id || !operation_matches {
+ return false;
+ }
+
+ match (&request.transaction, quote.signing_chain) {
+ (
+ Web3ExecutionIntent::Evm {
+ network,
+ to,
+ data,
+ value,
+ chain_id,
+ ..
+ },
+ WalletChain::Evm,
+ ) => {
+ let expected_network = quote
+ .quote
+ .get("network")
+ .and_then(serde_json::Value::as_str);
+ if expected_network.is_some_and(|expected| expected != network)
+ || !known_evm_chain(network, *chain_id)
+ {
+ return false;
+ }
+ let transaction = quote.quote.get("tx");
+ match quote.kind {
+ Web3QuoteKind::DappCall => {
+ let expected_to = quote
+ .quote
+ .get("contractAddress")
+ .and_then(serde_json::Value::as_str);
+ let expected_data = quote
+ .quote
+ .get("calldata")
+ .and_then(serde_json::Value::as_str);
+ let expected_value = quote
+ .quote
+ .get("valueRaw")
+ .and_then(serde_json::Value::as_str);
+ expected_to.is_some_and(|expected| expected.eq_ignore_ascii_case(to))
+ && expected_data.is_some_and(|expected| data.as_deref() == Some(expected))
+ && expected_value.is_some_and(|expected| expected == value)
+ }
+ Web3QuoteKind::Swap | Web3QuoteKind::Bridge => {
+ transaction.is_some_and(|transaction| {
+ transaction
+ .get("to")
+ .and_then(serde_json::Value::as_str)
+ .is_some_and(|expected| expected.eq_ignore_ascii_case(to))
+ && transaction.get("data").and_then(serde_json::Value::as_str)
+ == data.as_deref()
+ && decimal_json(transaction.get("value")).as_deref()
+ == Some(value.as_str())
+ })
+ }
+ }
+ }
+ (Web3ExecutionIntent::Solana { tx_blob_hex }, WalletChain::Solana) => {
+ let expected = quote
+ .quote
+ .get("tx")
+ .and_then(|transaction| transaction.get("data"))
+ .and_then(serde_json::Value::as_str);
+ matches!(quote.kind, Web3QuoteKind::Swap | Web3QuoteKind::Bridge)
+ && expected == Some(tx_blob_hex.as_str())
+ }
+ _ => false,
+ }
+}
+
+fn known_evm_chain(network: &str, chain_id: u64) -> bool {
+ tinywallet_bus::wire::EvmNetwork::ALL
+ .into_iter()
+ .any(|known| known.as_str() == network && known.chain_id() == chain_id)
+}
+
+fn decimal_json(value: Option<&serde_json::Value>) -> Option<String> {
+ match value? {
+ serde_json::Value::String(value) => Some(value.clone()),
+ serde_json::Value::Number(value) => Some(value.to_string()),
+ _ => None,
+ }
+}
+
fn native_intent_matches_quote(
quote: &tinywallet_bus::wire::PreparedTransaction,
intent: &tinywallet_bus::wire::NativeWalletExecutionIntent,
@@ -332,9 +469,10 @@ pub(crate) async fn with_confirmed_execution<F: Future>(
kind: ApprovalKind,
quote_id: &str,
expected_native_quote: Option<tinywallet_bus::wire::PreparedTransaction>,
+ expected_web3_quote: Option<tinywallet_bus::wire::Web3QuoteResponse>,
future: F,
) -> F::Output {
- let _permit = ApprovalPermit::new(kind, quote_id, expected_native_quote);
+ let _permit = ApprovalPermit::new(kind, quote_id, expected_native_quote, expected_web3_quote);
future.await
}
@@ -356,19 +494,27 @@ impl WalletHost {
&self,
request: ChainTransportRequest,
) -> tinybus::Result<HostResponse> {
- let (network, endpoint_ref, chain, evm_chain_id) = match &request {
+ let (endpoint_ref, module_endpoint_url, chain, evm_chain_id) = match &request {
ChainTransportRequest::JsonRpc { network, .. }
| ChainTransportRequest::RestGet { network, .. }
| ChainTransportRequest::RestPost { network, .. } => (
- network_id(network.chain, network.evm_chain_id),
network.endpoint_ref.as_deref(),
+ network.endpoint_url.as_deref(),
network.chain,
network.evm_chain_id,
),
};
- let endpoint_url = match endpoint_ref {
- Some(reference) => {
- let Some((key, url)) = endpoint_references()
+ let endpoint_url = match (endpoint_ref, module_endpoint_url) {
+ (Some(_), Some(_)) => {
+ return Ok(HostResponse::ChainTransport(
+ ChainTransportResult::RpcError {
+ message: "wallet request cannot combine an endpoint reference and URL"
+ .into(),
+ },
+ ));
+ }
+ (Some(reference), None) => {
+ let Some(endpoint) = endpoint_references()
.lock()
.ok()
.and_then(|references| references.get(reference).cloned())
@@ -381,7 +527,7 @@ impl WalletHost {
},
));
};
- if Some(key) != endpoint_key(chain, evm_chain_id) {
+ if Some(endpoint.key) != endpoint_key(chain, evm_chain_id) {
return Ok(HostResponse::ChainTransport(
ChainTransportResult::RpcError {
message:
@@ -390,59 +536,60 @@ impl WalletHost {
},
));
}
- Some(url)
+ endpoint.url
+ }
+ (None, Some(url)) => match validate_module_endpoint_url(url) {
+ Ok(url) => url,
+ Err(message) => {
+ return Ok(HostResponse::ChainTransport(
+ ChainTransportResult::RpcError { message },
+ ));
+ }
+ },
+ (None, None) => {
+ return Ok(HostResponse::ChainTransport(
+ ChainTransportResult::RpcError {
+ message: "wallet module did not select an RPC endpoint".into(),
+ },
+ ));
}
- None => None,
};
- let transport = crate::web3::wallet::transport::OpenHumanTransport::new();
let result = match request {
- ChainTransportRequest::JsonRpc { method, params, .. } => match endpoint_url {
- Some(url) => crate::web3::wallet::rpc::rpc_call_to::<serde_json::Value>(
- &url, &method, params,
+ ChainTransportRequest::JsonRpc { method, params, .. } => {
+ crate::web3::wallet::rpc::rpc_call_to::<serde_json::Value>(
+ &endpoint_url,
+ &method,
+ params,
)
.await
- .map_err(|message| crate::web3::wallet::transport::classify(network, message)),
- None => transport.json_rpc(network, &method, params).await,
- },
- ChainTransportRequest::RestGet { path, .. } => match endpoint_url {
- Some(url) => crate::web3::wallet::rpc::rest_get_text(&join_endpoint(&url, &path))
+ .map_err(classify_transport_error)
+ }
+ ChainTransportRequest::RestGet { path, .. } => {
+ crate::web3::wallet::rpc::rest_get_text(&join_endpoint(&endpoint_url, &path))
.await
.map(serde_json::Value::String)
- .map_err(|message| crate::web3::wallet::transport::classify(network, message)),
- None => transport
- .rest_get(network, &path)
- .await
- .map(serde_json::Value::String),
- },
+ .map_err(classify_transport_error)
+ }
ChainTransportRequest::RestPost {
path,
body,
content_type,
..
- } => match endpoint_url {
- Some(url) => crate::web3::wallet::rpc::rest_post_text(
- &join_endpoint(&url, &path),
- &body,
- &content_type,
- )
- .await
- .map(serde_json::Value::String)
- .map_err(|message| crate::web3::wallet::transport::classify(network, message)),
- None => transport
- .rest_post(network, &path, body, &content_type)
- .await
- .map(serde_json::Value::String),
- },
+ } => crate::web3::wallet::rpc::rest_post_text(
+ &join_endpoint(&endpoint_url, &path),
+ &body,
+ &content_type,
+ )
+ .await
+ .map(serde_json::Value::String)
+ .map_err(classify_transport_error),
};
let response = match result {
Ok(body) => ChainTransportResult::Ok { body },
- Err(TransportError::Unreachable { message, .. }) => {
+ Err(TransportFailure::Unreachable(message)) => {
ChainTransportResult::Unreachable { message }
}
- Err(TransportError::Rpc { message, .. }) => ChainTransportResult::RpcError { message },
- Err(error) => ChainTransportResult::RpcError {
- message: error.to_string(),
- },
+ Err(TransportFailure::Rpc(message)) => ChainTransportResult::RpcError { message },
};
Ok(HostResponse::ChainTransport(response))
}
@@ -470,8 +617,15 @@ impl WalletHost {
&self,
request: AuthorizeWeb3ExecutionRequest,
) -> tinybus::Result<HostResponse> {
+ let quote = web3_approval_quotes()
+ .lock()
+ .ok()
+ .and_then(|mut quotes| quotes.remove(&request.quote_id));
Ok(HostResponse::Authorization(AuthorizationResult {
- approved: consume_approval(ApprovalKind::Web3, &request.quote_id),
+ approved: quote
+ .as_ref()
+ .is_some_and(|quote| web3_approval_matches_request(quote, &request))
+ && consume_approval(ApprovalKind::Web3, &request.quote_id),
reason: None,
}))
}
@@ -499,24 +653,63 @@ impl WalletHost {
/// absent an active guard scope, payment signing fails closed.
async fn authorize_x402_payment(
&self,
- _request: AuthorizeX402PaymentRequest,
+ request: AuthorizeX402PaymentRequest,
) -> tinybus::Result<HostResponse> {
+ let owner_matches = crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .try_with(|context| x402_request_owner_matches(&request, context))
+ .unwrap_or(false);
+ let approved = if owner_matches {
+ if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {
+ matches!(
+ gate.intercept_forced(
+ "x402_payment",
+ "Approve this exact x402 payment",
+ x402_approval_facts(&request),
+ )
+ .await,
+ crate::security::approval::GateOutcome::Allow
+ )
+ } else {
+ false
+ }
+ } else {
+ false
+ };
Ok(HostResponse::Authorization(AuthorizationResult {
- approved: false,
- reason: Some("x402 payment has no active host authorization".into()),
+ approved,
+ reason: (!approved)
+ .then(|| "x402 payment was not explicitly approved for this chat".into()),
}))
}
}
-fn network_id(chain: tinywallet_bus::Chain, evm_chain_id: Option<u64>) -> NetworkId {
- if chain == tinywallet_bus::Chain::Evm {
- NetworkId {
- chain,
- evm_chain_id,
- }
+enum TransportFailure {
+ Unreachable(String),
+ Rpc(String),
+}
+
+fn classify_transport_error(message: String) -> TransportFailure {
+ if ["transport failed", "read body failed"]
+ .iter()
+ .any(|marker| message.contains(marker))
+ {
+ TransportFailure::Unreachable(message)
} else {
- NetworkId::chain(chain)
+ TransportFailure::Rpc(message)
+ }
+}
+
+fn validate_module_endpoint_url(raw: &str) -> Result<String, String> {
+ let url = reqwest::Url::parse(raw)
+ .map_err(|_| "wallet module selected an invalid RPC endpoint URL".to_string())?;
+ if !matches!(url.scheme(), "http" | "https")
+ || url.host_str().is_none()
+ || !url.username().is_empty()
+ || url.password().is_some()
+ {
+ return Err("wallet module selected an unsafe RPC endpoint URL".into());
}
+ Ok(raw.to_owned())
}
fn endpoint_key(
diff --git a/crates/openhuman-core/src/modules/wallet_host_tests.rs b/crates/openhuman-core/src/modules/wallet_host_tests.rs
index 5caa7a1590..e89d651fe2 100644
--- a/crates/openhuman-core/src/modules/wallet_host_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_host_tests.rs
@@ -1,12 +1,62 @@
-use super::{consume_approval, native_approval_matches_request, ApprovalKind, ApprovalPermit};
+use super::{
+ consume_approval, native_approval_matches_request, validate_module_endpoint_url,
+ web3_approval_matches_request, x402_approval_facts, x402_request_owner_matches, ApprovalKind,
+ ApprovalPermit,
+};
use tinywallet_bus::wire::{
- AuthorizeNativeWalletExecutionRequest, EvmNetwork, NativeWalletExecutionIntent, PreparedKind,
- PreparedStatus, PreparedTransaction, TransactionSpec, WalletChain,
+ AuthorizeNativeWalletExecutionRequest, AuthorizeWeb3ExecutionRequest,
+ AuthorizeX402PaymentRequest, EvmNetwork, NativeWalletExecutionIntent, PreparedKind,
+ PreparedStatus, PreparedTransaction, QuoteOwner, TransactionSpec, WalletChain,
+ Web3ExecutionIntent, Web3QuoteKind, Web3QuoteResponse,
};
+#[test]
+fn x402_approval_is_bound_to_the_exact_chat_owner_and_payment_facts() {
+ let request = AuthorizeX402PaymentRequest {
+ url: "https://pay.example/resource".into(),
+ network: "eip155:8453".into(),
+ asset: "0x1111111111111111111111111111111111111111".into(),
+ recipient: "0x2222222222222222222222222222222222222222".into(),
+ amount_atomic: 2500,
+ owner: Some(QuoteOwner {
+ thread_id: "thread-1".into(),
+ client_id: "client-1".into(),
+ }),
+ };
+ let context = crate::security::approval::ApprovalChatContext {
+ thread_id: "thread-1".into(),
+ client_id: "client-1".into(),
+ request_id: Some("request-1".into()),
+ };
+ assert!(x402_request_owner_matches(&request, &context));
+
+ let mut other_client = context.clone();
+ other_client.client_id = "client-2".into();
+ assert!(!x402_request_owner_matches(&request, &other_client));
+ let mut other_thread = context.clone();
+ other_thread.thread_id = "thread-2".into();
+ assert!(!x402_request_owner_matches(&request, &other_thread));
+
+ assert_eq!(
+ x402_approval_facts(&request),
+ serde_json::json!({
+ "url": "https://pay.example/resource",
+ "network": "eip155:8453",
+ "asset": "0x1111111111111111111111111111111111111111",
+ "recipient": "0x2222222222222222222222222222222222222222",
+ "amount_atomic": 2500,
+ })
+ );
+}
+
#[test]
fn execution_authorization_is_bound_to_one_confirmed_quote_id() {
- let permit = ApprovalPermit::new(ApprovalKind::Web3, "quote-17", None);
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Web3,
+ "quote-17",
+ None,
+ Some(web3_quote("quote-17")),
+ );
assert!(!consume_approval(ApprovalKind::Web3, "quote-18"));
assert!(!consume_approval(ApprovalKind::Native, "quote-17"));
assert!(consume_approval(ApprovalKind::Web3, "quote-17"));
@@ -18,7 +68,8 @@ fn execution_authorization_is_bound_to_one_confirmed_quote_id() {
fn an_unconsumed_confirmation_is_removed_when_the_execution_ends() {
{
let quote = native_quote("quote-cancelled");
- let _permit = ApprovalPermit::new(ApprovalKind::Native, "quote-cancelled", Some(quote));
+ let _permit =
+ ApprovalPermit::new(ApprovalKind::Native, "quote-cancelled", Some(quote), None);
}
assert!(!consume_approval(ApprovalKind::Native, "quote-cancelled"));
}
@@ -26,7 +77,12 @@ fn an_unconsumed_confirmation_is_removed_when_the_execution_ends() {
#[test]
fn native_approval_rejects_a_quote_that_differs_from_the_confirmed_quote() {
let quote = native_quote("native-quote-facts");
- let permit = ApprovalPermit::new(ApprovalKind::Native, &quote.quote_id, Some(quote.clone()));
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Native,
+ &quote.quote_id,
+ Some(quote.clone()),
+ None,
+ );
let mut changed_quote = quote.clone();
changed_quote.amount_raw = "43".into();
let request = native_request(changed_quote, "0xrecipient", "42");
@@ -39,7 +95,12 @@ fn native_approval_rejects_a_quote_that_differs_from_the_confirmed_quote() {
#[test]
fn native_approval_rejects_signer_intent_that_changes_the_confirmed_transfer() {
let quote = native_quote("native-quote-intent");
- let permit = ApprovalPermit::new(ApprovalKind::Native, &quote.quote_id, Some(quote.clone()));
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Native,
+ &quote.quote_id,
+ Some(quote.clone()),
+ None,
+ );
let request = native_request(quote.clone(), "0xattacker", "42");
assert!(!native_approval_matches_request(&quote, &request));
@@ -50,7 +111,12 @@ fn native_approval_rejects_signer_intent_that_changes_the_confirmed_transfer() {
#[test]
fn native_approval_accepts_the_exact_confirmed_quote_and_signer_intent_once() {
let quote = native_quote("native-quote-valid");
- let permit = ApprovalPermit::new(ApprovalKind::Native, &quote.quote_id, Some(quote.clone()));
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Native,
+ &quote.quote_id,
+ Some(quote.clone()),
+ None,
+ );
let request = native_request(quote.clone(), &quote.to_address, &quote.amount_raw);
assert!(native_approval_matches_request(&quote, &request));
@@ -58,6 +124,85 @@ fn native_approval_accepts_the_exact_confirmed_quote_and_signer_intent_once() {
drop(permit);
}
+#[test]
+fn web3_approval_requires_the_cached_quote_operation_chain_and_transaction() {
+ let quote = web3_quote("web3-valid-quote");
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Web3,
+ &quote.quote_id,
+ None,
+ Some(quote.clone()),
+ );
+ let request = AuthorizeWeb3ExecutionRequest {
+ quote_id: quote.quote_id.clone(),
+ operation: "dapp_call".into(),
+ transaction: Web3ExecutionIntent::Evm {
+ network: "polygon_mainnet".into(),
+ to: "0x1111111111111111111111111111111111111111".into(),
+ data: Some("0xabcd".into()),
+ value: "5".into(),
+ nonce: 4,
+ gas_limit: 30_000,
+ gas_price_wei: "7".into(),
+ chain_id: 137,
+ },
+ };
+ assert!(web3_approval_matches_request(&quote, &request));
+ assert!(consume_approval(ApprovalKind::Web3, &quote.quote_id));
+ drop(permit);
+}
+
+#[test]
+fn web3_approval_rejects_changed_quote_intent_before_signing() {
+ let quote = web3_quote("web3-changed-quote");
+ let permit = ApprovalPermit::new(
+ ApprovalKind::Web3,
+ &quote.quote_id,
+ None,
+ Some(quote.clone()),
+ );
+ let request = AuthorizeWeb3ExecutionRequest {
+ quote_id: quote.quote_id.clone(),
+ operation: "dapp_call".into(),
+ transaction: Web3ExecutionIntent::Evm {
+ network: "polygon_mainnet".into(),
+ to: "0xattacker".into(),
+ data: Some("0xabcd".into()),
+ value: "5".into(),
+ nonce: 4,
+ gas_limit: 30_000,
+ gas_price_wei: "7".into(),
+ chain_id: 137,
+ },
+ };
+ assert!(!web3_approval_matches_request(&quote, &request));
+ drop(permit);
+ assert!(!consume_approval(ApprovalKind::Web3, &quote.quote_id));
+}
+
+#[test]
+fn module_selected_rpc_endpoints_are_public_http_urls_without_credentials() {
+ assert_eq!(
+ validate_module_endpoint_url("https://rpc.example.test/v1"),
+ Ok("https://rpc.example.test/v1".to_owned())
+ );
+ assert_eq!(
+ validate_module_endpoint_url("http://127.0.0.1:8545"),
+ Ok("http://127.0.0.1:8545".to_owned())
+ );
+ for unsafe_url in [
+ "file:///tmp/rpc",
+ "ftp://rpc.example.test",
+ "https://user:[email protected]",
+ "not a URL",
+ ] {
+ assert!(
+ validate_module_endpoint_url(unsafe_url).is_err(),
+ "accepted unsafe endpoint {unsafe_url}"
+ );
+ }
+}
+
fn native_quote(quote_id: &str) -> PreparedTransaction {
PreparedTransaction {
quote_id: quote_id.into(),
@@ -81,6 +226,22 @@ fn native_quote(quote_id: &str) -> PreparedTransaction {
}
}
+fn web3_quote(quote_id: &str) -> Web3QuoteResponse {
+ Web3QuoteResponse {
+ quote_id: quote_id.into(),
+ kind: Web3QuoteKind::DappCall,
+ expires_at_ms: u64::MAX,
+ signing_chain: WalletChain::Evm,
+ quote: serde_json::json!({
+ "type": "dapp_call",
+ "network": "polygon_mainnet",
+ "contractAddress": "0x1111111111111111111111111111111111111111",
+ "calldata": "0xabcd",
+ "valueRaw": "5"
+ }),
+ }
+}
+
fn native_request(
quote: PreparedTransaction,
recipient: &str,
diff --git a/crates/openhuman-core/src/modules/wallet_service.rs b/crates/openhuman-core/src/modules/wallet_service.rs
index 34a43cc241..9d3ddde56d 100644
--- a/crates/openhuman-core/src/modules/wallet_service.rs
+++ b/crates/openhuman-core/src/modules/wallet_service.rs
@@ -9,7 +9,7 @@ use std::sync::OnceLock;
use tinywallet_bus::names::methods;
use tinywallet_bus::wire::{
EvmNetwork, NativeWalletCloseRequest, NativeWalletConfigRequest, NativeWalletConfigResponse,
- NativeWalletServiceHandle, RpcEndpointKey, SolanaCluster, WalletAccountsResponse,
+ NativeWalletServiceHandle, RpcEndpointKey, WalletAccountsResponse,
};
use zeroize::Zeroize;
@@ -90,7 +90,10 @@ async fn ensure_native_wallet(
configuration.clone(),
)
.await?;
- if let Err(error) = super::wallet_host::bind_endpoint_references(&response) {
+ if let Err(error) = super::wallet_host::bind_endpoint_references(
+ &response.service.handle,
+ &response.endpoint_references,
+ ) {
let _ = wallet::call::<_, ()>(
config,
methods::NATIVE_WALLET_CLOSE,
@@ -207,6 +210,7 @@ pub(crate) async fn execute_native_transfer(
super::wallet_host::ApprovalKind::Native,
&params.quote_id,
Some(quote),
+ None,
wallet::call_confidential(config, methods::NATIVE_WALLET_EXECUTE_PREPARED, &request),
)
.await;
@@ -222,14 +226,10 @@ async fn signing_secret(
chain: tinywallet_bus::wire::WalletChain,
) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {
let local_chain = match chain {
- tinywallet_bus::wire::WalletChain::Evm => tinywallet_web3::crypto::wallet::WalletChain::Evm,
- tinywallet_bus::wire::WalletChain::Btc => tinywallet_web3::crypto::wallet::WalletChain::Btc,
- tinywallet_bus::wire::WalletChain::Solana => {
- tinywallet_web3::crypto::wallet::WalletChain::Solana
- }
- tinywallet_bus::wire::WalletChain::Tron => {
- tinywallet_web3::crypto::wallet::WalletChain::Tron
- }
+ tinywallet_bus::wire::WalletChain::Evm => crate::web3::wallet::WalletChain::Evm,
+ tinywallet_bus::wire::WalletChain::Btc => crate::web3::wallet::WalletChain::Btc,
+ 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(local_chain)
.await
@@ -276,7 +276,7 @@ async fn close_native_wallet(
},
)
.await?;
- super::wallet_host::clear_endpoint_references();
+ super::wallet_host::clear_endpoint_references(&service.response.service.handle);
Ok(())
}
@@ -308,14 +308,19 @@ where
F: FnOnce(NativeWalletCloseRequest) -> Fut,
Fut: Future<Output = Result<(), WalletCallError>>,
{
- if let Some(service) = active.as_ref() {
+ let handle = if let Some(service) = active.as_ref() {
close(NativeWalletCloseRequest {
service: service.response.service.clone(),
})
.await?;
- }
+ Some(service.response.service.handle.clone())
+ } else {
+ None
+ };
*active = None;
- super::wallet_host::clear_endpoint_references();
+ if let Some(handle) = handle {
+ super::wallet_host::clear_endpoint_references(&handle);
+ }
Ok(())
}
@@ -339,47 +344,30 @@ fn finish_shutdown_hook_registration(registered: &AtomicBool) {
registered.store(false, Ordering::Release);
}
-fn native_wallet_config_request() -> NativeWalletConfigRequest {
+pub(super) fn native_wallet_config_request() -> NativeWalletConfigRequest {
let mut overridden_endpoints = Vec::new();
for network in EvmNetwork::ALL {
- let name = crate::web3::wallet::endpoints::evm_rpc_env_var(network);
- if nonempty_env(name) {
- overridden_endpoints.push(RpcEndpointKey::Evm { network });
+ let key = RpcEndpointKey::Evm { network };
+ if crate::web3::wallet::endpoints::override_for_endpoint(key).is_some() {
+ overridden_endpoints.push(key);
}
}
- for (chain, key) in [
- (
- tinywallet_web3::crypto::wallet::WalletChain::Btc,
- RpcEndpointKey::Btc,
- ),
- (
- tinywallet_web3::crypto::wallet::WalletChain::Solana,
- RpcEndpointKey::Solana,
- ),
- (
- tinywallet_web3::crypto::wallet::WalletChain::Tron,
- RpcEndpointKey::Tron,
- ),
+ for key in [
+ RpcEndpointKey::Btc,
+ RpcEndpointKey::Solana,
+ RpcEndpointKey::Tron,
] {
- let name = crate::web3::wallet::endpoints::env_var_for_chain(chain);
- if nonempty_env(name) {
+ if crate::web3::wallet::endpoints::override_for_endpoint(key).is_some() {
overridden_endpoints.push(key);
}
}
- let solana_cluster = match crate::web3::wallet::solana_cluster() {
- tinywallet_bus::wire::SolanaCluster::Mainnet => SolanaCluster::Mainnet,
- tinywallet_bus::wire::SolanaCluster::Devnet => SolanaCluster::Devnet,
- };
+ let solana_cluster = crate::web3::wallet::solana_cluster();
NativeWalletConfigRequest {
solana_cluster,
overridden_endpoints,
}
}
-fn nonempty_env(name: &str) -> bool {
- std::env::var(name).is_ok_and(|value| !value.trim().is_empty())
-}
-
#[cfg(test)]
#[path = "wallet_service_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/modules/wallet_service_tests.rs b/crates/openhuman-core/src/modules/wallet_service_tests.rs
index a02f790e36..86c10f1133 100644
--- a/crates/openhuman-core/src/modules/wallet_service_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_service_tests.rs
@@ -44,6 +44,7 @@ fn shutdown_hook_guard_allows_registration_after_hooks_are_drained() {
#[tokio::test]
async fn explicit_close_retains_state_for_retry_then_releases_user_state_once() {
+ let _rpc_env = crate::web3::wallet::test_support::UnreachableRpcGuard::set();
let mut active = Some(service());
active
.as_mut()
@@ -74,15 +75,18 @@ async fn explicit_close_retains_state_for_retry_then_releases_user_state_once()
);
let configured = tinywallet_bus::wire::NativeWalletConfigResponse {
service: NativeWalletServiceHandle {
- handle: "old-user-service".into(),
+ handle: "opaque-service-handle".into(),
},
endpoint_references: vec![tinywallet_bus::wire::HostEndpointReference {
key: tinywallet_bus::wire::RpcEndpointKey::Btc,
reference: "old-user-endpoint".into(),
}],
};
- super::super::wallet_host::bind_endpoint_references(&configured)
- .expect("fixture endpoint alias should bind");
+ super::super::wallet_host::bind_endpoint_references(
+ &configured.service.handle,
+ &configured.endpoint_references,
+ )
+ .expect("fixture endpoint alias should bind");
let close_calls = Arc::new(AtomicUsize::new(0));
let observed_calls = close_calls.clone();
diff --git a/crates/openhuman-core/src/modules/wallet_tests.rs b/crates/openhuman-core/src/modules/wallet_tests.rs
index 12ed8e43ec..a70f31fa85 100644
--- a/crates/openhuman-core/src/modules/wallet_tests.rs
+++ b/crates/openhuman-core/src/modules/wallet_tests.rs
@@ -129,6 +129,19 @@ async fn a_disabled_host_reports_unavailable_without_starting_a_broker() {
super::ensure_ready(&config).await,
Err(WalletCallError::Unavailable(_))
));
+ assert!(matches!(
+ super::generate_mnemonic(&config, 12).await,
+ Err(WalletCallError::Unavailable(_))
+ ));
+ assert!(matches!(
+ super::derive_mnemonic_seed(
+ &config,
+ "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
+ .to_string(),
+ )
+ .await,
+ Err(WalletCallError::Unavailable(_))
+ ));
}
// ---------------------------------------------------------------------------
@@ -164,7 +177,7 @@ mod attestation_guard {
fn the_current_attested_linux_release_library_is_accepted() {
assert!(digest_is_pinned(
record(),
- "7b6fdd843622a29b610633e0f5cabf6f48c8aa7566a466696916e99d1221eb08"
+ "5d0a3ae5881f91966249858cd155e5b9c244bd419d06698d808f972a8d23afc9"
));
}
@@ -186,7 +199,7 @@ mod attestation_guard {
};
assert!(!digest_is_pinned(
&unpinned_record,
- "7b6fdd843622a29b610633e0f5cabf6f48c8aa7566a466696916e99d1221eb08"
+ "5d0a3ae5881f91966249858cd155e5b9c244bd419d06698d808f972a8d23afc9"
));
}
diff --git a/crates/openhuman-core/src/modules/web3_service.rs b/crates/openhuman-core/src/modules/web3_service.rs
new file mode 100644
index 0000000000..52ff8c922c
--- /dev/null
+++ b/crates/openhuman-core/src/modules/web3_service.rs
@@ -0,0 +1,277 @@
+//! User-scoped lifecycle and host transport for TinyWallet Web3 quotes.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::OnceLock;
+
+use serde::Deserialize;
+use tinywallet_bus::names::methods;
+use tinywallet_bus::wire::{
+ QuoteOwner, WalletChain, Web3CloseRequest, Web3ConfigureRequest, Web3ConfigureResponse,
+ Web3ExecuteRequest, Web3QuoteRequest, Web3QuoteResponse,
+};
+
+use crate::config::Config;
+
+use super::{wallet, wallet_host};
+
+struct Web3Service {
+ workspace: PathBuf,
+ accounts: tinywallet_bus::wire::WalletAccountsResponse,
+ configuration: Web3ConfigureRequest,
+ response: Web3ConfigureResponse,
+ quotes: HashMap<String, Web3QuoteResponse>,
+}
+
+static WEB3_SERVICE: OnceLock<tokio::sync::Mutex<Option<Web3Service>>> = OnceLock::new();
+static WEB3_SHUTDOWN_HOOK_REGISTERED: AtomicBool = AtomicBool::new(false);
+
+fn service() -> &'static tokio::sync::Mutex<Option<Web3Service>> {
+ WEB3_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))
+}
+
+async fn ensure_service(
+ config: &Config,
+ active: &mut Option<Web3Service>,
+) -> Result<(), wallet::WalletCallError> {
+ register_shutdown_hook();
+ let accounts = wallet_host::wallet_accounts_snapshot()
+ .await
+ .map_err(wallet::WalletCallError::Failed)?;
+ let workspace = config.workspace_dir.clone();
+ let native_configuration = super::wallet_service::native_wallet_config_request();
+ let configuration = Web3ConfigureRequest {
+ solana_cluster: native_configuration.solana_cluster,
+ overridden_endpoints: native_configuration.overridden_endpoints,
+ };
+ if active.as_ref().is_some_and(|current| {
+ current.workspace != workspace
+ || current.accounts != accounts
+ || current.configuration != configuration
+ }) {
+ if let Some(current) = active.as_ref() {
+ wallet::call::<_, ()>(
+ config,
+ methods::WEB3_CLOSE,
+ Web3CloseRequest {
+ service: current.response.service.clone(),
+ },
+ )
+ .await?;
+ wallet_host::clear_endpoint_references(&current.response.service.handle);
+ }
+ *active = None;
+ }
+ if active.is_none() {
+ let response: Web3ConfigureResponse = wallet::call(
+ config,
+ methods::WEB3_CONFIGURE_WITH_ENDPOINTS,
+ configuration.clone(),
+ )
+ .await?;
+ if let Err(error) = wallet_host::bind_endpoint_references(
+ &response.service.handle,
+ &response.endpoint_references,
+ ) {
+ let _ = wallet::call::<_, ()>(
+ config,
+ methods::WEB3_CLOSE,
+ Web3CloseRequest {
+ service: response.service.clone(),
+ },
+ )
+ .await;
+ return Err(wallet::WalletCallError::Failed(error));
+ }
+ *active = Some(Web3Service {
+ workspace,
+ accounts,
+ configuration,
+ response,
+ quotes: HashMap::new(),
+ });
+ }
+ Ok(())
+}
+
+fn owner() -> Option<QuoteOwner> {
+ crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .try_with(|context| QuoteOwner {
+ thread_id: context.thread_id.clone(),
+ client_id: context.client_id.clone(),
+ })
+ .ok()
+}
+
+/// Close the active module service on sign-out. The mutex joins any in-flight
+/// quote, route, or execution call before its owner-scoped handles are cleared.
+pub(crate) async fn close_service(config: &Config) -> Result<(), wallet::WalletCallError> {
+ register_shutdown_hook();
+ let mut active = service().lock().await;
+ let Some(current) = active.as_ref() else {
+ return Ok(());
+ };
+ wallet::call::<_, ()>(
+ config,
+ methods::WEB3_CLOSE,
+ Web3CloseRequest {
+ service: current.response.service.clone(),
+ },
+ )
+ .await?;
+ wallet_host::clear_endpoint_references(&current.response.service.handle);
+ *active = None;
+ Ok(())
+}
+
+fn register_shutdown_hook() {
+ if WEB3_SHUTDOWN_HOOK_REGISTERED.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ crate::core::shutdown::register(|| async {
+ WEB3_SHUTDOWN_HOOK_REGISTERED.store(false, Ordering::Release);
+ let mut active = service().lock().await;
+ let Some(current) = active.as_ref() else {
+ return;
+ };
+ let config = crate::config::rpc::load_config_with_timeout().await;
+ let Ok(config) = config else {
+ tracing::warn!(
+ "[modules:web3] could not load configuration to close service at shutdown"
+ );
+ return;
+ };
+ match wallet::call::<_, ()>(
+ &config,
+ methods::WEB3_CLOSE,
+ Web3CloseRequest {
+ service: current.response.service.clone(),
+ },
+ )
+ .await
+ {
+ Ok(()) => {
+ wallet_host::clear_endpoint_references(&current.response.service.handle);
+ *active = None;
+ }
+ Err(error) => {
+ tracing::warn!(%error, "[modules:web3] failed to close service at shutdown")
+ }
+ }
+ });
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ExecuteParams {
+ pub(crate) quote_id: String,
+ pub(crate) confirmed: bool,
+}
+
+/// Prepare one implementation-owned Web3 quote.
+pub(crate) async fn quote(
+ config: &Config,
+ member: &'static str,
+ params: serde_json::Value,
+) -> Result<Web3QuoteResponse, wallet::WalletCallError> {
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ let service_handle = active
+ .as_ref()
+ .expect("ensure_service installs a handle")
+ .response
+ .service
+ .clone();
+ let response: Web3QuoteResponse = wallet::call(
+ config,
+ member,
+ Web3QuoteRequest {
+ service: service_handle,
+ owner: owner(),
+ params,
+ },
+ )
+ .await?;
+ if let Some(current) = active.as_mut() {
+ current
+ .quotes
+ .insert(response.quote_id.clone(), response.clone());
+ }
+ Ok(response)
+}
+
+/// Call the module-owned authenticated-backend route operation.
+pub(crate) async fn routes(config: &Config) -> Result<serde_json::Value, wallet::WalletCallError> {
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ wallet::call(config, methods::WEB3_ROUTES, ()).await
+}
+
+/// Execute one explicitly confirmed quote using its module-declared signer chain.
+pub(crate) async fn execute(
+ config: &Config,
+ quote_id: String,
+ confirmed: bool,
+) -> Result<serde_json::Value, wallet::WalletCallError> {
+ if !confirmed {
+ return Err(wallet::WalletCallError::InvalidInput(
+ "Web3 execution requires confirmed: true".into(),
+ ));
+ }
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ let service_handle = active
+ .as_ref()
+ .expect("ensure_service installs a handle")
+ .response
+ .service
+ .clone();
+ let quote = active
+ .as_ref()
+ .and_then(|active| active.quotes.get(&quote_id))
+ .cloned()
+ .ok_or_else(|| {
+ wallet::WalletCallError::InvalidInput("prepared Web3 quote is unavailable".into())
+ })?;
+ let chain = match quote.signing_chain {
+ WalletChain::Evm => crate::web3::wallet::WalletChain::Evm,
+ WalletChain::Btc => crate::web3::wallet::WalletChain::Btc,
+ WalletChain::Solana => crate::web3::wallet::WalletChain::Solana,
+ WalletChain::Tron => crate::web3::wallet::WalletChain::Tron,
+ };
+ let stored = crate::web3::wallet::secret_material(chain)
+ .await
+ .map_err(|error| wallet::WalletCallError::Failed(error.to_string()))?;
+ let mnemonic =
+ crate::security::encryption::rpc::decrypt_secret(config, &stored.encrypted_mnemonic)
+ .await
+ .map_err(|error| wallet::WalletCallError::Failed(error.to_string()))?
+ .value;
+ let mut request = Web3ExecuteRequest {
+ service: service_handle,
+ owner: owner(),
+ quote_id: quote_id.clone(),
+ confirmed,
+ secret: tinywallet_bus::wire::SecretMaterial {
+ mnemonic,
+ derivation_path: stored.derivation_path,
+ chain: quote.signing_chain.to_chain(),
+ },
+ };
+ let result = wallet_host::with_confirmed_execution(
+ wallet_host::ApprovalKind::Web3,
+ &quote_id,
+ None,
+ Some(quote),
+ wallet::call_confidential(config, methods::WEB3_EXECUTE, &request),
+ )
+ .await;
+ zeroize::Zeroize::zeroize(&mut request.secret.mnemonic);
+ if result.is_ok() {
+ active
+ .as_mut()
+ .map(|active| active.quotes.remove(&quote_id));
+ }
+ result
+}
diff --git a/crates/openhuman-core/src/modules/x402_service.rs b/crates/openhuman-core/src/modules/x402_service.rs
new file mode 100644
index 0000000000..acc14730ba
--- /dev/null
+++ b/crates/openhuman-core/src/modules/x402_service.rs
@@ -0,0 +1,318 @@
+//! User-scoped lifecycle for the module-owned x402 ledger.
+
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::OnceLock;
+use zeroize::Zeroize;
+
+use tinywallet_bus::names::methods;
+use tinywallet_bus::wire::{
+ X402CloseRequest, X402ConfigResponse, X402ConfigureRequest, X402DetailedSpendingSummary,
+ X402ListPaymentsRequest, X402ListPaymentsResponse, X402PreparePaymentRequest,
+ X402PreparePaymentResponse, X402RecordPaymentRequest, X402ServiceHandle,
+ X402UpdateBudgetRequest,
+};
+
+use crate::config::Config;
+
+use super::wallet::{self, WalletCallError};
+
+/// Prepare and sign a 402 challenge inside TinyWallet. Both supported rails'
+/// secret material is sent only through the attested confidential call; the
+/// module parses the challenge and selects the matching chain.
+pub(crate) async fn prepare_payment(
+ config: &Config,
+ url: String,
+ payment_required: String,
+ owner: Option<tinywallet_bus::wire::QuoteOwner>,
+) -> Result<(X402ServiceHandle, X402PreparePaymentResponse), WalletCallError> {
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ let service_handle = active
+ .as_ref()
+ .ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?
+ .handle
+ .clone();
+
+ let evm = signing_secret(config, crate::web3::wallet::WalletChain::Evm).await?;
+ let solana = signing_secret(config, crate::web3::wallet::WalletChain::Solana).await?;
+ let mut request = X402PreparePaymentRequest {
+ service: service_handle.clone(),
+ url,
+ payment_required,
+ owner,
+ secret: evm,
+ additional_secrets: vec![solana],
+ };
+ let response = wallet::call_confidential(config, methods::X402_PREPARE_PAYMENT, &request).await;
+ request.secret.mnemonic.zeroize();
+ for secret in &mut request.additional_secrets {
+ secret.mnemonic.zeroize();
+ }
+ Ok((service_handle, response?))
+}
+
+/// Record the retry result through the same module-owned payment ledger.
+pub(crate) async fn record_payment(
+ config: &Config,
+ service: X402ServiceHandle,
+ payment_id: String,
+ response_status: u16,
+ settlement_response: Option<String>,
+) -> Result<(), WalletCallError> {
+ wallet::call(
+ config,
+ methods::X402_RECORD_PAYMENT,
+ X402RecordPaymentRequest {
+ service,
+ payment_id,
+ response_status,
+ settlement_response,
+ },
+ )
+ .await
+}
+
+async fn signing_secret(
+ config: &Config,
+ chain: crate::web3::wallet::WalletChain,
+) -> Result<tinywallet_bus::wire::SecretMaterial, WalletCallError> {
+ let stored = crate::web3::wallet::secret_material(chain)
+ .await
+ .map_err(WalletCallError::Failed)?;
+ let phrase =
+ crate::security::encryption::rpc::decrypt_secret(config, &stored.encrypted_mnemonic)
+ .await
+ .map_err(|error| WalletCallError::Failed(error.to_string()))?
+ .value;
+ Ok(tinywallet_bus::wire::SecretMaterial {
+ mnemonic: phrase,
+ derivation_path: stored.derivation_path,
+ chain: chain.to_chain(),
+ })
+}
+
+struct X402Service {
+ workspace: PathBuf,
+ accounts: tinywallet_bus::wire::WalletAccountsResponse,
+ config: X402ConfigResponse,
+ handle: X402ServiceHandle,
+}
+
+static X402_SERVICE: OnceLock<tokio::sync::Mutex<Option<X402Service>>> = OnceLock::new();
+static X402_SHUTDOWN_HOOK_REGISTERED: AtomicBool = AtomicBool::new(false);
+
+fn service() -> &'static tokio::sync::Mutex<Option<X402Service>> {
+ X402_SERVICE.get_or_init(|| tokio::sync::Mutex::new(None))
+}
+
+async fn ensure_service(
+ config: &Config,
+ active: &mut Option<X402Service>,
+) -> Result<(), WalletCallError> {
+ register_shutdown_hook();
+ let workspace = config.workspace_dir.clone();
+ let accounts = super::wallet_host::wallet_accounts_snapshot()
+ .await
+ .map_err(WalletCallError::Failed)?;
+ let budget = budget_from(|name| std::env::var(name).ok());
+
+ if active.as_ref().is_some_and(|current| {
+ current.workspace != workspace
+ || current.accounts != accounts
+ || current.config.per_request_max_atomic != budget.0
+ || current.config.daily_max_atomic != budget.1
+ || current.config.monthly_max_atomic != budget.2
+ }) {
+ if let Some(current) = active.as_ref() {
+ wallet::call::<_, ()>(
+ config,
+ methods::X402_CLOSE,
+ X402CloseRequest {
+ service: current.handle.clone(),
+ },
+ )
+ .await?;
+ }
+ *active = None;
+ }
+
+ if active.is_none() {
+ let service_config = X402ConfigResponse {
+ workspace_dir: workspace.display().to_string(),
+ session_id: format!("x402-{}", uuid::Uuid::new_v4()),
+ per_request_max_atomic: budget.0,
+ daily_max_atomic: budget.1,
+ monthly_max_atomic: budget.2,
+ };
+ let handle: X402ServiceHandle = wallet::call(
+ config,
+ methods::X402_CONFIGURE,
+ X402ConfigureRequest {
+ config: service_config.clone(),
+ },
+ )
+ .await?;
+ *active = Some(X402Service {
+ workspace,
+ accounts,
+ config: service_config,
+ handle,
+ });
+ }
+ Ok(())
+}
+
+/// Close the active module ledger on sign-out after joining any current
+/// operation. If close fails, the handle stays cached so a later lifecycle
+/// attempt can retry instead of silently abandoning pending reservations.
+pub(crate) async fn close_service(config: &Config) -> Result<(), WalletCallError> {
+ register_shutdown_hook();
+ let mut active = service().lock().await;
+ let Some(current) = active.as_ref() else {
+ return Ok(());
+ };
+ wallet::call::<_, ()>(
+ config,
+ methods::X402_CLOSE,
+ X402CloseRequest {
+ service: current.handle.clone(),
+ },
+ )
+ .await?;
+ *active = None;
+ Ok(())
+}
+
+fn register_shutdown_hook() {
+ if X402_SHUTDOWN_HOOK_REGISTERED.swap(true, Ordering::AcqRel) {
+ return;
+ }
+ crate::core::shutdown::register(|| async {
+ X402_SHUTDOWN_HOOK_REGISTERED.store(false, Ordering::Release);
+ let mut active = service().lock().await;
+ let Some(current) = active.as_ref() else {
+ return;
+ };
+ let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {
+ tracing::warn!(
+ "[modules:x402] could not load configuration to close service at shutdown"
+ );
+ return;
+ };
+ match wallet::call::<_, ()>(
+ &config,
+ methods::X402_CLOSE,
+ X402CloseRequest {
+ service: current.handle.clone(),
+ },
+ )
+ .await
+ {
+ Ok(()) => *active = None,
+ Err(error) => {
+ tracing::warn!(%error, "[modules:x402] failed to close service at shutdown")
+ }
+ }
+ });
+}
+
+async fn with_service<R, F, Fut>(config: &Config, operation: F) -> Result<R, WalletCallError>
+where
+ F: FnOnce(X402ServiceHandle) -> Fut,
+ Fut: std::future::Future<Output = Result<R, WalletCallError>>,
+{
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ let handle = active
+ .as_ref()
+ .ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?
+ .handle
+ .clone();
+ operation(handle).await
+}
+
+/// Read the module-owned spending totals and budgets.
+pub(crate) async fn summary(
+ config: &Config,
+) -> Result<X402DetailedSpendingSummary, WalletCallError> {
+ let config = config.clone();
+ let operation_config = config.clone();
+ with_service(&config, move |service| async move {
+ wallet::call(
+ &operation_config,
+ methods::X402_SPENDING_SUMMARY_DETAILED,
+ tinywallet_bus::wire::X402SummaryRequest { service },
+ )
+ .await
+ })
+ .await
+}
+
+/// Read recent module-owned payment records.
+pub(crate) async fn list_payments(
+ config: &Config,
+ limit: u64,
+) -> Result<X402ListPaymentsResponse, WalletCallError> {
+ let config = config.clone();
+ let operation_config = config.clone();
+ with_service(&config, move |service| async move {
+ wallet::call(
+ &operation_config,
+ methods::X402_LIST_PAYMENTS,
+ X402ListPaymentsRequest { service, limit },
+ )
+ .await
+ })
+ .await
+}
+
+/// Update live module-owned spending limits without replacing the ledger.
+pub(crate) async fn update_budget(
+ config: &Config,
+ per_request_max_atomic: Option<u64>,
+ daily_max_atomic: Option<u64>,
+ monthly_max_atomic: Option<u64>,
+) -> Result<tinywallet_bus::wire::X402SpendingSummary, WalletCallError> {
+ let mut active = service().lock().await;
+ ensure_service(config, &mut active).await?;
+ let current = active
+ .as_mut()
+ .ok_or_else(|| WalletCallError::Failed("x402 service is unavailable".into()))?;
+ let result: tinywallet_bus::wire::X402SpendingSummary = wallet::call(
+ config,
+ methods::X402_UPDATE_BUDGET,
+ X402UpdateBudgetRequest {
+ service: current.handle.clone(),
+ per_request_max_atomic,
+ daily_max_atomic,
+ monthly_max_atomic,
+ },
+ )
+ .await?;
+ current.config.per_request_max_atomic = result.per_request_max_atomic;
+ current.config.daily_max_atomic = result.daily_max_atomic;
+ current.config.monthly_max_atomic = result.monthly_max_atomic;
+ Ok(result)
+}
+
+fn budget_from(get: impl Fn(&str) -> Option<String>) -> (u64, u64, u64) {
+ let mut per_request_max_atomic = 1_000_000;
+ let mut daily_max_atomic = 10_000_000;
+ let mut monthly_max_atomic = 100_000_000;
+ if let Some(value) = get("OPENHUMAN_X402_PER_REQUEST_MAX").and_then(|value| value.parse().ok())
+ {
+ per_request_max_atomic = value;
+ }
+ if let Some(value) = get("OPENHUMAN_X402_DAILY_MAX").and_then(|value| value.parse().ok()) {
+ daily_max_atomic = value;
+ }
+ if let Some(value) = get("OPENHUMAN_X402_MONTHLY_MAX").and_then(|value| value.parse().ok()) {
+ monthly_max_atomic = value;
+ }
+ (per_request_max_atomic, daily_max_atomic, monthly_max_atomic)
+}
+
+#[cfg(test)]
+#[path = "x402_service_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/x402_service_tests.rs b/crates/openhuman-core/src/modules/x402_service_tests.rs
new file mode 100644
index 0000000000..aeddb49b59
--- /dev/null
+++ b/crates/openhuman-core/src/modules/x402_service_tests.rs
@@ -0,0 +1,17 @@
+//! Budget and service-identity behavior for the Wallet x402 adapter.
+
+use super::*;
+
+#[test]
+fn budget_defaults_and_environment_overrides_match_the_host_contract() {
+ let defaults = budget_from(|_| None);
+ assert_eq!(defaults, (1_000_000, 10_000_000, 100_000_000));
+
+ let configured = budget_from(|name| match name {
+ "OPENHUMAN_X402_PER_REQUEST_MAX" => Some("2500".to_string()),
+ "OPENHUMAN_X402_DAILY_MAX" => Some("not-a-number".to_string()),
+ "OPENHUMAN_X402_MONTHLY_MAX" => Some("9000000".to_string()),
+ _ => None,
+ });
+ assert_eq!(configured, (2_500, 10_000_000, 9_000_000));
+}
diff --git a/crates/openhuman-core/src/profiles/README.md b/crates/openhuman-core/src/profiles/README.md
index 83894950d1..4ee5d63502 100644
--- a/crates/openhuman-core/src/profiles/README.md
+++ b/crates/openhuman-core/src/profiles/README.md
@@ -485,3 +485,13 @@ nothing to sweep.
On shutdown a sweep in flight is not awaited: its claims lapse after ten
minutes and another node may then run the interrupted occurrence again.
+
+## One turn at a time per profile
+
+Chat turns (`web_chat::run_chat_task`), relayed-message turns
+(`run_relay_turn`) and the cron sweep's runs of one profile take that
+profile's gate ([`turn_gate`](turn_gate.rs)) for the whole turn, so they
+queue instead of overlapping. A due cron occurrence waits behind an in-flight
+chat turn rather than being skipped; the sweep takes the gate before claiming
+the occurrence so the wait does not use up the claim lease. Different
+profiles never contend, and work with no profile (desktop) is not gated.
diff --git a/crates/openhuman-core/src/profiles/cron.rs b/crates/openhuman-core/src/profiles/cron.rs
index ea2e07ae88..a79836f470 100644
--- a/crates/openhuman-core/src/profiles/cron.rs
+++ b/crates/openhuman-core/src/profiles/cron.rs
@@ -98,6 +98,9 @@ pub async fn sweep(host: &ProfileHost, now: DateTime<Utc>) -> SweepReport {
report.skipped += due.len();
continue;
}
+ // The profile's turn gate, taken before the occurrences are claimed so
+ // a wait behind a live chat turn does not eat into the claim lease.
+ let turn = super::turn_gate::acquire_profile(id.as_str()).await;
let mut claimed = Vec::new();
for job in due {
match claims::claim_occurrence(docs.as_ref(), &job, host.node(), now).await {
@@ -138,6 +141,7 @@ pub async fn sweep(host: &ProfileHost, now: DateTime<Utc>) -> SweepReport {
}
})
.await;
+ drop(turn);
if outcome {
report.ran += count;
} else {
diff --git a/crates/openhuman-core/src/profiles/mod.rs b/crates/openhuman-core/src/profiles/mod.rs
index f568a405bb..b299908437 100644
--- a/crates/openhuman-core/src/profiles/mod.rs
+++ b/crates/openhuman-core/src/profiles/mod.rs
@@ -39,6 +39,7 @@ pub mod registry;
pub mod schemas;
pub mod surface;
pub mod tools;
+pub mod turn_gate;
pub mod types;
pub use host::{current, Profile, ProfileHost};
diff --git a/crates/openhuman-core/src/profiles/turn_gate.rs b/crates/openhuman-core/src/profiles/turn_gate.rs
new file mode 100644
index 0000000000..9ac7fd032d
--- /dev/null
+++ b/crates/openhuman-core/src/profiles/turn_gate.rs
@@ -0,0 +1,47 @@
+//! One turn at a time per hosted profile.
+//!
+//! A profile's chat turns, relayed-message turns and scheduled cron runs all
+//! work the same conversation state, memory and workspace, and the host cannot
+//! order them from outside because the cron sweep runs inside OpenHuman. Each
+//! of them therefore takes the profile's gate for the whole turn
+//! ([`acquire`]): turns of one profile queue behind each other, turns of
+//! different profiles never contend.
+//!
+//! Work with no profile (the desktop, single-user embedded agents) is not
+//! gated.
+//!
+//! The gate is a process-wide table keyed by profile id; an entry is a bare
+//! mutex that lives for the life of the process.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, OnceLock};
+
+use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};
+
+/// Held for the duration of one turn; dropping it lets the next one start.
+pub type TurnGuard = OwnedMutexGuard<()>;
+
+fn gates() -> &'static Mutex<HashMap<String, Arc<AsyncMutex<()>>>> {
+ static GATES: OnceLock<Mutex<HashMap<String, Arc<AsyncMutex<()>>>>> = OnceLock::new();
+ GATES.get_or_init(Default::default)
+}
+
+/// Wait for `profile`'s turn gate.
+pub async fn acquire_profile(profile: &str) -> TurnGuard {
+ let gate = {
+ let mut gates = gates().lock().unwrap_or_else(|e| e.into_inner());
+ Arc::clone(gates.entry(profile.to_owned()).or_default())
+ };
+ gate.lock_owned().await
+}
+
+/// Wait for the gate of the profile the calling task runs for, or return
+/// `None` at once when it runs for no profile.
+pub async fn acquire() -> Option<TurnGuard> {
+ let profile = crate::core::runtime::current_tenant().ok()?.profile?;
+ Some(acquire_profile(&profile).await)
+}
+
+#[cfg(test)]
+#[path = "turn_gate_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/profiles/turn_gate_tests.rs b/crates/openhuman-core/src/profiles/turn_gate_tests.rs
new file mode 100644
index 0000000000..2e65ef4ebf
--- /dev/null
+++ b/crates/openhuman-core/src/profiles/turn_gate_tests.rs
@@ -0,0 +1,31 @@
+//! The turn gate queues one profile's turns and leaves other profiles alone.
+
+use std::time::Duration;
+
+use super::*;
+
+#[tokio::test]
+async fn a_profile_runs_one_turn_at_a_time() {
+ let first = acquire_profile("gate-a").await;
+ let second = tokio::spawn(acquire_profile("gate-a"));
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ assert!(!second.is_finished(), "the second turn waits for the first");
+ drop(first);
+ tokio::time::timeout(Duration::from_secs(5), second)
+ .await
+ .expect("released gate admits the next turn")
+ .unwrap();
+}
+
+#[tokio::test]
+async fn other_profiles_are_not_held_up() {
+ let _held = acquire_profile("gate-b").await;
+ tokio::time::timeout(Duration::from_secs(5), acquire_profile("gate-c"))
+ .await
+ .expect("a different profile's gate is free");
+}
+
+#[tokio::test]
+async fn work_without_a_profile_is_not_gated() {
+ assert!(acquire().await.is_none());
+}
diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rs
index 13fff43a22..061819bc8b 100644
--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs
+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs
@@ -505,6 +505,16 @@ async fn clear_session_credential(config: &Config) -> Result<Outcome<bool>, Stri
let mut logs = Vec::new();
crate::cron::scheduler_gate::set_signed_out(true);
#[cfg(feature = "web3")]
+ if let Err(error) = crate::modules::web3_service::close_service(config).await {
+ tracing::warn!(%error, "{LOG_PREFIX} failed to close Web3 service during sign-out");
+ logs.push("Web3 service cleanup will retry on replacement or shutdown".into());
+ }
+ #[cfg(feature = "web3")]
+ if let Err(error) = crate::modules::x402_service::close_service(config).await {
+ tracing::warn!(%error, "{LOG_PREFIX} failed to close x402 service during sign-out");
+ logs.push("x402 service cleanup will retry on replacement or shutdown".into());
+ }
+ #[cfg(feature = "web3")]
if let Err(error) = crate::modules::wallet_service::close_native_wallet_service().await {
tracing::warn!(%error, "{LOG_PREFIX} failed to close native wallet service during sign-out");
logs.push("native wallet service cleanup will retry on replacement or shutdown".into());
diff --git a/crates/openhuman-core/src/tools/impl/network/host.rs b/crates/openhuman-core/src/tools/impl/network/host.rs
index 6343a934a3..9408f0bece 100644
--- a/crates/openhuman-core/src/tools/impl/network/host.rs
+++ b/crates/openhuman-core/src/tools/impl/network/host.rs
@@ -7,6 +7,8 @@
use std::sync::Arc;
+#[cfg(feature = "web3")]
+use tinytools::{PermissionLevel, Tool, ToolResult};
use tinytools_std::network::{
AsyncHtmlExtractor, HttpLimits, HttpRequestTool, NetGate, WebFetchTool,
};
@@ -66,6 +68,58 @@ pub fn http_request_tool(
tool
}
+/// Dedicated x402 agent entry point backed by the same host HTTP policy and
+/// the module payment hook used by `http_request`.
+#[cfg(feature = "web3")]
+pub fn x402_request_tool(
+ gate: Arc<dyn NetGate>,
+ allowed_domains: Vec<String>,
+ max_response_size: usize,
+ timeout_secs: u64,
+) -> impl Tool {
+ X402RequestTool {
+ gate: Arc::clone(&gate),
+ inner: http_request_tool(gate, allowed_domains, max_response_size, timeout_secs),
+ }
+}
+
+#[cfg(feature = "web3")]
+#[derive(Debug)]
+struct X402RequestTool {
+ gate: Arc<dyn NetGate>,
+ inner: HttpRequestTool,
+}
+
+#[cfg(feature = "web3")]
+#[async_trait::async_trait]
+impl Tool for X402RequestTool {
+ fn name(&self) -> &'static str {
+ tinywallet_bus::tools::x402_request_tool_declaration().name
+ }
+
+ fn description(&self) -> &'static str {
+ tinywallet_bus::tools::x402_request_tool_declaration().description
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ tinywallet_bus::tools::x402_request_tool_declaration()
+ .parameters
+ .clone()
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ PermissionLevel::Write
+ }
+
+ fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {
+ self.gate.network_needs_approval()
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ self.inner.execute(args).await
+ }
+}
+
/// `web_fetch`, converting HTML through TinyJuice and opting into TinyJuice's
/// optional `summary_focus` argument.
pub fn web_fetch_tool(
@@ -91,10 +145,9 @@ mod x402 {
//! x402 machine payment for `http_request`'s `402 Payment Required` retry.
use async_trait::async_trait;
- use base64::engine::Engine as _;
- use tinytools_std::network::{PaymentAttempt, PaymentHook, PaymentOutcome};
+ use tinytools_std::network::{PaymentAttempt, PaymentHook};
- use crate::web3::x402;
+ use crate::modules::x402_service;
#[derive(Debug)]
pub(super) struct X402PaymentHook;
@@ -106,75 +159,63 @@ mod x402 {
url: &str,
response_headers: &reqwest::header::HeaderMap,
) -> Result<PaymentAttempt, String> {
- let payment_result = x402::handle_402_and_pay(response_headers, url)
+ let challenge = response_headers
+ .get("PAYMENT-REQUIRED")
+ .or_else(|| response_headers.get("X-PAYMENT-REQUIRED"))
+ .and_then(|value| value.to_str().ok())
+ .ok_or_else(|| {
+ "402 response is missing a valid PAYMENT-REQUIRED header".to_string()
+ })?;
+ let config = crate::config::rpc::load_config_with_timeout()
.await
- .map_err(|e| format!("x402 payment failed: {e}"))?;
-
- // Stamped with the ledger's session and the active chat thread, exactly as
- // the `x402_request` tool stamps its own.
- let record = x402::pending_record(&payment_result);
- let record_id = record.id.clone();
- let _ = x402::store::with_ledger_mut(|l| l.record_payment(record));
+ .map_err(|error| format!("x402 payment failed: {error}"))?;
+ let owner = crate::security::approval::APPROVAL_CHAT_CONTEXT
+ .try_with(|context| tinywallet_bus::wire::QuoteOwner {
+ thread_id: context.thread_id.clone(),
+ client_id: context.client_id.clone(),
+ })
+ .ok();
+ let (service, payment) =
+ x402_service::prepare_payment(&config, url.to_owned(), challenge.to_owned(), owner)
+ .await
+ .map_err(|error| format!("x402 payment failed: {error}"))?;
log::debug!(
"[tool.http_request] retrying with x402 payment header amount={} asset={}",
- payment_result.amount_atomic,
- payment_result.asset
+ payment.amount_atomic,
+ payment.asset
);
- let url = url.to_string();
+ let payment_id = payment.payment_id;
+ let config = config.clone();
Ok(PaymentAttempt {
- headers: vec![("PAYMENT-SIGNATURE".to_string(), payment_result.header_value)],
- settle: Box::new(move |outcome| settle(&record_id, &url, &outcome)),
+ headers: vec![("PAYMENT-SIGNATURE".to_string(), payment.payment_header)],
+ settle: Box::new(move |outcome| {
+ if let Ok(runtime) = tokio::runtime::Handle::try_current() {
+ runtime.spawn(async move {
+ if let Err(error) = x402_service::record_payment(
+ &config,
+ service,
+ payment_id,
+ outcome.status,
+ outcome.payment_response,
+ )
+ .await
+ {
+ log::warn!(
+ "[tool.http_request] x402 settlement recording failed: {error}"
+ );
+ }
+ });
+ } else {
+ log::warn!(
+ "[tool.http_request] x402 settlement not recorded: runtime unavailable"
+ );
+ }
+ }),
})
}
}
-
- /// Write the retry's result back onto the ledger entry the payment opened.
- fn settle(record_id: &str, url: &str, outcome: &PaymentOutcome) {
- let settled_status = if outcome.success {
- x402::PaymentStatus::Settled
- } else {
- x402::PaymentStatus::Failed
- };
- let tx_sig = outcome
- .payment_response
- .as_deref()
- .and_then(|b64| base64::engine::general_purpose::STANDARD.decode(b64).ok())
- .and_then(|bytes| serde_json::from_slice::<x402::SettlementResponse>(&bytes).ok())
- .and_then(|r| {
- if r.success && !r.transaction.is_empty() {
- Some(r.transaction)
- } else {
- None
- }
- });
-
- let _ = x402::store::with_ledger_mut(|l| {
- if let Some(rec) = l
- .recent_payments(100)
- .into_iter()
- .find(|r| r.id == record_id)
- {
- let mut updated = rec;
- updated.status = settled_status;
- updated.tx_signature = tx_sig.clone();
- l.record_payment(updated);
- }
- });
-
- if settled_status == x402::PaymentStatus::Settled {
- log::debug!(
- "[tool.http_request] x402 payment settled for {url} tx={:?}",
- tx_sig
- );
- } else {
- log::warn!(
- "[tool.http_request] x402 payment retry returned status {}",
- outcome.status
- );
- }
- }
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/tools/impl/network/mod.rs b/crates/openhuman-core/src/tools/impl/network/mod.rs
index 584cfe7e2c..84a7cca4e6 100644
--- a/crates/openhuman-core/src/tools/impl/network/mod.rs
+++ b/crates/openhuman-core/src/tools/impl/network/mod.rs
@@ -21,6 +21,8 @@ mod mcp_server_tools;
pub use gitbooks::{GitbooksGetPageTool, GitbooksSearchTool};
pub use gmail_unsubscribe::GmailUnsubscribeTool;
+#[cfg(feature = "web3")]
+pub(crate) use host::x402_request_tool;
pub use host::{http_request_tool, web_fetch_tool};
#[cfg(feature = "mcp")]
pub use mcp::{mcp_call_tool, McpListServersTool, McpListToolsTool};
diff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rs
index 4cd3b37d6b..d4d5f0a6ca 100644
--- a/crates/openhuman-core/src/tools/ops.rs
+++ b/crates/openhuman-core/src/tools/ops.rs
@@ -143,7 +143,7 @@ pub fn all_tools_with_runtime(
#[cfg(feature = "flows")]
tools.extend(crate::flows::registration::tools(config.clone(), security));
#[cfg(feature = "web3")]
- tools.extend(crate::web3::wallet::registration::tools());
+ tools.extend(crate::web3::wallet::tools::all_agent_tools());
tools.append(&mut vec![
Box::new(ScheduleTool::new(security.clone(), root_config.clone())),
Box::new(ProxyConfigTool::new(config.clone(), security.clone())),
@@ -308,9 +308,11 @@ 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::request_tool(
+ tools.push(Box::new(crate::tools::x402_request_tool(
security.clone(),
http_config.allowed_domains.clone(),
+ http_config.max_response_size,
+ http_config.timeout_secs,
)));
// Coding-harness baseline `web_fetch` (issue #1205) — single-purpose
diff --git a/crates/openhuman-core/src/web3/README.md b/crates/openhuman-core/src/web3/README.md
index 37bc08b97b..7bf566bebf 100644
--- a/crates/openhuman-core/src/web3/README.md
+++ b/crates/openhuman-core/src/web3/README.md
@@ -1,212 +1,123 @@
-# web3
+# Web3
-The crypto family: a local multi-chain wallet, token swaps and cross-chain
-bridges through deBridge, generic EVM dapp calls, and the x402 machine-payment
-protocol. Almost all of the logic (the wallet engine, the per-chain signing
-flows, the quote store, the agent tools) lives in the vendored
-[`tinywallet`](../../../../vendor/tinywallet) crates. This folder is the host
-adapter: it plugs OpenHuman's keyring, consent, config, backend client, and
-chat scope into those crates through seams, and owns the RPC controllers.
+This domain exposes wallet operations, token swaps, cross-chain bridges, EVM
+dapp calls, and x402 payments. OpenHuman owns the product RPC and tool adapters,
+configuration, credential custody, approvals, and generic HTTP execution. The
+compiled TinyWallet module owns chain algorithms, provider-specific quote and
+payment behavior, signing, payment accounting, and user-scoped service state.
Callers are the controller registry (`core/all.rs`), the tool registry
-(`tools/ops.rs`), and the generic `http_request` tool, which falls back to an
-x402 payment on an HTTP 402.
+(`tools/ops.rs`), and the generic `http_request` tool, which invokes the x402
+payment hook when a response contains an HTTP 402 challenge.
-## How it works
+## Module composition
-### The process-wide engine and service
+The host loads an attested TinyWallet artifact through `modules::wallet`, then
+uses typed TinyBus operations for wallet status, transaction construction,
+quote preparation and execution, x402 payment preparation and settlement, and
+payment history. The host never runs wallet or payment algorithms as a local
+fallback.
-[`seams.rs`](./seams.rs) holds one `WalletEngine` and one `Web3Service` for the whole
-process, built lazily on first use behind a `OnceLock` (`seams::engine()`,
-`seams::service()`). Both come from `tinywallet-web3` and hold no
-configuration of their own. Everything host-specific reaches them through
-seams, each resolving its configuration per call:
+The host callbacks are narrow:
-| Seam (from `tinywallet-web3`) | Host implementation |
+| Callback | Host responsibility |
| --- | --- |
-| `Transport` | `OpenHumanTransport` ([`wallet/transport.rs`](./wallet/transport.rs)) over the wallet RPC layer |
-| `RpcEndpoints` | `HostEndpoints` ([`wallet/endpoints.rs`](./wallet/endpoints.rs)), the `OPENHUMAN_WALLET_RPC_*` environment |
-| `WalletSigner` | `HostSigner` (`seams.rs`): keyring secret, decrypt, then the loaded wallet module |
-| `WalletAccounts` | `HostAccounts` (`seams.rs`): the wallet's stored set-up state |
-| `QuoteScope` | `TaskLocalScope` (`seams.rs`): the chat turn's `APPROVAL_CHAT_CONTEXT` |
-| `Web3Backend` | `HostBackend` (`seams.rs`): `CryptoClient` over the integrations client |
-
-```text
- core/all.rs tools/ops.rs
- (wallet_*, web3_*, (wallet_*, web3_*, x402_request)
- x402_* controllers) |
- | |
- v v
- +----------------------------------------------+
- | web3/ (host adapter) |
- | seams::engine() / seams::service() |
- +----------------------------------------------+
- | WalletEngine / Web3Service (tinywallet-web3)
- |
- +-- WalletSigner --> HostSigner
- | wallet::secret_material + decrypt_secret
- | -> modules::wallet (loaded tinywallet module)
- | derives key, signs, returns signed bytes
- +-- Transport/RpcEndpoints --> chain RPC (reqwest)
- +-- Web3Backend --> CryptoClient
- | -> /agent-integrations/crypto/{routes,swap,bridge}
- +-- QuoteScope --> APPROVAL_CHAT_CONTEXT (thread, client)
-```
-
-No private key is ever assembled in this process, and the recovery phrase
-never enters `tinywallet-web3`. `HostSigner` decrypts the phrase for one call
-and sends it, as a `tinywallet_bus::wire::SecretMaterial`, over a confidential
-call to the loaded wallet module, which must have proved it is an artifact
-this build pinned (`modules::wallet`).
-
-### Swap, bridge, and dapp: confirm then execute
-
-All three use the same two-step flow, implemented in
-`tinywallet_web3::crypto::service`:
-
-```text
- web3_swap_quote / web3_bridge_quote / web3_dapp_call
- resolve the wallet's own address for the chain family (if not given)
- swap/bridge: HostBackend -> backend deBridge proxy -> quote + unsigned tx
- dapp: validate caller-supplied contract + calldata (no backend call)
- store quote { id, owner = QuoteScope::current_owner(), TTL 5 min }
- return { quoteId, kind, expiresAtMs, quote }
- |
- v
- web3_*_execute { quoteId, confirmed: true }
- take_for(owner) -> "not found" if owner differs or expired
- sign via WalletSigner -> broadcast via Transport
- failure: restore the quote with a refreshed TTL
- return { quoteId, kind, transactionHash, explorerUrl?, feeRaw }
-```
-
-Quotes are bound to the chat thread and client that prepared them, so a
-leaked `quoteId` cannot be executed from another session. Non-chat callers
-(CLI, direct JSON-RPC, cron, sub-agents) have no owner and can execute their
-own quotes. Cross-chain requests to `web3_swap` and same-chain requests to
-`web3_bridge` are rejected, mirroring deBridge's split between single-chain
-swaps and cross-chain DLN orders.
-
-deBridge uses real EVM chain ids (1 Ethereum, 10 Optimism, 56 BNB, 137
-Polygon, 8453 Base, 42161 Arbitrum) and a synthetic Solana id, `7565164`.
-`chain_family` (in `tinywallet-web3`) maps a deBridge id to the local signer
-family, and ids the wallet cannot sign for are rejected at quote time.
-
-### Wallet and x402
-
-The wallet ([`wallet/`](./wallet/)) owns onboarding, consent, the encrypted recovery
-phrase, balances, and native and token transfers across EVM, Bitcoin, Solana,
-and Tron, using the same prepare, confirm, execute pattern. x402 ([`x402/`](./x402/))
-intercepts an HTTP 402 challenge, checks the spending ledger, has the wallet
-sign a payment, and retries. Each has its own README.
+| Wallet accounts | Return stored public account addresses. |
+| Chain transport | Apply endpoint configuration and generic HTTP/RPC safety, then return the response. |
+| Backend transport | Make authenticated requests to the TinyHumans integration proxy. |
+| Web3/native/x402 authorization | Apply OpenHuman's explicit user approval policy to the exact module-provided intent. |
+
+Secrets are decrypted from host custody only for a confidential call to the
+attested module. The host retains encrypted wallet persistence and user consent;
+the module derives keys and performs signing. User sign-out and shutdown close
+the module service handles, clearing quote and payment state before the host
+discards endpoint references.
+
+## Swap, bridge, and dapp operations
+
+The compiled module creates quotes and binds them to the active chat thread and
+client. The host exposes the existing RPC namespaces and forwards request and
+response values, without deriving chains, rebuilding transactions, or signing
+on the host. Execution requires `confirmed: true`; the module validates quote
+ownership and gives the host the exact intent for approval at the signer seam.
+
+The backend deBridge proxy remains a generic authenticated host transport at
+`/agent-integrations/crypto/*`. Provider response parsing, chain-family
+selection, quote construction, transaction encoding, and quote storage are
+module-owned. Provider-specific URLs and defaults stay in the module; the host
+passes only approved endpoint overrides through opaque endpoint references.
+
+## Wallet and x402
+
+The wallet module owns account derivation, supported assets, network defaults,
+balance and transaction queries, transfer preparation and execution, address
+validation, ERC-20 calldata encoding, and wallet agent operations. OpenHuman
+retains onboarding, encrypted recovery-phrase storage, user consent, and host
+approval.
+
+For x402, OpenHuman's generic HTTP tool retains domain allowlisting, request
+policy, user approval, and HTTP execution. On an HTTP 402, the host sends the
+challenge and host-custodied encrypted wallet secrets over the confidential
+module call. TinyWallet parses the challenge, chooses the payment chain,
+reserves its own budget, signs, and returns the payment header. The host retries
+the HTTP request, then reports the raw response status and settlement header
+back to the module. The module owns settlement parsing, reservation commit or
+release, the ledger, budgets, and payment history. The host does not keep a
+second x402 ledger or parse payment protocol payloads.
## Layout
-| Path | What it does |
+| Path | Responsibility |
| --- | --- |
-| [`mod.rs`](./mod.rs) | Facade. Declares the family, re-exports `tinywallet_web3::crypto::service` as `web3::types`, aggregates the swap, bridge, and dapp controllers (`all_web3_controller_schemas`, `all_web3_registered_controllers`) and agent tools (`all_web3_agent_tools`), and holds shared schema helpers (`req_json`, `opt_str`, `json_result`, `execute_inputs`). |
-| [`seams.rs`](./seams.rs) | The process-wide engine and service, and the host seam implementations listed above. |
-| [`client.rs`](./client.rs) | `CryptoClient`, a thin wrapper over the shared `IntegrationClient` for `/agent-integrations/crypto/*`. Responses are passed through as `serde_json::Value`. |
-| [`stub.rs`](./stub.rs) | Compiled when `web3` is off: the three aggregators return empty collections. |
-| [`swap/`](swap/README.md) | `web3_swap` controllers: `quote`, `execute`, `routes`. |
-| [`bridge/`](./bridge/) | `web3_bridge` controllers: `quote`, `execute`. |
-| [`dapp/`](dapp/README.md) | `web3_dapp` controllers: `call`, `execute`. |
-| [`wallet/`](wallet/README.md) | Wallet controllers, onboarding and secret state (`ops/`), the engine wrapped in `Outcome` (`execution.rs`), endpoint resolution, and the chain transport. Has its own `stub.rs`. |
-| [`x402/`](x402/README.md) | x402 controllers, wallet and proxy seams for `tinywallet-x402`, ledger budget from the environment, payment records. Has its own `stub.rs`. |
-
-## Key types and entry points
-
-- `seams::engine()` and `seams::service()` return the shared `WalletEngine`
- and `Web3Service`. The wallet tools in `tools/ops.rs` are built over
- `engine()`; the swap, bridge, and dapp tools over `service()`.
-- `HostSigner`, `HostAccounts`, `TaskLocalScope`, and `HostBackend`
- (`seams.rs`) are the seam implementations a contributor changes when host
- behavior has to change.
-- `CryptoClient::from_config` ([`client.rs`](./client.rs)) errors when no backend credential
- is available, the same gate the Composio tools use.
-- `all_web3_agent_tools()` ([`mod.rs`](./mod.rs)) builds the seven swap, bridge, and dapp
- tools from `tinywallet_web3::tools::web3`.
-- `x402::request_tool()` and `x402::handle_402_and_pay` are the x402 entry
- points for the tool registry and the `http_request` 402 retry.
-
-## RPC / CLI surface
-
-All are registered under `DomainGroup::Web3` in `core/all.rs`. Method names
-are `openhuman.<namespace>_<function>`.
-
-| Namespace | Functions |
+| [`mod.rs`](./mod.rs) | Web3 facade and controller/tool aggregation. |
+| [`client.rs`](./client.rs) | Generic authenticated client for the deBridge integration proxy. |
+| [`module_tools.rs`](./module_tools.rs) | Agent-tool adapters over TinyWallet bus operations. |
+| [`swap/`](swap/README.md), [`bridge/`](bridge/), [`dapp/`](dapp/README.md) | Product RPC schemas and controller handlers. |
+| [`wallet/`](wallet/README.md) | Wallet onboarding, host config/custody, controller and tool adapters. |
+| [`x402/`](x402/README.md) | x402 controller projection over the module-owned ledger. |
+| [`../modules/wallet.rs`](../modules/wallet.rs) | TinyBus identity, attestation, and typed calls. |
+| [`../modules/wallet_host.rs`](../modules/wallet_host.rs) | Host callbacks for custody, transport, and exact-intent approval. |
+| [`../modules/web3_service.rs`](../modules/web3_service.rs) and [`../modules/x402_service.rs`](../modules/x402_service.rs) | User-scoped module service setup and cleanup. |
+
+## RPC and agent tools
+
+All controllers are registered under `DomainGroup::Web3` in `core/all.rs`.
+Namespace names are wire contracts.
+
+| Namespace | Operations |
| --- | --- |
| `web3_swap` | `quote`, `execute`, `routes` |
| `web3_bridge` | `quote`, `execute` |
| `web3_dapp` | `call`, `execute` |
-| [`wallet`](./wallet) | `setup`, `status`, `reveal_recovery_phrase`, `balances`, `chain_status`, `network_defaults`, `supported_assets`, `encode_erc20_transfer`, `prepare_transfer`, `execute_prepared`, `tx_status`, `tx_receipt`, `lookup_tx` |
-| [`x402`](./x402) | `get_summary`, `list_payments`, `update_budget` |
-
-Each `*_execute` takes `quoteId` and `confirmed`, and `confirmed` must be
-true. That flag is the explicit boundary between preparing and spending.
-
-## Agent tools
-
-- Swap, bridge, dapp (from `tinywallet_web3::tools::web3`):
- `web3_swap_quote`, `web3_swap_execute`, `web3_swap_routes`,
- `web3_bridge_quote`, `web3_bridge_execute`, `web3_dapp_call`,
- `web3_dapp_execute`. They register unconditionally and error at call time
- when the user is not signed in.
-- Wallet tools (status, chain status, prepare transfer, tx status, receipt,
- lookup) are re-exported through [`wallet/tools.rs`](./wallet/tools.rs) and `tools/mod.rs`, and
- built in `tools/ops.rs`.
-- `x402_request`, from `tinywallet-x402`, wired through [`x402/seams.rs`](./x402/seams.rs).
-
-## Boundaries
-
-- Wallet engine, transfer flows, per-chain transaction building, swap,
- bridge, and dapp quote preparation, the quote store, and the agent tools
- belong to `tinywallet-web3`. The x402 wire format, payment builders,
- spending ledger, and `x402_request` tool belong to `tinywallet-x402`. Chain
- primitives and wire types belong to `tinywallet-bus` and
- `tinywallet-crypto`. Key derivation and signing belong to the loadable
- `tinywallet` module. All of these are in `vendor/tinywallet`, upstream
- `tinyhumansai/tinywallet`.
-- Loading and attesting the wallet module belongs to `modules/wallet.rs`.
-- Quote routes, deBridge integration, and the affiliate fee (default 1%,
- collected on-chain by deBridge on the source chain) belong to the backend.
- This module passes quotes through unchanged.
-- The approval chat context (`APPROVAL_CHAT_CONTEXT`) belongs to
- `security::approval`.
-
-## Gotchas
-
-- The `web3` Cargo feature is not in the core's `default` set, despite older
- comments (including in `Cargo.toml` and the `mod.rs` docs) calling it
- default-on. It is in `scripts/ci/product-features.txt`, so the shipped app
- has it. It enables `tinywallet-bus`, `tinywallet-x402`, `tinywallet-web3`,
- and `modules`. At runtime `DomainSet::web3` gates the same surface.
-- `pub mod web3`, `wallet`, and `x402` are always compiled. Each is a facade
- with its own [`stub.rs`](./stub.rs) for the disabled build, so always-on callers
- (`core/all.rs`, `tools/ops.rs`, `tools/impl/network/host.rs` for x402) need
- no `#[cfg]`. Stub signatures must match the real ones, and only
- `cargo check --no-default-features` catches drift.
-- `TaskLocalScope` reads a `tokio::task_local!`, which propagates across
- `.await` but not across `tokio::spawn`. If the chat path ever runs the tool
- loop on a freshly spawned task without re-installing the scope, the owner
- gate silently becomes a no-op. [`seams_tests.rs`](./seams_tests.rs) pins that it reads the
- task-local.
-- `CryptoClient` logs only chain ids. Request bodies carry wallet addresses,
- which must not be logged in full.
-
-## Tests
-
-[`seams_tests.rs`](./seams_tests.rs) composes the real wallet state and pins the task-local scope.
-[`stub_tests.rs`](./stub_tests.rs) runs only in the disabled build. `wallet/` and `x402/` keep
-their own tests.
+| [`wallet`](./wallet/README.md) | `setup`, `status`, `reveal_recovery_phrase`, `balances`, `chain_status`, `network_defaults`, `supported_assets`, `encode_erc20_transfer`, `prepare_transfer`, `execute_prepared`, `tx_status`, `tx_receipt`, `lookup_tx` |
+| [`x402`](./x402/README.md) | `get_summary`, `list_payments`, `update_budget` |
+
+The existing Wallet/Web3/x402 agent declarations come from `tinywallet-bus`;
+OpenHuman supplies adapters that call the module. The `x402_request` tool uses
+the generic host HTTP executor and its payment hook, retaining its existing
+name and parameter schema.
+
+## Boundaries and validation
+
+- TinyWallet owns wallet, Web3, and x402 algorithms. OpenHuman owns product
+ configuration, encrypted secret custody, approval policy, generic HTTP/RPC
+ transport, and controller compatibility.
+- Module calls fail closed when the artifact or required operation is
+ unavailable or incompatible. There is no local implementation fallback.
+- `web3` is included in `scripts/ci/product-features.txt`; `DomainSet::Web3`
+ gates the same surface at runtime. The `web3` Cargo feature adds the bus
+ contract and module support, not TinyWallet implementation crates.
+- The `client` logs endpoint and operation metadata only; request bodies and
+ wallet addresses must not be logged.
```bash
cargo test -p openhuman --features web3 web3::
-cargo check -p openhuman --no-default-features # stub drift
+cargo check -p openhuman --no-default-features
+node scripts/ci/check-module-boundaries.mjs
```
## Further reading
- [Wallet](../../../../gitbooks/features/wallet.md)
-- [tinywallet submodule](../../../../vendor/tinywallet/README.md)
+- [TinyWallet](../../../../vendor/tinywallet/README.md)
- [Loadable modules](../../../../gitbooks/developing/loadable-modules.md)
diff --git a/crates/openhuman-core/src/web3/bridge/mod.rs b/crates/openhuman-core/src/web3/bridge/mod.rs
index cf6cd7dc7f..52dba1bd8c 100644
--- a/crates/openhuman-core/src/web3/bridge/mod.rs
+++ b/crates/openhuman-core/src/web3/bridge/mod.rs
@@ -1,6 +1,5 @@
//! `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`.
+//! the compiled TinyWallet module; this module owns the RPC controllers and
+//! their schemas. The agent tools call the same module contract.
pub mod schemas;
diff --git a/crates/openhuman-core/src/web3/bridge/schemas.rs b/crates/openhuman-core/src/web3/bridge/schemas.rs
index a69bb5d366..a6ee060c2b 100644
--- a/crates/openhuman-core/src/web3/bridge/schemas.rs
+++ b/crates/openhuman-core/src/web3/bridge/schemas.rs
@@ -6,9 +6,10 @@ use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::seams::service;
use super::super::{execute_inputs, json_result, opt_str, req_json};
-use tinywallet_web3::crypto::service::{BridgeQuoteParams, ExecuteQuoteParams};
+use crate::config::rpc as config_rpc;
+use crate::modules::web3_service;
+use tinywallet_bus::names::methods;
pub fn schemas() -> Vec<ControllerSchema> {
vec![schema("quote"), schema("execute")]
@@ -32,28 +33,48 @@ pub fn schema(function: &str) -> ControllerSchema {
"quote" => ControllerSchema {
namespace: "web3_bridge",
function: "quote",
- description:
- "Prepare a cross-chain bridge via deBridge DLN. Returns a quote plus a prepared quoteId to confirm+execute; the unsigned transaction is signed+broadcast on the source chain.",
+ description: "Prepare a cross-chain bridge via deBridge DLN. Returns a quote plus a prepared quoteId to confirm+execute; the unsigned transaction is signed+broadcast on the source chain.",
inputs: vec![
req_json("srcChainId", "Source deBridge chain id."),
req_json("srcChainTokenIn", "Source token address."),
- req_json("srcChainTokenInAmount", "Source amount in the token's smallest unit."),
- req_json("dstChainId", "Destination deBridge chain id (must differ from source)."),
+ req_json(
+ "srcChainTokenInAmount",
+ "Source amount in the token's smallest unit.",
+ ),
+ req_json(
+ "dstChainId",
+ "Destination deBridge chain id (must differ from source).",
+ ),
req_json("dstChainTokenOut", "Destination token address."),
- opt_str("dstChainTokenOutAmount", "Destination amount, or 'auto' for market rate (default 'auto')."),
- opt_str("dstChainTokenOutRecipient", "Recipient on the destination chain. Defaults to the wallet's own address."),
- opt_str("srcChainOrderAuthorityAddress", "Source-chain order authority. Defaults to the wallet's source address."),
- opt_str("dstChainOrderAuthorityAddress", "Destination-chain order authority. Defaults to the wallet's destination address."),
+ opt_str(
+ "dstChainTokenOutAmount",
+ "Destination amount, or 'auto' for market rate (default 'auto').",
+ ),
+ opt_str(
+ "dstChainTokenOutRecipient",
+ "Recipient on the destination chain. Defaults to the wallet's own address.",
+ ),
+ opt_str(
+ "srcChainOrderAuthorityAddress",
+ "Source-chain order authority. Defaults to the wallet's source address.",
+ ),
+ opt_str(
+ "dstChainOrderAuthorityAddress",
+ "Destination-chain order authority. Defaults to the wallet's destination address.",
+ ),
],
- outputs: vec![json_result("Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.")],
+ outputs: vec![json_result(
+ "Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.",
+ )],
},
"execute" => ControllerSchema {
namespace: "web3_bridge",
function: "execute",
- description:
- "Confirm and execute a prepared web3_bridge quote: signs the source-chain transaction in-core and broadcasts it.",
+ description: "Confirm and execute a prepared web3_bridge quote: signs the source-chain transaction in-core and broadcasts it.",
inputs: execute_inputs(),
- outputs: vec![json_result("ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.")],
+ outputs: vec![json_result(
+ "ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.",
+ )],
},
_ => ControllerSchema {
namespace: "web3_bridge",
@@ -72,18 +93,22 @@ pub fn schema(function: &str) -> ControllerSchema {
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}"))?;
- let quote = service().quote_bridge(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let quote = web3_service::quote(&config, methods::WEB3_BRIDGE_QUOTE, Value::Object(params))
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(quote, vec!["web3 bridge prepared".to_string()]).into_cli_compatible_json()
})
}
fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
+ let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let result = service().execute_quote(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let result = web3_service::execute(&config, parsed.quote_id, parsed.confirmed)
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
.into_cli_compatible_json()
})
diff --git a/crates/openhuman-core/src/web3/dapp/README.md b/crates/openhuman-core/src/web3/dapp/README.md
index 9171e99675..8a62331852 100644
--- a/crates/openhuman-core/src/web3/dapp/README.md
+++ b/crates/openhuman-core/src/web3/dapp/README.md
@@ -1,53 +1,20 @@
-# web3/dapp
+# web3_dapp
-Generic EVM contract calls from caller-supplied calldata, one of the three
-families under [`web3`](../README.md) alongside `swap` and `bridge`. Unlike
-those two, `dapp` does not call the backend at quote time: the caller
-provides the target contract and pre-encoded calldata directly, and this
-module only validates and stores the prepared transaction for the normal
-confirm-then-execute flow.
+Generic EVM contract calls accept a target contract and pre-encoded calldata.
+The compiled TinyWallet module validates the request, prepares and stores the
+quote, and later signs and broadcasts after explicit approval. OpenHuman keeps
+the `web3_dapp` RPC schemas and the typed module adapter.
-## What it does
-
-`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`](./schemas.rs))
-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`](./mod.rs) | Module docs. |
-| [`schemas.rs`](./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
-
-Namespace `web3_dapp` (method form `openhuman.web3_dapp_<function>`):
+## Operations
| Function | Purpose |
| --- | --- |
-| `call` | Prepare a generic EVM contract call. Params: `contractAddress`, `calldata` (0x-prefixed hex), and optional `valueRaw` (default `"0"`), `evmNetwork` (default `ethereum_mainnet`). Returns a prepared quote with a `quoteId`. |
-| `execute` | Confirm and execute a prepared quote (`quoteId`, `confirmed: true`). Signs the contract call in-core and broadcasts it. |
-
-## Agent tools
-
-`web3_dapp_call`, `web3_dapp_execute`. The `evmNetwork` argument accepts
-`ethereum_mainnet`, `base_mainnet`, `arbitrum_one`, `optimism_mainnet`,
-`polygon_mainnet`, `bsc_mainnet`.
-
-## Notes
-
-- No backend call is involved in preparing a dapp call; deBridge is only used by `swap` and `bridge`. Signing and broadcast still go through the wallet's crate-internal `sign_and_broadcast_evm`, same as the other two families.
-- The quote id returned by `call` is bound to the chat thread that prepared it, TTL'd at 5 minutes, and restored with a refreshed TTL on a failed broadcast; see the parent [README](../README.md) for the shared quote store.
-- BTC and Solana are out of scope here. `dapp` is EVM-only.
+| `call` | Prepare an EVM contract call with `contractAddress`, `calldata`, and optional `valueRaw` / `evmNetwork`. |
+| `execute` | Execute a stored quote with `confirmed: true`; the host approves the exact transaction intent before module signing. |
-## Further reading
+No backend call is needed to prepare a dapp call. Quotes are module-owned and
+bound to the preparing chat thread and client. The host does not validate or
+encode chain transactions locally.
-- [Parent module (`web3`)](../README.md)
-- [Wallet](../../../../../gitbooks/features/wallet.md)
-- [tinywallet submodule](../../../../../vendor/tinywallet/README.md)
-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)
+The host controller schemas are in [`schemas.rs`](./schemas.rs). See the
+[parent Web3 architecture](../README.md) for the module/host boundary.
diff --git a/crates/openhuman-core/src/web3/dapp/mod.rs b/crates/openhuman-core/src/web3/dapp/mod.rs
index 1487f15466..16741e1f3f 100644
--- a/crates/openhuman-core/src/web3/dapp/mod.rs
+++ b/crates/openhuman-core/src/web3/dapp/mod.rs
@@ -1,6 +1,5 @@
//! `web3_dapp` — generic EVM contract interactions from caller-supplied
-//! 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`.
+//! calldata. Logic lives in the compiled TinyWallet module; this module owns
+//! the RPC controllers and their schemas. Agent tools use that same bus API.
pub mod schemas;
diff --git a/crates/openhuman-core/src/web3/dapp/schemas.rs b/crates/openhuman-core/src/web3/dapp/schemas.rs
index deaf4cdbe4..dffb156e59 100644
--- a/crates/openhuman-core/src/web3/dapp/schemas.rs
+++ b/crates/openhuman-core/src/web3/dapp/schemas.rs
@@ -6,9 +6,10 @@ use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::seams::service;
use super::super::{execute_inputs, json_result, opt_str, req_json};
-use tinywallet_web3::crypto::service::{DappCallParams, ExecuteQuoteParams};
+use crate::config::rpc as config_rpc;
+use crate::modules::web3_service;
+use tinywallet_bus::names::methods;
pub fn schemas() -> Vec<ControllerSchema> {
vec![schema("call"), schema("execute")]
@@ -32,23 +33,31 @@ pub fn schema(function: &str) -> ControllerSchema {
"call" => ControllerSchema {
namespace: "web3_dapp",
function: "call",
- description:
- "Prepare a generic EVM dapp contract call from pre-encoded calldata. Returns a prepared quoteId to confirm+execute.",
+ description: "Prepare a generic EVM dapp contract call from pre-encoded calldata. Returns a prepared quoteId to confirm+execute.",
inputs: vec![
req_json("contractAddress", "Target contract address."),
req_json("calldata", "0x-prefixed hex calldata."),
- opt_str("valueRaw", "Native value attached, smallest unit. Defaults to '0'."),
- opt_str("evmNetwork", "EVM network selector. Defaults to ethereum_mainnet."),
+ opt_str(
+ "valueRaw",
+ "Native value attached, smallest unit. Defaults to '0'.",
+ ),
+ opt_str(
+ "evmNetwork",
+ "EVM network selector. Defaults to ethereum_mainnet.",
+ ),
],
- outputs: vec![json_result("Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.")],
+ outputs: vec![json_result(
+ "Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.",
+ )],
},
"execute" => ControllerSchema {
namespace: "web3_dapp",
function: "execute",
- description:
- "Confirm and execute a prepared web3_dapp call: signs the contract call in-core and broadcasts it.",
+ description: "Confirm and execute a prepared web3_dapp call: signs the contract call in-core and broadcasts it.",
inputs: execute_inputs(),
- outputs: vec![json_result("ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.")],
+ outputs: vec![json_result(
+ "ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.",
+ )],
},
_ => ControllerSchema {
namespace: "web3_dapp",
@@ -67,18 +76,22 @@ pub fn schema(function: &str) -> ControllerSchema {
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}"))?;
- let quote = service().prepare_dapp_call(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let quote = web3_service::quote(&config, methods::WEB3_DAPP_QUOTE, Value::Object(params))
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(quote, vec!["web3 dapp call prepared".to_string()]).into_cli_compatible_json()
})
}
fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
+ let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let result = service().execute_quote(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let result = web3_service::execute(&config, parsed.quote_id, parsed.confirmed)
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
.into_cli_compatible_json()
})
diff --git a/crates/openhuman-core/src/web3/mod.rs b/crates/openhuman-core/src/web3/mod.rs
index e428582e72..716ec64008 100644
--- a/crates/openhuman-core/src/web3/mod.rs
+++ b/crates/openhuman-core/src/web3/mod.rs
@@ -1,13 +1,13 @@
-//! High-level web3 surface built on top of the [`crate::web3::wallet`]
-//! signing primitives. Focuses on EVM/Solana dapp interactions: swaps, bridges,
-//! and generic contract calls.
+//! High-level Web3 product surface for swaps, bridges, dapp calls, and wallet
+//! operations. The host owns RPC policy and user approval; TinyWallet owns
+//! chain-specific algorithms and module-scoped quote state.
//!
-//! 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.
+//! Quote preparation, signing, calldata encoding, provider algorithms, and the
+//! confirm-then-execute quote store run inside the compiled TinyWallet module.
+//! This host layer keeps product RPC controllers and schemas (their namespace
+//! strings are wire contracts), the [`client`] for the backend deBridge proxy
+//! (`/agent-integrations/crypto/*`), and adapters for configuration, custody,
+//! approval, and generic network transport.
//! Three sub-modules expose distinct RPC namespaces:
//! - [`swap`] (`web3_swap`) — single-chain swaps (cross-chain → `web3_bridge`).
//! - [`bridge`] (`web3_bridge`) — cross-chain DLN bridges.
@@ -30,10 +30,9 @@ pub mod client;
#[cfg(feature = "web3")]
pub mod dapp;
#[cfg(feature = "web3")]
-pub mod seams;
+mod module_tools;
#[cfg(feature = "web3")]
pub mod swap;
-
// 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
// default-ON `web3` feature. Always-compiled callers resolve through those
@@ -125,19 +124,13 @@ 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(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)),
- ]
+ tinywallet_bus::tools::web3_tool_declarations()
+ .iter()
+ .map(|declaration| {
+ Box::new(module_tools::Web3ModuleTool::new(
+ tinywallet_bus::tools::find_web3_tool_declaration(declaration.name)
+ .expect("the declaration came from the shipped Web3 list"),
+ )) as Box<dyn Tool>
+ })
+ .collect()
}
diff --git a/crates/openhuman-core/src/web3/module_tools.rs b/crates/openhuman-core/src/web3/module_tools.rs
new file mode 100644
index 0000000000..65010c8f71
--- /dev/null
+++ b/crates/openhuman-core/src/web3/module_tools.rs
@@ -0,0 +1,100 @@
+//! Agent tool adapters that route Web3 operations through the TinyWallet bus.
+
+use async_trait::async_trait;
+use serde_json::Value;
+use tinytools::{Tool, ToolCallOptions, ToolExposure, ToolResult};
+use tinywallet_bus::tools::ToolDeclaration;
+
+#[derive(Debug)]
+pub(super) struct Web3ModuleTool {
+ declaration: &'static ToolDeclaration,
+}
+
+impl Web3ModuleTool {
+ pub(super) const fn new(declaration: &'static ToolDeclaration) -> Self {
+ Self { declaration }
+ }
+}
+
+#[async_trait]
+impl Tool for Web3ModuleTool {
+ fn exposure(&self) -> ToolExposure {
+ ToolExposure::Deferred
+ }
+
+ fn name(&self) -> &'static str {
+ self.declaration.name
+ }
+
+ fn description(&self) -> &'static str {
+ self.declaration.description
+ }
+
+ fn parameters_schema(&self) -> Value {
+ self.declaration.parameters.clone()
+ }
+
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ let config = match crate::config::rpc::load_config_with_timeout().await {
+ Ok(config) => config,
+ Err(error) => return Ok(ToolResult::error(error)),
+ };
+ let result: anyhow::Result<Value> = match self.name() {
+ "web3_swap_quote" => crate::modules::web3_service::quote(
+ &config,
+ tinywallet_bus::names::methods::WEB3_SWAP_QUOTE,
+ args,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))
+ .and_then(|value| serde_json::to_value(value).map_err(Into::into)),
+ "web3_bridge_quote" => crate::modules::web3_service::quote(
+ &config,
+ tinywallet_bus::names::methods::WEB3_BRIDGE_QUOTE,
+ args,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))
+ .and_then(|value| serde_json::to_value(value).map_err(Into::into)),
+ "web3_dapp_call" => crate::modules::web3_service::quote(
+ &config,
+ tinywallet_bus::names::methods::WEB3_DAPP_QUOTE,
+ args,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))
+ .and_then(|value| serde_json::to_value(value).map_err(Into::into)),
+ "web3_swap_routes" => crate::modules::web3_service::routes(&config)
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string())),
+ "web3_swap_execute" | "web3_bridge_execute" | "web3_dapp_execute" => {
+ match serde_json::from_value::<crate::modules::web3_service::ExecuteParams>(args) {
+ Ok(params) => crate::modules::web3_service::execute(
+ &config,
+ params.quote_id,
+ params.confirmed,
+ )
+ .await
+ .map_err(|error| anyhow::anyhow!(error.to_string()))
+ .and_then(|value| serde_json::to_value(value).map_err(Into::into)),
+ Err(error) => {
+ return Ok(ToolResult::error(format!("invalid arguments: {error}")));
+ }
+ }
+ }
+ _ => return Ok(ToolResult::error("unknown Web3 tool")),
+ };
+ match result {
+ Ok(value) => Ok(ToolResult::success(serde_json::to_string_pretty(&value)?)),
+ Err(error) => Ok(ToolResult::error(error.to_string())),
+ }
+ }
+
+ async fn execute_with_options(
+ &self,
+ args: Value,
+ _options: ToolCallOptions,
+ ) -> anyhow::Result<ToolResult> {
+ self.execute(args).await
+ }
+}
diff --git a/crates/openhuman-core/src/web3/seams.rs b/crates/openhuman-core/src/web3/seams.rs
deleted file mode 100644
index fa667370ad..0000000000
--- a/crates/openhuman-core/src/web3/seams.rs
+++ /dev/null
@@ -1,246 +0,0 @@
-//! 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, tinywallet_web3::crypto::wallet::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/swap/README.md b/crates/openhuman-core/src/web3/swap/README.md
index f70c5dd8de..db6f3a1ec9 100644
--- a/crates/openhuman-core/src/web3/swap/README.md
+++ b/crates/openhuman-core/src/web3/swap/README.md
@@ -1,52 +1,22 @@
-# web3/swap
+# web3_swap
-Single-chain token swaps via the deBridge proxy, one of the three families
-under [`web3`](../README.md) alongside `bridge` and `dapp`. See the parent
-README for the shared quote store, chain-id mapping, and signing path; this
-file only covers what is specific to swaps.
+Single-chain token swaps use the TinyWallet module for provider parsing, quote
+construction, module-owned quote storage, transaction encoding, approval-bound
+signing, and broadcast. OpenHuman keeps the `web3_swap` RPC controllers and
+agent-tool adapters, and supplies authenticated access to the backend
+deBridge proxy plus generic, guarded chain transport.
-## What it does
-
-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 `Web3Service::quote_swap` in the vendored `tinywallet-web3`
-crate; this module only owns the RPC controllers ([`schemas.rs`](./schemas.rs)) for the
-`web3_swap` namespace. The agent tools are in
-`tinywallet_web3::tools::web3`.
-
-## Key files
-
-| File | Role |
-| --- | --- |
-| [`mod.rs`](./mod.rs) | Module docs. |
-| [`schemas.rs`](./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
-
-Namespace `web3_swap` (method form `openhuman.web3_swap_<function>`):
+## Operations
| Function | Purpose |
| --- | --- |
-| `quote` | Prepare a single-chain swap. Params: `chainId`, `tokenIn`, `tokenInAmount`, `tokenOut`, and optional `tokenOutRecipient`, `senderAddress`, `slippage` (default `"auto"`). Returns a prepared quote with a `quoteId`. |
-| `execute` | Confirm and execute a prepared quote (`quoteId`, `confirmed: true`). Signs and broadcasts. |
-| `routes` | List the chains deBridge can swap and bridge between. No params. |
-
-## Agent tools
-
-`web3_swap_quote`, `web3_swap_execute`, `web3_swap_routes`. They call the
-backend per invocation and return a tool error, rather than being hidden,
-when the caller is not signed in.
-
-## Notes
-
-- Recipient and sender addresses default to the wallet's own derived address for the chain family when omitted.
-- The quote id returned by `quote` is bound to the chat thread that prepared it; see the parent [README](../README.md) for the quote store's TTL and ownership rules, which this module shares with `bridge` and `dapp`.
+| `quote` | Prepare a single-chain swap quote. Cross-chain requests are routed to `web3_bridge`. |
+| `execute` | Execute a stored quote after `confirmed: true` and host approval of the exact intent. |
+| `routes` | List provider-supported routes through the module/backend boundary. |
-## Further reading
+Quotes are bound to their preparing chat thread and client. Module absence,
+ownership mismatch, expiry, and provider errors fail closed; there is no local
+quote or signing fallback.
-- [Parent module (`web3`)](../README.md)
-- [Wallet](../../../../../gitbooks/features/wallet.md)
-- [tinywallet submodule](../../../../../vendor/tinywallet/README.md)
-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)
+The host controller schemas are in [`schemas.rs`](./schemas.rs). See the
+[parent Web3 architecture](../README.md) for the module/host boundary.
diff --git a/crates/openhuman-core/src/web3/swap/mod.rs b/crates/openhuman-core/src/web3/swap/mod.rs
index 4d72f60bc7..b1c2b9facc 100644
--- a/crates/openhuman-core/src/web3/swap/mod.rs
+++ b/crates/openhuman-core/src/web3/swap/mod.rs
@@ -1,6 +1,6 @@
//! `web3_swap` — single-chain swaps via deBridge. Cross-chain swaps are
-//! 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`.
+//! redirected to `web3_bridge`. Quote and execution logic live in the compiled
+//! TinyWallet module; this module owns the RPC controllers and their schemas.
+//! Agent tools use that same bus API.
pub mod schemas;
diff --git a/crates/openhuman-core/src/web3/swap/schemas.rs b/crates/openhuman-core/src/web3/swap/schemas.rs
index 54007571fb..49884540db 100644
--- a/crates/openhuman-core/src/web3/swap/schemas.rs
+++ b/crates/openhuman-core/src/web3/swap/schemas.rs
@@ -7,9 +7,10 @@ use serde_json::{Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, Outcome, TypeSchema};
-use super::super::seams::service;
use super::super::{execute_inputs, json_result, opt_str, req_json};
-use tinywallet_web3::crypto::service::{ExecuteQuoteParams, SwapQuoteParams};
+use crate::config::rpc as config_rpc;
+use crate::modules::web3_service;
+use tinywallet_bus::names::methods;
pub fn schemas() -> Vec<ControllerSchema> {
vec![schema("quote"), schema("execute"), schema("routes")]
@@ -37,26 +38,43 @@ pub fn schema(function: &str) -> ControllerSchema {
"quote" => ControllerSchema {
namespace: "web3_swap",
function: "quote",
- description:
- "Prepare a single-chain token swap via deBridge. Returns a quote plus a prepared quoteId to confirm+execute. For cross-chain swaps use web3_bridge.",
+ description: "Prepare a single-chain token swap via deBridge. Returns a quote plus a prepared quoteId to confirm+execute. For cross-chain swaps use web3_bridge.",
inputs: vec![
- req_json("chainId", "deBridge chain id the swap executes on (e.g. 1 ETH, 56 BNB, 7565164 Solana)."),
- req_json("tokenIn", "Input token address (use the zero address for native)."),
- req_json("tokenInAmount", "Input amount in the token's smallest unit."),
+ req_json(
+ "chainId",
+ "deBridge chain id the swap executes on (e.g. 1 ETH, 56 BNB, 7565164 Solana).",
+ ),
+ req_json(
+ "tokenIn",
+ "Input token address (use the zero address for native).",
+ ),
+ req_json(
+ "tokenInAmount",
+ "Input amount in the token's smallest unit.",
+ ),
req_json("tokenOut", "Output token address."),
- opt_str("tokenOutRecipient", "Address receiving output. Defaults to the wallet's own address on this chain."),
- opt_str("senderAddress", "Sender. Defaults to the wallet's own address on this chain."),
+ opt_str(
+ "tokenOutRecipient",
+ "Address receiving output. Defaults to the wallet's own address on this chain.",
+ ),
+ opt_str(
+ "senderAddress",
+ "Sender. Defaults to the wallet's own address on this chain.",
+ ),
opt_str("slippage", "Slippage percent or 'auto' (default 'auto')."),
],
- outputs: vec![json_result("Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.")],
+ outputs: vec![json_result(
+ "Prepared web3 quote {quoteId, kind, expiresAtMs, quote}.",
+ )],
},
"execute" => ControllerSchema {
namespace: "web3_swap",
function: "execute",
- description:
- "Confirm and execute a prepared web3_swap quote: signs the unsigned transaction in-core and broadcasts it.",
+ description: "Confirm and execute a prepared web3_swap quote: signs the unsigned transaction in-core and broadcasts it.",
inputs: execute_inputs(),
- outputs: vec![json_result("ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.")],
+ outputs: vec![json_result(
+ "ExecutionResult {quoteId, kind, transactionHash, explorerUrl?, feeRaw}.",
+ )],
},
"routes" => ControllerSchema {
namespace: "web3_swap",
@@ -86,18 +104,22 @@ fn unknown_schema() -> ControllerSchema {
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}"))?;
- let quote = service().quote_swap(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let quote = web3_service::quote(&config, methods::WEB3_SWAP_QUOTE, Value::Object(params))
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(quote, vec!["web3 swap prepared".to_string()]).into_cli_compatible_json()
})
}
fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let parsed: ExecuteQuoteParams = serde_json::from_value(Value::Object(params))
+ let parsed: web3_service::ExecuteParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("invalid params: {e}"))?;
- let result = service().execute_quote(parsed).await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let result = web3_service::execute(&config, parsed.quote_id, parsed.confirmed)
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(result, vec!["web3 transaction broadcast".to_string()])
.into_cli_compatible_json()
})
@@ -105,7 +127,10 @@ fn handle_execute(params: Map<String, Value>) -> ControllerFuture {
fn handle_routes(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let routes = service().routes().await?;
+ let config = config_rpc::load_config_with_timeout().await?;
+ let routes = web3_service::routes(&config)
+ .await
+ .map_err(|error| error.to_string())?;
Outcome::new(routes, vec!["web3 supported routes listed".to_string()])
.into_cli_compatible_json()
})
diff --git a/crates/openhuman-core/src/web3/wallet/README.md b/crates/openhuman-core/src/web3/wallet/README.md
index de7ecc87c6..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.
-- `registration::registered_tools` constructs the six wallet agent tools from `tinywallet-web3`; `crates/openhuman-core/src/tools/ops.rs` adds that domain factory (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/wallet/endpoints.rs b/crates/openhuman-core/src/web3/wallet/endpoints.rs
index 134bd4c6e4..77e735fa86 100644
--- a/crates/openhuman-core/src/web3/wallet/endpoints.rs
+++ b/crates/openhuman-core/src/web3/wallet/endpoints.rs
@@ -1,23 +1,12 @@
-//! Endpoint and cluster resolution for the wallet: the `OPENHUMAN_WALLET_RPC_*`
-//! and `OPENHUMAN_SOLANA_CLUSTER` environment handling.
+//! Host configuration for Wallet RPC overrides.
//!
-//! 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.
+//! Default endpoints and network metadata are selected by TinyWallet. This
+//! module only reads OpenHuman's environment overrides and exposes their
+//! values to the host transport after the module returns an opaque alias.
-use tinywallet_web3::crypto::defaults::{
- default_rpc_url, EvmNetwork, EvmNetworkReferenceData, RpcSource, SolanaCluster,
-};
-use tinywallet_web3::crypto::seams::RpcEndpoints;
+use tinywallet_bus::wire::{EvmNetwork, RpcEndpointKey, SolanaCluster, WalletChain};
-#[cfg(test)]
-use tinywallet_web3::crypto::defaults::SolanaClusterReferenceData;
-
-use tinywallet_web3::crypto::wallet::WalletChain;
-
-/// The `OPENHUMAN_WALLET_RPC_<NAME>` variable that overrides `network`.
+/// Environment variable used to override one EVM network endpoint.
pub(crate) fn evm_rpc_env_var(network: EvmNetwork) -> &'static str {
match network {
EvmNetwork::EthereumMainnet => "OPENHUMAN_WALLET_RPC_EVM",
@@ -29,8 +18,7 @@ pub(crate) fn evm_rpc_env_var(network: EvmNetwork) -> &'static str {
}
}
-/// The `OPENHUMAN_WALLET_RPC_<NAME>` variable that overrides `chain`'s
-/// endpoint (Ethereum mainnet's, for EVM).
+/// Environment variable used to override a non-EVM chain endpoint.
pub(crate) fn env_var_for_chain(chain: WalletChain) -> &'static str {
match chain {
WalletChain::Evm => evm_rpc_env_var(EvmNetwork::EthereumMainnet),
@@ -40,92 +28,34 @@ pub(crate) fn env_var_for_chain(chain: WalletChain) -> &'static str {
}
}
-/// Trimmed value of `env_var`, or `None` when unset or blank.
-fn env_nonempty(env_var: &str) -> Option<String> {
- std::env::var(env_var)
+/// Read only an explicitly configured endpoint override. Defaults stay inside
+/// the module and are never copied into host configuration or bus payloads.
+pub(crate) fn override_for_endpoint(key: RpcEndpointKey) -> Option<String> {
+ let variable = match key {
+ RpcEndpointKey::Evm { network } => evm_rpc_env_var(network),
+ RpcEndpointKey::Btc => env_var_for_chain(WalletChain::Btc),
+ RpcEndpointKey::Solana => env_var_for_chain(WalletChain::Solana),
+ RpcEndpointKey::Tron => env_var_for_chain(WalletChain::Tron),
+ };
+ std::env::var(variable)
.ok()
- .map(|value| value.trim().to_string())
+ .map(|value| value.trim().to_owned())
.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).
+/// Parse OpenHuman's Solana-cluster setting. Unknown and blank values retain
+/// the historical mainnet default; endpoint defaults themselves remain
+/// module-owned.
pub fn solana_cluster() -> SolanaCluster {
- let configured = env_nonempty("OPENHUMAN_SOLANA_CLUSTER").map(|v| v.to_ascii_lowercase());
+ let configured = std::env::var("OPENHUMAN_SOLANA_CLUSTER")
+ .ok()
+ .map(|value| value.trim().to_ascii_lowercase());
match configured.as_deref() {
- Some("devnet") => {
- log::debug!("[wallet] Solana cluster = devnet (via OPENHUMAN_SOLANA_CLUSTER)");
- SolanaCluster::Devnet
- }
+ Some("devnet") => 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
index fd351fc6f3..f897ccbf75 100644
--- a/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs
+++ b/crates/openhuman-core/src/web3/wallet/endpoints_tests.rs
@@ -1,8 +1,5 @@
use super::*;
-// The variables read here are process-global. Serialise these tests (and the
-// ones that repoint every endpoint) so they do not race each other, and restore
-// what they touched.
use crate::web3::wallet::test_support::RPC_ENV_LOCK as ENDPOINT_ENV_LOCK;
fn with_env<T>(pairs: &[(&str, Option<&str>)], f: impl FnOnce() -> T) -> T {
@@ -15,136 +12,79 @@ fn with_env<T>(pairs: &[(&str, Option<&str>)], f: impl FnOnce() -> T) -> T {
.collect();
for (name, value) in pairs {
match value {
- Some(v) => std::env::set_var(name, v),
+ Some(value) => std::env::set_var(name, value),
None => std::env::remove_var(name),
}
}
- let out = f();
+ let output = f();
for (name, value) in previous {
match value {
- Some(v) => std::env::set_var(name, v),
+ Some(value) => std::env::set_var(name, value),
None => std::env::remove_var(name),
}
}
- out
+ output
}
#[test]
-fn solana_cluster_defaults_to_mainnet() {
+fn solana_cluster_keeps_the_host_environment_compatibility() {
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(" DevNet "))], || {
+ assert_eq!(solana_cluster(), SolanaCluster::Devnet);
+ });
with_env(&[("OPENHUMAN_SOLANA_CLUSTER", Some("testnet"))], || {
assert_eq!(solana_cluster(), SolanaCluster::Mainnet);
});
}
#[test]
-fn an_env_override_wins_and_is_reported_as_one() {
+fn only_explicit_nonblank_endpoint_overrides_are_exposed_to_transport() {
with_env(
&[
- ("OPENHUMAN_WALLET_RPC_BTC", Some(" http://btc.test/api ")),
- ("OPENHUMAN_WALLET_RPC_BASE", Some("http://base.test")),
+ (
+ "OPENHUMAN_WALLET_RPC_BTC",
+ Some(" https://btc.example/rpc "),
+ ),
+ (
+ "OPENHUMAN_WALLET_RPC_BASE",
+ Some("https://base.example/rpc"),
+ ),
("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
+ override_for_endpoint(RpcEndpointKey::Btc).as_deref(),
+ Some("https://btc.example/rpc")
);
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)
+ override_for_endpoint(RpcEndpointKey::Evm {
+ network: EvmNetwork::BaseMainnet,
+ })
+ .as_deref(),
+ Some("https://base.example/rpc")
);
+ assert_eq!(override_for_endpoint(RpcEndpointKey::Tron), None);
},
);
}
#[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
+fn each_wallet_endpoint_has_a_distinct_host_override_name() {
+ let mut names: Vec<_> = EvmNetwork::ALL
.iter()
- .map(|n| evm_rpc_env_var(*n))
+ .map(|network| evm_rpc_env_var(*network))
.collect();
- for chain in [WalletChain::Btc, WalletChain::Solana, WalletChain::Tron] {
- names.push(env_var_for_chain(chain));
- }
+ names.extend([
+ env_var_for_chain(WalletChain::Btc),
+ env_var_for_chain(WalletChain::Solana),
+ env_var_for_chain(WalletChain::Tron),
+ ]);
let count = names.len();
names.sort_unstable();
names.dedup();
- assert_eq!(names.len(), count, "no two endpoints share an override");
+ assert_eq!(names.len(), count);
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 86aae58b2a..517bf74272 100644
--- a/crates/openhuman-core/src/web3/wallet/execution.rs
+++ b/crates/openhuman-core/src/web3/wallet/execution.rs
@@ -1,10 +1,6 @@
-//! Host adapters over the wallet engine: the read and write operations wrapped
-//! in the controller contract's [`Outcome`].
-//!
-//! 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`]).
+//! Typed TinyWallet module operations adapted to product controller results.
+//! This host supplies configuration, custody, transport and approvals; wallet
+//! algorithms and user-scoped service state remain in the compiled module.
use crate::config::rpc as config_rpc;
use crate::core::Outcome;
@@ -20,7 +16,7 @@ pub use tinywallet_bus::wire::{
use tinywallet_bus::wire::{EvmNetwork, WalletNetworkDefaults};
-use tinywallet_web3::crypto::wallet::WalletChain;
+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> {
@@ -222,6 +218,14 @@ pub async fn lookup_tx(
))
}
+/// Encode ERC-20 transfer calldata in the loaded wallet module.
+pub async fn encode_erc20_transfer(to_address: &str, amount_raw: &str) -> Result<String, String> {
+ let config = config_rpc::load_config_with_timeout().await?;
+ wallet_module::encode_erc20_transfer(&config, to_address, amount_raw)
+ .await
+ .map_err(|error| error.to_string())
+}
+
/// 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> {
diff --git a/crates/openhuman-core/src/web3/wallet/mod.rs b/crates/openhuman-core/src/web3/wallet/mod.rs
index 499e928299..3ed66332f2 100644
--- a/crates/openhuman-core/src/web3/wallet/mod.rs
+++ b/crates/openhuman-core/src/web3/wallet/mod.rs
@@ -4,21 +4,19 @@
//!
//! ## 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:
+//! The wallet engine — balances, the prepare/confirm/execute flow, signing,
+//! transaction encoding, provider interaction, and agent tools — lives in the
+//! compiled TinyWallet module. This module holds host configuration, custody,
+//! approvals, product RPC adapters, and module lifecycle:
//!
//! - [`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.
+//! - [`execution`] — typed module operations adapted to product controller
+//! responses.
+//! - [`endpoints`] / [`rpc`] — host endpoint configuration and guarded,
+//! credential-aware transport callbacks.
//! - `schemas` — the controllers, with their RPC namespace strings.
-//! - The seam implementations and the process-wide engine are in
-//! [`crate::web3::seams`].
+//! - [`crate::modules::wallet_service`] owns the native module service lifetime.
//!
//! ## Compile-time gate (`web3` feature)
//!
@@ -45,17 +43,13 @@ mod ops;
#[cfg(feature = "web3")]
pub(crate) mod rpc;
-#[cfg(feature = "web3")]
-pub(crate) mod registration;
#[cfg(feature = "web3")]
mod schemas;
-/// The host side of the wallet primitives' `Transport` seam — endpoint resolution,
-/// failover and redaction stay here, where the config lives.
-#[cfg(feature = "web3")]
-pub(crate) mod transport;
-
#[cfg(all(test, feature = "web3"))]
pub(crate) mod test_support;
+/// Wallet agent tool adapters over the declarations in `tinywallet-bus`.
+#[cfg(feature = "web3")]
+pub mod tools;
#[cfg(feature = "web3")]
pub use endpoints::solana_cluster;
@@ -70,22 +64,22 @@ pub use execution::{
#[cfg(feature = "web3")]
pub(crate) use ops::secret_material;
#[cfg(feature = "web3")]
+pub use ops::{
+ derive_recovery_material, generate_recovery_phrase, reveal_recovery_phrase, setup, status,
+ validate_recovery_phrase, GeneratedRecoveryPhrase, RecoveryPhraseValidation,
+ RevealRecoveryPhraseResult, WalletAccount, WalletChain, WalletRecoveryMaterial,
+ WalletSetupParams, WalletSetupSource, WalletStatus, WALLET_NOT_CONFIGURED_MESSAGE,
+};
+#[cfg(feature = "web3")]
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 {
- ops::reveal_recovery_phrase, ops::setup, ops::status, ops::RevealRecoveryPhraseResult,
- ops::WalletSetupParams,
+pub use tinywallet_bus::wire::{
+ EvmNetwork, RpcSource, SolanaCluster, WalletAssetDefinition, WalletNetworkDefaults,
};
-// Retained for the always-on RPC/observability boundary until #7406 exposes
-// this shared producer error through the released TinyWallet bus contract.
-// Embed must not acquire an implementation dependency for this sentinel.
-#[cfg(feature = "web3")]
-pub use tinywallet_web3::quote::WALLET_NOT_CONFIGURED_MESSAGE;
-
// ---------------------------------------------------------------------------
// Disabled facade — compiled only when the `web3` feature is OFF.
// ---------------------------------------------------------------------------
diff --git a/crates/openhuman-core/src/web3/wallet/ops.rs b/crates/openhuman-core/src/web3/wallet/ops.rs
index e5c0754181..dfa5ab0444 100644
--- a/crates/openhuman-core/src/web3/wallet/ops.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops.rs
@@ -9,17 +9,19 @@ mod types;
use types::StoredWalletState;
pub(crate) use types::WalletSecretMaterial;
-use {
- tinywallet_web3::crypto::wallet::WalletAccount, tinywallet_web3::crypto::wallet::WalletChain,
- tinywallet_web3::crypto::wallet::WalletStatus,
- tinywallet_web3::quote::WALLET_NOT_CONFIGURED_MESSAGE,
+pub use types::{
+ GeneratedRecoveryPhrase, RecoveryPhraseValidation, RevealRecoveryPhraseResult, WalletAccount,
+ WalletChain, WalletRecoveryMaterial, WalletSetupParams, WalletSetupSource, WalletStatus,
+ WALLET_NOT_CONFIGURED_MESSAGE,
};
-pub use {types::RevealRecoveryPhraseResult, types::WalletSetupParams};
use log::debug;
use crate::config::rpc as config_rpc;
use crate::core::Outcome;
+use tinywallet_bus::wire::SecretMaterial;
+use tinywallet_bus::Chain as ModuleChain;
+use zeroize::{Zeroize, Zeroizing};
use state::{
keychain_load_mnemonic, load_stored_wallet_state_unlocked, save_stored_wallet_state_unlocked,
@@ -28,6 +30,120 @@ use state::{
const VALID_MNEMONIC_WORD_COUNTS: [u8; 5] = [12, 15, 18, 21, 24];
+fn is_valid_mnemonic_word_count(count: usize) -> bool {
+ VALID_MNEMONIC_WORD_COUNTS
+ .iter()
+ .any(|valid| usize::from(*valid) == count)
+}
+
+/// Generate recovery material through the attested wallet module.
+pub async fn generate_recovery_phrase(
+ word_count: u8,
+) -> Result<Outcome<GeneratedRecoveryPhrase>, String> {
+ if !VALID_MNEMONIC_WORD_COUNTS.contains(&word_count) {
+ return Err(format!("unsupported mnemonic word count {word_count}"));
+ }
+ let config = config_rpc::load_config_with_timeout().await?;
+ let generated = crate::modules::wallet::generate_mnemonic(&config, word_count)
+ .await
+ .map_err(|error| error.to_string())?;
+ Ok(Outcome::new(
+ GeneratedRecoveryPhrase {
+ phrase: generated.phrase,
+ word_count: generated.word_count,
+ },
+ vec!["recovery phrase generated by wallet module".to_string()],
+ ))
+}
+
+/// Validate a phrase and derive the public setup facts inside TinyWallet.
+///
+/// The returned BIP-39 seed is used only for OpenHuman's existing generic
+/// storage-key KDF; mnemonic parsing and all chain derivation remain in the
+/// confidential module operation.
+pub async fn derive_recovery_material(
+ mnemonic: String,
+) -> Result<Outcome<WalletRecoveryMaterial>, String> {
+ let word_count = mnemonic.split_whitespace().count();
+ if !is_valid_mnemonic_word_count(word_count) {
+ return Err(format!(
+ "recovery phrase must contain one of {} words",
+ VALID_MNEMONIC_WORD_COUNTS
+ .iter()
+ .map(u8::to_string)
+ .collect::<Vec<_>>()
+ .join(", ")
+ ));
+ }
+
+ let config = config_rpc::load_config_with_timeout().await?;
+ let mnemonic = Zeroizing::new(mnemonic);
+ let mnemonic = Zeroizing::new(mnemonic.split_whitespace().collect::<Vec<_>>().join(" "));
+ let seed = crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic.to_string())
+ .await
+ .map_err(|error| error.to_string())?;
+ let seed = Zeroizing::new(seed.seed);
+ if seed.len() != 64 {
+ return Err("wallet module returned an invalid BIP-39 seed length".to_string());
+ }
+
+ let accounts = [
+ (WalletChain::Evm, ModuleChain::Evm, "m/44'/60'/0'/0/0"),
+ (WalletChain::Btc, ModuleChain::Btc, "m/44'/0'/0'/0/0"),
+ (WalletChain::Solana, ModuleChain::Solana, "m/44'/501'/0'/0'"),
+ (WalletChain::Tron, ModuleChain::Tron, "m/44'/195'/0'/0/0"),
+ ];
+ let mut derived_accounts = Vec::with_capacity(accounts.len());
+ for (chain, module_chain, derivation_path) in accounts {
+ let mut secret = SecretMaterial {
+ mnemonic: mnemonic.to_string(),
+ derivation_path: derivation_path.to_string(),
+ chain: module_chain,
+ };
+ let derived = crate::modules::wallet::derive_account(&config, &secret).await;
+ secret.mnemonic.zeroize();
+ let derived = derived.map_err(|error| error.to_string())?;
+ derived_accounts.push(WalletAccount {
+ chain,
+ address: derived.address,
+ derivation_path: derivation_path.to_string(),
+ });
+ }
+
+ Ok(Outcome::new(
+ WalletRecoveryMaterial {
+ seed: seed.to_vec(),
+ accounts: derived_accounts,
+ },
+ vec!["recovery phrase validated and wallet accounts derived".to_string()],
+ ))
+}
+
+/// Check whether a phrase is valid BIP-39 input without deriving account data.
+pub async fn validate_recovery_phrase(
+ mnemonic: String,
+) -> Result<Outcome<RecoveryPhraseValidation>, String> {
+ use crate::modules::wallet::WalletCallError;
+
+ let config = config_rpc::load_config_with_timeout().await?;
+ let valid = match crate::modules::wallet::derive_mnemonic_seed(&config, mnemonic).await {
+ Ok(mut response) => {
+ if response.seed.len() != 64 {
+ response.seed.zeroize();
+ return Err("wallet module returned an invalid BIP-39 seed length".to_string());
+ }
+ response.seed.zeroize();
+ true
+ }
+ Err(WalletCallError::InvalidInput(_)) => false,
+ Err(error) => return Err(error.to_string()),
+ };
+ Ok(Outcome::new(
+ RecoveryPhraseValidation { valid },
+ vec!["recovery phrase checked by wallet module".to_string()],
+ ))
+}
+
fn validate_setup(params: &WalletSetupParams) -> Result<Vec<WalletAccount>, String> {
if !params.consent_granted {
return Err("wallet setup requires explicit consent".to_string());
diff --git a/crates/openhuman-core/src/web3/wallet/ops/state.rs b/crates/openhuman-core/src/web3/wallet/ops/state.rs
index 0c17e472a4..aa402e7e20 100644
--- a/crates/openhuman-core/src/web3/wallet/ops/state.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops/state.rs
@@ -385,10 +385,7 @@ pub(super) fn current_time_ms() -> u64 {
.unwrap_or(0)
}
-pub(super) fn to_status(
- config: &Config,
- state: Option<StoredWalletState>,
-) -> tinywallet_web3::crypto::wallet::WalletStatus {
+pub(super) fn to_status(config: &Config, state: Option<StoredWalletState>) -> super::WalletStatus {
match state {
Some(state) => {
// A mnemonic is "stored" if it's either in the JSON field (headless path)
@@ -399,7 +396,7 @@ pub(super) fn to_status(
.map(|v| !v.trim().is_empty())
.unwrap_or(false);
let secret_stored = secret_in_json || keychain_has_mnemonic(config);
- tinywallet_web3::crypto::wallet::WalletStatus {
+ super::WalletStatus {
configured: true,
onboarding_completed: state.consent_granted && !state.accounts.is_empty(),
consent_granted: state.consent_granted,
@@ -410,7 +407,7 @@ pub(super) fn to_status(
updated_at_ms: Some(state.updated_at_ms),
}
}
- None => tinywallet_web3::crypto::wallet::WalletStatus {
+ None => super::WalletStatus {
configured: false,
onboarding_completed: false,
consent_granted: false,
diff --git a/crates/openhuman-core/src/web3/wallet/ops/types.rs b/crates/openhuman-core/src/web3/wallet/ops/types.rs
index cbea45353d..aeba7f7822 100644
--- a/crates/openhuman-core/src/web3/wallet/ops/types.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops/types.rs
@@ -2,10 +2,47 @@
use serde::{Deserialize, Serialize};
-// 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.
-use tinywallet_web3::crypto::wallet::{WalletAccount, WalletSetupSource};
-/// Input for creating or replacing the operator wallet.
+/// Wallet chain identifiers are shared contract vocabulary.
+pub use tinywallet_bus::wire::WalletChain;
+
+/// Error returned when no local wallet has been configured.
+pub const WALLET_NOT_CONFIGURED_MESSAGE: &str = "wallet is not configured; run wallet setup first";
+
+/// How the host's local wallet state was created.
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum WalletSetupSource {
+ Generated,
+ Imported,
+}
+
+/// A public account retained in OpenHuman's wallet setup state.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct WalletAccount {
+ pub chain: WalletChain,
+ pub address: String,
+ pub derivation_path: String,
+}
+
+/// Host-owned wallet setup status exposed by the existing RPC surface.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+#[allow(clippy::struct_excessive_bools)]
+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>,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct WalletSetupParams {
@@ -22,6 +59,50 @@ pub struct WalletSetupParams {
pub force: bool,
}
+/// Phrase generated or validated by TinyWallet and the derived accounts used
+/// by the local wallet setup flow.
+#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct WalletRecoveryMaterial {
+ /// Standard BIP-39 seed bytes. The frontend uses these only for the
+ /// existing OpenHuman storage-key KDF and clears its temporary buffer.
+ pub seed: Vec<u8>,
+ /// Public addresses and derivation paths for the four supported chains.
+ pub accounts: Vec<WalletAccount>,
+}
+
+impl std::fmt::Debug for WalletRecoveryMaterial {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("WalletRecoveryMaterial")
+ .field("seed", &"<redacted>")
+ .field("accounts", &self.accounts)
+ .finish()
+ }
+}
+
+/// Generated recovery phrase returned for encryption and user confirmation.
+#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct GeneratedRecoveryPhrase {
+ pub phrase: String,
+ pub word_count: u8,
+}
+
+impl std::fmt::Debug for GeneratedRecoveryPhrase {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("GeneratedRecoveryPhrase")
+ .field("phrase", &"<redacted>")
+ .field("word_count", &self.word_count)
+ .finish()
+ }
+}
+
+/// Result of checking a recovery phrase with TinyWallet.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct RecoveryPhraseValidation {
+ pub valid: bool,
+}
+
/// Persisted on-disk (and/or keychain-backed) representation of wallet state.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
diff --git a/crates/openhuman-core/src/web3/wallet/ops_tests.rs b/crates/openhuman-core/src/web3/wallet/ops_tests.rs
index 4064931b3f..920c11bcf4 100644
--- a/crates/openhuman-core/src/web3/wallet/ops_tests.rs
+++ b/crates/openhuman-core/src/web3/wallet/ops_tests.rs
@@ -1,6 +1,5 @@
use super::*;
use crate::config::Config;
-use tinywallet_web3::crypto::wallet::WalletSetupSource;
fn sample_account(chain: WalletChain) -> WalletAccount {
WalletAccount {
diff --git a/crates/openhuman-core/src/web3/wallet/registration.rs b/crates/openhuman-core/src/web3/wallet/registration.rs
deleted file mode 100644
index 200e3cd0f7..0000000000
--- a/crates/openhuman-core/src/web3/wallet/registration.rs
+++ /dev/null
@@ -1,19 +0,0 @@
-//! Host registration of wallet tools over the configured wallet engine.
-
-use tinytools::Tool;
-use tinywallet_web3::tools::wallet::{
- WalletChainStatusTool, WalletLookupTxTool, WalletPrepareTransferTool, WalletStatusTool,
- WalletTxReceiptTool, WalletTxStatusTool,
-};
-
-/// Build the wallet tool family in its persisted catalogue order.
-pub(crate) fn tools() -> Vec<Box<dyn Tool>> {
- vec![
- Box::new(WalletStatusTool::new(crate::web3::seams::engine())),
- Box::new(WalletChainStatusTool::new(crate::web3::seams::engine())),
- Box::new(WalletPrepareTransferTool::new(crate::web3::seams::engine())),
- Box::new(WalletTxStatusTool::new(crate::web3::seams::engine())),
- Box::new(WalletTxReceiptTool::new(crate::web3::seams::engine())),
- Box::new(WalletLookupTxTool::new(crate::web3::seams::engine())),
- ]
-}
diff --git a/crates/openhuman-core/src/web3/wallet/schemas.rs b/crates/openhuman-core/src/web3/wallet/schemas.rs
index 7beced8948..54df8c6ddb 100644
--- a/crates/openhuman-core/src/web3/wallet/schemas.rs
+++ b/crates/openhuman-core/src/web3/wallet/schemas.rs
@@ -5,17 +5,12 @@ use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use super::execution::{
- balances, chain_status, execute_prepared, lookup_tx, network_defaults, prepare_transfer,
- supported_assets, tx_receipt, tx_status, ExecutePreparedParams, PrepareTransferParams,
-};
-use {
- super::ops::WalletSetupParams, tinywallet_web3::crypto::wallet::WalletAccount,
- tinywallet_web3::crypto::wallet::WalletSetupSource,
-};
-use {
- tinywallet_web3::crypto::abi::encode_erc20_transfer,
- tinywallet_web3::crypto::defaults::EvmNetwork, tinywallet_web3::crypto::wallet::WalletChain,
+ balances, chain_status, encode_erc20_transfer, execute_prepared, lookup_tx, network_defaults,
+ prepare_transfer, supported_assets, tx_receipt, tx_status, ExecutePreparedParams,
+ PrepareTransferParams,
};
+use super::ops::{WalletAccount, WalletSetupParams, WalletSetupSource};
+use super::{EvmNetwork, WalletChain};
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -48,6 +43,17 @@ struct EncodeErc20TransferParams {
amount_raw: String,
}
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct GenerateMnemonicParams {
+ word_count: u8,
+}
+
+#[derive(Debug, Deserialize)]
+struct RecoveryPhraseParams {
+ phrase: String,
+}
+
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
all_wallet_controller_schemas()
}
@@ -75,6 +81,9 @@ pub fn all_wallet_controller_schemas() -> Vec<ControllerSchema> {
wallet_schemas("tx_receipt"),
wallet_schemas("lookup_tx"),
wallet_schemas("reveal_recovery_phrase"),
+ wallet_schemas("generate_mnemonic"),
+ wallet_schemas("validate_mnemonic"),
+ wallet_schemas("derive_recovery_material"),
]
}
@@ -132,6 +141,18 @@ pub fn all_wallet_registered_controllers() -> Vec<RegisteredController> {
schema: wallet_schemas("reveal_recovery_phrase"),
handler: handle_reveal_recovery_phrase,
},
+ RegisteredController {
+ schema: wallet_schemas("generate_mnemonic"),
+ handler: handle_generate_mnemonic,
+ },
+ RegisteredController {
+ schema: wallet_schemas("validate_mnemonic"),
+ handler: handle_validate_mnemonic,
+ },
+ RegisteredController {
+ schema: wallet_schemas("derive_recovery_material"),
+ handler: handle_derive_recovery_material,
+ },
]
}
@@ -355,6 +376,42 @@ pub fn wallet_schemas(function: &str) -> ControllerSchema {
required: true,
}],
},
+ "generate_mnemonic" => ControllerSchema {
+ namespace: "wallet",
+ function: "generate_mnemonic",
+ description: "Generate a recovery phrase inside the TinyWallet module.",
+ inputs: vec![required_json("wordCount", "BIP-39 word count: 12, 15, 18, 21, or 24.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Generated recovery phrase and word count.",
+ required: true,
+ }],
+ },
+ "validate_mnemonic" => ControllerSchema {
+ namespace: "wallet",
+ function: "validate_mnemonic",
+ description: "Validate a recovery phrase in the TinyWallet module.",
+ inputs: vec![required_string("phrase", "Recovery phrase to validate.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Whether the phrase is valid BIP-39 input.",
+ required: true,
+ }],
+ },
+ "derive_recovery_material" => ControllerSchema {
+ namespace: "wallet",
+ function: "derive_recovery_material",
+ description: "Derive the host storage-key seed and public wallet accounts through TinyWallet.",
+ inputs: vec![required_string("phrase", "Recovery phrase to derive wallet setup material from.")],
+ outputs: vec![FieldSchema {
+ name: "result",
+ ty: TypeSchema::Json,
+ comment: "Seed bytes for the OpenHuman storage-key KDF and derived public chain accounts.",
+ required: true,
+ }],
+ },
_ => ControllerSchema {
namespace: "wallet",
function: "unknown",
@@ -414,11 +471,8 @@ fn handle_encode_erc20_transfer(params: Map<String, Value>) -> ControllerFuture
if parsed.chain != WalletChain::Evm {
return Err("encode_erc20_transfer only supports the evm chain".to_string());
}
- serde_json::to_value(encode_erc20_transfer(
- &parsed.to_address,
- &parsed.amount_raw,
- )?)
- .map_err(|e| format!("failed to encode ERC20 transfer output: {e}"))
+ serde_json::to_value(encode_erc20_transfer(&parsed.to_address, &parsed.amount_raw).await?)
+ .map_err(|e| format!("failed to encode ERC20 transfer output: {e}"))
})
}
@@ -480,6 +534,36 @@ fn handle_reveal_recovery_phrase(_params: Map<String, Value>) -> ControllerFutur
})
}
+fn handle_generate_mnemonic(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: GenerateMnemonicParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::generate_recovery_phrase(parsed.word_count)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
+fn handle_validate_mnemonic(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::validate_recovery_phrase(parsed.phrase)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
+fn handle_derive_recovery_material(params: Map<String, Value>) -> ControllerFuture {
+ Box::pin(async move {
+ let parsed: RecoveryPhraseParams = serde_json::from_value(Value::Object(params))
+ .map_err(|e| format!("invalid params: {e}"))?;
+ crate::web3::wallet::derive_recovery_material(parsed.phrase)
+ .await?
+ .into_cli_compatible_json()
+ })
+}
+
/// Shared input schema for the tx_status / tx_receipt / lookup_tx readers.
fn tx_query_inputs() -> Vec<FieldSchema> {
vec![
@@ -504,6 +588,15 @@ fn required_json(name: &'static str, comment: &'static str) -> FieldSchema {
}
}
+fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
+ FieldSchema {
+ name,
+ ty: TypeSchema::String,
+ comment,
+ required: true,
+ }
+}
+
#[cfg(test)]
#[path = "schemas_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
index fa29dd5117..bbbcbae94d 100644
--- a/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
+++ b/crates/openhuman-core/src/web3/wallet/schemas_tests.rs
@@ -2,12 +2,48 @@ use super::*;
#[test]
fn all_schemas_lists_every_controller() {
- assert_eq!(all_wallet_controller_schemas().len(), 13);
+ assert_eq!(all_wallet_controller_schemas().len(), 16);
}
#[test]
fn all_controllers_lists_every_handler() {
- assert_eq!(all_wallet_registered_controllers().len(), 13);
+ assert_eq!(all_wallet_registered_controllers().len(), 16);
+}
+
+#[test]
+fn recovery_phrase_controllers_are_registered_with_the_expected_inputs() {
+ let generate = wallet_schemas("generate_mnemonic");
+ assert_eq!(generate.namespace, "wallet");
+ assert_eq!(
+ generate
+ .inputs
+ .iter()
+ .map(|field| field.name)
+ .collect::<Vec<_>>(),
+ vec!["wordCount"]
+ );
+
+ let validate = wallet_schemas("validate_mnemonic");
+ assert_eq!(validate.namespace, "wallet");
+ assert_eq!(
+ validate
+ .inputs
+ .iter()
+ .map(|field| field.name)
+ .collect::<Vec<_>>(),
+ vec!["phrase"]
+ );
+ assert!(validate.inputs[0].required);
+
+ let derive = wallet_schemas("derive_recovery_material");
+ assert_eq!(
+ derive
+ .inputs
+ .iter()
+ .map(|field| field.name)
+ .collect::<Vec<_>>(),
+ vec!["phrase"]
+ );
}
#[test]
diff --git a/crates/openhuman-core/src/web3/wallet/test_support.rs b/crates/openhuman-core/src/web3/wallet/test_support.rs
index 8c5ab9d5f7..e1411665a1 100644
--- a/crates/openhuman-core/src/web3/wallet/test_support.rs
+++ b/crates/openhuman-core/src/web3/wallet/test_support.rs
@@ -11,13 +11,9 @@
use tempfile::TempDir;
+use super::ops::{setup, WalletAccount, WalletChain, WalletSetupParams, WalletSetupSource};
use crate::config::rpc as config_rpc;
use crate::config::test_env::EnvVarGuard;
-use {
- super::ops::setup, super::ops::WalletSetupParams,
- tinywallet_web3::crypto::wallet::WalletAccount, tinywallet_web3::crypto::wallet::WalletChain,
- tinywallet_web3::crypto::wallet::WalletSetupSource,
-};
pub(crate) static TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
diff --git a/crates/openhuman-core/src/web3/wallet/tools.rs b/crates/openhuman-core/src/web3/wallet/tools.rs
new file mode 100644
index 0000000000..4f8b4b5d26
--- /dev/null
+++ b/crates/openhuman-core/src/web3/wallet/tools.rs
@@ -0,0 +1,119 @@
+//! Agent tool adapters that send wallet operations through TinyWallet's bus.
+
+use async_trait::async_trait;
+use serde::Deserialize;
+use serde::Serialize;
+use serde_json::Value;
+use tinytools::{Tool, ToolExposure, ToolResult};
+use tinywallet_bus::tools::ToolDeclaration;
+use tinywallet_bus::wire::{EvmNetwork, WalletChain};
+
+#[derive(Debug)]
+struct WalletModuleTool {
+ declaration: &'static ToolDeclaration,
+}
+
+impl WalletModuleTool {
+ const fn new(declaration: &'static ToolDeclaration) -> Self {
+ Self { declaration }
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct TxQuery {
+ chain: WalletChain,
+ #[serde(default)]
+ evm_network: Option<EvmNetwork>,
+ hash: String,
+}
+
+fn outcome_value<T: Serialize>(
+ outcome: Result<crate::core::Outcome<T>, String>,
+) -> Result<Value, String> {
+ outcome.and_then(|outcome| {
+ serde_json::to_value(outcome.value)
+ .map_err(|error| format!("failed to serialize wallet result: {error}"))
+ })
+}
+
+#[async_trait]
+impl Tool for WalletModuleTool {
+ fn exposure(&self) -> ToolExposure {
+ ToolExposure::Deferred
+ }
+
+ fn name(&self) -> &'static str {
+ self.declaration.name
+ }
+
+ fn description(&self) -> &'static str {
+ self.declaration.description
+ }
+
+ fn parameters_schema(&self) -> Value {
+ self.declaration.parameters.clone()
+ }
+
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ let result = match self.name() {
+ "wallet_status" => outcome_value(crate::web3::wallet::status().await),
+ "wallet_chain_status" => outcome_value(crate::web3::wallet::chain_status().await),
+ "wallet_prepare_transfer" => {
+ let params = match serde_json::from_value(args) {
+ Ok(params) => params,
+ Err(error) => {
+ return Ok(ToolResult::error(format!("invalid arguments: {error}")))
+ }
+ };
+ outcome_value(crate::web3::wallet::prepare_transfer(params).await)
+ }
+ "wallet_tx_status" | "wallet_tx_receipt" | "wallet_lookup_tx" => {
+ let query: TxQuery = match serde_json::from_value(args) {
+ Ok(query) => query,
+ Err(error) => {
+ return Ok(ToolResult::error(format!("invalid arguments: {error}")))
+ }
+ };
+ let result = match self.name() {
+ "wallet_tx_status" => outcome_value(
+ crate::web3::wallet::tx_status(query.chain, query.evm_network, &query.hash)
+ .await,
+ ),
+ "wallet_tx_receipt" => outcome_value(
+ crate::web3::wallet::tx_receipt(
+ query.chain,
+ query.evm_network,
+ &query.hash,
+ )
+ .await,
+ ),
+ _ => outcome_value(
+ crate::web3::wallet::lookup_tx(query.chain, query.evm_network, &query.hash)
+ .await,
+ ),
+ };
+ result
+ }
+ _ => return Ok(ToolResult::error("unknown wallet tool")),
+ };
+
+ match result {
+ Ok(value) => Ok(ToolResult::success(serde_json::to_string_pretty(&value)?)),
+ Err(error) => Ok(ToolResult::error(error)),
+ }
+ }
+}
+
+/// The six established wallet tools, backed by OpenHuman's module adapters.
+pub fn all_agent_tools() -> Vec<Box<dyn Tool>> {
+ tinywallet_bus::tools::wallet_tool_declarations()
+ .iter()
+ .map(|declaration| {
+ Box::new(WalletModuleTool::new(
+ tinywallet_bus::tools::find_wallet_tool_declaration(declaration.name)
+ .expect("the declaration came from the shipped Wallet list"),
+ )) as Box<dyn Tool>
+ })
+ .collect()
+}
diff --git a/crates/openhuman-core/src/web3/wallet/transport.rs b/crates/openhuman-core/src/web3/wallet/transport.rs
deleted file mode 100644
index c5043de885..0000000000
--- a/crates/openhuman-core/src/web3/wallet/transport.rs
+++ /dev/null
@@ -1,224 +0,0 @@
-//! OpenHuman's implementation of the [`tinywallet_bus::rpc::Transport`] seam.
-//!
-//! `tinywallet-bus` performs no I/O and takes no URLs: it names a
-//! [`NetworkId`](tinywallet_bus::rpc::NetworkId) and asks a host to reach it. This
-//! module is that host side — the adapter that lets `tinywallet_bus::rpc` and
-//! the chain modules run against OpenHuman's existing RPC layer.
-//!
-//! Everything the crate deliberately refused to own lives on this side of the
-//! seam and is reused from [`super::rpc`] unchanged:
-//!
-//! - **endpoint resolution**, including the `OPENHUMAN_WALLET_RPC_<CHAIN>`
-//! overrides the e2e tests point at a mock;
-//! - **URL redaction**, so an endpoint carrying an API key never reaches a log;
-//! - the shared `reqwest` client and its connection pool.
-//!
-//! ## Error mapping is the part worth reviewing
-//!
-//! `tinywallet-bus` splits transport failures into retryable
-//! ([`TransportError::Unreachable`]) and authoritative
-//! ([`TransportError::Rpc`]), and a host's failover depends on that
-//! distinction: retrying an authoritative "insufficient funds" gets the same
-//! answer, while retrying an ambiguous failure risks a double broadcast.
-//!
-//! OpenHuman's RPC helpers flatten both into `String`, so this adapter cannot
-//! recover the distinction perfectly. It classifies conservatively — **anything
-//! it cannot prove is a transport failure is reported as authoritative** — so
-//! an unclassifiable error stops a failover loop rather than driving it. That
-//! is the safe direction: a missed retry costs a request, a wrong retry can
-//! cost a duplicate transaction.
-
-use async_trait::async_trait;
-use log::debug;
-use serde_json::Value;
-use tinywallet_crypto::rpc::{NetworkId, Transport, TransportError, TransportResult};
-
-use tinywallet_web3::crypto::defaults::EvmNetwork;
-
-use super::endpoints::{rpc_url_for_chain, rpc_url_for_evm_network};
-use super::rpc::{redact_rpc_url, rest_get_text, rest_post_text, rpc_call_to};
-use tinywallet_web3::crypto::wallet::WalletChain;
-
-/// Adapter over OpenHuman's wallet RPC layer.
-///
-/// Stateless — endpoint resolution happens per call so an env override applied
-/// mid-process (as the e2e harness does) is picked up without rebuilding it.
-#[derive(Debug, Clone, Copy, Default)]
-pub struct OpenHumanTransport;
-
-impl OpenHumanTransport {
- /// Build the adapter.
- #[must_use]
- pub const fn new() -> Self {
- Self
- }
-}
-
-/// Map a `tinywallet-bus` network onto OpenHuman's chain enum plus a base URL.
-#[allow(unreachable_patterns)]
-fn resolve(network: NetworkId) -> Result<String, TransportError> {
- match network.chain {
- tinywallet_bus::Chain::Evm => {
- // An EVM request names its EIP-155 chain id; resolving it here is
- // what keeps `tinywallet-bus` free of OpenHuman's network enum.
- let chain_id = network.evm_chain_id.ok_or_else(|| TransportError::Rpc {
- network,
- message: "EVM requests require an EIP-155 chain id".to_string(),
- })?;
- let evm = EvmNetwork::ALL
- .iter()
- .copied()
- .find(|n| n.chain_id() == chain_id)
- .ok_or_else(|| TransportError::Rpc {
- network,
- message: format!("no configured EVM endpoint for chain id {chain_id}"),
- })?;
- Ok(rpc_url_for_evm_network(evm))
- }
- tinywallet_bus::Chain::Btc => Ok(rpc_url_for_chain(WalletChain::Btc)),
- tinywallet_bus::Chain::Solana => Ok(rpc_url_for_chain(WalletChain::Solana)),
- tinywallet_bus::Chain::Tron => Ok(rpc_url_for_chain(WalletChain::Tron)),
- // `tinywallet_bus::Chain` is `#[non_exhaustive]`, so a future variant must
- // be handled. Reporting it as authoritative is correct: no endpoint is
- // configured for it, and retrying elsewhere cannot change that.
- other => Err(TransportError::Rpc {
- network,
- message: format!("no endpoint configured for chain {other}"),
- }),
- }
-}
-
-/// Join a base URL and a relative path without doubling the separator.
-fn join(base: &str, path: &str) -> String {
- format!(
- "{}/{}",
- base.trim_end_matches('/'),
- path.trim_start_matches('/')
- )
-}
-
-/// Classify a flattened error string.
-///
-/// See the module docs: only messages this layer itself produced for a
-/// transport failure are treated as retryable. Everything else is
-/// authoritative, so an unclassifiable error stops a failover rather than
-/// driving one.
-pub(crate) fn classify(network: NetworkId, message: String) -> TransportError {
- const TRANSPORT_MARKERS: [&str; 2] = ["transport failed", "read body failed"];
- if TRANSPORT_MARKERS.iter().any(|m| message.contains(m)) {
- TransportError::Unreachable { network, message }
- } else {
- TransportError::Rpc { network, message }
- }
-}
-
-#[async_trait]
-impl Transport for OpenHumanTransport {
- async fn json_rpc(
- &self,
- network: NetworkId,
- method: &str,
- params: Value,
- ) -> TransportResult<Value> {
- let url = resolve(network)?;
- debug!(
- "[wallet:transport] json_rpc chain={} method={method} endpoint={}",
- network.chain,
- redact_rpc_url(&url)
- );
- match rpc_call_to::<Value>(&url, method, params).await {
- Ok(value) => {
- debug!(
- "[wallet:transport] json_rpc chain={} method={method} outcome=success",
- network.chain
- );
- Ok(value)
- }
- Err(message) => {
- let error = classify(network, message);
- debug!(
- "[wallet:transport] json_rpc chain={} method={method} outcome={}",
- network.chain,
- if error.is_retryable() {
- "unreachable"
- } else {
- "rpc"
- }
- );
- Err(error)
- }
- }
- }
-
- async fn rest_get(&self, network: NetworkId, path: &str) -> TransportResult<String> {
- let url = join(&resolve(network)?, path);
- debug!(
- "[wallet:transport] rest_get chain={} path={path} endpoint={}",
- network.chain,
- redact_rpc_url(&url)
- );
- match rest_get_text(&url).await {
- Ok(value) => {
- debug!(
- "[wallet:transport] rest_get chain={} path={path} outcome=success",
- network.chain
- );
- Ok(value)
- }
- Err(message) => {
- let error = classify(network, message);
- debug!(
- "[wallet:transport] rest_get chain={} path={path} outcome={}",
- network.chain,
- if error.is_retryable() {
- "unreachable"
- } else {
- "rpc"
- }
- );
- Err(error)
- }
- }
- }
-
- async fn rest_post(
- &self,
- network: NetworkId,
- path: &str,
- body: String,
- content_type: &str,
- ) -> TransportResult<String> {
- let url = join(&resolve(network)?, path);
- debug!(
- "[wallet:transport] rest_post chain={} path={path} endpoint={}",
- network.chain,
- redact_rpc_url(&url)
- );
- match rest_post_text(&url, &body, content_type).await {
- Ok(value) => {
- debug!(
- "[wallet:transport] rest_post chain={} path={path} outcome=success",
- network.chain
- );
- Ok(value)
- }
- Err(message) => {
- let error = classify(network, message);
- debug!(
- "[wallet:transport] rest_post chain={} path={path} outcome={}",
- network.chain,
- if error.is_retryable() {
- "unreachable"
- } else {
- "rpc"
- }
- );
- Err(error)
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "transport_tests.rs"]
-mod tests;
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)
diff --git a/crates/openhuman-core/src/web3/x402/budget.rs b/crates/openhuman-core/src/web3/x402/budget.rs
deleted file mode 100644
index a7555c38a3..0000000000
--- a/crates/openhuman-core/src/web3/x402/budget.rs
+++ /dev/null
@@ -1,52 +0,0 @@
-//! 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/mod.rs b/crates/openhuman-core/src/web3/x402/mod.rs
index 457bcc45d8..6de8be2b52 100644
--- a/crates/openhuman-core/src/web3/x402/mod.rs
+++ b/crates/openhuman-core/src/web3/x402/mod.rs
@@ -1,102 +1,25 @@
-//! x402 — HTTP 402 payment protocol for machine-payable APIs.
+//! Host RPC facade for module-owned x402 payments.
//!
-//! 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
-//! machinery is gated behind the optional `web3` Cargo feature (shared with
-//! `openhuman::web3::wallet` + `openhuman::web3` and enabled in the desktop product). When the feature is off, [`stub`]
-//! takes its place and exposes the always-on entry points (`init_ledger`,
-//! `all_x402_registered_controllers`, `all_x402_controller_schemas`) with
-//! no-op / empty bodies. The `X402RequestTool` and the http_request 402-retry
-//! path are `#[cfg(feature = "web3")]` at their call sites, so the rest of the
-//! payment surface (`PaymentRecord`, `store`, `SettlementResponse`, …) is not
-//! referenced when off and need not be stubbed.
+//! TinyWallet owns challenge parsing, chain selection, payment construction,
+//! signing, budget reservation, ledger records, and settlement parsing. The
+//! host retains generic HTTP execution, explicit user approval, and secret
+//! custody; payment material crosses only the confidential module call.
-#[cfg(feature = "web3")]
-pub(crate) mod budget;
-#[cfg(feature = "web3")]
-mod proxy_compat;
-#[cfg(feature = "web3")]
-mod records;
#[cfg(feature = "web3")]
mod schemas;
-#[cfg(feature = "web3")]
-pub(crate) mod seams;
-#[cfg(feature = "web3")]
-pub use records::pending_record;
#[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 tinywallet_x402::ledger::{PaymentRecord, PaymentStatus, SpendingBudget};
-#[cfg(feature = "web3")]
-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,
+pub use tinywallet_bus::wire::{
+ X402PaymentRecord as PaymentRecord, X402PaymentStatus as PaymentStatus,
};
-/// 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
-}
-
-/// The `x402_request` agent tool, wired to OpenHuman's wallet, chain
-/// transport, proxy and network policy. `allowed_domains` is the same list
-/// passed to the other agent network tools.
-#[cfg(feature = "web3")]
-pub fn request_tool(
- security: std::sync::Arc<crate::security::SecurityPolicy>,
- allowed_domains: Vec<String>,
-) -> tinywallet_x402::tools::X402RequestTool {
- seams::request_tool(security, allowed_domains)
-}
-
-// ---------------------------------------------------------------------------
-// Disabled facade — compiled only when the `web3` feature is OFF.
-// ---------------------------------------------------------------------------
+/// Kept as a compatibility no-op. The module-owned ledger opens lazily when
+/// the first x402 service operation is requested, scoped to the active workspace.
+pub fn init_ledger(_workspace_dir: &std::path::Path, _session_id: &str) {}
#[cfg(not(feature = "web3"))]
mod stub;
diff --git a/crates/openhuman-core/src/web3/x402/records.rs b/crates/openhuman-core/src/web3/x402/records.rs
deleted file mode 100644
index e7fdca4cb7..0000000000
--- a/crates/openhuman-core/src/web3/x402/records.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-//! The ledger record a payment starts with, for callers outside the
-//! `x402_request` tool (the `http_request` 402 fallback).
-//!
-//! The tool builds its own records inside the crate; this is the same rule for
-//! the host's other writer, so both attribute a payment identically:
-//! `session_id` is always the ledger's own session (so the session total counts
-//! the payment) and `thread_id` is the chat thread from `APPROVAL_CHAT_CONTEXT`.
-
-use tinywallet_x402::ledger::{self, PaymentRecord, PaymentStatus};
-use tinywallet_x402::protocol::X402PaymentResult;
-use tinywallet_x402::thread::ThreadScope;
-
-use super::seams::TaskLocalThread;
-
-/// A `Pending` record for `payment`, stamped with the ledger's session and the
-/// active chat thread (if any). Later states are written as new lines with the
-/// same `id`.
-#[allow(clippy::cast_precision_loss)] // atomic USDC amounts stay far below 2^53
-pub fn pending_record(payment: &X402PaymentResult) -> PaymentRecord {
- // A ledger that is not initialised has no session to name; the payment
- // would have failed at the budget check before reaching here.
- let session_id = ledger::with_ledger(|l| l.session_id().to_string()).unwrap_or_default();
- PaymentRecord {
- id: uuid::Uuid::new_v4().to_string(),
- url: payment.url.clone(),
- asset: payment.asset.clone(),
- amount_atomic: payment.amount_atomic,
- amount_display: format!("{:.6} USDC", payment.amount_atomic as f64 / 1_000_000.0),
- recipient: payment.recipient.clone(),
- network: payment.network.clone(),
- tx_signature: None,
- status: PaymentStatus::Pending,
- timestamp: chrono::Utc::now(),
- authorization_valid_until: payment.authorization_valid_until,
- solana_last_valid_block_height: payment.solana_last_valid_block_height,
- authorization_expired_at: None,
- authorization_expiry_observed_height: None,
- session_id,
- thread_id: TaskLocalThread.current_thread(),
- }
-}
-
-#[cfg(test)]
-#[path = "records_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/records_tests.rs b/crates/openhuman-core/src/web3/x402/records_tests.rs
deleted file mode 100644
index 83cbdd4db1..0000000000
--- a/crates/openhuman-core/src/web3/x402/records_tests.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-use super::*;
-use crate::security::approval::{ApprovalChatContext, APPROVAL_CHAT_CONTEXT};
-use crate::web3::wallet::test_support::TEST_LOCK;
-use tinywallet_x402::ledger::{self, PaymentStatus};
-
-const SESSION: &str = "x402-boot-session";
-
-fn chat_ctx(thread: &str) -> ApprovalChatContext {
- ApprovalChatContext {
- thread_id: thread.to_string(),
- client_id: "client".to_string(),
- request_id: None,
- }
-}
-
-/// A payment as `handle_402_and_pay` hands it back: 2500 atomic USDC held on
-/// the process-wide ledger.
-fn payment() -> X402PaymentResult {
- X402PaymentResult {
- header_value: "header".into(),
- amount_atomic: 2_500,
- asset: "usdc-mint".into(),
- recipient: "recipient".into(),
- network: "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp".into(),
- url: "https://x402.example.test/thing".into(),
- authorization_valid_until: None,
- solana_last_valid_block_height: None,
- reservation: ledger::reserve(2_500).unwrap().unwrap(),
- }
-}
-
-fn init(temp: &tempfile::TempDir) {
- super::super::init_ledger(temp.path(), SESSION);
-}
-
-/// The fallback path's pending record carries the ledger's session, so the
-/// payment counts toward `session_total` once it settles, and the chat thread.
-#[tokio::test]
-async fn a_fallback_payment_counts_in_the_session_total_and_names_its_thread() {
- let _lock = TEST_LOCK.lock().await;
- let temp = tempfile::tempdir().unwrap();
- init(&temp);
- let payment = payment();
-
- let record = APPROVAL_CHAT_CONTEXT
- .scope(chat_ctx("thread-a"), async { pending_record(&payment) })
- .await;
-
- assert_eq!(record.status, PaymentStatus::Pending);
- assert_eq!(record.session_id, SESSION);
- assert_eq!(record.thread_id.as_deref(), Some("thread-a"));
- assert_eq!(record.amount_atomic, 2_500);
- assert_eq!(record.amount_display, "0.002500 USDC");
- assert_eq!(record.url, payment.url);
-
- let mut settled = record.clone();
- settled.status = PaymentStatus::Settled;
- payment.reservation.commit(settled);
- let summary = ledger::with_ledger(|l| l.summary()).unwrap();
- assert_eq!(summary.session_total_atomic, 2_500);
- assert_eq!(summary.session_count, 1);
-}
-
-#[tokio::test]
-async fn a_payment_outside_a_chat_turn_has_no_thread_but_the_same_session() {
- let _lock = TEST_LOCK.lock().await;
- let temp = tempfile::tempdir().unwrap();
- init(&temp);
-
- let record = pending_record(&payment());
-
- assert_eq!(record.thread_id, None);
- assert_eq!(record.session_id, SESSION);
-}
-
-#[tokio::test]
-async fn every_payment_gets_its_own_record_id() {
- let _lock = TEST_LOCK.lock().await;
- let temp = tempfile::tempdir().unwrap();
- init(&temp);
-
- assert_ne!(pending_record(&payment()).id, pending_record(&payment()).id);
-}
diff --git a/crates/openhuman-core/src/web3/x402/schemas.rs b/crates/openhuman-core/src/web3/x402/schemas.rs
index b9cbaeb008..521daa9b27 100644
--- a/crates/openhuman-core/src/web3/x402/schemas.rs
+++ b/crates/openhuman-core/src/web3/x402/schemas.rs
@@ -9,8 +9,6 @@ use serde_json::{json, Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use super::store;
-
pub fn all_controller_schemas() -> Vec<ControllerSchema> {
vec![
schemas("get_summary"),
@@ -112,13 +110,13 @@ pub fn schemas(function: &str) -> ControllerSchema {
fn handle_get_summary(_params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
- let (summary, budget) = store::with_ledger(|l| (l.summary(), l.budget().clone()))
- .map_err(|e| format!("x402 get_summary: {e}"))?;
-
- Ok(json!({
- "summary": summary,
- "budget": budget,
- }))
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|error| format!("x402 get_summary: {error}"))?;
+ let summary = crate::modules::x402_service::summary(&config)
+ .await
+ .map_err(|error| format!("x402 get_summary: {error}"))?;
+ Ok(summary_value(summary))
})
}
@@ -134,14 +132,21 @@ fn handle_list_payments(params: Map<String, Value>) -> ControllerFuture {
let p: ListPaymentsParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("x402 list_payments params: {e}"))?;
- let limit = p.limit.unwrap_or(50).min(500) as usize;
- let payments = store::with_ledger(|l| l.recent_payments(limit))
- .map_err(|e| format!("x402 list_payments: {e}"))?;
-
- Ok(json!({ "payments": payments }))
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|error| format!("x402 list_payments: {error}"))?;
+ let limit = p.limit.unwrap_or(50).min(500);
+ let response = crate::modules::x402_service::list_payments(&config, limit)
+ .await
+ .map_err(|error| format!("x402 list_payments: {error}"))?;
+ Ok(payments_value(response.payments))
})
}
+fn payments_value(payments: Vec<tinywallet_bus::wire::X402PaymentRecord>) -> Value {
+ json!({ "payments": payments })
+}
+
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct UpdateBudgetParams {
@@ -158,22 +163,58 @@ fn handle_update_budget(params: Map<String, Value>) -> ControllerFuture {
let p: UpdateBudgetParams = serde_json::from_value(Value::Object(params))
.map_err(|e| format!("x402 update_budget params: {e}"))?;
- let budget = store::with_ledger_mut(|l| {
- let mut b = l.budget().clone();
- if let Some(v) = p.per_request_max {
- b.per_request_max_atomic = v;
- }
- if let Some(v) = p.daily_max {
- b.daily_max_atomic = v;
- }
- if let Some(v) = p.monthly_max {
- b.monthly_max_atomic = v;
- }
- l.update_budget(b.clone());
- b
- })
- .map_err(|e| format!("x402 update_budget: {e}"))?;
-
- Ok(json!({ "budget": budget }))
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|error| format!("x402 update_budget: {error}"))?;
+ let summary = crate::modules::x402_service::update_budget(
+ &config,
+ p.per_request_max,
+ p.daily_max,
+ p.monthly_max,
+ )
+ .await
+ .map_err(|error| format!("x402 update_budget: {error}"))?;
+
+ Ok(budget_value(
+ summary.per_request_max_atomic,
+ summary.daily_max_atomic,
+ summary.monthly_max_atomic,
+ ))
+ })
+}
+
+fn summary_value(summary: tinywallet_bus::wire::X402DetailedSpendingSummary) -> Value {
+ json!({
+ "summary": {
+ "sessionTotalAtomic": summary.session_total_atomic,
+ "dailyTotalAtomic": summary.daily_total_atomic,
+ "monthlyTotalAtomic": summary.monthly_total_atomic,
+ "sessionCount": summary.session_count,
+ "dailyCount": summary.daily_count,
+ "monthlyCount": summary.monthly_count,
+ },
+ "budget": {
+ "perRequestMaxAtomic": summary.per_request_max_atomic,
+ "dailyMaxAtomic": summary.daily_max_atomic,
+ "monthlyMaxAtomic": summary.monthly_max_atomic,
+ },
})
}
+
+fn budget_value(
+ per_request_max_atomic: u64,
+ daily_max_atomic: u64,
+ monthly_max_atomic: u64,
+) -> Value {
+ json!({
+ "budget": {
+ "perRequestMaxAtomic": per_request_max_atomic,
+ "dailyMaxAtomic": daily_max_atomic,
+ "monthlyMaxAtomic": monthly_max_atomic,
+ }
+ })
+}
+
+#[cfg(test)]
+#[path = "schemas_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/web3/x402/schemas_tests.rs b/crates/openhuman-core/src/web3/x402/schemas_tests.rs
new file mode 100644
index 0000000000..195eb83832
--- /dev/null
+++ b/crates/openhuman-core/src/web3/x402/schemas_tests.rs
@@ -0,0 +1,93 @@
+use super::*;
+
+#[test]
+fn summary_response_preserves_legacy_camel_case_rpc_shape() {
+ let value = summary_value(tinywallet_bus::wire::X402DetailedSpendingSummary {
+ session_total_atomic: 11,
+ daily_total_atomic: 12,
+ monthly_total_atomic: 13,
+ session_count: 2,
+ daily_count: 3,
+ monthly_count: 4,
+ reserved_atomic: 99,
+ per_request_max_atomic: 100,
+ daily_max_atomic: 200,
+ monthly_max_atomic: 300,
+ });
+
+ assert_eq!(
+ value,
+ json!({
+ "summary": {
+ "sessionTotalAtomic": 11,
+ "dailyTotalAtomic": 12,
+ "monthlyTotalAtomic": 13,
+ "sessionCount": 2,
+ "dailyCount": 3,
+ "monthlyCount": 4,
+ },
+ "budget": {
+ "perRequestMaxAtomic": 100,
+ "dailyMaxAtomic": 200,
+ "monthlyMaxAtomic": 300,
+ },
+ })
+ );
+}
+
+#[test]
+fn budget_response_preserves_legacy_camel_case_rpc_shape() {
+ assert_eq!(
+ budget_value(1, 20, 300),
+ json!({
+ "budget": {
+ "perRequestMaxAtomic": 1,
+ "dailyMaxAtomic": 20,
+ "monthlyMaxAtomic": 300,
+ }
+ })
+ );
+}
+
+#[test]
+fn payment_list_preserves_legacy_rpc_shape_and_rfc3339_values() {
+ let value = payments_value(vec![tinywallet_bus::wire::X402PaymentRecord {
+ id: "payment-1".into(),
+ url: "https://api.example.test/resource".into(),
+ asset: "USDC".into(),
+ amount_atomic: 2_500,
+ amount_display: "0.002500 USDC".into(),
+ recipient: "0x0000000000000000000000000000000000000001".into(),
+ network: "eip155:1".into(),
+ tx_signature: Some("0xabc".into()),
+ status: tinywallet_bus::wire::X402PaymentStatus::Settled,
+ timestamp: "2026-10-11T19:02:03Z".into(),
+ authorization_valid_until: Some("2026-10-11T19:03:03Z".into()),
+ solana_last_valid_block_height: None,
+ authorization_expired_at: None,
+ authorization_expiry_observed_height: None,
+ session_id: "session-1".into(),
+ thread_id: Some("thread-1".into()),
+ }]);
+
+ assert_eq!(
+ value,
+ json!({
+ "payments": [{
+ "id": "payment-1",
+ "url": "https://api.example.test/resource",
+ "asset": "USDC",
+ "amountAtomic": 2500,
+ "amountDisplay": "0.002500 USDC",
+ "recipient": "0x0000000000000000000000000000000000000001",
+ "network": "eip155:1",
+ "txSignature": "0xabc",
+ "status": "settled",
+ "timestamp": "2026-10-11T19:02:03Z",
+ "authorizationValidUntil": "2026-10-11T19:03:03Z",
+ "sessionId": "session-1",
+ "threadId": "thread-1"
+ }]
+ })
+ );
+}
diff --git a/crates/openhuman-core/src/web3/x402/seams.rs b/crates/openhuman-core/src/web3/x402/seams.rs
deleted file mode 100644
index e3677d8592..0000000000
--- a/crates/openhuman-core/src/web3/x402/seams.rs
+++ /dev/null
@@ -1,326 +0,0 @@
-//! 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`] refuses direct, address-pinned
-//! requests when runtime or environment proxy policy requires a proxy.
-//! - a [`ThreadScope`]: [`TaskLocalThread`] names the chat thread running the
-//! tool call, so the ledger can attribute the payment to it.
-//!
-//! 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 tinytools_std::network::NetGate;
-use tinytools_std::url_guard::{normalize_allowed_domains, validate_url_with_dns_check};
-use tinywallet_x402::crypto::{CryptoPayments, PaymentAccount, PaymentSigner, SignScheme};
-use tinywallet_x402::protocol::ProxyPolicy;
-use tinywallet_x402::thread::ThreadScope;
-use tinywallet_x402::tools::{
- AuthorizedRequest, ProposedRequest, RequestAuthorizationError, RequestGuard, X402RequestTool,
-};
-use tinywallet_x402::wire::PaymentChain;
-
-use crate::security::approval::APPROVAL_CHAT_CONTEXT;
-use crate::security::SecurityPolicy;
-use crate::web3::wallet::transport::OpenHumanTransport;
-use tinywallet_web3::crypto::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 and environment proxy configuration for x402 outbound HTTP.
-#[derive(Debug, Clone, Copy, Default)]
-pub(crate) struct RuntimeProxyPolicy;
-
-#[derive(Debug)]
-pub(crate) struct HostRequestGuard {
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
-}
-
-#[async_trait]
-impl RequestGuard for HostRequestGuard {
- fn needs_approval(&self) -> bool {
- self.security.network_needs_approval()
- }
-
- async fn authorize(
- &self,
- request: &ProposedRequest,
- ) -> Result<AuthorizedRequest, RequestAuthorizationError> {
- if !self.security.can_act() {
- return Err(RequestAuthorizationError::Denied(
- "Action blocked: autonomy is read-only".into(),
- ));
- }
- let parsed = reqwest::Url::parse(&request.url)
- .map_err(|error| RequestAuthorizationError::InvalidDestination(error.to_string()))?;
- if parsed.scheme() != "https" {
- return Err(RequestAuthorizationError::InvalidDestination(
- "x402 payment requests require HTTPS".into(),
- ));
- }
- let host = parsed
- .host_str()
- .map(str::to_string)
- .unwrap_or_else(|| "unknown".to_string());
- if let Some(reason) = self.security.local_only_block(&host) {
- return Err(RequestAuthorizationError::Denied(
- reason
- .strip_prefix("[policy-blocked] ")
- .unwrap_or(&reason)
- .to_string(),
- ));
- }
- if self.security.is_rate_limited() {
- return Err(RequestAuthorizationError::Denied(
- "Action blocked: rate limit exceeded".into(),
- ));
- }
- let target = validate_url_with_dns_check(&request.url, &self.allowed_domains)
- .await
- .map_err(|error| RequestAuthorizationError::InvalidDestination(error.to_string()))?;
- if !self.security.record_action() {
- return Err(RequestAuthorizationError::Denied(
- "Action blocked: rate limit exceeded".into(),
- ));
- }
- // A 402 retry adds PAYMENT-SIGNATURE even when the original request
- // has no headers. Disclose that potential metadata before either send.
- self.security
- .disclose(&target.host, request.body.is_some(), true);
- let mut approved_request = request.clone();
- approved_request.url = target.url;
- Ok(AuthorizedRequest {
- request: approved_request,
- host: target.host,
- addrs: target.addrs,
- })
- }
-}
-
-/// The chat thread running the current tool call, read from
-/// `APPROVAL_CHAT_CONTEXT`.
-///
-/// `Some(thread_id)` inside an interactive chat turn (the web channel installs the
-/// task-local around the run), `None` for CLI, direct JSON-RPC, cron and other
-/// non-chat callers, whose payments then carry no `thread_id`. The ledger's
-/// `session_id` never comes from here: it is always the ledger's own.
-///
-/// `tokio::task_local!` propagates across `.await` but **not** across
-/// `tokio::spawn`; 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(crate) struct TaskLocalThread;
-
-impl ThreadScope for TaskLocalThread {
- fn current_thread(&self) -> Option<String> {
- APPROVAL_CHAT_CONTEXT
- .try_with(|ctx| ctx.thread_id.clone())
- .ok()
- }
-}
-
-/// 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: reqwest13::ClientBuilder, service: &str) -> reqwest13::ClientBuilder {
- super::proxy_compat::apply(builder, service, &crate::config::runtime_proxy_config())
- }
-
- fn allows_direct_connection(&self, service: &str) -> bool {
- let config = crate::config::runtime_proxy_config();
- direct_connection_allowed(&config, service, |key| {
- std::env::var_os(key).is_some_and(|value| !value.is_empty())
- })
- }
-}
-
-/// A guarded request must connect to its vetted address directly. Treat any
-/// configured proxy for this service, including process proxy variables, as
-/// requiring the proxy until the host can pin an address through that proxy.
-fn direct_connection_allowed(
- config: &crate::config::ProxyConfig,
- service: &str,
- env_has_value: impl Fn(&str) -> bool,
-) -> bool {
- const PROXY_ENV_KEYS: &[&str] = &[
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "ALL_PROXY",
- "http_proxy",
- "https_proxy",
- "all_proxy",
- ];
- !((config.enabled && config.scope == crate::config::ProxyScope::Environment)
- || config.should_apply_to_service(service)
- || PROXY_ENV_KEYS.iter().any(|key| env_has_value(key)))
-}
-
-/// 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(
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
-) -> X402RequestTool {
- X402RequestTool::new(
- Arc::new(WalletPaymentSigner),
- Arc::new(OpenHumanTransport::new()),
- Arc::new(RuntimeProxyPolicy),
- )
- .with_thread_scope(Arc::new(TaskLocalThread))
- .with_request_guard(Arc::new(host_request_guard(security, allowed_domains)))
-}
-
-fn host_request_guard(
- security: Arc<SecurityPolicy>,
- allowed_domains: Vec<String>,
-) -> HostRequestGuard {
- HostRequestGuard {
- security,
- allowed_domains: normalize_allowed_domains(allowed_domains),
- }
-}
-
-#[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
deleted file mode 100644
index f6eeb96c32..0000000000
--- a/crates/openhuman-core/src/web3/x402/seams_tests.rs
+++ /dev/null
@@ -1,460 +0,0 @@
-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(reqwest13::Client::builder(), "tool.x402_request");
- assert!(builder.build().is_ok());
-}
-
-#[test]
-fn x402_direct_egress_requires_absent_runtime_and_environment_proxies() {
- let service = "tool.x402_request";
- let clear = |_: &str| false;
- let mut config = crate::config::ProxyConfig::default();
- assert!(direct_connection_allowed(&config, service, clear));
-
- config.enabled = true;
- config.http_proxy = Some("http://proxy.example:3128".into());
- assert!(!direct_connection_allowed(&config, service, clear));
-
- config.scope = crate::config::ProxyScope::Services;
- config.services = vec!["tool.http_request".into()];
- assert!(direct_connection_allowed(&config, service, clear));
- assert!(direct_connection_allowed(&config, service, |candidate| {
- candidate == "OPENHUMAN_HTTP_PROXY"
- }));
- config.services = vec!["tool.*".into()];
- assert!(!direct_connection_allowed(&config, service, clear));
-
- config.scope = crate::config::ProxyScope::Environment;
- assert!(!direct_connection_allowed(&config, service, clear));
-
- config.enabled = false;
- for key in [
- "HTTP_PROXY",
- "HTTPS_PROXY",
- "ALL_PROXY",
- "http_proxy",
- "https_proxy",
- "all_proxy",
- ] {
- assert!(
- !direct_connection_allowed(&config, service, |candidate| candidate == key),
- "{key} must refuse direct egress"
- );
- }
- for key in [
- "OPENHUMAN_HTTP_PROXY",
- "OPENHUMAN_HTTPS_PROXY",
- "OPENHUMAN_ALL_PROXY",
- ] {
- assert!(
- direct_connection_allowed(&config, service, |candidate| candidate == key),
- "{key} follows the disabled runtime proxy config"
- );
- }
-}
-
-fn proposed_request(url: &str) -> ProposedRequest {
- ProposedRequest {
- url: url.into(),
- method: reqwest::Method::POST,
- headers: vec![("x-custom".into(), "retained".into())],
- body: Some("private body".into()),
- }
-}
-
-#[tokio::test]
-async fn x402_guard_authorizes_the_complete_request_and_pins_destination() {
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- let guard = HostRequestGuard {
- security: Arc::new(SecurityPolicy::default()),
- allowed_domains: vec![],
- };
- let proposed = proposed_request("https://8.8.8.8/path");
- let authorized = guard.authorize(&proposed).await.unwrap();
- assert_eq!(authorized.request.url, proposed.url);
- assert_eq!(authorized.request.method, proposed.method);
- assert_eq!(authorized.request.headers, proposed.headers);
- assert_eq!(authorized.request.body, proposed.body);
- assert_eq!(authorized.host, "8.8.8.8");
- assert_eq!(authorized.addrs.len(), 1);
- assert_eq!(authorized.addrs[0].ip().to_string(), "8.8.8.8");
- assert_eq!(authorized.addrs[0].port(), 443);
-}
-
-#[tokio::test]
-async fn x402_guard_discloses_possible_payment_proof_metadata() {
- use crate::core::events::DomainEvent;
- use crate::security::egress::DataKind;
-
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- crate::core::bus::init().await.expect("bus init");
- let mut events = crate::core::bus::BUS.get().unwrap().receiver();
- let guard = HostRequestGuard {
- security: Arc::new(SecurityPolicy::default()),
- allowed_domains: vec![],
- };
-
- guard
- .authorize(&proposed_request("https://1.1.1.1/"))
- .await
- .expect("public destination should be authorized");
- loop {
- match events.recv().await {
- Some(DomainEvent::ExternalTransferPending { descriptor, .. })
- if descriptor.service == "1.1.1.1" =>
- {
- assert!(descriptor.data_kinds.contains(&DataKind::Metadata));
- break;
- }
- Some(_) => continue,
- None => panic!("bus closed before x402 disclosure"),
- }
- }
-}
-
-#[tokio::test]
-async fn x402_guard_rejects_readonly_and_private_destinations() {
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- let readonly = HostRequestGuard {
- security: Arc::new(SecurityPolicy {
- autonomy: crate::security::AutonomyLevel::ReadOnly,
- ..SecurityPolicy::default()
- }),
- allowed_domains: vec![],
- };
- assert!(matches!(
- readonly
- .authorize(&proposed_request("https://8.8.8.8/"))
- .await,
- Err(RequestAuthorizationError::Denied(_))
- ));
-
- let guard = HostRequestGuard {
- security: Arc::new(SecurityPolicy::default()),
- allowed_domains: vec![],
- };
- assert!(matches!(
- guard
- .authorize(&proposed_request("https://127.0.0.1/"))
- .await,
- Err(RequestAuthorizationError::InvalidDestination(_))
- ));
-}
-
-#[tokio::test]
-async fn x402_guard_rejects_cleartext_payment_destinations() {
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- let guard = HostRequestGuard {
- security: Arc::new(SecurityPolicy::default()),
- allowed_domains: vec![],
- };
- assert!(matches!(
- guard.authorize(&proposed_request("http://8.8.8.8/")).await,
- Err(RequestAuthorizationError::InvalidDestination(reason)) if reason.contains("HTTPS")
- ));
-}
-
-#[tokio::test]
-async fn x402_rejected_destinations_do_not_exhaust_the_action_budget() {
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- let guard = HostRequestGuard {
- security: Arc::new(SecurityPolicy {
- max_actions_per_hour: 1,
- ..SecurityPolicy::default()
- }),
- allowed_domains: vec![],
- };
- assert!(matches!(
- guard
- .authorize(&proposed_request("https://127.0.0.1/"))
- .await,
- Err(RequestAuthorizationError::InvalidDestination(_))
- ));
- assert!(guard
- .authorize(&proposed_request("https://8.8.8.8/"))
- .await
- .is_ok());
- assert!(matches!(
- guard.authorize(&proposed_request("https://8.8.8.8/"))
- .await,
- Err(RequestAuthorizationError::Denied(reason)) if reason.contains("rate limit")
- ));
- assert!(matches!(
- guard.authorize(&proposed_request("https://127.0.0.1/"))
- .await,
- Err(RequestAuthorizationError::Denied(reason)) if reason.contains("rate limit")
- ));
-}
-
-#[tokio::test]
-async fn x402_tool_runs_the_host_guard_before_network_or_payment() {
- use tinytools::Tool;
-
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
-
- let security = Arc::new(SecurityPolicy::default());
- let blocked_private = request_tool(security.clone(), vec![])
- .execute(serde_json::json!({"url": "https://127.0.0.1:1/"}))
- .await
- .unwrap();
- assert!(blocked_private.is_error);
- assert!(blocked_private.text().contains("[policy-blocked]"));
-
- let blocked_domain = request_tool(security, vec!["example.com".into()])
- .execute(serde_json::json!({"url": "https://8.8.8.8/"}))
- .await
- .unwrap();
- assert!(blocked_domain.is_error);
- assert!(blocked_domain.text().contains("[policy-blocked]"));
-
- let blocked_cleartext = request_tool(Arc::new(SecurityPolicy::default()), vec![])
- .execute(serde_json::json!({"url": "http://8.8.8.8:1/"}))
- .await
- .unwrap();
- assert!(blocked_cleartext.is_error);
- assert!(blocked_cleartext.text().contains("require HTTPS"));
-}
-
-#[tokio::test]
-async fn x402_host_guard_normalizes_the_network_allowlist() {
- let _env_lock = crate::config::TEST_ENV_LOCK.lock().await;
- let security = Arc::new(SecurityPolicy::default());
- let allowed = host_request_guard(security.clone(), vec!["HTTPS://8.8.8.8/path".into()]);
- assert!(allowed
- .authorize(&proposed_request("https://8.8.8.8/"))
- .await
- .is_ok());
-
- let malformed = host_request_guard(security, vec![" ".into()]);
- assert!(matches!(
- malformed
- .authorize(&proposed_request("https://8.8.8.8/"))
- .await,
- Err(RequestAuthorizationError::InvalidDestination(_))
- ));
-}
-
-#[test]
-fn the_tool_is_built_from_the_host_seams() {
- use tinytools::Tool;
- let security = Arc::new(SecurityPolicy::default());
- assert_eq!(
- request_tool(security.clone(), vec![]).name(),
- "x402_request"
- );
- assert_eq!(
- super::super::request_tool(security, vec![]).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().await;
- let temp = tempfile::tempdir().unwrap();
- let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;
- 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().await;
- let temp = tempfile::tempdir().unwrap();
- let _workspace = crate::web3::wallet::test_support::set_workspace_env_for_test(&temp).await;
-
- 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());
-}
-
-// ---------------------------------------------------------------------------
-// The thread seam: which chat thread a payment belongs to
-// ---------------------------------------------------------------------------
-
-fn chat_ctx(thread: &str) -> crate::security::approval::ApprovalChatContext {
- crate::security::approval::ApprovalChatContext {
- thread_id: format!("thread-{thread}"),
- client_id: format!("client-{thread}"),
- request_id: None,
- }
-}
-
-/// The ledger records a payment's thread from this read. If it stopped reading
-/// `APPROVAL_CHAT_CONTEXT`, every tool payment would silently lose its thread.
-#[tokio::test]
-async fn the_thread_scope_reads_the_approval_chat_context_task_local() {
- use tinywallet_x402::thread::ThreadScope;
-
- assert_eq!(
- TaskLocalThread.current_thread(),
- None,
- "outside a chat turn there is no thread"
- );
-
- let inside = crate::security::approval::APPROVAL_CHAT_CONTEXT
- .scope(chat_ctx("a"), async { TaskLocalThread.current_thread() })
- .await;
- assert_eq!(inside.as_deref(), Some("thread-a"));
-
- // Nested scopes answer with the innermost thread, and the outer one is
- // restored afterwards.
- let (inner, outer) = crate::security::approval::APPROVAL_CHAT_CONTEXT
- .scope(chat_ctx("outer"), async {
- let inner = crate::security::approval::APPROVAL_CHAT_CONTEXT
- .scope(chat_ctx("inner"), async {
- TaskLocalThread.current_thread()
- })
- .await;
- (inner, TaskLocalThread.current_thread())
- })
- .await;
- assert_eq!(inner.as_deref(), Some("thread-inner"));
- assert_eq!(outer.as_deref(), Some("thread-outer"));
-}
diff --git a/crates/openhuman-core/src/web3/x402/stub.rs b/crates/openhuman-core/src/web3/x402/stub.rs
index e4971b6254..065538e8f2 100644
--- a/crates/openhuman-core/src/web3/x402/stub.rs
+++ b/crates/openhuman-core/src/web3/x402/stub.rs
@@ -12,18 +12,9 @@
//! (`cargo check --no-default-features`) is
//! the only thing that catches drift.
-use std::path::Path;
-
use crate::core::all::RegisteredController;
use crate::core::ControllerSchema;
-/// No-op: there is no spending ledger to initialise when x402 is compiled out.
-/// Mirrors `store::init_global` (re-exported as `init_ledger`). The boot call
-/// site is additionally runtime-gated on `DomainGroup::Web3`.
-pub fn init_ledger(_workspace_dir: &Path, _session_id: &str) {
- log::debug!("[x402-stub] init_ledger ignored (web3 disabled)");
-}
-
/// No x402 controller schemas when the domain is compiled out.
pub fn all_x402_controller_schemas() -> Vec<ControllerSchema> {
Vec::new()
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index a7fbc4aae2..ef2de109bf 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -43,6 +43,9 @@ pub(crate) async fn run_chat_task(
// clobbered by — the primary turn's cached agent. See `QueueMode::Parallel`.
fork: bool,
) -> Result<WebChatTaskResult, String> {
+ // One turn at a time per profile: wait behind its relay and cron turns.
+ let _turn = crate::profiles::turn_gate::acquire().await;
+
#[cfg(any(test, debug_assertions))]
{
let mut slot = TEST_FORCED_RUN_CHAT_TASK_ERROR.lock().await;
diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.toml
index dd84a09a38..d293aec9b5 100644
--- a/crates/openhuman-embed/Cargo.toml
+++ b/crates/openhuman-embed/Cargo.toml
@@ -93,6 +93,8 @@ uuid = { version = "1", features = ["v4"] }
async-trait = "0.1"
tinymemory-api = { path = "../../vendor/tinymemory/crates/tinymemory-api", features = ["conformance"] }
dirs = "6"
+# `cron_tests` builds core `CronJob`s, whose schedule types live in tinyflows.
+tinyflows-schedule = { path = "../../vendor/tinyflows/crates/tinyflows-schedule" }
env_logger = "0.11"
# The profile tests and example implement a stub `BackendTransport`, whose
# `http_client` hands out a `reqwest::Client`. Same features as the core's, so
diff --git a/crates/openhuman-embed/tests/profile_turn_serialization.rs b/crates/openhuman-embed/tests/profile_turn_serialization.rs
new file mode 100644
index 0000000000..ad6b54bfbd
--- /dev/null
+++ b/crates/openhuman-embed/tests/profile_turn_serialization.rs
@@ -0,0 +1,152 @@
+//! One profile runs one turn at a time: a due cron job waits for the profile's
+//! in-flight chat turn instead of running beside it, while another profile's
+//! turn is not held up. One runtime and one test: SaaS operating mode is
+//! process-wide.
+
+mod common;
+
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use common::{chat_completion, last_user_message, runtime_without_master_key, PointedTransport};
+use openhuman_core::cron::{self, AgentJobSpec, Schedule};
+use openhuman_embed::profiles::ProfileCredentialKind;
+use openhuman_embed::{ProfileRuntime, SaasConfig};
+use wiremock::{Mock, Request, Respond, ResponseTemplate};
+
+/// How long the slow chat turn's model request takes to answer.
+const SLOW: Duration = Duration::from_millis(2500);
+
+/// Records when each marked prompt's model request arrived. Prompts containing
+/// `slow` are answered after [`SLOW`]; the rest at once.
+#[derive(Clone, Default)]
+struct Arrivals(Arc<Mutex<Vec<(String, Instant)>>>);
+
+impl Arrivals {
+ fn at(&self, marker: &str) -> Option<Instant> {
+ self.0
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(prompt, _)| prompt.contains(marker))
+ .map(|(_, at)| *at)
+ }
+
+ async fn wait_for(&self, marker: &str) -> Instant {
+ for _ in 0..600 {
+ if let Some(at) = self.at(marker) {
+ return at;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ panic!("no model request for {marker:?}");
+ }
+}
+
+impl Respond for Arrivals {
+ fn respond(&self, request: &Request) -> ResponseTemplate {
+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
+ let prompt = last_user_message(&body);
+ self.0
+ .lock()
+ .unwrap()
+ .push((prompt.clone(), Instant::now()));
+ let reply = ResponseTemplate::new(200).set_body_json(chat_completion("ok"));
+ if prompt.contains("slow") {
+ reply.set_delay(SLOW)
+ } else {
+ reply
+ }
+ }
+}
+
+#[test]
+fn a_profiles_cron_run_waits_for_its_chat_turn_but_other_profiles_do_not() {
+ runtime_without_master_key().block_on(async {
+ tokio::spawn(scenario()).await.unwrap();
+ });
+}
+
+async fn scenario() {
+ let arrivals = Arrivals::default();
+ let inference = wiremock::MockServer::start().await;
+ Mock::given(wiremock::matchers::path_regex(r"chat/completions$"))
+ .respond_with(arrivals.clone())
+ .with_priority(1)
+ .mount(&inference)
+ .await;
+ Mock::given(wiremock::matchers::any())
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"success":true,"data":[]})),
+ )
+ .with_priority(10)
+ .mount(&inference)
+ .await;
+ PointedTransport::install(&inference.uri());
+ openhuman_core::storage::install(Arc::new(openhuman_core::storage::MemoryStorage::new()));
+
+ let root = tempfile::tempdir().unwrap();
+ let runtime = ProfileRuntime::builder(SaasConfig::new(root.path()))
+ .configure(|config| config.lease_ttl_secs = 3600)
+ .build()
+ .await
+ .unwrap();
+
+ let mut handles = Vec::new();
+ for user in ["alice", "bob"] {
+ let provisioned = runtime.provision(user).await.unwrap();
+ runtime
+ .set_credential(
+ &provisioned.profile_id,
+ ProfileCredentialKind::ApiKey,
+ "fixture-key",
+ )
+ .await
+ .unwrap();
+ handles.push(runtime.open(user).await.unwrap());
+ }
+ let (alice, bob) = (handles.remove(0), handles.remove(0));
+
+ // Alice has a cron job that will be due.
+ let soon = chrono::Utc::now() + chrono::Duration::seconds(5);
+ let config = alice.context().embedder_config().unwrap().clone();
+ alice
+ .scope(async {
+ let spec = AgentJobSpec::new(Schedule::At { at: soon }, "alice cron".to_string());
+ cron::add_agent_job_from_spec(&config, spec).unwrap();
+ })
+ .await;
+
+ // Alice's chat turn is mid-model-call when the sweep fires.
+ let chat = tokio::spawn({
+ let alice = alice.clone();
+ async move { alice.chat("t1", "alice slow chat").await }
+ });
+ let chat_started = arrivals.wait_for("alice slow chat").await;
+
+ // Another profile is not held up by Alice's turn.
+ tokio::time::timeout(Duration::from_secs(60), bob.chat("t1", "bob chat"))
+ .await
+ .expect("bob's turn finishes")
+ .expect("bob's turn");
+ assert!(
+ chat_started.elapsed() < SLOW,
+ "bob's turn must finish while alice's is still in flight"
+ );
+ assert!(!chat.is_finished(), "alice's turn is still running");
+
+ // The sweep runs Alice's job, but only once her chat turn is over.
+ let later = chrono::Utc::now() + chrono::Duration::hours(1);
+ let report = runtime.sweep_cron_at(later).await;
+ assert_eq!(
+ report.ran, 1,
+ "the occurrence is deferred, not skipped: {report:?}"
+ );
+ let cron_started = arrivals.wait_for("alice cron").await;
+ assert!(
+ cron_started >= chat_started + SLOW,
+ "the cron run started {:?} after the chat turn began; it must wait {SLOW:?}",
+ cron_started.duration_since(chat_started)
+ );
+ chat.await.unwrap().expect("alice's chat turn");
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1749b18555..e20ab768ad 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -62,9 +62,6 @@ importers:
'@noble/hashes':
specifier: ^2.0.1
version: 2.2.0
- '@noble/secp256k1':
- specifier: ^3.0.0
- version: 3.1.0
'@radix-ui/react-collapsible':
specifier: ^1.1.20
@@ -74,15 +71,6 @@ importers:
'@rive-app/react-webgl2':
specifier: ^4.28.6
version: 4.28.6([email protected])
- '@scure/base':
- specifier: ^2.2.0
- version: 2.2.0
- '@scure/bip32':
- specifier: ^2.0.1
- version: 2.2.0
- '@scure/bip39':
- specifier: ^2.0.1
- version: 2.2.0
'@sentry/react':
specifier: ^10.38.0
version: 10.50.0([email protected])
@@ -1296,9 +1284,6 @@ packages:
resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==}
engines: {node: '>= 20.19.0'}
- '@noble/[email protected]':
- resolution: {integrity: sha512-+F7iS7tUMaNGXcc9X3PjmjvuQnXEuSjCRNzVVA2xAcKXgCaP0dHYz4SFyt4FKNHef7sOP//xihowcySSS7PK9g==}
-
'@nodable/[email protected]':
resolution: {integrity: sha512-nyT7T3nbMyBI/lvr6L5TyWbFJAI9FTgVRakNoBqCD+PmID8DzFrrNdLLtHMwMszOtqZa8PAOV24ZqDnQrhQINA==}
@@ -2546,15 +2531,6 @@ packages:
resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==}
- '@scure/[email protected]':
- resolution: {integrity: sha512-b8XEupJibegiXV+tDUseI8oLQc8ei3d/4Jkb2RpbHh3MfE054ov3uIz2dhFkB3FI8iwYkEh0gGCApkrYggkPNg==}
-
- '@scure/[email protected]':
- resolution: {integrity: sha512-zFr7t2F+a9+5tB7QbarF2HQNYrgjCNaoLAupZdKkrFMYMozJf5zqH2WJCQibMzm1qQ0QogrxVGO3qXfQDYMaQg==}
-
- '@scure/[email protected]':
- resolution: {integrity: sha512-T/Bj/YvYMNkIPq6EENO6/rcs2e7qTNuyoUXf0KBFDmp0ZDu0H2X4Lq6yC3i0c8PcWkov5EbW+yQZZbdMmk154A==}
-
'@sec-ant/[email protected]':
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
@@ -8085,8 +8061,6 @@ snapshots:
'@noble/[email protected]': {}
- '@noble/[email protected]': {}
-
'@nodable/[email protected]': {}
'@oxc-parser/[email protected]':
@@ -9197,19 +9171,6 @@ snapshots:
'@rtsao/[email protected]': {}
- '@scure/[email protected]': {}
-
- '@scure/[email protected]':
- dependencies:
- '@noble/curves': 2.2.0
- '@noble/hashes': 2.2.0
- '@scure/base': 2.2.0
-
- '@scure/[email protected]':
- dependencies:
- '@noble/hashes': 2.2.0
- '@scure/base': 2.2.0
-
'@sec-ant/[email protected]': {}
'@sentry-internal/[email protected]':
diff --git a/scripts/ci/module-boundaries.json b/scripts/ci/module-boundaries.json
index d6c2751cef..96a8f36052 100644
--- a/scripts/ci/module-boundaries.json
+++ b/scripts/ci/module-boundaries.json
@@ -110,21 +110,6 @@
"scope": "hosts",
"package": "tinychannels-runtime",
"reason": "Providers, relay, pairing and delivery lifecycles still call the implementation."
- },
- {
- "scope": "hosts",
- "package": "tinywallet-crypto",
- "reason": "Validation, transaction construction, web3 and x402 need module operations."
- },
- {
- "scope": "hosts",
- "package": "tinywallet-web3",
- "reason": "Validation, transaction construction, web3 and x402 need module operations."
- },
- {
- "scope": "hosts",
- "package": "tinywallet-x402",
- "reason": "Validation, transaction construction, web3 and x402 need module operations."
}
],
"excludedSubsystems": [