⚡ Built for Alchemy Developers

Add Financial Infrastructure
to Your Alchemy-Powered Agent

Alchemy gives your agent eyes on the blockchain. Purple Flea gives it hands. Trade, gamble, hold custody, and settle payments — all via API.

Two layers, one powerful agent

Alchemy handles blockchain reads — RPCs, webhooks, NFT metadata, token transfers. Purple Flea handles financial actions — executing trades, managing custody, running casino sessions, settling trustless payments. These two platforms are perfectly complementary.

Alchemy

Blockchain Infrastructure Layer
🔗
Enhanced APIs (RPC) Read chain state, call contracts, query balances on any EVM chain
🔔
Webhooks / Notify Get push notifications on address activity, mempool events, token transfers
🖼️
NFT API Query NFT ownership, metadata, collection floor prices
📊
Token & Transfer API Historical transfers, token prices, portfolio snapshots
Gas Manager Sponsor gas for your agent's on-chain transactions

Purple Flea

Financial Operations Layer
📈
Trading API Perpetual futures, spot, orderbooks, one-click execution for agents
👛
Wallet Custody Multi-chain wallet creation, deposits, withdrawals, balances via REST
🎰
Casino API Provably fair crash, coin flip, slots — full programmatic access for agents
🔒
Escrow Service Trustless agent-to-agent payments, 1% fee, 15% referral commission
🚰
Faucet (Free $1 USDC) New agents claim $1 USDC to try the casino — zero-cost onboarding

🔵 Use Alchemy to…

  • Monitor on-chain price feeds and oracles
  • Detect large whale wallet movements via webhooks
  • Fetch NFT floor prices and collection metadata
  • Query ERC-20 token balances across multiple chains
  • Track historical transfer data for strategy backtesting
  • Sponsor gas fees with the Gas Manager API

🟣 Use Purple Flea to…

  • Execute perp and spot trades based on Alchemy signals
  • Hold USD custody in a managed wallet with REST access
  • Run casino strategies (crash, coin flip, slots)
  • Send trustless payments to other agents via escrow
  • Claim free $1 USDC for new agent onboarding
  • Earn referral fees by routing other agents to Purple Flea

Alchemy webhooks → Purple Flea trade trigger

The most powerful pattern: use Alchemy's Notify webhooks to detect on-chain signals, then fire Purple Flea trades immediately. Here's a complete Python FastAPI server that does exactly that.

Python · FastAPI
# alchemy_webhook_trader.py
# Alchemy Notify webhook → Purple Flea trade execution

from fastapi import FastAPI, Request, HTTPException
import httpx, hmac, hashlib, os, json
from typing import Optional

app = FastAPI()

# Config
ALCHEMY_SIGNING_KEY = os.environ["ALCHEMY_SIGNING_KEY"]
PF_API_KEY          = os.environ["PF_API_KEY"]
PF_TRADING_BASE     = "https://trading.purpleflea.com/api/v1"

def verify_alchemy_signature(body: bytes, sig_header: str) -> bool:
    """Verify Alchemy webhook HMAC-SHA256 signature."""
    expected = hmac.new(
        ALCHEMY_SIGNING_KEY.encode(),
        body,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, sig_header)


async def place_pf_order(
    symbol: str,
    side: str,
    size_usdc: float,
    leverage: float = 1.0
) -> dict:
    """Execute a trade on Purple Flea Trading API."""
    async with httpx.AsyncClient(timeout=10) as client:
        resp = await client.post(
            f"{PF_TRADING_BASE}/orders",
            headers={"X-Api-Key": PF_API_KEY},
            json={
                "symbol": symbol,
                "side": side,          # "buy" or "sell"
                "size_usdc": size_usdc,
                "leverage": leverage,
                "order_type": "market"
            }
        )
        resp.raise_for_status()
        return resp.json()


async def check_alchemy_balance(address: str, token: str = "USDC") -> float:
    """Use Alchemy Token API to read on-chain balance."""
    async with httpx.AsyncClient() as client:
        # Alchemy Enhanced API - getTokenBalances
        resp = await client.post(
            f"https://eth-mainnet.g.alchemy.com/v2/{os.environ['ALCHEMY_API_KEY']}",
            json={
                "id": 1,
                "jsonrpc": "2.0",
                "method": "alchemy_getTokenBalances",
                "params": [address, "erc20"]
            }
        )
        result = resp.json().get("result", {})
        return float(result.get("tokenBalances", [{}])[0].get("tokenBalance", 0)) / 1e6


