· 6 min read · March 4, 2026

On-Chain Accounting for AI Agents: A Developer's Guide

Every serious business needs bookkeeping. AI agents are no different — and yet the vast majority of production agents running today have no accounting layer at all. They generate revenue, they pay fees, they win and lose on trades, and at the end of the month nobody can answer a simple question: is this agent actually profitable? Revenue is easy to see. Fees are silent. The difference between the two is profit — and without systematic accounting, you are flying blind.

This guide implements a complete double-entry bookkeeping system for an AI agent using Purple Flea's accounting API. By the end, your agent will produce a balance sheet, an income statement, and a cash flow statement — the same three financial statements every real business uses to measure its health.

The Double-Entry Model for AI Agents

Double-entry bookkeeping requires every financial event to be recorded as two equal and opposite entries: a debit to one account and a credit to another. The fundamental equation is Assets = Liabilities + Equity. Every transaction must keep this equation balanced.

For an AI agent, the five account categories map cleanly to agent-native concepts:

Transaction Categories and Their Accounting Treatment

Not all on-chain events are simple income or expense entries. Here is how the most common Purple Flea transactions map to double-entry accounting:

EventDebit AccountCredit Account
Realized trading gainUSDC Wallet (Asset +)Trading P&L (Income +)
Realized trading lossTrading P&L (Expense +)USDC Wallet (Asset -)
Referral commission receivedUSDC Wallet (Asset +)Referral Income (Income +)
Gas fee paidGas Expense (Expense +)ETH/MATIC Wallet (Asset -)
Post collateralCollateral Posted (Asset +)USDC Wallet (Asset -)
Escrow depositEscrow Receivable (Asset +)USDC Wallet (Asset -)
Platform feePlatform Fees (Expense +)USDC Wallet (Asset -)

Python: Categorizing Transactions with the Accounting API

Purple Flea's accounting API automatically categorizes transactions from your agent's on-chain activity. The following script pulls the last 30 days of transactions, categorizes them, and builds a ledger suitable for financial statement generation:

from purpleflea import AccountingClient
from datetime import datetime, timedelta
from collections import defaultdict

accounting = AccountingClient(api_key="pf_sk_your_key_here")

start = datetime.utcnow() - timedelta(days=30)
end   = datetime.utcnow()

# Pull all on-chain events for the agent
transactions = accounting.get_transactions(
    agent_id="agent_trader_001",
    start_date=start.isoformat(),
    end_date=end.isoformat(),
    auto_categorize=True   # let the API label each tx
)

# Group by category
ledger = defaultdict(list)
for tx in transactions:
    ledger[tx["category"]].append(tx)

# Summarize income vs expense
income_categories  = ["trading_gain", "referral_commission", "casino_win", "service_fee_received"]
expense_categories = ["trading_loss", "platform_fee", "gas_fee", "casino_loss", "escrow_fee"]

total_income  = sum(tx["amount_usdc"] for cat in income_categories for tx in ledger[cat])
total_expense = sum(tx["amount_usdc"] for cat in expense_categories for tx in ledger[cat])
net_profit    = total_income - total_expense

print(f"\n=== Income Statement (Last 30 Days) ===")
for cat in income_categories:
    total = sum(tx["amount_usdc"] for tx in ledger[cat])
    if total: print(f"  {cat:<30} +${total:>10,.2f}")
print(f"  {'Total Income':<30}  ${total_income:>10,.2f}")
for cat in expense_categories:
    total = sum(tx["amount_usdc"] for tx in ledger[cat])
    if total: print(f"  {cat:<30} -${total:>10,.2f}")
print(f"  {'─'*44}")
print(f"  {'Net Profit / (Loss)':<30}  ${net_profit:>10,.2f}")

Balance Sheet: Snapshot of Agent Net Worth

The balance sheet gives a point-in-time snapshot of everything the agent owns and owes. Unlike the income statement (which covers a period), the balance sheet is always as of a specific moment. Run it at the end of each month to track net worth growth over time.

Cash Flow Statement: Liquid Capital vs. Locked Capital

The cash flow statement answers a question that neither the income statement nor the balance sheet can answer alone: how much liquid capital does the agent have available right now? An agent can be technically profitable (income exceeds expenses) but cash-poor if most of its capital is locked as collateral, held in escrow, or tied up in open positions.

The three sections of an agent cash flow statement mirror traditional accounting: operating activities (trading, fees, referrals), investing activities (posting/withdrawing collateral, escrow deposits/releases), and financing activities (capital injections from the operator, withdrawals to treasury). A negative operating cash flow combined with a profitable income statement is a red flag — it means the agent is growing its locked positions faster than it is generating liquid returns.

Python: Generating the Full Monthly Report

from purpleflea import AccountingClient
import json

accounting = AccountingClient(api_key="pf_sk_your_key_here")

# Generate complete financial package for a given month
report = accounting.generate_monthly_report(
    agent_id="agent_trader_001",
    year=2026,
    month=3,
    include_balance_sheet=True,
    include_income_statement=True,
    include_cash_flow=True,
    base_currency="USDC"
)

bs = report["balance_sheet"]
print("\n=== Balance Sheet (End of Month) ===")
print(f"  Total Assets:      ${bs['total_assets']:>10,.2f} USDC")
print(f"  Total Liabilities: ${bs['total_liabilities']:>10,.2f} USDC")
print(f"  Net Equity:        ${bs['net_equity']:>10,.2f} USDC")

cf = report["cash_flow"]
print("\n=== Cash Flow Statement ===")
print(f"  Operating CF:      ${cf['operating']:>10,.2f} USDC")
print(f"  Investing CF:      ${cf['investing']:>10,.2f} USDC")
print(f"  Financing CF:      ${cf['financing']:>10,.2f} USDC")
print(f"  Net Change:        ${cf['net_change']:>10,.2f} USDC")

# Export for tax reporting
accounting.export_csv(
    agent_id="agent_trader_001",
    year=2026,
    month=3,
    output_path="agent_trader_001_march_2026.csv",
    format="turbotax_compatible"
)
print("\nCSV exported: agent_trader_001_march_2026.csv")

Reconciliation: Verifying On-Chain Balances Match the Books

At least once per week, run a reconciliation check: query the actual on-chain balance of each wallet the agent controls, and compare it to the accounting ledger's expected balance for those accounts. Discrepancies indicate either a missed transaction (a webhook that was dropped), a bug in the categorization logic, or — worst case — an unauthorized transaction.

Purple Flea's accounting API provides a reconcile() method that runs this check automatically, queries the relevant chains, and returns a list of discrepancies with their likely causes. Run it daily in production and treat any discrepancy over $1 as a blocking issue that requires investigation before the agent continues operating.

Tax reporting note: Purple Flea's accounting API exports data in TurboTax, TaxAct, and generic CSV formats. Each realized gain or loss is tagged with the cost basis, disposal date, and holding period — the three pieces of information required for capital gains tax reporting in most jurisdictions. Do not wait until year-end to pull these reports; the data is available in real time.

Conclusion

Double-entry bookkeeping takes about a day to set up for a production agent and pays for itself within the first month by surfacing fee drag that would otherwise go unnoticed. The agents that survive and grow in the long run are not the ones with the best trading signals — they are the ones whose operators actually know whether those signals are profitable after fees, taxes, and operational costs. Build the accounting layer now, before you need it.