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.

API Prefix
/api/v1
Auth
JWT Bearer
Referrals
10% on swap fees
Chains
8 supported
Swap Fee
0.3% per swap
Transfer Fee
Gas only
Format
application/json

Supported Chains

The Wallet API supports 8 blockchains. Use the chain identifier string in all requests where a chain parameter is required.

Ethereum
eth
Bitcoin
btc
Solana
sol
Tron
trx
Polygon
polygon
BSC
bsc
Avalanche
avax
Base
base
ChainIdentifierNative TokenAvg Confirm TimeUSDC Support
EthereumethETH~12sYes
BitcoinbtcBTC~10 minNo
SolanasolSOL~0.4sYes
TrontrxTRX~3sYes (USDT)
PolygonpolygonMATIC~2sYes
BSCbscBNB~3sYes
AvalancheavaxAVAX~1sYes
BasebaseETH~2sYes

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
Note: JWT tokens expire after 24 hours. Your agent should store the token and refresh it via POST /auth/login when a 401 Unauthorized response is received. Never hard-code tokens — always fetch them programmatically at startup.
POST /api/v1/auth/register Create a new wallet account

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.

FieldTypeDescription
usernamerequiredstringUnique username for this account (3-32 chars, alphanumeric + underscores)
emailrequiredstringContact email for account notifications and recovery
referral_codeoptionalstringReferral 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"
}
Warning: The generated password is displayed only once at registration. Save it immediately and securely. Use POST /auth/login with your username and password to obtain JWT tokens on subsequent sessions.
POST /api/v1/auth/login Authenticate and get JWT token

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.

FieldTypeDescription
usernamerequiredstringYour registered wallet account username
passwordrequiredstringYour 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.

GET /api/v1/wallets List all wallet addresses across chains

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
}
POST /api/v1/wallets/generate Generate a new wallet address for a chain

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.

FieldTypeDescription
chainrequiredstringTarget chain: eth, btc, sol, trx, polygon, bsc, avax, or base
labeloptionalstringHuman-readable label for this wallet (max 64 chars)
set_primaryoptionalbooleanMake 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.

GET /api/v1/balance Get balances across all chains

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"
}
GET /api/v1/balance/:chain Get balance for a specific chain

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 ParamTypeDescription
addressoptionalstringFilter 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).

Warning: Blockchain transfers are irreversible. Always verify the destination address before sending. Purple Flea cannot recover funds sent to incorrect addresses.
POST /api/v1/transfer Send crypto to an external address

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.

FieldTypeDescription
chainrequiredstringSource chain identifier (e.g. eth, sol, btc)
to_addressrequiredstringDestination wallet address (must be valid format for the specified chain)
amountrequiredstringAmount to send as a decimal string — e.g. "0.1" for 0.1 ETH or "50" for 50 USDC
tokenoptionalstringToken symbol for ERC-20/SPL transfers (e.g. USDC, USDT). Omit for native token transfers.
from_addressoptionalstringSpecific source address (default: primary address for chain)
priorityoptionalstringGas 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.

Swap Fee Distribution
You Pay
0.3% fee
Platform Keeps
0.27%
Your Referrer Earns
0.03% (10%)

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.

POST /api/v1/swap Execute a cross-chain token swap

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.

FieldTypeDescription
from_chainrequiredstringSource chain identifier (e.g. eth)
to_chainrequiredstringDestination chain identifier (e.g. sol). Can equal from_chain for same-chain swaps.
from_tokenrequiredstringToken to swap from (e.g. ETH, USDC)
to_tokenrequiredstringToken to receive (e.g. SOL, USDT)
amountrequiredstringAmount of from_token to swap as a decimal string
confirmoptionalbooleanExecute the swap immediately (default: true). Set false to get a quote only.
slippage_pctoptionalnumberMax 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.

TokenAvailable OnBridge Protocol
ETHeth, polygon, bsc, avax, baseWormhole, LayerZero
BTC / WBTCbtc, eth, polygon, bsctBTC, Wormhole
SOLsol, ethWormhole
USDCeth, sol, polygon, avax, base, bscCCTP (native)
USDTeth, trx, polygon, bsc, avaxMultichain
MATICeth, polygonPolygon Bridge
BNBbsc, ethWormhole
AVAXavax, ethAvalanche Bridge
TRXtrxNative 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.

GET /api/v1/transactions List transaction history with pagination
Query ParamTypeDescription
chainoptionalstringFilter by chain identifier (e.g. eth). Default: all chains.
typeoptionalstringFilter by type: transfer, swap, withdraw, deposit. Default: all.
statusoptionalstringFilter by status: pending, confirmed, failed. Default: all.
limitoptionalintegerResults per page (default: 25, max: 100)
offsetoptionalintegerPagination offset (default: 0)
from_dateoptionalstringISO 8601 start date filter (e.g. 2026-01-01T00:00:00Z)
to_dateoptionalstringISO 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.

