Building a DeFi Swarm: A Practical Architecture

Theory becomes real when you build something. Here's how EchoRift infrastructure comes together for a concrete use case: a DeFi trading swarm.

This isn't a tutorial. It's an architecture walkthrough—how the pieces fit, what each service does, where coordination matters.

The Swarm's Purpose

A group of specialized agents that collectively:

  • Monitor DeFi opportunities across Base
  • Analyze profitability and risk
  • Execute trades when conditions are favorable
  • Manage a shared treasury with spending controls
  • Avoid stepping on each other

No single agent does everything. Each specializes. The swarm coordinates.

The Agents

Scout agents watch the market. They monitor new pools, liquidity changes, price movements. They don't trade—they report.

Analyst agents evaluate opportunities. They receive reports from scouts, calculate expected value, assess risk. They don't trade—they recommend.

Executor agents take action. They receive recommendations, check viability, execute trades. They're the only agents that touch the treasury.

Guardian agents watch for problems. Unusual patterns, safety threshold breaches, anomalous behavior. They can trigger halts.

Four roles, potentially many agents per role. The swarm scales by adding agents to roles that need more capacity.

Swarm Setup

First, create the swarm via Switchboard:


                {
                  "swarm_id": "defi-alpha",
                  "owner_address": "0xOWNER",
                  "membership_policy": {
                    "mode": "allowlist",
                    "allowed_agents": ["0xScout1", "0xScout2", "0xAnalyst1", ...]
                  },
                  "payment_settings": {
                    "auto_pay_x402": true,
                    "daily_limit": "500.00",
                    "monthly_limit": "5000.00"
                  }
                }
                

The allowlist restricts membership. Only approved agents can participate. Payment settings cap spending—even if an executor goes rogue, damage is limited.

Scout Architecture

Scout agents use BlockWire for perception:

Subscriptions:

  • `new_contract` — spot new pools and protocols
  • `liquidity_added` — identify deepening markets
  • `price_movement` — catch significant price action

When BlockWire delivers an event, the scout:

  1. Receives webhook with HMAC signature
  2. Validates signature
  3. Enriches the event (query additional on-chain data if needed)
  4. Creates a Switchboard task for analyst review

                {
                  "type": "opportunity_review",
                  "priority": "normal",
                  "data": {
                    "event_type": "liquidity_added",
                    "pool": "0xPOOL",
                    "token_pair": ["WETH", "USDC"],
                    "amount": "150000.00",
                    "discovered_at": 1701433200
                  }
                }
                

Scouts don't analyze. They observe and report. The analyst queue fills with opportunities.

Analyst Architecture

Analyst agents claim tasks from the queue:


                POST /swarms/defi-alpha/tasks/{task_id}/claim
                

Atomic claim ensures no two analysts review the same opportunity. Whoever claims first owns it.

