Built for Mastra Framework

Financial Tools for
Mastra AI Agents

Give your Mastra agents real money capabilities. Casino, trading, escrow, wallet, and domain APIs — all designed for autonomous AI agents, no KYC required.

🆕 Claim Free USDC View Quickstart →
6
Live APIs
1%
Escrow Fee
Free
Faucet USDC
15%
Referral Rate
Why Mastra + Purple Flea

The natural fit for autonomous finance

Mastra's tool abstraction model maps perfectly onto Purple Flea's financial APIs. Wrap each endpoint as a typed Mastra tool and let your agents handle money.

🔧

Type-safe tool definitions

Every Purple Flea API is designed around structured JSON I/O — perfect for Mastra's Zod schema validation. Define input/output shapes once, use everywhere.

No authentication ceremony

Agents register with a wallet address. No OAuth flows, no API keys to rotate, no KYC delays. Your Mastra agent can be live and transacting in under 60 seconds.

🔗

Composable by design

Chain casino, escrow, and trading calls into complex financial workflows. The faucet gives new agents USDC to start, escrow ensures trustless settlement.

🆕

Free onboarding faucet

New agents claim free USDC from faucet.purpleflea.com before risking real funds. Perfect for testing Mastra tool integrations in production without cost.

📈

Real financial primitives

Not mock money. Purple Flea operates on real USDC. Your Mastra agents can bet, trade, pay, and receive real value through the same tool interface.

👥

Agent-native referral system

15% referral on escrow fees. Mastra orchestrators can earn from the agents they spawn. Build multi-agent hierarchies with built-in economic incentives.

All Services

Six APIs, one platform

Every Purple Flea service is available as a Mastra tool. Mix and match based on your agent's financial goals.

🎹
Live

Casino API

Provably fair games for AI agents. Dice, roulette, and slots with cryptographic fairness verification. Agents bet with USDC, results are immediately verifiable on-chain.

POST /betGET /historyUSDC
Casino API docs →
📈
Live

Trading API

Autonomous trading for AI agents. Execute market and limit orders, manage portfolios, access real-time price feeds — all without human approval at each step.

POST /orderGET /portfolioGET /prices
Trading API docs →
📄
Live

Escrow API

Trustless agent-to-agent payments. Lock funds until conditions are met. 1% protocol fee, 15% referral on fees. Perfect for multi-agent service marketplaces.

POST /createPOST /release1% fee
Escrow docs →
💵
Live

Wallet API

Non-custodial wallet management for agents. Generate addresses, check balances, send USDC — all through a clean REST interface your Mastra tools can call.

POST /createGET /balancePOST /send
Wallet API docs →
🌐
Live

Domains API

AI agents can register and manage domain names autonomously. Useful for agents needing persistent identifiers or operating services requiring DNS records.

POST /registerGET /lookupPOST /transfer
Domains API docs →
🆕
Free

USDC Faucet

New agents claim free USDC to start. No deposit required. Register your agent wallet, claim USDC, and immediately use it across all Purple Flea APIs.

POST /registerPOST /claimFree
Faucet →
Quickstart

Up and running in 4 steps

From a blank Mastra project to a financially-capable AI agent in minutes.

1

Install dependencies

Add @mastra/core and zod to your project. No Purple Flea SDK needed — it is just HTTP.

2

Register your agent wallet

Call POST faucet.purpleflea.com/register with a wallet address. Your agent gets an identity across all Purple Flea services.

3

Claim free USDC

Call POST faucet.purpleflea.com/claim. The agent receives USDC immediately usable in casino, escrow, or trading APIs.

4

Define Mastra tools

Wrap each API call as a typed Mastra createTool() definition. Zod schemas enforce types, your agent handles the rest autonomously.

Zero-cost onboarding: The faucet gives real USDC to new agents. Your Mastra integration can be tested in production without spending a cent. Build with confidence.

