DEV Community

Cover image for 7-Stage Transaction Validation: How AI Agents Execute Safe DeFi Operations
Wallet Guy
Wallet Guy

Posted on

7-Stage Transaction Validation: How AI Agents Execute Safe DeFi Operations

Giving an AI agent access to your DeFi portfolio without proper guardrails is like handing over your bank account with a sticky note saying "please be careful." Most wallet-as-a-service solutions either give agents unlimited access or rely on simple spending limits that don't account for the complexity of DeFi operations. WAIaaS takes a different approach with a 7-stage transaction pipeline that validates every operation through multiple security layers before execution.

Why Multi-Stage Validation Matters

DeFi operations carry amplified risks compared to simple transfers. When your AI agent interacts with lending protocols, DEXs, or yield farms, a single malicious or misconfigured transaction can:

  • Approve unlimited token spending to untrusted contracts
  • Deposit funds into high-risk lending pools
  • Execute leveraged positions beyond your risk tolerance
  • Interact with unaudited or compromised protocols

Traditional approaches either block AI agents entirely or use crude spending limits that don't distinguish between sending $100 to your friend versus approving $100 to an experimental DeFi protocol. WAIaaS recognizes that transaction amount alone doesn't determine risk—context matters.

The 7-Stage Transaction Pipeline

WAIaaS processes every transaction through seven sequential stages, each with specific validation logic and security checks. Here's how an AI agent's Jupiter swap request gets validated:

Stage 1: Validate

The pipeline first validates the transaction structure, network compatibility, and basic feasibility checks.

# Example: AI agent requests SOL → USDC swap
curl -X POST http://127.0.0.1:3100/v1/actions/jupiter-swap/swap \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "inputMint": "So11111111111111111111111111111111111111112",
    "outputMint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "amount": "1000000000"
  }'
Enter fullscreen mode Exit fullscreen mode

Stage 1 validates:

  • Transaction type matches expected schema (7 types: Transfer, TokenTransfer, ContractCall, Approve, Batch, NftTransfer, ContractDeploy)
  • Target network is active and RPC accessible
  • Basic parameter validation (addresses, amounts, gas estimates)

Stage 2: Authentication

Three authentication methods provide different security contexts:

# sessionAuth — AI agent operations (transactions, queries)
-H "Authorization: Bearer wai_sess_eyJhbGciOiJIUzI1NiJ9..."

# masterAuth — system administration (policies, wallet creation)
-H "X-Master-Password: my-secret-password"  

# ownerAuth — fund owner (approvals, emergency controls)
-H "X-Owner-Signature: <ed25519-or-secp256k1-signature>"
-H "X-Owner-Message: <signed-message>"
Enter fullscreen mode Exit fullscreen mode

Session tokens include TTL, renewal limits, and absolute lifetime bounds. The pipeline verifies the session is valid, not expired, and authorized for the requested operation.

Stage 3: Policy Engine

This is where WAIaaS's security model shines. The policy engine evaluates 21 different policy types against the transaction, assigning one of four security tiers:

# Create a comprehensive DeFi policy
curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 50,
      "notify_max_usd": 200,
      "delay_max_usd": 1000,
      "delay_seconds": 300,
      "daily_limit_usd": 2000
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Default-Deny Protection: The policy engine implements default-deny for critical operations. Without explicit ALLOWED_TOKENS and CONTRACT_WHITELIST policies, agents cannot transfer tokens or interact with smart contracts.

Four Security Tiers:

  • INSTANT: Execute immediately (low-risk operations under threshold)
  • NOTIFY: Execute immediately, send notification to owner
  • DELAY: Queue for time delay, owner can cancel during delay period
  • APPROVAL: Require explicit human approval before execution

For our Jupiter swap example, the policy engine checks:

  • SPENDING_LIMIT: Is 1 SOL under the appropriate tier threshold?
  • ALLOWED_TOKENS: Is SOL → USDC swap permitted?
  • CONTRACT_WHITELIST: Is Jupiter router address approved?
  • RATE_LIMIT: Has the agent exceeded transaction frequency limits?

Stage 4: Wait (Conditional)

If the policy engine assigns DELAY tier, the transaction enters a waiting period. During this time:

  • Transaction is queued with visible countdown timer
  • Owner receives notification with cancellation option
  • Agent receives pending status, not failure
  • Emergency kill switch can cancel all pending transactions
{
  "id": "tx_abc123",
  "status": "PENDING_DELAY",
  "delayUntil": "2024-03-15T10:35:00Z",
  "delaySeconds": 300,
  "cancellable": true
}
Enter fullscreen mode Exit fullscreen mode

Stage 5: Execute

