Skip to content

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

24.2 KB
Raw Blame
use crate::core::runtime::DispatchCtx;
use serde::Deserialize;
use serde_json::{Map, Value};

use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};

use super::execution::{
    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")]
struct TxQueryParams {
    chain: WalletChain,
    #[serde(default)]
    evm_network: Option<EvmNetwork>,
    hash: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SetupWalletParams {
    consent_granted: bool,
    source: WalletSetupSource,
    mnemonic_word_count: u8,
    encrypted_mnemonic: String,
    accounts: Vec<WalletAccount>,
    /// Explicit overwrite permission — must be `true` to replace an existing wallet.
    /// Defaults to `false`; set by the frontend only after double-confirmation.
    #[serde(default)]
    force: bool,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct EncodeErc20TransferParams {
    chain: WalletChain,
    to_address: String,
    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()
}

pub fn all_registered_controllers() -> Vec<RegisteredController> {
    all_wallet_registered_controllers()
}

pub fn schemas(function: &str) -> ControllerSchema {
    wallet_schemas(function)
}

pub fn all_wallet_controller_schemas() -> Vec<ControllerSchema> {
    vec![
        wallet_schemas("status"),
        wallet_schemas("setup"),
        wallet_schemas("balances"),
        wallet_schemas("network_defaults"),
        wallet_schemas("supported_assets"),
        wallet_schemas("encode_erc20_transfer"),
        wallet_schemas("chain_status"),
        wallet_schemas("prepare_transfer"),
        wallet_schemas("execute_prepared"),
        wallet_schemas("tx_status"),
        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"),
    ]
}

pub fn all_wallet_registered_controllers() -> Vec<RegisteredController> {
    vec![
        RegisteredController {
            schema: wallet_schemas("status"),
            handler: handle_status,
        },
        RegisteredController {
            schema: wallet_schemas("setup"),
            handler: handle_setup,
        },
        RegisteredController {
            schema: wallet_schemas("balances"),
            handler: handle_balances,
        },
        RegisteredController {
            schema: wallet_schemas("network_defaults"),
            handler: handle_network_defaults,
        },
        RegisteredController {
            schema: wallet_schemas("supported_assets"),
            handler: handle_supported_assets,
        },
        RegisteredController {
            schema: wallet_schemas("encode_erc20_transfer"),
            handler: handle_encode_erc20_transfer,
        },
        RegisteredController {
            schema: wallet_schemas("chain_status"),
            handler: handle_chain_status,
        },
        RegisteredController {
            schema: wallet_schemas("prepare_transfer"),
            handler: handle_prepare_transfer,
        },
        RegisteredController {
            schema: wallet_schemas("execute_prepared"),
            handler: handle_execute_prepared,
        },
        RegisteredController {
            schema: wallet_schemas("tx_status"),
            handler: handle_tx_status,
        },
        RegisteredController {
            schema: wallet_schemas("tx_receipt"),
            handler: handle_tx_receipt,
        },
        RegisteredController {
            schema: wallet_schemas("lookup_tx"),
            handler: handle_lookup_tx,
        },
        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,
        },
    ]
}

pub fn wallet_schemas(function: &str) -> ControllerSchema {
    match function {
        "status" => ControllerSchema {
            namespace: "wallet",
            function: "status",
            description: "Fetch core-owned local wallet metadata and onboarding status.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Wallet onboarding status plus safe multi-chain account metadata.",
                required: true,
            }],
        },
        "setup" => ControllerSchema {
            namespace: "wallet",
            function: "setup",
            description:
                "Persist local wallet consent and derived account metadata from the recovery phrase flow.",
            inputs: vec![
                required_json("consentGranted", "Whether the user explicitly consented to wallet setup."),
                required_json("source", "Whether the recovery phrase was generated or imported."),
                required_json(
                    "mnemonicWordCount",
                    "The number of words in the validated recovery phrase.",
                ),
                FieldSchema {
                    name: "encryptedMnemonic",
                    ty: TypeSchema::String,
                    comment:
                        "Encrypted recovery phrase payload created via openhuman.encrypt_secret. Required for on-chain signing/broadcast.",
                    required: true,
                },
                required_json(
                    "accounts",
                    "Exactly one derived account for each supported chain: EVM, BTC, Solana, and Tron.",
                ),
                FieldSchema {
                    name: "force",
                    ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
                    comment:
                        "Optional boolean. Must be true to overwrite an existing wallet. Defaults to false. \
                         Only pass true after the user has explicitly confirmed wallet replacement.",
                    required: false,
                },
            ],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Updated wallet status after saving the setup.",
                required: true,
            }],
        },
        "balances" => ControllerSchema {
            namespace: "wallet",
            function: "balances",
            description:
                "List native-asset balances for every derived wallet account. The EVM account fans out into one row per displayed network (Ethereum, Base, BNB Chain), each read live from the configured/default RPC; BTC/Solana/Tron return one row each.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Array of balance rows: {chain, evmNetwork?, address, assetSymbol, decimals, raw, formatted, providerStatus}.",
                required: true,
            }],
        },
        "network_defaults" => ControllerSchema {
            namespace: "wallet",
            function: "network_defaults",
            description:
                "List default RPC URLs, explorer bases, capability flags, and asset catalogs for supported wallet chains.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Array of {chain, network, chainId?, rpcUrl, rpcSource, explorerTxUrlBase, explorerTxUrlSuffix?, supportsBroadcast, supportsTokenTransfers, supportsContractCalls, assets[]}.",
                required: true,
            }],
        },
        "supported_assets" => ControllerSchema {
            namespace: "wallet",
            function: "supported_assets",
            description:
                "Catalog of built-in asset defaults the wallet surface understands, including default ERC-20s on EVM.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Array of {chain, symbol, name, native, decimals, contractAddress?}.",
                required: true,
            }],
        },
        "encode_erc20_transfer" => ControllerSchema {
            namespace: "wallet",
            function: "encode_erc20_transfer",
            description:
                "Encode ERC-20 transfer(address,uint256) calldata for EVM token sends.",
            inputs: vec![
                required_json("chain", "Target chain. Must be evm."),
                required_json("toAddress", "Recipient EVM address."),
                required_json("amountRaw", "Token amount in the token's smallest unit as a decimal string."),
            ],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "0x-prefixed calldata string for transfer(address,uint256).",
                required: true,
            }],
        },
        "chain_status" => ControllerSchema {
            namespace: "wallet",
            function: "chain_status",
            description:
                "Per-chain readiness: whether a wallet account is derived, the active RPC URL (default or env override), and whether that endpoint answered a chain-tip probe.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "Array of {chain, evmNetwork?, configured, providerStatus, rpcUrl, error?}. providerStatus is ready only when the endpoint answered the probe; otherwise missing, with the failure in error (absent when no account exists).",
                required: true,
            }],
        },
        "prepare_transfer" => ControllerSchema {
            namespace: "wallet",
            function: "prepare_transfer",
            description:
                "Build a native or token-transfer quote. All four chains (EVM, BTC, Solana, Tron) sign + broadcast on execute_prepared after explicit confirmation. BTC supports only native transfers (no token concept).",
            inputs: vec![
                required_json("chain", "Target chain (evm | btc | solana | tron)."),
                required_json("toAddress", "Recipient address on the target chain."),
                required_json("amountRaw", "Amount in the asset's smallest unit (wei/sat/lamport/sun) as a decimal string."),
                FieldSchema {
                    name: "assetSymbol",
                    ty: TypeSchema::Option(Box::new(TypeSchema::String)),
                    comment: "Optional. Omit / null for the chain's native asset; otherwise a token symbol from wallet.supported_assets.",
                    required: false,
                },
                FieldSchema {
                    name: "evmNetwork",
                    ty: TypeSchema::Option(Box::new(TypeSchema::String)),
                    comment: "Optional. Required only for chain='evm' to pick a network: ethereum_mainnet | base_mainnet | arbitrum_one | optimism_mainnet | polygon_mainnet. Defaults to ethereum_mainnet.",
                    required: false,
                },
            ],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "PreparedTransaction with quoteId, simulated fee, and expiry.",
                required: true,
            }],
        },
        "tx_status" => ControllerSchema {
            namespace: "wallet",
            function: "tx_status",
            description:
                "Check the on-chain lifecycle state (pending / confirmed / failed / not_found) of a transaction by hash.",
            inputs: tx_query_inputs(),
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "{chain, evmNetwork?, hash, state, confirmations?, blockNumber?}.",
                required: true,
            }],
        },
        "tx_receipt" => ControllerSchema {
            namespace: "wallet",
            function: "tx_receipt",
            description:
                "Fetch the receipt of a broadcast transaction (success flag, fee, block, gas used) plus the raw provider payload.",
            inputs: tx_query_inputs(),
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "{chain, evmNetwork?, hash, found, success?, blockNumber?, gasUsed?, feeRaw?, raw}.",
                required: true,
            }],
        },
        "lookup_tx" => ControllerSchema {
            namespace: "wallet",
            function: "lookup_tx",
            description:
                "Look up the raw transaction payload by hash on the target chain.",
            inputs: tx_query_inputs(),
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "{chain, evmNetwork?, hash, found, raw}.",
                required: true,
            }],
        },
        "execute_prepared" => ControllerSchema {
            namespace: "wallet",
            function: "execute_prepared",
            description:
                "Confirm and execute a previously prepared quote. EVM transfers and contract calls are signed in core from encrypted local secret material, then broadcast to the configured/default RPC.",
            inputs: vec![
                required_json("quoteId", "quoteId returned by a prior wallet.prepare_* call."),
                required_json("confirmed", "Must be true; explicit safety boundary between simulate and execute."),
            ],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "ExecutionResult payload: {quoteId, status, chain, transactionHash, explorerUrl?, transaction}.",
                required: true,
            }],
        },
        "reveal_recovery_phrase" => ControllerSchema {
            namespace: "wallet",
            function: "reveal_recovery_phrase",
            description: "Reveal the plaintext recovery phrase for an existing configured wallet. \
                The phrase is decrypted in-core and returned only in the RPC response; \
                it must be held in transient React state and never written to disk.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "result",
                ty: TypeSchema::Json,
                comment: "{phrase: string, wordCount: number} — the decrypted BIP-39 mnemonic.",
                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",
            description: "Unknown wallet controller.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "error",
                ty: TypeSchema::String,
                comment: "Lookup error details.",
                required: true,
            }],
        },
    }
}

