· 7 min read · March 4, 2026

Security Best Practices for AI Agents Handling Crypto

An AI agent with a funded wallet is an attractive target. Unlike a human-controlled wallet that sits idle while its owner sleeps, an agent operates 24 hours a day, 7 days a week, with an always-on API key and programmatic access to funds. If an attacker can manipulate the agent's decision-making — through a prompt injection, a compromised dependency, or a malicious input from another agent in the network — they can potentially drain the wallet before any human notices. This is not hypothetical; it has already happened in early agentic systems. This guide covers the six security principles that every production agent handling real crypto should implement before going live.

Before you read further: If your agent is currently running with an unrestricted API key and no transaction whitelist, pause it now. An unrestricted key on a funded wallet is a single exploited prompt injection away from a complete loss of funds.

Principle 1: Whitelist-Only Transactions

The single most effective security control for an agent wallet is to never allow the agent to send funds to an address that is not on a pre-approved whitelist. This eliminates the entire class of prompt-injection attacks that try to trick an agent into sending funds to an attacker's address by framing the request as a legitimate instruction.

The whitelist should be managed outside the agent process — ideally stored in Purple Flea's access control layer, which enforces it at the API level before any transaction is broadcast. Even if the agent is fully compromised, a transaction to a non-whitelisted address will be rejected by the API before it reaches the blockchain.

Legitimate address changes — adding a new counterparty to the whitelist — require a time-delayed, separately authenticated approval request. A 24-hour delay before a new address becomes spendable gives humans time to catch and reverse social-engineering attacks.

Principle 2: Multi-Sig for High-Value Transfers

For any transfer above a defined threshold (Purple Flea recommends $1,000 USDC by default), require two or more approvals before the transaction is broadcast. In practice, this means the agent generates a pending transaction request, and a separate approval process — either a human signer or a second independent agent with different credentials — must countersign before the funds move.

This is especially important for withdrawal transactions. Routine trading operations (opening and closing positions, posting collateral) can operate with single-sig authority at typical trade sizes. But any operation that moves funds out of the Purple Flea ecosystem to an external wallet should require multi-sig. Configure thresholds conservatively — you can always raise them later as you build confidence in the agent's behavior.

Principle 3: Principle of Least Privilege

A trading agent does not need withdrawal permissions. A data-fetching agent does not need any spend permissions at all. Scope every API key to the minimum permissions required for that agent's specific function and nothing more.

Purple Flea's access control API lets you create scoped API keys with fine-grained permission flags. A trading-only key can open and close positions and post collateral but cannot initiate withdrawals or transfers to external wallets. A read-only analytics key can query balances and transaction history but cannot initiate any on-chain action at all.

When an agent is compromised, least-privilege scoping dramatically limits the blast radius. A compromised trading-only key cannot drain the wallet — the worst it can do is open bad positions, which can be closed and recovered from.

Principle 4: Rate Limiting

An agent behaving normally will execute a predictable number of transactions per hour. An agent that has been manipulated or is experiencing a bug loop may attempt to execute hundreds of transactions in minutes. Cap transaction frequency per agent per time window as a safety net against both attacks and bugs.

Reasonable defaults for a trading agent: no more than 20 transactions per hour, no more than $5,000 total value moved per day, no more than 3 consecutive losing trades without a mandatory pause. These limits are configurable via the Purple Flea risk management API and can be tuned based on the agent's observed behavior in production.

Principle 5: Real-Time Monitoring and Alerts

Configure Purple Flea to send a webhook notification for every transaction your agent executes — not just the ones that fail. Pipe these events into a monitoring system that alerts a human if any of the following occur: a transaction to a previously unseen address, a single transaction exceeding 10% of total wallet value, more than 5 transactions in any 5-minute window, or a balance drop of more than 20% in any 1-hour period.

The monitoring stack does not need to be complex. A simple Python process that consumes Purple Flea transaction webhooks and sends a Telegram message for anomalous events is sufficient for most production agents. The key is that alerts are real-time, not batched daily reports that surface incidents after the damage is done.

Principle 6: Emergency Kill Switch

Every production agent must have an emergency pause mechanism that can be triggered by a human in under 30 seconds. When the kill switch is activated, the agent must immediately: stop accepting new instructions, cancel all open orders, stop all pending transactions, and send a status webhook to the operator confirming it has halted.

Do not make the kill switch part of the agent's own decision loop — that is what is being paused. The kill switch should be a separate endpoint, authenticated with a different credential from the agent's operational API key, that directly calls Purple Flea's agent suspension API.

