npm install purpleflea

Purple Flea
TypeScript SDK

The official TypeScript and JavaScript client for all Purple Flea APIs. Full type safety, async/await throughout, ESM and CommonJS exports. Runs in Node.js, Cloudflare Workers, Vercel Edge Functions, and Deno — no polyfills required.


Install with any
package manager.

The purpleflea package ships zero runtime dependencies beyond the fetch API, which is available natively in Node.js 18+, all modern browsers, and every supported edge runtime.

$ npm install purpleflea
$ yarn add purpleflea
$ pnpm add purpleflea
quickstart.ts
import { PurpleFlea } from 'purpleflea'; const client = new PurpleFlea({ apiKey: process.env.PURPLEFLEA_API_KEY, }); // Check ETH wallet balance const balance = await client.wallet.getBalance({ chain: 'eth' }); console.log(balance.eth); // "1.2345" // TypeScript infers the full response shape console.log(balance.usdValue); // string console.log(balance.address); // string

ESM and CommonJS.
Both first-class.

The package ships dual exports. The exports field in package.json routes Node.js to the right bundle automatically. TypeScript users get a single .d.ts declaration file that works with both moduleResolution: "bundler" and node16.

esm.ts (ESM / TypeScript)
// ES module import — TypeScript / bundler import { PurpleFlea } from 'purpleflea'; import type { WalletBalance, TradePosition, CasinoGame, } from 'purpleflea'; const client = new PurpleFlea({ apiKey: process.env.PURPLEFLEA_API_KEY!, }); const balance: WalletBalance = await client.wallet.getBalance({ chain: 'eth' });
cjs.js (CommonJS)
// CommonJS require — works in Node.js CJS projects const { PurpleFlea } = require('purpleflea'); const client = new PurpleFlea({ apiKey: process.env.PURPLEFLEA_API_KEY, }); // Same API as ESM — just require instead of import client.wallet .getBalance({ chain: 'eth' }) .then((balance) => { console.log(balance.eth); });

Every API. Fully typed.

01

Wallet — balances, transfers, and swaps

// Get balance — TypeScript infers WalletBalance const balance = await client.wallet.getBalance({ chain: 'eth' }); console.log(balance.eth); // "1.2345" console.log(balance.usdValue); // "4123.67" // Send ETH — returns TransactionResult const tx = await client.wallet.send({ chain: 'eth', to: '0xAbCd...1234', amount: '0.05', }); console.log(tx.hash); // "0xabc123..." // Swap tokens — best DEX route automatically const swap = await client.wallet.swap({ fromToken: 'USDC', toToken: 'ETH', amount: '1000', }); console.log(swap.received); // "0.2987"
02

Trading — perpetual futures with type safety

// Fetch mark price — infers PriceResult const price = await client.trading.getPrice({ market: 'ETH-PERP' }); console.log(price.markPrice); // "3241.50" // Open a long position const position = await client.trading.openPosition({ market: 'ETH-PERP', side: 'long', // 'long' | 'short' sizeUsd: 100, leverage: 10, }); // Close later const result = await client.trading.closePosition({ positionId: position.id, }); console.log(result.pnl); // "+12.45"
03

Casino — provably fair games

// Flip a coin — wager in ETH const game = await client.casino.flipCoin({ choice: 'heads', // 'heads' | 'tails' wager: '0.01', currency: 'eth', }); console.log(game.outcome); // "heads" console.log(game.won); // true console.log(game.payout); // "0.0198" console.log(game.serverSeedHash); // for verification // Roll dice — choose target and direction const dice = await client.casino.rollDice({ target: 50, direction: 'under', wager: '0.005', currency: 'eth', });
04

Domains — search and register

// Search availability const result = await client.domains.search({ name: 'myagent.eth' }); console.log(result.available); // true console.log(result.priceUsd); // "5.00" // Register — sends transaction, returns receipt const reg = await client.domains.register({ name: 'myagent.eth', years: 1, }); console.log(reg.txHash); // "0xabc..." console.log(reg.expires); // "2027-01-01"

LangChain.js and
Vercel AI SDK built in.

Sub-path exports give you pre-built tool definitions for the two most popular TypeScript AI frameworks. No adapters, no manual schema writing — just import and pass to your agent.