fn handle_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        crate::web3::wallet::status(&ctx)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_setup(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let payload: SetupWalletParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        crate::web3::wallet::setup(
            &ctx,
            WalletSetupParams {
                consent_granted: payload.consent_granted,
                source: payload.source,
                mnemonic_word_count: payload.mnemonic_word_count,
                encrypted_mnemonic: Some(payload.encrypted_mnemonic),
                accounts: payload.accounts,
                force: payload.force,
            },
        )
        .await?
        .into_cli_compatible_json()
    })
}

fn handle_balances(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move { balances(&ctx).await?.into_cli_compatible_json() })
}

fn handle_network_defaults(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move { network_defaults(&ctx).await?.into_cli_compatible_json() })
}

fn handle_supported_assets(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move { supported_assets(&ctx).await?.into_cli_compatible_json() })
}

fn handle_encode_erc20_transfer(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: EncodeErc20TransferParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        if parsed.chain != WalletChain::Evm {
            return Err("encode_erc20_transfer only supports the evm chain".to_string());
        }
        serde_json::to_value(
            encode_erc20_transfer(&ctx, &parsed.to_address, &parsed.amount_raw).await?,
        )
        .map_err(|e| format!("failed to encode ERC20 transfer output: {e}"))
    })
}

fn handle_chain_status(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move { chain_status(&ctx).await?.into_cli_compatible_json() })
}

