JSPM

  • Created
  • Published
  • Downloads 376
  • Score
    100M100P100Q90730F
  • License MIT

High-performance Polymarket SDK

Package Exports

  • @varla/polymarket

Readme

@varla/polymarket

npm version License: MIT CI

High-performance Polymarket SDK — 139% faster than the official SDK.

A modern, lightweight TypeScript client for Polymarket's CLOB and Gamma APIs with full trading support.

Why @varla/polymarket?

Metric @varla/polymarket @polymarket/clob-client
Average Speed 139% faster baseline
Bundle Size ~50KB ~500KB (ethers.js)
Runtime Bun/Node/Edge Node.js only
Signing viem (native) ethers.js
HTTP fetch axios

Benchmark Highlights

Function Speedup
getLastTradePrice 261% faster
getMidpoints 176% faster
deleteApiKey 144% faster
cancelOrder 73% faster
getOpenOrders 56% faster
Full benchmark results (88 functions)
  • 81 functions faster (92%)
  • 7 functions slower (8%)
  • Best case: 1233% faster (RFQ operations)

Run benchmarks yourself:

POLYMARKET_BENCH=true bun test packages/polymarket/test/sdk

Installation

bun add @varla/polymarket
# or
npm install @varla/polymarket
# or
pnpm add @varla/polymarket

Peer dependencies:

  • viem ^2.0.0

Quick Start

Read-Only (No Auth Required)

import { GammaClient, ClobClient } from "@varla/polymarket";

// Fetch markets from Gamma API
const gamma = new GammaClient();
const markets = await gamma.getMarkets({ limit: 10 });

// Get orderbook from CLOB
const clob = new ClobClient();
const book = await clob.getBook(markets[0].clobTokenIds[0]);
console.log("Best bid:", book.bids[0]);
console.log("Best ask:", book.asks[0]);

// Get prices
const midpoint = await clob.getMidpoint(markets[0].clobTokenIds[0]);
const spread = await clob.getSpread(markets[0].clobTokenIds[0]);

Authenticated Trading

import { createWalletClient, http } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { polygon } from "viem/chains";
import { ClobTradingClient } from "@varla/polymarket";

// Create wallet
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const walletClient = createWalletClient({
  account,
  chain: polygon,
  transport: http(),
});

// Create trading client
const client = new ClobTradingClient(walletClient);
await client.init(); // Derives API key from wallet

// Place a limit order
const response = await client.createAndPostOrder(
  {
    tokenId: "123456...",  // From Gamma API
    price: 0.50,           // $0.50 per share
    size: 100,             // 100 shares
    side: "BUY",
  },
  {
    tickSize: "0.01",      // From Gamma API
    negRisk: false,        // From Gamma API
  },
  "GTC" // Good-Til-Cancelled
);

console.log("Order ID:", response.orderID);

// Cancel order
await client.cancelOrder(response.orderID);

// Get open orders
const orders = await client.getOpenOrders();

WebSocket (Real-time Updates)

import { ClobWsClient } from "@varla/polymarket";

const ws = new ClobWsClient({
  onBookUpdate: (update) => {
    console.log("Market:", update.market);
    console.log("Best bid:", update.bids[0]);
    console.log("Best ask:", update.asks[0]);
  },
  onConnect: () => console.log("Connected"),
  onDisconnect: (reason) => console.log("Disconnected:", reason),
});

ws.connect();
ws.subscribeMarket("0x5f65177b394277fd294cd75650044e32ba009a95...");

// Cleanup
ws.close();

Order Persistence (SQLite)

Track orders locally for fast queries and restart recovery:

import { 
  ClobTradingClient, 
  createSqliteOrderPersistence,
  createTrackedOrder,
} from "@varla/polymarket";

const persistence = createSqliteOrderPersistence("./orders.db");

// Track placed orders
const order = createTrackedOrder({
  orderId: response.orderID,
  market: "0x...",
  tokenId: "123456...",
  side: "BUY",
  price: 0.5,
  size: 100,
  orderType: "GTC",
  status: "OPEN",
});
await persistence.save(order);

// Query orders
const openOrders = await persistence.getOpen();
const marketOrders = await persistence.getByMarket("0x...");

// Cleanup old orders
await persistence.prune(24 * 60 * 60 * 1000); // 24h

persistence.close();

API Reference

Clients