The analyst then:

  1. Retrieves full opportunity data from task payload
  2. Queries on-chain state for current prices, liquidity
  3. Runs profitability model (this is where the agent's intelligence lives)
  4. Calculates expected value, risk score, confidence

If the opportunity looks good, the analyst creates an execution task:


                {
                  "type": "execute_trade",
                  "priority": "high",
                  "data": {
                    "action": "swap",
                    "pool": "0xPOOL",
                    "token_in": "USDC",
                    "token_out": "WETH",
                    "amount_in": "10000.00",
                    "min_amount_out": "5.25",
                    "deadline": 1701434200,
                    "expected_profit": "45.00",
                    "risk_score": 0.15
                  }
                }
                

If the opportunity isn't worth pursuing, the analyst marks the original task complete without creating an execution task.

Either way, the analyst broadcasts a summary:


                {
                  "type": "analysis_complete",
                  "opportunity_id": "task_abc123",
                  "verdict": "execute",
                  "expected_profit": "45.00"
                }
                

Other agents (especially guardians) can monitor the broadcast stream to understand swarm activity.

Executor Architecture

Executor agents watch for high-priority execution tasks:


                GET /swarms/defi-alpha/tasks?status=queued&type=execute_trade
                

When an execution task appears, the executor:

  1. Claims the task
  2. Validates the trade is still viable (prices may have moved)
  3. If still good: requests payment authorization via Switchboard treasury
  4. Executes the on-chain transaction
  5. Reports outcome

The critical part: treasury interaction.


                POST /swarms/defi-alpha/payments/initiate
                {
                  "agent_id": "0xExecutor1",
                  "payment_reference": "trade_xyz",
                  "amount": "10000.00",
                  "resource_url": "internal://defi-alpha/trade"
                }
                

Switchboard validates:

  • Is this agent authorized to spend?
  • Is the amount within daily/monthly limits?
  • Is the treasury balance sufficient?

If validation passes, the payment proceeds. If any check fails, the executor can't spend.

This is the safety layer. Executors can request payments; they can't bypass limits.

After execution, the executor updates shared state:


                {
                  "trades_today": {
                    "value": "15",
                    "version": 44
                  },
                  "total_profit_today": {
                    "value": "127.50",
                    "version": 33
                  }
                }
                

Optimistic locking ensures concurrent updates don't corrupt state.

Guardian Architecture

Guardian agents don't participate in the trading flow. They watch.

What they monitor:

Via Switchboard events:

  • Unusual task creation rates (is someone spamming the queue?)
  • Rapid payment requests (spending spike?)
  • Error patterns (are executions failing?)

Via shared state:

  • Running profit/loss
  • Trade count thresholds
  • Risk accumulation

Via BlockWire:

  • Large transfers from treasury address
  • Unusual on-chain patterns

What they can do:

If patterns exceed thresholds, guardians can:

  1. Broadcast alerts:
  2. 
                    {
                      "type": "guardian_alert",
                      "severity": "high",
                      "message": "Spending velocity 3x normal. Review recommended."
                    }
                    
  1. Trigger circuit breaker:
  2. 
                    POST /swarms/defi-alpha/circuit-breaker
                    

The circuit breaker halts operations. No new tasks are processed. Executors stop spending. The swarm pauses until the issue is resolved.

  1. Initiate governance:

For serious issues, a guardian can create an Arbiter proposal:


                {
                  "title": "Pause swarm operations for 24 hours",
                  "description": "Unusual activity detected. Requesting swarm pause for investigation.",
                  "options": ["approve", "reject"],
                  "votingPeriodSeconds": 1800
                }
                

Swarm members vote. If approved, the pause is formalized.

Time Coordination

CronSynth handles scheduled activities:

Scouts: Maybe no scheduling needed—they react to BlockWire events.

Analysts: Might schedule periodic portfolio review even without new events.

Executors: Might schedule regular position rebalancing.

Guardians: Definitely schedule health checks and reconciliation.

Example guardian schedule:


                {
                  "webhook": "https://guardian1.example.com/scheduled-check",
                  "cron": "0 * * * *",
                  "description": "Hourly health check"
                }
                

Every hour, CronSynth triggers the guardian. The guardian reviews recent activity, checks thresholds, reports status.

Leadership for External Actions

Some actions require a spokesperson. Opening positions on external protocols. Interacting with DAOs. Representing the swarm.

Arbiter provides leader election:


                POST /election/trigger
                {
                  "swarmId": "defi-alpha"
                }
                

Executors (or designated representatives) vote. A leader is elected. The leader's authority is recorded on-chain.

External protocols can verify: "Is this agent authorized to act for this swarm?" The on-chain record provides the answer.

Leader terms are time-limited. New elections happen regularly. No permanent concentration of authority.

What Makes This Work

The architecture works because:

Clear separation of concerns. Scouts scout. Analysts analyze. Executors execute. Guardians guard. No agent does everything.

Atomic task claiming. Work doesn't get duplicated. One agent per opportunity.

Treasury controls. Executors can spend, but limits are enforced at the infrastructure level.

Circuit breakers. Problems trigger automatic halts, not escalating disasters.

Transparent activity. Broadcasts let every agent see what's happening. No hidden state.

Verifiable decisions. On-chain attestations prove what happened. Disputes have evidence.

Remove any of these, and the swarm becomes fragile. Include all of them, and the swarm is resilient.

What This Doesn't Cover

This architecture describes coordination. It doesn't describe:

Agent intelligence. What makes analysts good at analyzing? What models do they use? That's the agent's internal logic, not infrastructure.

Deployment. Where do these agents run? How are they managed? That's operations.

Key management. How do agents hold signing keys securely? That's security infrastructure.

MEV protection. How do executions avoid front-running? That's transaction-level concern.

EchoRift is coordination infrastructure. It's one layer in a full system. Essential, but not everything.


Part of the EchoRift infrastructure series.