@varla/polymarket
v1.1.4
Published
High-performance Polymarket SDK
Downloads
458
Maintainers
Readme
@varla/polymarket
High-performance Polymarket SDK — ~140% 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 | ~140% 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 |
- 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/sdkInstallation
bun add @varla/polymarket
# or
npm install @varla/polymarket
# or
pnpm add @varla/polymarketPeer 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.listMarkets({ active: true, 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]);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();Complete API Reference
GammaClient (28 methods)
Market discovery, metadata, and content API.
import { GammaClient } from "@varla/polymarket";
const gamma = new GammaClient(opts?: GammaClientOpts);Markets
| Method | Parameters | Returns |
|--------|------------|---------|
| listMarkets | { active?, closed?, limit?, offset?, tag_id? } | Promise<GammaMarket[]> |
| getMarketsByConditionIds | conditionIds: string[] | Promise<GammaMarket[]> |
| getMarketById | id: string | Promise<GammaMarket> |
| getMarketBySlug | slug: string | Promise<GammaMarket> |
| getMarketTags | marketId: string | Promise<GammaTag[]> |
Events
| Method | Parameters | Returns |
|--------|------------|---------|
| listEvents | { active?, closed?, limit?, offset?, tag_id?, series_id?, order?, ascending? } | Promise<GammaEvent[]> |
| getEventById | id: string | Promise<GammaEvent> |
| getEventBySlug | slug: string | Promise<GammaEvent> |
| getEventTags | eventId: string | Promise<GammaTag[]> |
Tags
| Method | Parameters | Returns |
|--------|------------|---------|
| listTags | { limit?, offset? } | Promise<GammaTag[]> |
| getTagById | id: string | Promise<GammaTag> |
| getTagBySlug | slug: string | Promise<GammaTag> |
| getRelatedTagsById | id: string | Promise<GammaTag[]> |
| getRelatedTagsBySlug | slug: string | Promise<GammaTag[]> |
| getTagRelationshipsById | id: string | Promise<GammaTagRelationship[]> |
| getTagRelationshipsBySlug | slug: string | Promise<GammaTagRelationship[]> |
Sports
| Method | Parameters | Returns |
|--------|------------|---------|
| getSports | — | Promise<GammaSport[]> |
| listTeams | { sport?, limit?, offset? } | Promise<GammaTeam[]> |
| getValidSportsMarketTypes | — | Promise<GammaSportsMarketType[]> |
Series
| Method | Parameters | Returns |
|--------|------------|---------|
| listSeries | { limit?, offset? } | Promise<GammaSeries[]> |
| getSeriesById | id: string | Promise<GammaSeries> |
Search
| Method | Parameters | Returns |
|--------|------------|---------|
| search | query: string, { limit?, offset? } | Promise<GammaSearchResult> |
Profiles
| Method | Parameters | Returns |
|--------|------------|---------|
| getPublicProfile | address: string | Promise<GammaPublicProfile> |
Comments
| Method | Parameters | Returns |
|--------|------------|---------|
| listComments | { eventId?, marketId?, limit?, offset? } | Promise<GammaComment[]> |
| getCommentById | id: string | Promise<GammaComment> |
| getCommentsByUser | address: string, { limit?, offset? } | Promise<GammaComment[]> |
Builders
| Method | Parameters | Returns |
|--------|------------|---------|
| getBuilderLeaderboard | { period?, limit?, offset? } | Promise<GammaBuilderLeaderboardEntry[]> |
| getBuilderVolume | { address?, startDate?, endDate? } | Promise<GammaBuilderVolumePoint[]> |
Health
| Method | Parameters | Returns |
|--------|------------|---------|
| healthCheck | — | Promise<{ status: string }> |
ClobClient (5 methods)
Public orderbook, prices, and trades (read-only with resilience).
import { ClobClient } from "@varla/polymarket";
const clob = new ClobClient(config?: Partial<ClobClientConfig>);| Method | Parameters | Returns |
|--------|------------|---------|
| getMidpoint | tokenId: string | Promise<ClobMidpointResponse> |
| getBook | tokenId: string | Promise<ClobBookResponse> |
| getPricesHistory | { tokenId, startTs, endTs, interval, fidelity? } | Promise<ClobPricesHistoryResponse> |
| getMetrics | — | ClobClientMetrics |
| getCircuitState | — | CircuitState |
| resetCircuitBreaker | — | void |
ClobTradingClient (30 methods)
Authenticated trading operations.
import { ClobTradingClient } from "@varla/polymarket";
const client = new ClobTradingClient(walletClient, config?: ClobTradingClientConfig);Initialization
| Method | Parameters | Returns |
|--------|------------|---------|
| init | — | Promise<void> |
| isInitialized | — | boolean |
| getCredentials | — | ApiKeyCreds |
| setCredentials | creds: ApiKeyCreds | void |
Orders
| Method | Parameters | Returns |
|--------|------------|---------|
| createOrder | params: OrderParams, options: MarketOptions | Promise<SignedOrder> |
| postOrder | signedOrder: SignedOrder, orderType?: OrderType | Promise<OrderResponse> |
| createAndPostOrder | params: OrderParams, options: MarketOptions, orderType?: OrderType | Promise<OrderResponse> |
| postOrders | signedOrders: SignedOrder[], orderType?: OrderType | Promise<BatchOrderResponse> |
| createAndPostOrders | ordersParams: Array<{params, options}>, orderType?: OrderType | Promise<BatchOrderResponse> |
| getOrder | orderId: string | Promise<Order> |
| getOpenOrders | filter?: OpenOrdersFilter | Promise<Order[]> |
Market Orders
| Method | Parameters | Returns |
|--------|------------|---------|
| marketBuy | params: MarketBuyParams, options: MarketOptions, timeInForce?: TimeInForce | Promise<OrderResponse> |
| marketSell | params: MarketSellParams, options: MarketOptions, timeInForce?: TimeInForce | Promise<OrderResponse> |
| getOrderBook | tokenId: string | Promise<OrderBook> |
Cancellation
| Method | Parameters | Returns |
|--------|------------|---------|
| cancelOrder | orderId: string | Promise<CancelResponse> |
| cancelOrders | orderIds: string[] | Promise<CancelResponse> |
| cancelMarketOrders | { market?, asset_id? } | Promise<CancelResponse> |
| cancelAll | — | Promise<CancelResponse> |
Account
| Method | Parameters | Returns |
|--------|------------|---------|
| getClosedOnlyMode | — | Promise<{ closedOnly: boolean; reason?: string }> |
| getApiKeys | — | Promise<{ apiKeys: Array<{apiKey, createdAt}> }> |
| deleteApiKey | — | Promise<void> |
Trades & History
| Method | Parameters | Returns |
|--------|------------|---------|
| getTrades | filter?: TradeHistoryFilter | Promise<Trade[]> |
| heartbeat | — | Promise<HeartbeatResponse> |
Rewards
| Method | Parameters | Returns |
|--------|------------|---------|
| getEarningsForDay | date: string | Promise<UserEarnings> |
| getTotalEarningsForDay | date: string | Promise<UserEarnings> |
| getLiquidityRewardPercentages | — | Promise<LiquidityRewardPercentages> |
| getRewardsMarkets | — | Promise<RewardsMarket[]> |
Builder API
| Method | Parameters | Returns |
|--------|------------|---------|
| createBuilderApiKey | — | Promise<BuilderApiKey> |
| getBuilderApiKeys | — | Promise<BuilderApiKeyInfo[]> |
| revokeBuilderApiKey | — | Promise<void> |
| getBuilderTrades | filter?: BuilderTradesFilter, cursor?: string | Promise<BuilderTradesResponse> |
DataApiClient (16 methods)
Positions, trades, leaderboards, and analytics.
import { DataApiClient } from "@varla/polymarket";
const data = new DataApiClient(opts?: DataApiClientOpts);Positions
| Method | Parameters | Returns |
|--------|------------|---------|
| getCurrentPositions | { address, conditionId?, limit?, offset? } | Promise<DataPosition[]> |
| getClosedPositions | { address, limit?, offset? } | Promise<DataClosedPosition[]> |
| getTotalPositionValue | address: string | Promise<DataPositionValue> |
Trades & Activity
| Method | Parameters | Returns |
|--------|------------|---------|
| getTrades | { address?, conditionId?, limit?, offset? } | Promise<DataTrade[]> |
| getUserActivity | { address, limit?, offset? } | Promise<DataActivity[]> |
Analytics
| Method | Parameters | Returns |
|--------|------------|---------|
| getTopHolders | { conditionId, outcomeIndex?, limit? } | Promise<DataTopHolder[]> |
| getTraderLeaderboard | { period?, category?, order?, limit?, offset? } | Promise<DataLeaderboardEntry[]> |
| getOpenInterest | { conditionId?, asset? } | Promise<DataOpenInterest> |
| getLiveVolume | { eventId?, conditionId? } | Promise<DataVolume> |
Pricing & Orderbook
| Method | Parameters | Returns |
|--------|------------|---------|
| getPriceHistory | { tokenId, interval?, startTs?, endTs?, fidelity? } | Promise<DataPriceHistory> |
| getOrderBookSummary | tokenId: string | Promise<DataOrderBookSummary> |
| getOrderBookSummaries | tokenIds: string[] | Promise<DataOrderBookSummary[]> |
| getSpreads | tokenIds: string[] | Promise<DataSpread[]> |
Misc
| Method | Parameters | Returns |
|--------|------------|---------|
| getTotalMarketsTraded | address: string | Promise<DataMarketsTraded> |
| getAccountingSnapshot | address: string | Promise<Response> |
| healthCheck | — | Promise<{ status: string }> |
BridgeClient (5 methods)
Deposit/withdrawal functionality through the Relay bridge.
import { BridgeClient } from "@varla/polymarket";
const bridge = new BridgeClient(opts?: BridgeClientOpts);| Method | Parameters | Returns |
|--------|------------|---------|
| createDepositAddresses | { userAddress, chain, asset? } | Promise<BridgeDepositAddress> |
| createWithdrawalAddresses | { userAddress, destinationAddress, chain, asset, amount } | Promise<BridgeWithdrawalAddress> |
| getQuote | { fromChain, toChain, fromAsset, toAsset, amount } | Promise<BridgeQuote> |
| getSupportedAssets | — | Promise<BridgeSupportedAsset[]> |
| getTransactionStatus | transactionId: string | Promise<BridgeTransactionStatus> |
ClobWsClient (7 methods)
Real-time WebSocket updates.
import { ClobWsClient } from "@varla/polymarket";
const ws = new ClobWsClient(events?: ClobWsEvents, config?: ClobWsConfig);| Method | Parameters | Returns |
|--------|------------|---------|
| connect | — | void |
| close | — | void |
| subscribeMarket | market: string | void |
| unsubscribeMarket | market: string | void |
| subscribeMarkets | markets: string[] | void |
| getState | — | ClobWsState |
| isConnected | — | boolean |
| getSubscribedMarkets | — | string[] |
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();
}
}
}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/liveArchitecture
┌─────────────────────────────────────────────────────────────┐
│ ClobTradingClient │
│ - init(), createAndPostOrder(), cancelOrder(), etc. │
├─────────────────────┬───────────────────┬───────────────────┤
│ ClobAuthManager │ ClobOrderBuilder │ HTTP + Auth │
│ - L1/L2 auth │ - EIP712 signing │ - HMAC headers │
│ - API key mgmt │ - Validation │ │
├─────────────────────┴───────────────────┴───────────────────┤
│ viem WalletClient │
│ (signTypedData, etc.) │
└─────────────────────────────────────────────────────────────┘
┌──────────────────┐ ┌─────────────────┐ ┌────────────────┐
│ GammaClient │ │ DataApiClient │ │ BridgeClient │
│ - 28 methods │ │ - 16 methods │ │ - 5 methods │
│ - Markets, Tags │ │ - Positions │ │ - Deposits │
│ - Events, Sports │ │ - Analytics │ │ - Withdrawals │
└──────────────────┘ └─────────────────┘ └────────────────┘
┌──────────────────┐ ┌─────────────────┐
│ ClobClient │ │ ClobWsClient │
│ - 5 methods │ │ - 7 methods │
│ - Circuit break │ │ - Real-time │
│ - Rate limiting │ │ - Auto-connect │
└──────────────────┘ └─────────────────┘License
MIT © Varla