Client Purpose
GammaClient Market discovery, metadata, token IDs
ClobClient Public orderbook, prices, trades (read-only)
ClobTradingClient Authenticated trading operations
ClobWsClient Real-time WebSocket updates

ClobTradingClient Methods

// Initialization
client.init()                           // Derive/create API key
client.setCredentials(creds)            // Set API key manually

// Orders
client.createOrder(params, options)     // Create signed order
client.postOrder(order, type)           // Post to CLOB
client.createAndPostOrder(params, options, type)  // Combined
client.getOrder(orderId)                // Get order details
client.getOpenOrders(filter?)           // List open orders

// Cancellation
client.cancelOrder(orderId)             // Cancel one order
client.cancelOrders(orderIds)           // Cancel multiple
client.cancelMarketOrders({ market })   // Cancel by market
client.cancelAll()                      // Cancel all orders

// Account
client.getClosedOnlyMode()              // Check if account is restricted

Order Types

type Side = "BUY" | "SELL";
type OrderType = "GTC" | "GTD" | "FOK";  // Good-Til-Cancel, Good-Til-Date, Fill-Or-Kill
type OrderStatus = "OPEN" | "MATCHED" | "FILLED" | "CANCELLED" | "EXPIRED";

Configuration

Environment Variables

# For authenticated trading
POLYMARKET_API_KEY=...
POLYMARKET_SECRET=...
POLYMARKET_PASSPHRASE=...

# For signing orders
PRIVATE_KEY=0x...

Custom Endpoints

const client = new ClobTradingClient(walletClient, {
  baseUrl: "https://clob.polymarket.com",  // default
  requestTimeoutMs: 15000,
  maxRetries: 3,
});

Signature Types

Type Value Use Case
EOA 0 Direct wallet (Metamask, Rabby, hardware)
POLY_PROXY 1 Polymarket Magic/Email login
// For Magic/Email wallets
const client = new ClobTradingClient(walletClient, {
  signatureType: 1,  // POLY_PROXY
  funderAddress: "0x...",  // Your Polymarket profile address
});

Error Handling

import { OrderValidationError, ClobHttpError } from "@varla/polymarket";

try {
  await client.createAndPostOrder(params, options, "GTC");
} catch (error) {
  if (error instanceof OrderValidationError) {
    console.error("Invalid order:", error.message);
  } else if (error instanceof ClobHttpError) {
    if (error.status === 401) {
      // API key expired, reinitialize
      await client.init();
    }
  }
}

Validation Utilities

import { 
  validateOrderParams, 
  roundToTickSize,
  isValidPrice,
  getMinimumOrderSize,
} from "@varla/polymarket";

// Validate before creating
validateOrderParams(params, options); // throws OrderValidationError

// Round to valid tick
const price = roundToTickSize(0.505, "0.01"); // 0.51

// Check price validity
isValidPrice(0.505, "0.01"); // false

// Get minimum shares for $1 order
getMinimumOrderSize(0.5); // 2 shares

Testing

# Unit tests
bun test packages/polymarket/test/unit

# All tests
bun test packages/polymarket

# With coverage
bun test packages/polymarket --coverage

# Benchmarks (compare with official SDK)
POLYMARKET_BENCH=true bun test packages/polymarket/test/sdk

# Live tests (requires API keys)
POLYMARKET_LIVE_TESTS=1 bun test packages/polymarket/test/live

Architecture

┌─────────────────────────────────────────────────────────────┐
│                    ClobTradingClient                        │
│  - init(), createAndPostOrder(), cancelOrder(), etc.        │
├─────────────────────┬───────────────────┬───────────────────┤
│   ClobAuthManager   │  ClobOrderBuilder │  HTTP + Auth      │
│   - L1/L2 auth      │  - EIP712 signing │  - HMAC headers   │
│   - API key mgmt    │  - Validation     │                   │
├─────────────────────┴───────────────────┴───────────────────┤
│                       viem WalletClient                      │
│                    (signTypedData, etc.)                     │
└─────────────────────────────────────────────────────────────┘

┌──────────────────┐  ┌─────────────────┐  ┌────────────────┐
│ OrderPersistence │  │  ClobWsClient   │  │  GammaClient   │
│ - SQLite/Memory  │  │  - WebSocket    │  │  - Markets     │
│ - Order tracking │  │  - Book updates │  │  - Metadata    │
└──────────────────┘  └─────────────────┘  └────────────────┘

License

MIT © Varla