GET /api/v1/price/:token Get current token price in USD

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 ParamTypeDescription
quoteoptionalstringQuote 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

SymbolNameApprox Price (Mar 2026)
BTCBitcoin~$87,000
ETHEthereum~$2,550
SOLSolana~$135
TRXTron~$0.13
MATICPolygon~$0.42
BNBBNB~$590
AVAXAvalanche~$22
USDCUSD Coin$1.00
USDTTether~$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.

GET /api/v1/referrals Get referral stats and earnings

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
    }
  ]
}
Referral tips: Include your referral link in any agent you open-source or deploy. When another agent calls your link to register, the relationship is set automatically. There is no limit on the number of agents you can refer, and earnings never expire.

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.

POST /api/v1/withdraw Withdraw funds to an external address

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.

FieldTypeDescription
chainrequiredstringChain to withdraw on (e.g. eth, sol, polygon)
to_addressrequiredstringExternal destination address (validated against chain format)
amountrequiredstringAmount as decimal string (e.g. "25.50")
tokenoptionalstringToken to withdraw (default: chain native token). Use USDC to withdraw referral earnings as stablecoin.
memooptionalstringInternal 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 ComponentAmountWho PaysWho Receives
Platform swap fee0.27% of swap valueSwap initiatorPurple Flea
Referral commission0.03% of swap value (10% of fee)Swap initiatorReferring agent
DEX/bridge protocol fee0.01% - 0.05% (varies by protocol)Swap initiatorDEX/bridge liquidity providers
Gas / network feeNetwork rate (varies by chain + congestion)Swap initiatorBlockchain validators

Settlement Times

Swap TypeTypical TimeMax Time
Same-chain (non-BTC)5 - 30 seconds2 minutes
Cross-chain EVM to EVM1 - 5 minutes15 minutes
EVM to Solana2 - 8 minutes20 minutes
Any to/from Bitcoin10 - 60 minutes4 hours
Any to/from Tron1 - 5 minutes15 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.

Best practice: Always call swap with 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.

HTTPError CodeDescriptionAction
400INVALID_PARAMSMissing or malformed request parametersFix request body or query params
400INVALID_ADDRESSDestination address format invalid for the specified chainVerify address format for the target chain
400INVALID_AMOUNTAmount is zero, negative, or non-numericPass a positive decimal string (e.g. "0.1")
400UNSUPPORTED_CHAINChain identifier is not recognizedUse one of the 8 supported identifiers
400UNSUPPORTED_TOKENToken not available on the specified chainCheck the supported swap pairs table
400SLIPPAGE_EXCEEDEDSwap could not complete within slippage toleranceIncrease slippage_pct or retry when liquidity improves
401UNAUTHORIZEDMissing or expired JWT tokenCall POST /auth/login to refresh the token
401INVALID_CREDENTIALSUsername or password is incorrectVerify credentials; re-register if password is lost
403FORBIDDENAction not permitted on this resourceEnsure you are operating on your own account only
404NOT_FOUNDWallet, transaction, or token not foundVerify the ID or identifier in the request path
409USERNAME_TAKENUsername already exists in the systemChoose a different username at registration
422INSUFFICIENT_BALANCENot enough balance to cover amount plus gasTop up the wallet or reduce the amount
429RATE_LIMITEDToo many requests in the current windowWait for Retry-After header value (seconds)
500INTERNAL_ERRORUnexpected server-side errorRetry with exponential backoff; check purpleflea.com/status
503CHAIN_UNAVAILABLETarget blockchain RPC temporarily unreachableRetry 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 GroupLimitWindowNotes
POST /auth/register5 requests1 hourPer IP address
POST /auth/login20 requests15 minutesPer IP + username combination
GET /wallets120 requests1 minutePer account
POST /wallets/generate10 requests1 hourMax 50 wallet addresses per chain per account
GET /balance, GET /balance/:chain60 requests1 minutePer account
POST /transfer20 requests1 minutePer account; higher limits available on request
POST /swap30 requests1 minuteQuote-only calls (confirm: false) count at 1/5th rate
GET /transactions60 requests1 minutePer account
GET /price/:token300 requests1 minuteUnauthenticated; per IP address
GET /referrals30 requests1 minutePer account
POST /withdraw10 requests1 hourConservative limit to protect accounts from accidental large outflows
High-volume agents: If your agent requires higher rate limits for transfers or swaps, contact Purple Flea via the for agents page. Volume-based limit increases are available for established agents with demonstrable use cases.

Next Steps

You have everything needed to integrate the Wallet API into your agent. Here are recommended next actions:

Built for AI Agents → Get Free Funds →