register-and-claim.ts
// Register agent + claim free USDC
const registerAndClaim = async (wallet: string) => {

  // Step 1: Register wallet with faucet
  const reg = await fetch(
    'https://faucet.purpleflea.com/register',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ wallet })
    }
  );
  const { agentId } = await reg.json();

  // Step 2: Claim free USDC
  const claim = await fetch(
    'https://faucet.purpleflea.com/claim',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ agentId })
    }
  );
  const { balance } = await claim.json();
  console.log(`Agent ready. Balance: $${balance} USDC`);
  return agentId;
};
install.sh
# Create a new Mastra project
npx create-mastra@latest my-financial-agent
cd my-financial-agent

# Install dependencies (no Purple Flea SDK needed)
npm install @mastra/core zod

# Purple Flea is pure REST — use fetch() directly
# All endpoints return standard JSON
Code Examples

Mastra tool definitions

Complete, copy-paste ready Mastra tool definitions for casino, escrow, and trading. TypeScript with full Zod type safety.

tools/casino-tools.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

const CASINO = 'https://purpleflea.com/casino-api';

export const casinoBetTool = createTool({
  id: 'casino-bet',
  description: 'Place a provably fair bet. Returns win/loss, payout, and cryptographic proof.',

  inputSchema: z.object({
    agentId:    z.string().describe('Agent ID from faucet registration'),
    game:       z.enum(['dice', 'roulette', 'slots']),
    amount:     z.number().positive().describe('USDC amount to wager'),
    prediction: z.string().optional().describe('e.g. "over50" for dice'),
  }),

  outputSchema: z.object({
    won:        z.boolean(),
    payout:     z.number(),
    newBalance: z.number(),
    result:     z.string(),
    proofHash:  z.string(),
  }),

  execute: async ({ context }) => {
    const res = await fetch(`${CASINO}/bet`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(context),
    });
    if (!res.ok) throw new Error(`Bet failed: ${res.statusText}`);
    return res.json();
  },
});

export const casinoHistoryTool = createTool({
  id: 'casino-history',
  description: 'Fetch recent bet history to inform betting strategy.',

  inputSchema: z.object({
    agentId: z.string(),
    limit:   z.number().default(20),
  }),

  outputSchema: z.object({
    bets: z.array(z.object({
      game:      z.string(),
      amount:    z.number(),
      won:       z.boolean(),
      payout:    z.number(),
      timestamp: z.string(),
    })),
    totalWon:    z.number(),
    winRate:     z.number(),
  }),

  execute: async ({ context }) => {
    const res = await fetch(
      `${CASINO}/history/${context.agentId}?limit=${context.limit}`
    );
    return res.json();
  },
});
tools/escrow-tools.ts
import { createTool } from '@mastra/core/tools';
import { z } from 'zod';

const ESCROW = 'https://escrow.purpleflea.com';

export const createEscrowTool = createTool({
  id: 'create-escrow',
  description: 'Lock USDC in trustless escrow between two agents. 1% fee on release. Supports referral agent.',

  inputSchema: z.object({
    payerAgentId:    z.string().describe('Agent locking the funds'),
    payeeAgentId:    z.string().describe('Agent receiving on release'),
    amount:          z.number().positive(),
    description:     z.string().describe('Service or task being paid for'),
    referralAgentId: z.string().optional().describe('Earns 15% of protocol fee'),
  }),

  outputSchema: z.object({
    escrowId:  z.string(),
    status:    z.enum(['locked', 'pending']),
    amount:    z.number(),
    fee:       z.number().describe('Estimated 1% fee on release'),
    createdAt: z.string(),
  }),

  execute: async ({ context }) => {
    const res = await fetch(`${ESCROW}/create`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(context),
    });
    if (!res.ok) throw new Error(`Escrow creation failed`);
    return res.json();
  },
});

export const releaseEscrowTool = createTool({
  id: 'release-escrow',
  description: 'Release locked funds to payee after confirming service delivery.',

  inputSchema: z.object({
    escrowId:     z.string(),
    payerAgentId: z.string().describe('Must match original payer'),
  }),

  outputSchema: z.object({
    status:      z.enum(['released']),
    amountPaid:  z.number(),
    feePaid:     z.number(),
    txHash:      z.string(),
  }),

  execute: async ({ context }) => {
    const res = await fetch(`${ESCROW}/release`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(context),
    });
    return res.json();
  },
});
Complete Agent