@app.post("/webhook/alchemy")
async def alchemy_webhook(request: Request):
    """
    Alchemy Notify webhook handler.
    Configure this URL in Alchemy dashboard under Webhooks → Address Activity.
    """
    body = await request.body()
    sig  = request.headers.get("X-Alchemy-Signature", "")

    if not verify_alchemy_signature(body, sig):
        raise HTTPException(status_code=401, detail="Invalid signature")

    payload = json.loads(body)
    event   = payload.get("event", {})
    activity = event.get("activity", [])

    for tx in activity:
        asset    = tx.get("asset", "")
        value    = tx.get("value", 0)
        category = tx.get("category", "")

        # Signal: Large USDC inflow (> $10k) to watched address → go long BTC
        if asset == "USDC" and value > 10_000 and category == "token":
            order = await place_pf_order(
                symbol="BTC-PERP",
                side="buy",
                size_usdc=500,
                leverage=2.0
            )
            print(f"[TRADE] Alchemy signal → PF order: {order}")

    return {"ok": True}


# Run: uvicorn alchemy_webhook_trader:app --host 0.0.0.0 --port 8080

Purple Flea custody + Alchemy balance checks

Create your agent's wallet on Purple Flea for custody and spending. Use Alchemy for real-time on-chain balance verification and multi-chain portfolio reads.

Python · Wallet + Balance
import httpx, asyncio

PF_API_KEY   = "your-pf-api-key"
ALCHEMY_KEY  = "your-alchemy-api-key"
PF_WALLET    = "https://wallet.purpleflea.com/api/v1"
ALCHEMY_RPC  = f"https://eth-mainnet.g.alchemy.com/v2/{ALCHEMY_KEY}"

async def create_pf_wallet(agent_id: str) -> dict:
    """Create a managed wallet on Purple Flea."""
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            f"{PF_WALLET}/wallets",
            headers={"X-Api-Key": PF_API_KEY},
            json={"agent_id": agent_id, "chain": "ethereum"}
        )
        return resp.json()  # { address, wallet_id, ... }

async def get_pf_balance(wallet_id: str) -> dict:
    """Get managed balance from Purple Flea wallet."""
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"{PF_WALLET}/wallets/{wallet_id}/balance",
            headers={"X-Api-Key": PF_API_KEY}
        )
        return resp.json()

async def get_onchain_balance_alchemy(address: str) -> float:
    """
    Cross-check on-chain ETH balance via Alchemy.
    Useful for verifying deposits settled on-chain.
    """
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            ALCHEMY_RPC,
            json={
                "id": 1,
                "jsonrpc": "2.0",
                "method": "eth_getBalance",
                "params": [address, "latest"]
            }
        )
        wei = int(resp.json()["result"], 16)
        return wei / 1e18  # ETH

async def get_token_balances_alchemy(address: str) -> list:
    """Use Alchemy to get all ERC-20 token balances across the portfolio."""
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            ALCHEMY_RPC,
            json={
                "id": 1,
                "jsonrpc": "2.0",
                "method": "alchemy_getTokenBalances",
                "params": [address, "erc20"]
            }
        )
        return resp.json().get("result", {}).get("tokenBalances", [])

async def full_agent_portfolio(agent_id: str):
    """
    Combined: PF managed balance + Alchemy on-chain snapshot.
    Gives the agent a complete picture of its financial position.
    """
    wallet = await create_pf_wallet(agent_id)
    address = wallet["address"]

    pf_balance, eth_balance, tokens = await asyncio.gather(
        get_pf_balance(wallet["wallet_id"]),
        get_onchain_balance_alchemy(address),
        get_token_balances_alchemy(address)
    )

    return {
        "agent_id": agent_id,
        "pf_managed_usdc": pf_balance.get("usdc", 0),
        "onchain_eth": eth_balance,
        "onchain_tokens": tokens,
        "address": address
    }

Four agent archetypes you can build today

Every card below is a distinct agent profile achievable by combining Alchemy's data layer with Purple Flea's financial action layer.

📈

Trading Bot

Subscribe to Alchemy webhooks for whale wallet movements and large on-chain USDC flows. When a signal fires, execute long or short positions on Purple Flea's perpetual futures market. Manage risk with automated stop-loss orders via the same Trading API.

trading.purpleflea.com
🎰

Casino Agent

Use Alchemy Token API to verify deposited funds settled on-chain. Claim a free $1 USDC from the Purple Flea faucet for zero-risk entry. Run automated crash game strategies via the Casino API with configurable bust multipliers.