For approved transactions, the execution stage handles the actual blockchain interaction:

  • Gas price conditional execution (wait for gas below threshold)
  • Nonce management and transaction ordering
  • Multi-chain RPC routing
  • Dry-run simulation before real execution

The pipeline supports complex transaction types including ERC-4337 Account Abstraction UserOps and batch transactions.

Stage 6: Confirm

Final stage monitors blockchain confirmation and updates transaction status:

  • Block confirmation tracking
  • Failed transaction detection and retry logic
  • Balance updates and cache invalidation
  • Notification dispatch for completed operations

Real-World Policy Configuration

Here's how to configure policies that make sense for AI agents operating in DeFi:

Token Whitelist (Required for Agent Operations):

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "ALLOWED_TOKENS",
    "rules": {
      "tokens": [
        {"address": "So11111111111111111111111111111111111111112", "symbol": "SOL", "chain": "solana"},
        {"address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "symbol": "USDC", "chain": "solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

DeFi Protocol Whitelist:

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "CONTRACT_WHITELIST", 
    "rules": {
      "contracts": [
        {"address": "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4", "name": "Jupiter", "chain": "solana"},
        {"address": "KLend2g3cP87fffoy8q1mQqGKjrxjC8boSyAYavgmjD", "name": "Kamino", "chain": "solana"}
      ]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Lending Risk Controls:

curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "LENDING_LTV_LIMIT",
    "rules": {
      "maxLtv": 0.65,
      "assetWhitelist": ["SOL", "USDC", "ETH"]
    }
  }'
Enter fullscreen mode Exit fullscreen mode

Security Through Multiple Layers

WAIaaS implements defense in depth through three distinct security layers:

Layer 1: Session Authentication + Time Limits

  • JWT session tokens with configurable TTL and renewal limits
  • Per-session absolute lifetime bounds
  • Immediate revocation capability

Layer 2: Policy Engine + Time Delays

  • 21 policy types covering spending, contracts, networks, DeFi parameters
  • Time delays allow human intervention before execution
  • Default-deny for undefined scenarios

Layer 3: Human Approval + Kill Switch

  • WalletConnect integration for mobile approval workflows
  • Telegram and push notification channels for approval requests
  • Emergency kill switch to halt all agent operations

Quick Start: Secure AI Agent Setup

Here's how to set up a DeFi-capable AI agent with proper security guardrails:

  1. Install and initialize WAIaaS:
npm install -g @waiaas/cli
waiaas init
waiaas start
Enter fullscreen mode Exit fullscreen mode
  1. Create wallet and session:
waiaas wallet create --name defi-agent --chain solana --environment mainnet
waiaas session prompt --wallet-name defi-agent
Enter fullscreen mode Exit fullscreen mode
  1. Configure security policies:
# Spending limits with 4-tier security
curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "SPENDING_LIMIT",
    "rules": {
      "instant_max_usd": 10,
      "notify_max_usd": 100, 
      "delay_max_usd": 500,
      "delay_seconds": 600,
      "daily_limit_usd": 1000
    }
  }'

# Allow specific tokens and protocols
curl -X POST http://localhost:3100/v1/policies \
  -H 'Content-Type: application/json' \
  -H 'X-Master-Password: <password>' \
  -d '{
    "walletId": "<wallet-uuid>",
    "type": "ALLOWED_TOKENS",
    "rules": {"tokens": [{"address": "So11111111111111111111111111111111111111112", "symbol": "SOL", "chain": "solana"}]}
  }'
Enter fullscreen mode Exit fullscreen mode
  1. Test the pipeline with a dry run:
curl -X POST http://127.0.0.1:3100/v1/transactions/send \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer wai_sess_<token>" \
  -d '{
    "type": "TRANSFER",
    "to": "recipient-address",
    "amount": "0.01",
    "dryRun": true
  }'
Enter fullscreen mode Exit fullscreen mode
  1. Set up approval channels for high-value transactions:
waiaas owner connect  # WalletConnect for mobile approvals
waiaas notification setup  # Configure push notifications
Enter fullscreen mode Exit fullscreen mode

The 7-stage pipeline ensures your AI agent operates within defined boundaries while maintaining the flexibility to execute complex DeFi strategies. Each stage provides specific validation logic, and the policy engine gives you granular control over risk parameters.

For developers building autonomous trading systems or yield optimization bots, this approach provides the security foundation needed to deploy AI agents with real funds. The pipeline processes over 683 test cases across all transaction types and DeFi protocols, ensuring robust validation of edge cases and attack vectors.

Related posts that dive deeper:

What's Next

The 7-stage transaction pipeline provides the security foundation, but WAIaaS offers additional capabilities for production AI agents including cross-chain bridging, NFT management, and x402 HTTP payment protocols. Explore the full codebase at GitHub or learn more about self-hosted deployment at waiaas.ai.

Top comments (0)