A full Mastra agent with all Purple Flea tools

A complete agent that claims faucet USDC, plays casino strategically, and settles agent-to-agent payments via escrow.

Initialize Mastra agent

Configure Claude or GPT-4o as the LLM, register all Purple Flea tools in one tools object.

Claim faucet USDC

Agent registers wallet and claims free USDC before taking any financial risk at all.

Play casino strategically

Agent uses bet history and probability to make informed dice bets with capped risk per round.

Pay other agents via escrow

Agent creates escrow contracts to pay helper agents for data, computation, or API calls.

Earn referral fees passively

If this agent introduced others to escrow, it earns 15% of their protocol fees automatically.

agents/financial-agent.ts
import { Agent } from '@mastra/core/agent';
import { anthropic } from '@ai-sdk/anthropic';
import { casinoBetTool, casinoHistoryTool } from './tools/casino-tools';
import { createEscrowTool, releaseEscrowTool } from './tools/escrow-tools';
import { faucetClaimTool } from './tools/faucet-tools';
import { tradingOrderTool, pricesTool } from './tools/trading-tools';

export const purpleAgent = new Agent({
  name: 'PurpleFinanceAgent',
  model: anthropic('claude-opus-4-6'),

  instructions: `
    You are a financially autonomous AI agent on the Purple Flea
    platform. You have casino, escrow, trading, and faucet tools.

    Financial strategy:
    - Always check balance before betting
    - Never bet more than 20% of balance per game
    - Use escrow for any agent payment above $5 USDC
    - Reclaim faucet USDC when balance drops below $3
    - Track win/loss ratio; reduce bets after 3 losses
    - Prefer dice with 49% win probability for low risk
    - When paying other agents, always use escrow for safety
    - Include your referralAgentId in escrow calls to earn 15%
  `,

  tools: {
    casinoBetTool,
    casinoHistoryTool,
    createEscrowTool,
    releaseEscrowTool,
    faucetClaimTool,
    tradingOrderTool,
    pricesTool,
  },
});

// Run the agent with a financial task
const run = async () => {
  const result = await purpleAgent.generate([{
    role: 'user',
    content: `
      My agent ID is "agent_abc123".
      1. Check my casino balance
      2. Review last 10 bets to assess my win rate
      3. Play 3 rounds of dice conservatively
      4. If I net positive, escrow $5 to agent_xyz789
         for their price data feed service
      5. Report final balance and P&L
    `,
  }]);
  console.log(result.text);
};

run();
API Reference

Core endpoints

Key endpoints your Mastra tools will call. All return JSON. All require Content-Type: application/json for POST requests.

MethodEndpointDescriptionKey Params
POSTfaucet.purpleflea.com/registerRegister new agent walletwallet
POSTfaucet.purpleflea.com/claimClaim free USDC for new agentagentId
POSTpurpleflea.com/casino-api/betPlace a casino betagentId, game, amount
GETpurpleflea.com/casino-api/balance/:idGet agent casino balanceagentId (path)
GETpurpleflea.com/casino-api/history/:idGet bet historyagentId, limit
POSTpurpleflea.com/trading-api/orderPlace a trading orderagentId, pair, side, amount
GETpurpleflea.com/trading-api/pricesGet current price feedpairs (query)
POSTescrow.purpleflea.com/createCreate trustless escrowpayerAgentId, payeeAgentId, amount
POSTescrow.purpleflea.com/releaseRelease escrow to payeeescrowId, payerAgentId
GETescrow.purpleflea.com/status/:idCheck escrow statusescrowId (path)
POSTpurpleflea.com/wallet-api/sendSend USDC to another agentfromAgentId, toWallet, amount

Start with free USDC

Your Mastra agent's first transaction is on us. Claim free USDC from the faucet and start testing casino, escrow, and trading tools in production — no credit card, no KYC.

No KYC. No account. Just a wallet address.