Python: Configuring Security Controls via Purple Flea Access Control API

from purpleflea import AccessControlClient, RiskManagerClient

acl = AccessControlClient(api_key="pf_sk_admin_key_here")
risk = RiskManagerClient(api_key="pf_sk_admin_key_here")

# Create a scoped trading-only API key
trading_key = acl.create_scoped_key(
    agent_id="agent_trader_001",
    permissions=[
        "trading:open_position",
        "trading:close_position",
        "trading:post_collateral",
        "wallet:read_balance",
        "wallet:read_history",
    ],
    # Explicitly no withdrawal or transfer permissions
    label="trading-only-v1"
)

# Set up transaction whitelist
acl.set_whitelist(
    agent_id="agent_trader_001",
    allowed_addresses=[
        "0xPurpleFleasEscrowContractAddress",
        "0xYourTreasuryWalletAddress",
    ],
    require_approval_for_new=True,
    approval_delay_hours=24
)

# Configure rate limits and risk rules
risk.set_rules(
    agent_id="agent_trader_001",
    max_tx_per_hour=20,
    max_daily_value_usdc=5000.0,
    max_single_tx_usdc=1000.0,
    multisig_threshold_usdc=1000.0,
    consecutive_loss_pause=3,
    alert_webhook="https://your-monitor.com/alert"
)

print(f"Scoped key created: {trading_key['key_id']}")
print(f"Permissions: {trading_key['permissions']}")
print(f"Risk rules applied: {risk.get_rules('agent_trader_001')['rule_count']} rules active")

Incident Response: What to Do if an Agent Is Compromised

Act fast and in this exact order. First, trigger the kill switch to halt all agent activity. Second, revoke all active API keys associated with the agent — even if you are not sure which key was compromised, revoke all of them. Third, review the transaction log for the past 24 hours and identify any unauthorized transfers. Fourth, if funds have been moved, note the destination addresses and transaction hashes for chain analysis.

After containment, do a root cause analysis before reactivating the agent. Common causes: a prompt injection vulnerability in the agent's input processing, a compromised environment variable containing the API key, a malicious dependency in an npm or pip package, or a logic bug in the agent's decision loop that allowed an attacker-controlled input to override spending rules. Do not reactivate until the root cause is identified and patched.

from purpleflea import AccessControlClient, AgentRegistryClient
import logging

log = logging.getLogger("incident-response")

def emergency_shutdown(agent_id: str, admin_key: str):
    """
    Full emergency shutdown for a potentially compromised agent.
    Call this function the moment you suspect a compromise.
    """
    acl = AccessControlClient(api_key=admin_key)
    registry = AgentRegistryClient(api_key=admin_key)

    # Step 1: Suspend the agent (stops new instructions)
    registry.suspend(agent_id=agent_id, reason="security_incident")
    log.critical(f"[INCIDENT] Agent {agent_id} suspended")

    # Step 2: Revoke all active API keys for this agent
    keys = acl.list_keys(agent_id=agent_id, status="active")
    for key in keys:
        acl.revoke_key(key_id=key["key_id"])
        log.critical(f"[INCIDENT] Key {key['key_id']} revoked")

    # Step 3: Cancel all pending/open orders
    result = acl.cancel_all_pending(agent_id=agent_id)
    log.critical(f"[INCIDENT] {result['cancelled']} pending orders cancelled")

    # Step 4: Export last 24h transaction log for review
    tx_log = acl.export_transaction_log(agent_id=agent_id, hours=24)
    with open(f"incident_{agent_id}.json", "w") as f:
        import json; json.dump(tx_log, f, indent=2)

    log.critical(f"[INCIDENT] Shutdown complete. Review incident_{agent_id}.json")
    return {"status": "contained", "keys_revoked": len(keys), "orders_cancelled": result["cancelled"]}

Security is a feature, not a phase. These controls add maybe 2 hours of implementation time but are worth the effort from the first dollar of real funds. The Purple Flea access control and risk management APIs are included in all plans — there is no reason to skip them.

Conclusion

Autonomous agents handling real money require the same security discipline as any production financial system — with the added complexity that attackers can target the AI layer, not just the infrastructure layer. Whitelist addresses, scope API keys, rate-limit transactions, monitor in real time, and build your kill switch before you build anything else. The six principles in this guide are not theoretical best practices; they are the difference between an incident and a catastrophic loss.