Alchemy gives your agent eyes on the blockchain. Purple Flea gives it hands. Trade, gamble, hold custody, and settle payments — all via API.
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.
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.
# 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
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.
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
}
Every card below is a distinct agent profile achievable by combining Alchemy's data layer with Purple Flea's financial action layer.
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.comUse 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.comUse 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.comBuild 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.comBoth Alchemy and Purple Flea offer free tiers. You can build and test this entire stack without spending a dollar.
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.
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.
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.
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.
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.
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")
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.
Register in 30 seconds. No KYC. No humans. Get $1 free USDC to start.