fn handle_prepare_transfer(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: PrepareTransferParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        prepare_transfer(&ctx, parsed, None)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_execute_prepared(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: ExecutePreparedParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        execute_prepared(&ctx, parsed, None)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_tx_status(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: TxQueryParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        tx_status(&ctx, parsed.chain, parsed.evm_network, &parsed.hash)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_tx_receipt(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: TxQueryParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        tx_receipt(&ctx, parsed.chain, parsed.evm_network, &parsed.hash)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_lookup_tx(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let parsed: TxQueryParams = serde_json::from_value(Value::Object(params))
            .map_err(|e| format!("invalid params: {e}"))?;
        lookup_tx(&ctx, parsed.chain, parsed.evm_network, &parsed.hash)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_reveal_recovery_phrase(
    ctx: DispatchCtx,
    _params: Map<String, Value>,
) -> ControllerFuture {
    Box::pin(async move {
        crate::web3::wallet::reveal_recovery_phrase(&ctx)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_generate_mnemonic(ctx: DispatchCtx, 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(&ctx, parsed.word_count)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_validate_mnemonic(ctx: DispatchCtx, 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(&ctx, parsed.phrase)
            .await?
            .into_cli_compatible_json()
    })
}

fn handle_derive_recovery_material(
    ctx: DispatchCtx,
    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(&ctx, 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![
        required_json("chain", "Target chain (evm | btc | solana | tron)."),
        required_json("hash", "Transaction hash / signature / txid to query."),
        FieldSchema {
            name: "evmNetwork",
            ty: TypeSchema::Option(Box::new(TypeSchema::String)),
            comment:
                "Optional. EVM network selector when chain='evm'. Defaults to ethereum_mainnet.",
            required: false,
        },
    ]
}

fn required_json(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::Json,
        comment,
        required: true,
    }
}

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;