> ## Documentation Index
> Fetch the complete documentation index at: https://docs.swarms.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Crypto On-Chain Whale Tracker: Multi-Chain Movement Classification

> An AgentRearrange flow that watches the top 100 wallets across ETH, BTC, SOL, and Base every block, classifies every movement, and alerts before the chart catches up.

Every twelve seconds the largest wallets on four chains get classified — and an hour before the spot move shows up on a chart, your Slack already knows where the flow is going.

## What This Example Shows

* An `AgentRearrange` flow that runs four per-chain monitors (ETH, BTC, SOL, Base) in parallel, then a classifier and an alerter in sequence — one swarm call per block, every block
* MCP wiring for Alchemy / Infura / Helius RPC endpoints so each chain agent reads its native mempool and block stream directly
* Function tool schemas the classifier returns calls to for every whale tx: CEX inflow/outflow, OTC, DEX swap, or bridge — with wallet-label enrichment that your code executes (the API doesn't run custom function tools)
* Sustained polling rate-limit math: ETH block time of 12 seconds compounds to \~7,200 swarm calls/day, blowing through the Free tier's per-day cap after a few hours
* Real-time alert routing into Slack and Discord with severity scoring, including programmatic muting on quiet hours

> [!NOTE]
>
> Continuous block-by-block polling breaches the Free tier per-day cap within a few hours of running. Watch the `X-RateLimit-*` response headers (or poll `GET /v1/rate/limits`) so you catch a tightening window before you start dropping blocks to 429s. See the [Rate Limits documentation](https://docs.swarms.ai/docs/documentation/resources/ratelimits.md) before you flip this loop on in production.

## Why This Matters

Whale wallets historically lead the tape by 15 to 60 minutes — a \$40M wBTC pull off Coinbase Prime, a fresh deposit into a Binance OTC sub-account, a bridge from Base to Solana — these are the movements that show up on a price chart later as a green or red candle. The alpha is not in seeing the transaction (any block explorer does that). The alpha is in classifying it inside the same block: is this a market maker rebalancing, an OTC settlement that will hit spot in 20 minutes, or a known fund unwinding into a bridge? Sub-block latency on that classification — and the wallet label that makes it tradeable — is the entire edge. An `AgentRearrange` flow lets you process all four major L1/L2 chains in parallel in the same swarm call, so when the ETH monitor sees a whale deposit on block N, the classifier reads it alongside the Base monitor's bridge ack from the same call.

## The Architecture

```text theme={null}
                    ┌──────────────────────┐
                    │  Block Trigger Loop  │
                    │  (every 12 seconds)  │
                    └──────────┬───────────┘
                               │
                               ▼
        ┌──────────────────────────────────────────┐
        │     AgentRearrange (parallel step)       │
        │                                          │
        │  ┌────────┐  ┌────────┐  ┌────────┐  ┌────────┐
        │  │  ETH   │  │  BTC   │  │  SOL   │  │  Base  │
        │  │Monitor │  │Monitor │  │Monitor │  │Monitor │
        │  └───┬────┘  └───┬────┘  └───┬────┘  └───┬────┘
        └──────┼───────────┼───────────┼───────────┼─────┘
               │           │           │           │
               └───────────┴─────┬─────┴───────────┘
                                 ▼
                  ┌──────────────────────────┐
                  │   Movement Classifier    │
                  │      (xai/grok-4.3)        │
                  └──────────────┬───────────┘
                                 ▼
                  ┌──────────────────────────┐
                  │     Alert Generator      │
                  │   (claude-sonnet-5)      │
                  └──────────────┬───────────┘
                                 ▼
                  ┌──────────────────────────┐
                  │     Slack / Discord      │
                  └──────────────────────────┘
```

## Step 1: Setup

Install the dependencies and pull keys for Swarms, your RPC provider, an explorer for label lookups, and your alert webhook.

```bash theme={null}
pip install requests python-dotenv
export SWARMS_API_KEY="your-swarms-key"
export ALCHEMY_API_KEY="your-alchemy-key"
export ETHERSCAN_API_KEY="your-etherscan-key"
export SLACK_WEBHOOK_URL="https://hooks.slack.com/services/..."
```

```python theme={null}
import json
import os
import time

import requests
from dotenv import load_dotenv

load_dotenv()

API_KEY = os.getenv("SWARMS_API_KEY")
BASE_URL = "https://api.swarms.world"

headers = {"x-api-key": API_KEY, "Content-Type": "application/json"}
```

The four per-chain agents each point to a different MCP server via the `mcp_url` field on the agent config. The Alchemy SSE endpoint is the simplest path for ETH and Base; Helius covers Solana; an Esplora/mempool.space MCP covers BTC. You can run all four as separate containers or terminate them behind a single proxy — the swarm only cares about the URL.

```python theme={null}
MCP_URLS = {
    "ETH":  "https://your-alchemy-mcp.internal/eth/sse",
    "BTC":  "https://your-mempool-mcp.internal/btc/sse",
    "SOL":  "https://your-helius-mcp.internal/sol/sse",
    "BASE": "https://your-alchemy-mcp.internal/base/sse",
}
```

## Step 2: Define the Function Tools

Function tools are OpenAI-schema JSON. Define them once, attach them per-agent. The API sends these schemas to the model and returns the model's tool calls in the output; it does not execute them, and there is no way to feed a tool result back in the middle of a run. Fetch the data the agents need in your own code and put it in the task, and execute the returned calls after the run. The classifier and chain agents share the lookup tools; the alert generator only gets `post_whale_alert`.

```python theme={null}
FETCH_RECENT_BLOCK = {
    "type": "function",
    "function": {
        "name": "fetch_recent_block",
        "description": "Return the full block (header + transactions) for a given chain at a given block number.",
        "parameters": {
            "type": "object",
            "properties": {
                "chain": {
                    "type": "string",
                    "enum": ["ETH", "BTC", "SOL", "BASE"],
                },
                "block_number": {"type": "integer"},
            },
            "required": ["chain", "block_number"],
        },
    },
}

GET_WALLET_TRANSACTIONS = {
    "type": "function",
    "function": {
        "name": "get_wallet_transactions",
        "description": "Return all transactions involving a specific wallet address since a given block.",
        "parameters": {
            "type": "object",
            "properties": {
                "address": {"type": "string"},
                "since_block": {"type": "integer"},
            },
            "required": ["address", "since_block"],
        },
    },
}

LOOKUP_WALLET_LABEL = {
    "type": "function",
    "function": {
        "name": "lookup_wallet_label",
        "description": "Resolve a wallet address to a known label (e.g. 'Binance 14', 'Jump Trading', 'a16z fund 2', 'Wintermute OTC').",
        "parameters": {
            "type": "object",
            "properties": {"address": {"type": "string"}},
            "required": ["address"],
        },
    },
}

IS_CEX_ADDRESS = {
    "type": "function",
    "function": {
        "name": "is_cex_address",
        "description": "Return whether the address is a known centralized exchange hot or cold wallet, and which exchange.",
        "parameters": {
            "type": "object",
            "properties": {"address": {"type": "string"}},
            "required": ["address"],
        },
    },
}

CLASSIFY_MOVEMENT = {
    "type": "function",
    "function": {
        "name": "classify_movement",
        "description": "Classify a single transaction into one of: CEX_INFLOW, CEX_OUTFLOW, OTC_SETTLEMENT, DEX_SWAP, BRIDGE_OUT, BRIDGE_IN, WALLET_REBALANCE, UNKNOWN.",
        "parameters": {
            "type": "object",
            "properties": {
                "tx": {
                    "type": "object",
                    "description": "Raw transaction object including from, to, value, input data, and chain.",
                },
            },
            "required": ["tx"],
        },
    },
}

IS_DEX_SWAP = {
    "type": "function",
    "function": {
        "name": "is_dex_swap",
        "description": "Return whether a transaction's `to` field matches a known DEX router (Uniswap V2/V3/V4, Jupiter, Raydium, Aerodrome).",
        "parameters": {
            "type": "object",
            "properties": {
                "tx": {"type": "object"},
                "dex_routers": {
                    "type": "array",
                    "items": {"type": "string"},
                },
            },
            "required": ["tx", "dex_routers"],
        },
    },
}

IS_BRIDGE_TX = {
    "type": "function",
    "function": {
        "name": "is_bridge_tx",
        "description": "Return whether a transaction interacts with a known canonical bridge (Wormhole, LayerZero, Across, Stargate, Base bridge).",
        "parameters": {
            "type": "object",
            "properties": {
                "tx": {"type": "object"},
                "bridge_contracts": {
                    "type": "array",
                    "items": {"type": "string"},
                },
            },
            "required": ["tx", "bridge_contracts"],
        },
    },
}

POST_WHALE_ALERT = {
    "type": "function",
    "function": {
        "name": "post_whale_alert",
        "description": "Post a formatted whale alert to the configured Slack and Discord webhooks.",
        "parameters": {
            "type": "object",
            "properties": {
                "text": {"type": "string"},
                "severity": {
                    "type": "string",
                    "enum": ["INFO", "WATCH", "ALERT", "CRITICAL"],
                },
                "ticker": {"type": "string"},
            },
            "required": ["text", "severity", "ticker"],
        },
    },
}

CHAIN_TOOLS = [
    FETCH_RECENT_BLOCK,
    GET_WALLET_TRANSACTIONS,
    LOOKUP_WALLET_LABEL,
    IS_CEX_ADDRESS,
    IS_DEX_SWAP,
    IS_BRIDGE_TX,
]

CLASSIFIER_TOOLS = [CLASSIFY_MOVEMENT, LOOKUP_WALLET_LABEL, IS_CEX_ADDRESS]
ALERT_TOOLS = [POST_WHALE_ALERT]
```

## Step 3: Define the Concurrent Per-Chain Agents

Each chain monitor runs on `gpt-4.1-mini` — fast and cheap is the only thing that matters when you are firing this swarm every 12 seconds. The Movement Classifier runs on `xai/grok-4.3` for its real-time bias and willingness to commit to a classification under uncertainty. The Alert Generator runs on `claude-sonnet-5` because the natural-language quality of the Slack message is what makes the desk actually read it.

```python theme={null}
CHAIN_MONITOR_PROMPT = (
    "You are an on-chain whale monitor for {chain}. "
    "For the given block, pull the transactions involving any address in the "
    "top-100 whale list. For each tx, return a structured row with: "
    "from, to, value_native, value_usd_estimate, raw_input_summary. "
    "Use the available tools to enrich with wallet labels and CEX/bridge/DEX flags. "
    "Output strict JSON. Do not editorialize. Speed matters — your output feeds the classifier "
    "in the same swarm call."
)

MOVEMENT_CLASSIFIER_PROMPT = (
    "You are the Movement Classifier. You receive per-chain whale tx rows from four monitors "
    "running concurrently. For each row, call classify_movement and assign one of: "
    "CEX_INFLOW, CEX_OUTFLOW, OTC_SETTLEMENT, DEX_SWAP, BRIDGE_OUT, BRIDGE_IN, "
    "WALLET_REBALANCE, UNKNOWN. "
    "Cross-correlate across chains — a BRIDGE_OUT on ETH and a matching BRIDGE_IN on BASE "
    "in the same swarm window should be linked. Output strict JSON, one row per movement. "
    "Bias toward committing — UNKNOWN is the last resort."
)

ALERT_GENERATOR_PROMPT = (
    "You are the Alert Generator. You receive classified whale movements from the Movement "
    "Classifier. For each one, decide severity (INFO/WATCH/ALERT/CRITICAL) based on "
    "value_usd, target_label, and movement_type. Write a one-line, desk-readable Slack message "
    "in this style: "
    "':whale: ALERT — 1,250 BTC moved from Tether Treasury 7 to Binance 14 (~$92M, BRIDGE_IN, block 879314)'. "
    "Then call post_whale_alert. Be precise, be brief, never speculate on price impact."
)


def build_whale_swarm(block_targets: dict[str, int]) -> dict:
    """block_targets maps chain → block number to inspect, e.g. {'ETH': 21000123, ...}"""

    chain_agents = []
    for chain, block_num in block_targets.items():
        chain_agents.append({
            "agent_name": f"{chain} Whale Monitor",
            "description": f"Pulls whale-relevant transactions on {chain} for a specific block.",
            "system_prompt": CHAIN_MONITOR_PROMPT.format(chain=chain),
            "model_name": "gpt-4.1-mini",
            "role": "worker",
            "max_loops": 1,
            "max_tokens": 4096,
            "temperature": 0.1,
            "tools_list_dictionary": CHAIN_TOOLS,
            "mcp_url": MCP_URLS[chain],
        })

    classifier = {
        "agent_name": "Movement Classifier",
        "description": "Classifies whale movements across chains in real time.",
        "system_prompt": MOVEMENT_CLASSIFIER_PROMPT,
        "model_name": "xai/grok-4.3",
        "role": "worker",
        "max_loops": 1,
        "max_tokens": 6144,
        "temperature": 0.2,
        "tools_list_dictionary": CLASSIFIER_TOOLS,
    }

    alert_generator = {
        "agent_name": "Alert Generator",
        "description": "Writes severity-scored Slack/Discord alerts.",
        "system_prompt": ALERT_GENERATOR_PROMPT,
        "model_name": "claude-sonnet-5",
        "role": "worker",
        "max_loops": 1,
        "max_tokens": 2048,
        "temperature": 0.3,
        "tools_list_dictionary": ALERT_TOOLS,
    }

    return {
        "name": "On-Chain Whale Tracker",
        "description": "Per-chain concurrent monitors → classifier → alerter, one swarm call per block.",
        "swarm_type": "AgentRearrange",
        "rearrange_flow": (
            ", ".join(agent["agent_name"] for agent in chain_agents)
            + " -> Movement Classifier -> Alert Generator"
        ),
        "max_loops": 1,
        "task": (
            "For the given block on each chain, identify and classify every whale-relevant "
            "transaction and emit structured alerts. Block targets: "
            + json.dumps(block_targets)
        ),
        "agents": chain_agents + [classifier, alert_generator],
    }
```

> [!NOTE]
>
> The `rearrange_flow` puts the four chain monitors in one comma-separated step, so they run in parallel, then hands their outputs to the Movement Classifier and its output to the Alert Generator (`->`). Use `AgentRearrange` rather than `ConcurrentWorkflow` here: a `ConcurrentWorkflow` sends the raw task to every agent at once, so a classifier in it would never see the monitors' outputs. Swarms can't be nested inside one another either, since `agents` only takes agent specs.

## Step 4: Process One Block End-to-End

Before flipping on the watcher, pin to a known block on each chain and dry-run the swarm. This validates MCP wiring, tool schemas, and the classifier's commitment behavior on a static input.

```python theme={null}
def run_one_block(block_targets: dict[str, int]) -> dict:
    payload = build_whale_swarm(block_targets)
    response = requests.post(
        f"{BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=payload,
        timeout=180,
    )
    response.raise_for_status()
    return response.json()


# Replay a known whale block
result = run_one_block({
    "ETH":  21000123,
    "BTC":  879314,
    "SOL":  301288010,
    "BASE": 22001456,
})

for output in result.get("output", []):
    print("=" * 60)
    print(output["role"])
    print("=" * 60)
    content = output["content"]
    if isinstance(content, list):
        content = " ".join(str(c) for c in content)
    print(str(content)[:600])

print(f"\nSwarm cost: ${result['usage']['billing_info']['total_cost']:.4f}")
print(f"Wall time:  {result['execution_time']:.2f}s")
```

If wall time on the replay exceeds ETH block time (12 seconds), you have a latency problem and the watcher will fall behind under live load. Lower `max_tokens` on the chain monitors and tighten the classifier prompt before going live.

## Step 5: The Continuous Block Watcher

This is the loop that bills. Every \~12 seconds — ETH block time, the slowest of the four — fire a fresh swarm against the latest block on each chain.

```python theme={null}
def get_latest_blocks() -> dict[str, int]:
    """Return the most recent block number on each chain via your RPC layer."""
    # Implementation depends on your RPC client; sketch:
    return {
        "ETH":  rpc_eth.block_number(),
        "BTC":  rpc_btc.block_height(),
        "SOL":  rpc_sol.slot(),
        "BASE": rpc_base.block_number(),
    }


def fire_swarm(block_targets: dict[str, int]) -> None:
    payload = build_whale_swarm(block_targets)
    requests.post(
        f"{BASE_URL}/v1/swarm/completions",
        headers=headers,
        json=payload,
        timeout=60,
    )


def whale_watcher_loop() -> None:
    last_seen = {"ETH": 0, "BTC": 0, "SOL": 0, "BASE": 0}
    while True:
        latest = get_latest_blocks()
        # Only fire if at least one chain has advanced
        if any(latest[c] > last_seen[c] for c in latest):
            fire_swarm(latest)
            last_seen = latest
        time.sleep(12)  # ETH block time pacing


if __name__ == "__main__":
    whale_watcher_loop()
```

The math is brutal:

* 12-second cadence → **300 calls/hour**, **7,200 calls/day**
* Free tier caps are **100/minute**, **350/hour**, **1,200/day** — the per-day cap is breached in **4 hours**
* Paid tiers (Pro, Ultra, Premium) share **2,000/minute**, **10,000/hour**, **100,000/day**, which holds this loop
* Watch `X-RateLimit-Remaining-*` on every response (or poll `GET /v1/rate/limits`) so you can back off before a 429 costs you a block

> [!NOTE]
>
> Live whale tracking is a Premium workload by construction. If you try to run this loop on Free you will hit 429s and miss blocks once the per-day cap is exhausted. See [Rate Limits](https://docs.swarms.ai/docs/documentation/resources/ratelimits.md) for the per-tier numbers and upgrade at [https://cloud.swarms.world/settings](https://cloud.swarms.world/settings).

## Step 6: The Alert Output Schema

The Alert Generator emits structured rows alongside the Slack post — persist these to your warehouse so you can correlate alerts against spot moves later and grade the classifier.

```json theme={null}
{
  "chain": "ETH",
  "block": 21000123,
  "whale_address": "0xab5801a7d398351b8be11c439e05c5b3259aec9b",
  "movement_type": "CEX_INFLOW",
  "value_usd": 92400000,
  "target_address": "0x28c6c06298d514db089934071355e5743bf21d60",
  "target_label": "Binance 14",
  "severity": "CRITICAL",
  "narrative": "1,250 BTC moved from a long-dormant cold wallet to Binance hot wallet 14 (~$92M). Last activity on source wallet: 187 days ago."
}
```

A simple persistence pattern:

```python theme={null}
def persist_alerts(swarm_response: dict, path: str = "whale_alerts.jsonl") -> None:
    alerts_block = next(
        (o["content"] for o in swarm_response.get("output", []) if "Alert Generator" in o.get("role", "")),
        None,
    )
    if not alerts_block:
        return
    if isinstance(alerts_block, list):
        alerts_block = " ".join(str(c) for c in alerts_block)
    # Alerts arrive as JSON lines from the Alert Generator
    with open(path, "a") as f:
        for line in str(alerts_block).splitlines():
            line = line.strip()
            if line.startswith("{") and line.endswith("}"):
                f.write(line + "\n")
```

## Real Cost vs. Whale Alert Service Subscriptions

| Stack | Monthly cost | What you actually get |
| - | - | - |
| **This stack** (gpt-4.1-mini chains + xai/grok-4.3 classifier + sonnet-5 alerter, night-mode discount applied automatically 8pm–6am Pacific on a paid plan) | **\~\$750/mo** (\~\$25/day) | Programmable layer you own, four chains, custom whale list, structured outputs to your warehouse |
| Retail whale-alert Twitter / Telegram services | \$50 – \$500/mo | Read-only Twitter feed, no classification, no programmatic access |
| Nansen Alpha (single chain) | \$1,500/mo | Best-in-class labels, read-only dashboard, no programmable layer |
| Arkham Intelligence Pro | \$1,000/mo | Strong labels, dashboard + alerts, no per-block classification |
| Building this in-house with engineers | \$40,000+/mo | One mid backend + one ML engineer plus infra; what you would actually do without this |

Night-mode tip: on a paid plan (tier `pro`, `premium` or `ultra`, or an active subscription), the API applies its off-peak 50% token-cost discount to swarm completions automatically between 8pm and 6am Pacific (`America/Los_Angeles`) — no request changes needed. Free accounts pay the full token price at any hour. Separately, most chains are quieter in the early-UTC-morning hours; if you want to cut call volume too (not just get the automatic discount), drop the watcher to a 60-second cadence during that quiet window.

The point is not that this is cheaper than a Twitter bot. The point is that a Twitter bot is read-only. This is a programmable layer with structured outputs that route into your own systems — execution, risk, research database — at whale-feed latency.

## Next Steps

* See [Crypto Quant Agent](https://docs.swarms.ai/docs/examples/examples/crypto-quant-agent.md) for the single-agent quant analyst that consumes these alerts as a signal stream
* See [AI Hedge Fund Research Pipeline](https://docs.swarms.ai/docs/examples/examples/ai-hedge-fund.md) for the hierarchical pattern when you want a PM agent grading the whale alerts against a fundamental thesis
* Read [MCP Integration](https://docs.swarms.ai/docs/documentation/capabilities/mcp_integration.md) for the full Alchemy / Helius / mempool MCP wiring
* Check [Rate Limits](https://docs.swarms.ai/docs/documentation/resources/ratelimits.md) before going live — the per-tier caps decide what cadence you can sustain


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.