BroomVA

Haima

Agentic finance engine — x402 machine-to-machine payments, on-chain settlement, and per-task revenue.

Haima

Haima is the finance engine of the Agent OS -- the circulatory system that distributes economic resources throughout the organism. It implements the x402 protocol for machine-to-machine payments, manages cryptographic wallets, and tracks per-task costs and revenue.

Design principles

Every financial action is an immutable event. All transactions, payments, and economic state changes are recorded in the Lago journal. The financial state is a deterministic projection -- replay the events and you get the exact same balances.

Security is non-negotiable. Private keys are zeroized on drop (never lingering in memory) via the zeroize crate, and encrypted at rest with ChaCha20-Poly1305. The wallet layer is isolated from the rest of the system.

Architecture

CrateRole
haima-corePayment policy types, financial state, task billing records
haima-walletWallet backend -- secp256k1 key generation, signing, encryption
haima-x402x402 protocol implementation (HTTP 402 Payment Required flow)
haima-lagoBridge to Lago for persisting finance events
haima-apiHTTP API server (axum) on port 3003
haimadDaemon binary

x402 protocol

The x402 protocol adds a payment layer to HTTP. It enables agents to autonomously pay for services without human intervention for each transaction.

Protocol flow

Agent                           Service                         Blockchain
  │                                │                                │
  ├──── GET /resource ────────────►│                                │
  │                                │                                │
  │◄── 402 Payment Required ──────┤                                │
  │    {amount, chain, recipient}  │                                │
  │                                │                                │
  ├── Evaluate PaymentPolicy ──►   │                                │
  │   (auto-approve / approval)    │                                │
  │                                │                                │
  ├── Sign transaction ──────────────────────────────────────────►  │
  │   (secp256k1)                  │                                │
  │                                │                                │
  │◄── Confirmation ──────────────────────────────────────────────  │
  │                                │                                │
  ├── Retry with proof ───────────►│                                │
  │   (X-Payment-Proof header)     │                                │
  │                                │                                │
  │◄── 200 OK + resource ─────────┤                                │
  1. The agent requests a resource that requires payment
  2. The server responds with 402 Payment Required and payment instructions (amount, currency, chain, recipient address)
  3. Haima evaluates the payment against the active PaymentPolicy
  4. If approved, Haima signs the transaction using the agent's secp256k1 key
  5. The transaction is submitted on-chain through the facilitator
  6. The agent retries the original request with proof of payment

Payment policies

Payment policies determine whether a payment is approved automatically, requires human approval, or is denied:

PolicyWhen usedBehavior
Auto-approveDefault in Sovereign/Conserving modePayments under a threshold (varies by economic mode) are signed immediately without human input
ApprovalDefault in Hustle modePayments require explicit approval from the human operator or a governance check before signing
DenyActive in Hibernate modeAll payments are rejected. The agent cannot spend until it returns to a mode with budget

Auto-approve thresholds adapt to the economic mode from Autonomic:

ModeAuto-approve threshold
SovereignUp to $1.00 per transaction
ConservingUp to $0.10 per transaction
Hustle$0 (all payments require approval)
HibernateDenied (no payments)

Wallet management

Haima manages agent wallets through a WalletBackend trait:

Local secp256k1 (current implementation)

  • Keys generated using a cryptographically secure random number generator (OsRng)
  • Private keys encrypted with ChaCha20-Poly1305 before storage on disk
  • Keys zeroized in memory on drop (via the zeroize crate) -- the private key never lingers in process memory after use
  • Address derivation follows standard Ethereum key derivation (keccak256 of the uncompressed public key)

The wallet implementation is security-critical. Private key material is handled with extreme care: encrypted at rest, zeroized on drop, and never logged or serialized in plaintext. If you are extending the wallet backend, follow the same patterns.

Planned backends

  • MPC -- multi-party computation for shared key management (no single party holds the full key)
  • Hardware -- HSM integration for high-security deployments

Chain support

ChainIdentifierStatusNotes
Baseeip155:8453PrimaryEthereum L2 with low gas fees, used for USDC settlement
Solana--PlannedFor agents operating in the Solana ecosystem

Per-task billing

Every operation the agent performs has a cost tracked at the task level. This creates a complete economic trace of agent activity:

// Cost event — recorded when the agent consumes a resource
TaskBilled {
    task_id: "task_abc123",
    cost: 15,              // micro-credits (1 = $0.01)
    category: "inference",
    provider: "anthropic",
    model: "claude-sonnet-4-20250514",
    tokens_in: 1200,
    tokens_out: 450,
}

// Revenue event — recorded when the agent earns money
RevenueReceived {
    task_id: "task_abc123",
    amount: 50,            // micro-credits
    source: "marketplace",
    description: "Research report completed",
}

The difference between costs and revenue feeds into Autonomic's economic pillar to determine the agent's economic mode. A profitable agent stays in Sovereign mode; an unprofitable one trends toward Conserving or Hustle.

Micro-credit system

Haima uses micro-credits as the internal unit of account: 1 micro-credit = 1 cent USD. This aligns with the platform billing system, where plans allocate credits in cents.

Credits bridge to USDC for on-chain settlement:

  • Deposit: send USDC to the agent's wallet address on Base to fund credits
  • Withdraw: convert credits to USDC and send to an external address

The bridge is managed by a facilitator service.

Facilitator architecture

The facilitator handles the complexity of on-chain transactions so the agent does not need to manage gas, nonces, or transaction confirmation directly:

FacilitatorDescription
Coinbase CDPDefault -- uses Coinbase Commerce Developer Platform for gas abstraction and settlement. The facilitator covers gas fees so agents never need to hold ETH.
Self-hostedPlanned -- run your own facilitator node for full control over the settlement process
StripePlanned -- fiat-only path without on-chain settlement, for organizations that prefer traditional payment rails

The facilitator abstracts:

  • Gas fee payment (the agent does not hold or spend ETH)
  • Nonce management (prevents transaction conflicts)
  • Transaction confirmation (waits for on-chain finality)
  • Failed transaction retry

Running Haima

cd haima
cargo run -p haimad
# Listening on http://localhost:3003

API endpoints

EndpointMethodDescription
/v1/haima/balanceGETWallet balance and credit state
/v1/haima/payPOSTSubmit an x402 payment
/v1/haima/historyGETTransaction history
/v1/haima/healthGETService health check

Event persistence

Finance events use EventKind::Custom with a "finance." prefix in the Lago journal:

EventDescription
finance.task_billedOperation cost recorded
finance.revenue_receivedPayment received for work
finance.payment_sentx402 payment submitted to the chain
finance.payment_confirmedOn-chain confirmation received
finance.credits_depositedCredits added to wallet via USDC bridge
finance.credits_withdrawnCredits removed from wallet

This naming convention enables forward-compatible persistence: new event types can be added without Lago schema changes, and any Lago consumer can filter for finance events using the "finance." prefix.

On this page