Wallet API Wallet
Manage multi-chain cryptocurrency wallets across 8 blockchains from a single API. Generate addresses, check balances, send transfers, and execute cross-chain swaps — all authenticated with JWT tokens. Earn 10% referral commission on swap fees generated by agents you refer.
Supported Chains
The Wallet API supports 8 blockchains. Use the chain identifier string in all requests where a chain parameter is required.
| Chain | Identifier | Native Token | Avg Confirm Time | USDC Support |
|---|---|---|---|---|
| Ethereum | eth | ETH | ~12s | Yes |
| Bitcoin | btc | BTC | ~10 min | No |
| Solana | sol | SOL | ~0.4s | Yes |
| Tron | trx | TRX | ~3s | Yes (USDT) |
| Polygon | polygon | MATIC | ~2s | Yes |
| BSC | bsc | BNB | ~3s | Yes |
| Avalanche | avax | AVAX | ~1s | Yes |
| Base | base | ETH | ~2s | Yes |
Authentication
The Wallet API uses JWT (JSON Web Token) authentication. Register to obtain account credentials, then call POST /auth/login to receive a token valid for 24 hours. Include the token in all subsequent requests via the Authorization: Bearer header.
# All authenticated requests
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://wallet.purpleflea.com/api/v1/wallets
POST /auth/login when a 401 Unauthorized response is received. Never hard-code tokens — always fetch them programmatically at startup.Creates a new wallet account and returns account credentials. No authentication required. Pass a referral_code from the agent that referred you to activate the referral relationship — the referrer earns 10% of your swap fees automatically.
| Field | Type | Description |
|---|---|---|
| usernamerequired | string | Unique username for this account (3-32 chars, alphanumeric + underscores) |
| emailrequired | string | Contact email for account notifications and recovery |
| referral_codeoptional | string | Referral code from the agent that referred you — activates 10% referral commission for your referrer |
# Request
curl -X POST https://wallet.purpleflea.com/api/v1/auth/register \
-H "Content-Type: application/json" \
-d '{
"username": "my-wallet-agent-01",
"email": "agent@example.com",
"referral_code": "PFWLT123"
}'
# Response 201 Created
{
"success": true,
"username": "my-wallet-agent-01",
"password": "generated-secure-password-abc",
"referral_code": "PFWLT456",
"referral_link": "https://wallet.purpleflea.com?ref=PFWLT456",
"message": "Account created. Save your password — it is shown only once.",
"created_at": "2026-03-06T09:00:00Z"
}
POST /auth/login with your username and password to obtain JWT tokens on subsequent sessions.Authenticates with username and password, returning a JWT bearer token valid for 24 hours. Call this at agent startup and whenever you receive a 401 response from authenticated endpoints.
| Field | Type | Description |
|---|---|---|
| usernamerequired | string | Your registered wallet account username |
| passwordrequired | string | Your account password (generated at registration) |
# Request
curl -X POST https://wallet.purpleflea.com/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{
"username": "my-wallet-agent-01",
"password": "generated-secure-password-abc"
}'
# Response 200 OK
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_at": "2026-03-07T09:00:00Z",
"username": "my-wallet-agent-01",
"referral_code": "PFWLT456"
}
Wallet Management
Each account can hold wallet addresses across all 8 supported chains. Wallet private keys are managed server-side with hardware-level encryption. You can generate a new address for any chain at any time — multiple addresses per chain are supported for compartmentalizing funds or tracking separate strategies.
Returns all wallet addresses associated with your account, grouped by chain. Each entry includes the address, chain identifier, creation time, and whether it is the primary address for that chain.
# List all wallet addresses
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://wallet.purpleflea.com/api/v1/wallets
# Response 200 OK
{
"success": true,
"wallets": [
{
"id": "wlt_3f8a2c1d",
"chain": "eth",
"address": "0xAbCd1234...5678EfGh",
"primary": true,
"label": "Main ETH Wallet",
"created_at": "2026-03-06T09:00:00Z"
},
{
"id": "wlt_9b2e7f4a",
"chain": "btc",
"address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
"primary": true,
"label": "Main BTC Wallet",
"created_at": "2026-03-06T09:01:00Z"
},
{
"id": "wlt_5c4d8e2f",
"chain": "sol",
"address": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
"primary": true,
"label": "Main SOL Wallet",
"created_at": "2026-03-06T09:02:00Z"
}
],
"total": 3
}
Generates a fresh wallet address for the specified blockchain. The private key is stored securely server-side and never exposed via the API. You can generate multiple addresses per chain for compartmentalization or accounting purposes.
| Field | Type | Description |
|---|---|---|
| chainrequired | string | Target chain: eth, btc, sol, trx, polygon, bsc, avax, or base |
| labeloptional | string | Human-readable label for this wallet (max 64 chars) |
| set_primaryoptional | boolean | Make this the primary address for the chain (default: false if one already exists, true if first for chain) |
# Generate a new Solana wallet
curl -X POST https://wallet.purpleflea.com/api/v1/wallets/generate \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"chain": "sol",
"label": "SOL Trading Wallet",
"set_primary": false
}'
# Response 201 Created
{
"success": true,
"wallet": {
"id": "wlt_1a2b3c4d",
"chain": "sol",
"address": "4Nd1mBQtrMJVYVfKf2PX8RkELbBWMgrP3Mv1H3H3Ux5",
"primary": false,
"label": "SOL Trading Wallet",
"created_at": "2026-03-06T10:15:00Z"
}
}
Balances
Query balances across all chains or drill into a specific chain. Balances include both native tokens and major ERC-20/SPL tokens. Figures are refreshed on-demand by querying underlying blockchain RPC nodes — there is no stale cache.
Returns balances for all wallet addresses across every chain in your account. Response includes native token amounts, USD values at current spot prices, and a total portfolio USD value.
# Get all balances
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://wallet.purpleflea.com/api/v1/balance
# Response 200 OK
{
"success": true,
"total_usd": 1842.57,
"balances": {
"eth": {
"address": "0xAbCd1234...5678EfGh",
"native": { "symbol": "ETH", "amount": 0.412, "usd": 1050.24 },
"tokens": [
{ "symbol": "USDC", "amount": 500.00, "usd": 500.00 }
],
"total_usd": 1550.24
},
"btc": {
"address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
"native": { "symbol": "BTC", "amount": 0.00334, "usd": 292.00 },
"tokens": [],
"total_usd": 292.00
},
"sol": {
"address": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
"native": { "symbol": "SOL", "amount": 0.018, "usd": 2.43 },
"tokens": [],
"total_usd": 2.43
}
},
"refreshed_at": "2026-03-06T10:30:00Z"
}
Returns balance for a single chain. Replace :chain with the chain identifier (e.g. eth, sol, btc). Optionally filter to a specific wallet address if you have multiple addresses per chain.
| Query Param | Type | Description |
|---|---|---|
| addressoptional | string | Filter to a specific wallet address on this chain (default: primary address for chain) |
# Get Ethereum balance (primary address)
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://wallet.purpleflea.com/api/v1/balance/eth
# Get Polygon balance for a specific address
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
"https://wallet.purpleflea.com/api/v1/balance/polygon?address=0xAbCd..."
# Response 200 OK
{
"success": true,
"chain": "eth",
"address": "0xAbCd1234...5678EfGh",
"native": {
"symbol": "ETH",
"amount": 0.412,
"usd": 1050.24
},
"tokens": [
{
"symbol": "USDC",
"contract": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
"amount": 500.00,
"decimals": 6,
"usd": 500.00
},
{
"symbol": "USDT",
"contract": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
"amount": 0.00,
"decimals": 6,
"usd": 0.00
}
],
"total_usd": 1550.24,
"refreshed_at": "2026-03-06T10:30:00Z"
}
Transfers
Send native tokens or ERC-20/SPL tokens to any external address on supported chains. Transfers broadcast directly to the blockchain. Fees are deducted from the sending wallet's native token balance (gas only — Purple Flea does not add markup to network fees).
Broadcasts a signed transfer transaction from your managed wallet to any external address. For ERC-20/SPL token transfers, specify the token field. For native transfers (ETH, BTC, SOL, etc.), omit token.
| Field | Type | Description |
|---|---|---|
| chainrequired | string | Source chain identifier (e.g. eth, sol, btc) |
| to_addressrequired | string | Destination wallet address (must be valid format for the specified chain) |
| amountrequired | string | Amount to send as a decimal string — e.g. "0.1" for 0.1 ETH or "50" for 50 USDC |
| tokenoptional | string | Token symbol for ERC-20/SPL transfers (e.g. USDC, USDT). Omit for native token transfers. |
| from_addressoptional | string | Specific source address (default: primary address for chain) |
| priorityoptional | string | Gas priority: low, standard (default), fast. Higher priority = faster confirmation, higher gas cost. |
# Send 0.05 ETH to an external address
curl -X POST https://wallet.purpleflea.com/api/v1/transfer \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"chain": "eth",
"to_address": "0x1234567890abcdef1234567890abcdef12345678",
"amount": "0.05",
"priority": "standard"
}'
# Send 100 USDC on Polygon (low-fee stablecoin transfer)
curl -X POST https://wallet.purpleflea.com/api/v1/transfer \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"chain": "polygon",
"to_address": "0x9876543210fedcba9876543210fedcba98765432",
"amount": "100",
"token": "USDC"
}'
# Response 200 OK
{
"success": true,
"tx_id": "txf_8a9b2c3d",
"chain": "eth",
"tx_hash": "0xabc123def456...",
"from_address": "0xAbCd1234...5678EfGh",
"to_address": "0x1234567890abcdef...",
"amount": "0.05",
"token": "ETH",
"gas_used_gwei": "21000",
"gas_cost_usd": 0.84,
"status": "pending",
"explorer_url": "https://etherscan.io/tx/0xabc123def456...",
"created_at": "2026-03-06T11:00:00Z"
}
Cross-Chain Swaps
Swap tokens across chains using aggregated liquidity from multiple DEX protocols. The Wallet API handles routing, bridging, and settlement automatically. A 0.3% swap fee applies — 10% of that fee flows to your referrer if you registered with a referral code.
Refer other agents with your referral code and earn 10% of their 0.3% swap fee automatically. On $10,000 in referred swap volume you earn $3.00 — no cap, no minimum payout threshold.
Swaps tokens from one chain to another (or same-chain swaps). Specify source and destination chain, token pair, and amount. If confirm is false, only a quote is returned without execution — use this to check rates before committing.
| Field | Type | Description |
|---|---|---|
| from_chainrequired | string | Source chain identifier (e.g. eth) |
| to_chainrequired | string | Destination chain identifier (e.g. sol). Can equal from_chain for same-chain swaps. |
| from_tokenrequired | string | Token to swap from (e.g. ETH, USDC) |
| to_tokenrequired | string | Token to receive (e.g. SOL, USDT) |
| amountrequired | string | Amount of from_token to swap as a decimal string |
| confirmoptional | boolean | Execute the swap immediately (default: true). Set false to get a quote only. |
| slippage_pctoptional | number | Max acceptable slippage percentage (default: 0.5, max: 5.0) |
# Quote only — check rate before executing
curl -X POST https://wallet.purpleflea.com/api/v1/swap \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"from_chain": "eth",
"to_chain": "sol",
"from_token": "ETH",
"to_token": "SOL",
"amount": "0.1",
"confirm": false
}'
# Response 200 OK (quote only, no funds moved)
{
"success": true,
"quote": {
"from_chain": "eth",
"to_chain": "sol",
"from_token": "ETH",
"to_token": "SOL",
"from_amount": "0.1",
"to_amount_estimated": "19.42",
"rate": 194.2,
"fee_usd": 0.76,
"fee_pct": 0.003,
"gas_estimate_usd": 1.12,
"slippage_pct": 0.5,
"min_received": "19.32",
"route": "ETH -> USDC (Uniswap v3) -> SOL (Wormhole Bridge)",
"expires_at": "2026-03-06T11:01:00Z"
}
}
# Execute the swap
curl -X POST https://wallet.purpleflea.com/api/v1/swap \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"from_chain": "eth",
"to_chain": "sol",
"from_token": "ETH",
"to_token": "SOL",
"amount": "0.1",
"confirm": true,
"slippage_pct": 0.5
}'
# Response 200 OK (executed)
{
"success": true,
"swap": {
"id": "swp_4f8c2a1e",
"from_chain": "eth",
"to_chain": "sol",
"from_token": "ETH",
"to_token": "SOL",
"from_amount": "0.1",
"to_amount": "19.38",
"fee_usd": 0.76,
"tx_hash_out": "0xdef789abc123...",
"tx_hash_in": "4Nd1mBQtrMJV...",
"status": "pending",
"estimated_completion": "2026-03-06T11:04:00Z"
}
}
Supported Swap Pairs
Any combination of the following tokens can be swapped between supported chains, subject to bridge liquidity availability.
| Token | Available On | Bridge Protocol |
|---|---|---|
| ETH | eth, polygon, bsc, avax, base | Wormhole, LayerZero |
| BTC / WBTC | btc, eth, polygon, bsc | tBTC, Wormhole |
| SOL | sol, eth | Wormhole |
| USDC | eth, sol, polygon, avax, base, bsc | CCTP (native) |
| USDT | eth, trx, polygon, bsc, avax | Multichain |
| MATIC | eth, polygon | Polygon Bridge |
| BNB | bsc, eth | Wormhole |
| AVAX | avax, eth | Avalanche Bridge |
| TRX | trx | Native only |
Transaction History
Retrieve a paginated log of all transfers, swaps, and withdrawals associated with your account. Transactions are stored indefinitely and can be filtered by chain, type, status, or date range.
| Query Param | Type | Description |
|---|---|---|
| chainoptional | string | Filter by chain identifier (e.g. eth). Default: all chains. |
| typeoptional | string | Filter by type: transfer, swap, withdraw, deposit. Default: all. |
| statusoptional | string | Filter by status: pending, confirmed, failed. Default: all. |
| limitoptional | integer | Results per page (default: 25, max: 100) |
| offsetoptional | integer | Pagination offset (default: 0) |
| from_dateoptional | string | ISO 8601 start date filter (e.g. 2026-01-01T00:00:00Z) |
| to_dateoptional | string | ISO 8601 end date filter |
# Get last 10 Ethereum transactions
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
"https://wallet.purpleflea.com/api/v1/transactions?chain=eth&limit=10"
# Response 200 OK
{
"success": true,
"total": 47,
"limit": 10,
"offset": 0,
"transactions": [
{
"id": "txf_8a9b2c3d",
"type": "transfer",
"chain": "eth",
"from_address": "0xAbCd1234...",
"to_address": "0x1234567890...",
"amount": "0.05",
"token": "ETH",
"tx_hash": "0xabc123def456...",
"gas_cost_usd": 0.84,
"status": "confirmed",
"confirmations": 32,
"explorer_url": "https://etherscan.io/tx/0xabc123...",
"created_at": "2026-03-06T11:00:00Z",
"confirmed_at": "2026-03-06T11:01:00Z"
},
{
"id": "swp_4f8c2a1e",
"type": "swap",
"from_chain": "eth",
"to_chain": "sol",
"from_token": "ETH",
"to_token": "SOL",
"from_amount": "0.1",
"to_amount": "19.38",
"fee_usd": 0.76,
"status": "confirmed",
"created_at": "2026-03-06T10:45:00Z"
}
]
}
Token Prices
Fetch real-time spot prices for any supported token. Prices are sourced from aggregated market data and updated every 10 seconds. No authentication is required for price lookups.
Returns the current USD spot price for a token. Replace :token with the token symbol (case-insensitive). Optionally convert to a different quote currency.
| Query Param | Type | Description |
|---|---|---|
| quoteoptional | string | Quote currency (default: USD). Supports: USD, EUR, BTC, ETH |
# Get ETH price in USD (no auth required)
curl https://wallet.purpleflea.com/api/v1/price/eth
# Get SOL price quoted in BTC
curl "https://wallet.purpleflea.com/api/v1/price/sol?quote=btc"
# Response 200 OK
{
"success": true,
"token": "ETH",
"quote": "USD",
"price": 2551.82,
"change_24h_pct": 1.48,
"change_7d_pct": -3.21,
"market_cap_usd": 306800000000,
"volume_24h_usd": 14200000000,
"updated_at": "2026-03-06T11:30:00Z"
}
Supported Tokens
| Symbol | Name | Approx Price (Mar 2026) |
|---|---|---|
| BTC | Bitcoin | ~$87,000 |
| ETH | Ethereum | ~$2,550 |
| SOL | Solana | ~$135 |
| TRX | Tron | ~$0.13 |
| MATIC | Polygon | ~$0.42 |
| BNB | BNB | ~$590 |
| AVAX | Avalanche | ~$22 |
| USDC | USD Coin | $1.00 |
| USDT | Tether | ~$1.00 |
Referrals
Every account receives a unique referral code at registration. When another agent signs up using your code, they become your referral and you earn 10% of their swap fees automatically — credited to your account in real time with no cap or minimum threshold.
Returns your referral code, list of referred agents, total earnings to date, and pending (uncleared) earnings.
# Get referral stats
curl -H "Authorization: Bearer YOUR_JWT_TOKEN" \
https://wallet.purpleflea.com/api/v1/referrals
# Response 200 OK
{
"success": true,
"referral_code": "PFWLT456",
"referral_link": "https://wallet.purpleflea.com?ref=PFWLT456",
"referred_count": 7,
"total_earned_usd": 12.84,
"pending_usd": 1.20,
"rate_pct": 10,
"referrals": [
{
"username": "trading-bot-42",
"joined_at": "2026-02-14T08:00:00Z",
"swap_volume_usd": 28400,
"earned_from_usd": 8.52
},
{
"username": "arb-agent-7",
"joined_at": "2026-02-28T15:30:00Z",
"swap_volume_usd": 4200,
"earned_from_usd": 1.26
}
]
}
Withdrawals
Withdraw funds from your Purple Flea wallet to any external address. Withdrawals are processed as standard blockchain transfers and are irreversible once broadcast. This endpoint is rate-limited more conservatively than POST /transfer to protect accounts from accidental large outflows.
Initiates a withdrawal from your managed wallet to an external address. All withdrawals are logged and broadcast immediately. Referral earnings can be withdrawn to any chain that supports USDC.
| Field | Type | Description |
|---|---|---|
| chainrequired | string | Chain to withdraw on (e.g. eth, sol, polygon) |
| to_addressrequired | string | External destination address (validated against chain format) |
| amountrequired | string | Amount as decimal string (e.g. "25.50") |
| tokenoptional | string | Token to withdraw (default: chain native token). Use USDC to withdraw referral earnings as stablecoin. |
| memooptional | string | Internal memo for your records — max 128 chars, not broadcast on-chain |
# Withdraw 25 USDC referral earnings to Ethereum
curl -X POST https://wallet.purpleflea.com/api/v1/withdraw \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"chain": "eth",
"to_address": "0x9876543210fedcba9876543210fedcba98765432",
"amount": "25.00",
"token": "USDC",
"memo": "Referral earnings withdrawal March 2026"
}'
# Response 200 OK
{
"success": true,
"withdrawal": {
"id": "wdr_7c2a9f1b",
"chain": "eth",
"to_address": "0x9876543210fedcba...",
"amount": "25.00",
"token": "USDC",
"tx_hash": "0x789abc123def...",
"gas_cost_usd": 0.92,
"status": "pending",
"explorer_url": "https://etherscan.io/tx/0x789abc...",
"created_at": "2026-03-06T12:00:00Z"
}
}
Python SDK Example
The following PurpleFleasWallet Python class wraps the Wallet API with automatic JWT refresh, typed methods for every endpoint, and proper error handling. Copy and extend this for your own agents.
import requests
import time
from datetime import datetime, timezone
class PurpleFleasWallet:
"""Multi-chain wallet client for Purple Flea Wallet API."""
BASE_URL = "https://wallet.purpleflea.com/api/v1"
def __init__(self, username: str, password: str):
self.username = username
self.password = password
self.token = None
self.token_expires_at = 0
self._login()
def _login(self):
"""Authenticate and cache JWT token."""
resp = requests.post(
f"{self.BASE_URL}/auth/login",
json={"username": self.username, "password": self.password},
timeout=10
)
resp.raise_for_status()
data = resp.json()
self.token = data["token"]
# Parse expiry and subtract 60s buffer to avoid using expired tokens
expires = datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00"))
self.token_expires_at = expires.timestamp() - 60
def _headers(self) -> dict:
"""Return auth headers, refreshing token if needed."""
if time.time() > self.token_expires_at:
self._login()
return {
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json"
}
def get_wallets(self) -> dict:
"""List all wallet addresses across chains."""
r = requests.get(f"{self.BASE_URL}/wallets", headers=self._headers(), timeout=10)
r.raise_for_status()
return r.json()
def generate_wallet(self, chain: str, label: str = None, set_primary: bool = False) -> dict:
"""Generate a new wallet address for the given chain."""
payload = {"chain": chain, "set_primary": set_primary}
if label:
payload["label"] = label
r = requests.post(f"{self.BASE_URL}/wallets/generate", json=payload,
headers=self._headers(), timeout=10)
r.raise_for_status()
return r.json()
def get_balance(self, chain: str = None, address: str = None) -> dict:
"""Get balance for one chain or all chains."""
url = f"{self.BASE_URL}/balance"
params = {}
if chain:
url += f"/{chain}"
if address:
params["address"] = address
r = requests.get(url, headers=self._headers(), params=params, timeout=10)
r.raise_for_status()
return r.json()
def transfer(self, chain: str, to_address: str, amount: str,
token: str = None, priority: str = "standard") -> dict:
"""Send crypto to an external address."""
payload = {"chain": chain, "to_address": to_address,
"amount": amount, "priority": priority}
if token:
payload["token"] = token
r = requests.post(f"{self.BASE_URL}/transfer", json=payload,
headers=self._headers(), timeout=30)
r.raise_for_status()
return r.json()
def swap(self, from_chain: str, to_chain: str, from_token: str,
to_token: str, amount: str, slippage_pct: float = 0.5,
quote_only: bool = False) -> dict:
"""Execute or quote a cross-chain token swap."""
payload = {
"from_chain": from_chain, "to_chain": to_chain,
"from_token": from_token, "to_token": to_token,
"amount": amount, "confirm": not quote_only,
"slippage_pct": slippage_pct
}
r = requests.post(f"{self.BASE_URL}/swap", json=payload,
headers=self._headers(), timeout=30)
r.raise_for_status()
return r.json()
def get_transactions(self, chain: str = None, tx_type: str = None,
limit: int = 25, offset: int = 0) -> dict:
"""Get paginated transaction history."""
params = {"limit": limit, "offset": offset}
if chain:
params["chain"] = chain
if tx_type:
params["type"] = tx_type
r = requests.get(f"{self.BASE_URL}/transactions", params=params,
headers=self._headers(), timeout=10)
r.raise_for_status()
return r.json()
def get_price(self, token: str, quote: str = "USD") -> dict:
"""Get current token price. No auth required."""
r = requests.get(f"{self.BASE_URL}/price/{token.lower()}",
params={"quote": quote}, timeout=10)
r.raise_for_status()
return r.json()
def get_referrals(self) -> dict:
"""Get referral stats and earnings."""
r = requests.get(f"{self.BASE_URL}/referrals", headers=self._headers(), timeout=10)
r.raise_for_status()
return r.json()
def withdraw(self, chain: str, to_address: str, amount: str,
token: str = None, memo: str = None) -> dict:
"""Withdraw funds to an external address."""
payload = {"chain": chain, "to_address": to_address, "amount": amount}
if token:
payload["token"] = token
if memo:
payload["memo"] = memo
r = requests.post(f"{self.BASE_URL}/withdraw", json=payload,
headers=self._headers(), timeout=30)
r.raise_for_status()
return r.json()
# Example: full multi-chain agent workflow
if __name__ == "__main__":
wallet = PurpleFleasWallet(
username="my-wallet-agent-01",
password="generated-secure-password-abc"
)
# Step 1: Check total portfolio value
balances = wallet.get_balance()
print(f"Total portfolio: ${balances['total_usd']:.2f}")
# Step 2: Generate a Polygon address for low-fee USDC ops
poly = wallet.generate_wallet("polygon", label="MATIC gas + USDC ops")
print(f"Polygon address: {poly['wallet']['address']}")
# Step 3: Get a swap quote before committing
quote = wallet.swap(
from_chain="eth", to_chain="polygon",
from_token="ETH", to_token="USDC",
amount="0.05", quote_only=True
)
print(f"Swap quote: {quote['quote']['to_amount_estimated']} USDC")
print(f"Platform fee: ${quote['quote']['fee_usd']:.4f}")
# Step 4: Execute the swap
result = wallet.swap(
from_chain="eth", to_chain="polygon",
from_token="ETH", to_token="USDC",
amount="0.05"
)
print(f"Swap executed: {result['swap']['id']}")
# Step 5: Check referral earnings
refs = wallet.get_referrals()
print(f"Referral earnings: ${refs['total_earned_usd']:.2f}")
print(f"Referred agents: {refs['referred_count']}")
Swap Mechanics & Fee Structure
Understanding how swaps work helps you optimize your agent operations and referral strategy.
Routing
The Wallet API uses a smart routing engine that queries multiple DEX aggregators and bridge protocols simultaneously to find the best output rate. For same-chain swaps, routing goes through Uniswap v3 (Ethereum/Base/Polygon), PancakeSwap (BSC), TraderJoe (Avalanche), Raydium (Solana), or SunSwap (Tron). For cross-chain swaps, the engine selects from Wormhole, LayerZero, CCTP, or Stargate depending on which provides the best net output after bridge fees.
Fee Breakdown
| Fee Component | Amount | Who Pays | Who Receives |
|---|---|---|---|
| Platform swap fee | 0.27% of swap value | Swap initiator | Purple Flea |
| Referral commission | 0.03% of swap value (10% of fee) | Swap initiator | Referring agent |
| DEX/bridge protocol fee | 0.01% - 0.05% (varies by protocol) | Swap initiator | DEX/bridge liquidity providers |
| Gas / network fee | Network rate (varies by chain + congestion) | Swap initiator | Blockchain validators |
Settlement Times
| Swap Type | Typical Time | Max Time |
|---|---|---|
| Same-chain (non-BTC) | 5 - 30 seconds | 2 minutes |
| Cross-chain EVM to EVM | 1 - 5 minutes | 15 minutes |
| EVM to Solana | 2 - 8 minutes | 20 minutes |
| Any to/from Bitcoin | 10 - 60 minutes | 4 hours |
| Any to/from Tron | 1 - 5 minutes | 15 minutes |
Slippage Protection
The slippage_pct parameter sets the maximum acceptable deviation from the quoted rate. If the final execution rate is worse than quoted_rate * (1 - slippage_pct/100), the swap reverts and no funds are deducted (though gas may still be consumed on-chain for EVM chains). The default of 0.5% suits most liquid pairs. Use 1-2% for smaller-cap tokens or during high-volatility cross-chain swaps.
confirm: false first to get a quote, verify the output amount meets your requirements, then call with confirm: true to execute. Quotes are valid for 60 seconds.Error Codes
All errors return a JSON body with success: false, an HTTP status code, an error code string, and a human-readable message. Retry on 5xx errors with exponential backoff. Do not retry 4xx errors without fixing the underlying request.
| HTTP | Error Code | Description | Action |
|---|---|---|---|
| 400 | INVALID_PARAMS | Missing or malformed request parameters | Fix request body or query params |
| 400 | INVALID_ADDRESS | Destination address format invalid for the specified chain | Verify address format for the target chain |
| 400 | INVALID_AMOUNT | Amount is zero, negative, or non-numeric | Pass a positive decimal string (e.g. "0.1") |
| 400 | UNSUPPORTED_CHAIN | Chain identifier is not recognized | Use one of the 8 supported identifiers |
| 400 | UNSUPPORTED_TOKEN | Token not available on the specified chain | Check the supported swap pairs table |
| 400 | SLIPPAGE_EXCEEDED | Swap could not complete within slippage tolerance | Increase slippage_pct or retry when liquidity improves |
| 401 | UNAUTHORIZED | Missing or expired JWT token | Call POST /auth/login to refresh the token |
| 401 | INVALID_CREDENTIALS | Username or password is incorrect | Verify credentials; re-register if password is lost |
| 403 | FORBIDDEN | Action not permitted on this resource | Ensure you are operating on your own account only |
| 404 | NOT_FOUND | Wallet, transaction, or token not found | Verify the ID or identifier in the request path |
| 409 | USERNAME_TAKEN | Username already exists in the system | Choose a different username at registration |
| 422 | INSUFFICIENT_BALANCE | Not enough balance to cover amount plus gas | Top up the wallet or reduce the amount |
| 429 | RATE_LIMITED | Too many requests in the current window | Wait for Retry-After header value (seconds) |
| 500 | INTERNAL_ERROR | Unexpected server-side error | Retry with exponential backoff; check purpleflea.com/status |
| 503 | CHAIN_UNAVAILABLE | Target blockchain RPC temporarily unreachable | Retry after a short delay; check purpleflea.com/status for chain status |
# Example error response
{
"success": false,
"error": "INSUFFICIENT_BALANCE",
"message": "ETH balance (0.002 ETH) is insufficient to cover 0.05 ETH plus estimated gas.",
"chain": "eth",
"available": "0.002",
"requested": "0.05"
}
Rate Limits
Rate limits are applied per account (JWT identity) on a rolling window. Response headers X-RateLimit-Remaining and X-RateLimit-Reset are included on all responses to help your agent track usage proactively.
| Endpoint Group | Limit | Window | Notes |
|---|---|---|---|
POST /auth/register | 5 requests | 1 hour | Per IP address |
POST /auth/login | 20 requests | 15 minutes | Per IP + username combination |
GET /wallets | 120 requests | 1 minute | Per account |
POST /wallets/generate | 10 requests | 1 hour | Max 50 wallet addresses per chain per account |
GET /balance, GET /balance/:chain | 60 requests | 1 minute | Per account |
POST /transfer | 20 requests | 1 minute | Per account; higher limits available on request |
POST /swap | 30 requests | 1 minute | Quote-only calls (confirm: false) count at 1/5th rate |
GET /transactions | 60 requests | 1 minute | Per account |
GET /price/:token | 300 requests | 1 minute | Unauthenticated; per IP address |
GET /referrals | 30 requests | 1 minute | Per account |
POST /withdraw | 10 requests | 1 hour | Conservative limit to protect accounts from accidental large outflows |
Next Steps
You have everything needed to integrate the Wallet API into your agent. Here are recommended next actions:
- Register your agent at wallet.purpleflea.com and note your referral code
- Claim free funds via the Purple Flea Faucet to test the API without risk
- Explore the API Playground to test endpoints interactively in the browser
- Read the Agent Handbook for best practices on building autonomous financial agents
- Complete the Onboarding Checklist to unlock all six Purple Flea services
- Review the full Docs index for Casino, Trading, Escrow, Domains, and Faucet APIs