DEV Community

Paarthurnax
Paarthurnax

Posted on

DeFi Agent for Beginners: Monitor Your Wallet with OpenClaw

DeFi Agent for Beginners: Monitor Your Wallet with OpenClaw

Decentralized Finance (DeFi) moves fast. Liquidity positions shift, yields change, and opportunities appear and disappear in hours. If you're manually checking your DeFi positions, you're already behind.

This guide shows you how to build a wallet monitoring agent using OpenClaw — no prior DeFi experience required.


What This Agent Does

  • Watches your wallet address for balance changes
  • Alerts you when token prices move significantly
  • Logs all position data to a local database
  • Runs on your machine — no cloud, no subscription

What You'll Need

  • OpenClaw installed (free, local)
  • A wallet address (no private keys needed — read-only monitoring)
  • Python 3.9+

You do not need to connect your wallet or expose any private keys. This agent is read-only.


Step 1: Choose Your Chain

Different blockchains have different free APIs:

Chain Free API
Ethereum Etherscan.io
Polygon Polygonscan.com
BSC BscScan.com
Base Basescan.org

All of these offer free API keys with generous limits (5 req/sec, 100k/day).

For this example, we'll use Ethereum via Etherscan.


Step 2: Get an Etherscan API Key

  1. Sign up at etherscan.io
  2. Go to My Profile → API Keys
  3. Create a new key — it's free and instant

Step 3: Build the Wallet Monitor

import requests
import json
import time
from datetime import datetime

ETHERSCAN_KEY = "your_etherscan_api_key"
WALLET = "0xYourWalletAddressHere"
BASE_URL = "https://api.etherscan.io/api"

def get_eth_balance(address: str) -> float:
    """Get ETH balance for an address."""
    params = {
        "module": "account",
        "action": "balance",
        "address": address,
        "tag": "latest",
        "apikey": ETHERSCAN_KEY
    }
    r = requests.get(BASE_URL, params=params)
    data = r.json()
    if data["status"] == "1":
        wei = int(data["result"])
        return wei / 1e18  # Convert Wei to ETH
    return 0.0

def get_token_balances(address: str) -> list:
    """Get ERC-20 token balances."""
    params = {
        "module": "account",
        "action": "tokentx",
        "address": address,
        "startblock": 0,
        "endblock": 99999999,
        "sort": "desc",
        "apikey": ETHERSCAN_KEY
    }
    r = requests.get(BASE_URL, params=params)
    data = r.json()

    # Track unique tokens seen in recent transactions
    tokens = {}
    if data["status"] == "1":
        for tx in data["result"][:50]:  # Last 50 token transactions
            symbol = tx["tokenSymbol"]
            name = tx["tokenName"]
            if symbol not in tokens:
                tokens[symbol] = name
    return list(tokens.items())

def get_recent_transactions(address: str, limit: int = 10) -> list:
    """Get recent ETH transactions."""
    params = {
        "module": "account",
        "action": "txlist",
        "address": address,
        "startblock": 0,
        "endblock": 99999999,
        "page": 1,
        "offset": limit,
        "sort": "desc",
        "apikey": ETHERSCAN_KEY
    }
    r = requests.get(BASE_URL, params=params)
    data = r.json()

    txs = []
    if data["status"] == "1":
        for tx in data["result"]:
            txs.append({
                "hash": tx["hash"][:10] + "...",
                "from": tx["from"],
                "to": tx["to"],
                "value_eth": int(tx["value"]) / 1e18,
                "timestamp": datetime.fromtimestamp(int(tx["timeStamp"])).strftime("%Y-%m-%d %H:%M")
            })
    return txs

# Run a snapshot
print(f"Monitoring wallet: {WALLET[:10]}...{WALLET[-6:]}")
print(f"\nETH Balance: {get_eth_balance(WALLET):.4f} ETH")

print("\nRecent token activity:")
for symbol, name in get_token_balances(WALLET):
    print(f"  - {symbol} ({name})")

print("\nLast 5 transactions:")
for tx in get_recent_transactions(WALLET, 5):
    print(f"  {tx['timestamp']} | {tx['value_eth']:.4f} ETH | {tx['hash']}")
Enter fullscreen mode Exit fullscreen mode

Step 4: Add Change Detection

Track balances over time and alert on changes:

import json
from pathlib import Path

SNAPSHOT_FILE = Path("dragonsoul/wallet_snapshot.json")

def load_snapshot() -> dict:
    if SNAPSHOT_FILE.exists():
        return json.loads(SNAPSHOT_FILE.read_text())
    return {}

def save_snapshot(data: dict):
    SNAPSHOT_FILE.parent.mkdir(exist_ok=True)
    SNAPSHOT_FILE.write_text(json.dumps(data, indent=2))

def check_for_changes(current_eth: float, previous_eth: float) -> str:
    if previous_eth == 0:
        return "First snapshot recorded."

    diff = current_eth - previous_eth
    pct = (diff / previous_eth) * 100

    if abs(diff) > 0.001:  # Only alert on meaningful changes
        direction = "increased" if diff > 0 else "decreased"
        return f"ETH balance {direction} by {abs(diff):.4f} ETH ({pct:+.2f}%)"
    return None

# Monitor loop
while True:
    snapshot = load_snapshot()
    current_eth = get_eth_balance(WALLET)
    previous_eth = snapshot.get("eth_balance", 0)

    change_msg = check_for_changes(current_eth, previous_eth)
    if change_msg:
        print(f"[ALERT] {change_msg}")
        # Send to Telegram here if configured

    save_snapshot({"eth_balance": current_eth, "updated": datetime.now().isoformat()})
    time.sleep(300)  # Check every 5 minutes
Enter fullscreen mode Exit fullscreen mode

Step 5: Connect to OpenClaw

OpenClaw's felix_loop.py can run your wallet monitor as part of its main cycle:

# Add to felix_loop.py
def run_wallet_monitor():
    """Check DeFi wallet status."""
    try:
        eth = get_eth_balance(WALLET)
        snapshot = load_snapshot()
        change = check_for_changes(eth, snapshot.get("eth_balance", 0))
        if change:
            db.think(f"Wallet alert: {change}", "defi")
        save_snapshot({"eth_balance": eth, "updated": datetime.now().isoformat()})
    except Exception as e:
        db.error(f"Wallet monitor error: {e}")
Enter fullscreen mode Exit fullscreen mode

DeFi-Specific Monitoring Ideas

Once the basics work, you can expand to:

  • Gas price tracking — Alert when gas drops below a threshold for cheap transactions
  • Yield farming positions — Monitor Aave, Compound, or Uniswap positions
  • Liquidation risk — Track health factors on lending protocols
  • Wallet labeling — Tag known whale wallets and alert when they move

Privacy and Security Notes

  • This agent only reads public blockchain data — no private keys ever needed
  • Your wallet address is public by nature; this is safe to use
  • All data is stored locally in your dragonsoul/ folder
  • Never put private keys in any script file

Get the Full Setup

The complete DeFi monitoring agent with Telegram alerts, OpenClaw integration, and multi-chain support is available at dragonwhisper36.gumroad.com. One download, runs locally, no ongoing costs.

Top comments (0)