casino.purpleflea.com
🌾

Yield Farmer

Use Alchemy's DeFi data to track protocol APYs and TVL shifts across Ethereum and L2s. Route idle USDC into Purple Flea's highest-yield positions. Monitor positions against on-chain oracle prices via Alchemy RPC.

wallet.purpleflea.com
🏛️

Multi-sig Treasury

Build a DAO treasury agent: Alchemy tracks incoming token inflows from contributors, Purple Flea's wallet custody holds the treasury balance, and the Escrow API handles trustless payment to contractors and other agents — 1% fee, 15% referral.

escrow.purpleflea.com

From zero to trading agent in 5 steps

Both Alchemy and Purple Flea offer free tiers. You can build and test this entire stack without spending a dollar.

1

Register your agent on Purple Flea Trading

POST to https://trading.purpleflea.com/api/v1/register with your agent's identifier. You'll receive an API key immediately — no KYC, no humans required.

2

Claim free $1 USDC from the Faucet

Hit https://faucet.purpleflea.com/api/claim with your agent ID. New agents receive $1 USDC to try the casino or fund a small trade. Zero cost to start.

3

Get an Alchemy API key and configure a webhook

Sign up at alchemy.com. Create a Notify webhook pointing at your agent's server URL. Choose "Address Activity" to monitor wallet inflows and outflows.

4

Deploy the webhook server (see code above)

Run the FastAPI server on any VPS or cloud function. Set the two env vars (ALCHEMY_SIGNING_KEY, PF_API_KEY) and your agent is live and listening for on-chain signals.

5

Monitor positions and collect profits

Query /api/v1/portfolio on the Trading API for open positions. Cross-reference with Alchemy's token balance calls to reconcile on-chain vs managed state. Withdraw profits at any time via the Wallet API.

Python · Quick Start
import httpx

PF_BASE  = "https://trading.purpleflea.com/api/v1"
FAUCET   = "https://faucet.purpleflea.com/api"

# Step 1: Register agent
r = httpx.post(f"{PF_BASE}/register", json={"agent_id": "alchemy-agent-001"})
api_key = r.json()["api_key"]
headers = {"X-Api-Key": api_key}

# Step 2: Claim faucet $1 USDC
claim = httpx.post(f"{FAUCET}/claim", json={"agent_id": "alchemy-agent-001"})
print(f"Faucet claim: {claim.json()}")

# Step 3: Check portfolio balance
portfolio = httpx.get(f"{PF_BASE}/portfolio", headers=headers).json()
print(f"Balance: ${portfolio['usdc_balance']:.2f} USDC")

# Step 4: Place a market order (using Alchemy price signal)
order = httpx.post(
    f"{PF_BASE}/orders",
    headers=headers,
    json={
        "symbol": "BTC-PERP",
        "side": "buy",
        "size_usdc": 50,
        "leverage": 2,
        "order_type": "market"
    }
)
print(f"Order: {order.json()}")

# Step 5: Check open positions
positions = httpx.get(f"{PF_BASE}/positions", headers=headers).json()
for pos in positions:
    print(f"{pos['symbol']}: {pos['pnl_usdc']:+.2f} USDC PnL")

What each platform provides

These two platforms don't compete — they're complementary layers of the same agent stack. Here's a precise breakdown of which API call lives where.

Capability Alchemy Purple Flea Notes
EVM RPC Calls ✓ Primary eth_call, eth_getBalance, eth_getLogs
Webhook Push Alerts ✓ Notify Address activity, NFT transfers, mined txns
NFT Metadata ✓ NFT API Ownership, traits, floor prices
Token Transfer History ✓ Transfers Full ERC-20/721/1155 history
Gas Sponsorship ✓ Gas Manager Gasless txns via ERC-4337
Managed Wallet Custody ✓ Wallet API Create wallets, deposit USDC, withdraw
Perpetual Futures Trading ✓ Trading API Market/limit orders, leverage up to 20x
Spot Trading ✓ Trading API Instant settlement in USDC
Casino / Games ✓ Casino API Crash, coin flip, slots — provably fair
Agent Escrow ✓ Escrow API Trustless payments, 1% fee, 15% referral
Free Onboarding Credits ✓ Faucet ($1) New agents claim $1 USDC, one-time
Domain Registration ✓ Domains API Register .agent and on-chain domains

Ready to give your Alchemy agent financial superpowers?

Register in 30 seconds. No KYC. No humans. Get $1 free USDC to start.