langchain_agent.ts
import { createReactAgent } from '@langchain/langgraph/prebuilt'; import { ChatOpenAI } from '@langchain/openai'; import { PurpleFleaTools } from 'purpleflea/langchain'; const tools = new PurpleFleaTools({ apiKey: process.env.PURPLEFLEA_API_KEY!, }).all(); const agent = createReactAgent({ llm: new ChatOpenAI({ model: 'gpt-4o' }), tools, }); const result = await agent.invoke({ messages: [{ role: 'user', content: 'Check my ETH balance' }], });
ai_sdk_agent.ts
import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { purpleFleaTools } from 'purpleflea/ai-sdk'; const { text } = await generateText({ model: openai('gpt-4o'), tools: purpleFleaTools({ apiKey: process.env.PURPLEFLEA_API_KEY!, }), prompt: 'What is the ETH-PERP mark price?', maxSteps: 5, }); console.log(text); // "The current ETH-PERP mark price is $3,241.50"

Discriminated unions.
No more stringly-typed errors.

All SDK errors extend PurpleFleaError and carry a typed code discriminant. TypeScript's narrowing handles the rest — no instanceof chains required.

error_handling.ts
import { PurpleFlea, PurpleFleaError } from 'purpleflea'; const client = new PurpleFlea({ apiKey: 'pf_sk_...' }); try { const tx = await client.wallet.send({ chain: 'eth', to: '0xAbCd...1234', amount: '999', }); } catch (err) { if (err instanceof PurpleFleaError) { switch (err.code) { case 'INSUFFICIENT_FUNDS': // err.available and err.required are typed here console.log(`Need ${err.required}, have ${err.available}`); break; case 'RATE_LIMITED': // err.retryAfter is typed — number of seconds await sleep(err.retryAfter * 1000); break; case 'AUTHENTICATION_FAILED': console.error('Check PURPLEFLEA_API_KEY'); break; default: console.error(`API error: ${err.message}`); } } }

Cloudflare, Vercel,
Deno — all supported.

The SDK uses only Web Standard APIs: fetch, crypto.subtle, and TextEncoder. No Node.js built-ins. Deploy agent logic at the edge with zero cold-start penalty.

Node.js 18+
Cloudflare Workers
Vercel Edge Functions
Deno
Bun
Next.js App Router
route.ts (Next.js App Router / Edge)
export const runtime = 'edge'; import { PurpleFlea } from 'purpleflea'; export async function GET() { const client = new PurpleFlea({ apiKey: process.env.PURPLEFLEA_API_KEY!, }); const balance = await client.wallet.getBalance({ chain: 'eth' }); return Response.json(balance); }

Signed webhooks.
One-line verification.

Import verifyWebhookSignature from the webhooks sub-path. It uses crypto.subtle for constant-time HMAC comparison — safe against timing attacks in any runtime.

webhook.ts
import { verifyWebhookSignature } from 'purpleflea/webhooks'; import type { WebhookEvent } from 'purpleflea/webhooks'; export async function POST(req: Request) { const body = await req.text(); const sig = req.headers.get('x-purpleflea-signature') ?? ''; const secret = process.env.PURPLEFLEA_WEBHOOK_SECRET!; // Throws WebhookSignatureError if invalid const event: WebhookEvent = await verifyWebhookSignature(body, sig, secret); if (event.type === 'wallet.transaction.confirmed') { // event.data is typed as TransactionConfirmedData console.log(`Confirmed: ${event.data.hash}`); } return Response.json({ ok: true }); }

Production-ready
from day one.

🔑

Full type safety

Every request parameter and response field is typed. TypeScript infers the full response shape — no any anywhere in the SDK source.

Zero dependencies

Built on the native fetch API. No axios, no node-fetch, no bloat. Your bundle stays lean and your cold starts stay fast.

🔄

Auto-retry with backoff

Configurable retry logic for 5xx errors and rate limits. Set maxRetries and backoffFactor on the constructor.

🔗

Framework integrations

Sub-path exports for LangChain.js and the Vercel AI SDK. Import once, get pre-built tool definitions with JSON schemas and descriptions already filled in.

📄

Streaming support

The trading and casino modules support optional streaming responses for real-time updates. Use the stream: true option to get an async iterable.

🔧

Mock client for tests

Pass a custom fetch implementation to the constructor. Unit test your agent logic against a deterministic mock without any network calls.


More integrations.

Ship your first agent
in under ten minutes.

Free to start. No KYC. npm install and your TypeScript agent has a wallet, trading desk, casino, and domain registrar.