@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.
Installationbun add @varla/polymarket
npm install @varla/polymarket
pnpm add @varla/polymarket Peer dependencies:
Quick Start Read-Only (No Auth Required)import { GammaClient, ClobClient } from "@varla/polymarket" ;
const gamma = new GammaClient ( ) ;
const markets = await gamma. listMarkets ( { active: true , limit: 10 } ) ;
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 ] ) ;
const midpoint = await clob. getMidpoint ( markets[ 0 ] . clobTokenIds[ 0 ] ) ; Authenticated Tradingimport { createWalletClient, http } from "viem" ;
import { privateKeyToAccount } from "viem/accounts" ;
import { polygon } from "viem/chains" ;
import { ClobTradingClient } from "@varla/polymarket" ;
const account = privateKeyToAccount ( process. env. PRIVATE_KEY as ` 0x ${ string } ` ) ;
const walletClient = createWalletClient ( {
account,
chain: polygon,
transport: http ( ) ,
} ) ;
const client = new ClobTradingClient ( walletClient) ;
await client. init ( ) ;
const response = await client. createAndPostOrder (
{
tokenId: "123456..." ,
price: 0.50 ,
size: 100 ,
side: "BUY" ,
} ,
{
tickSize: "0.01" ,
negRisk: false ,
} ,
"GTC"
) ;
console . log ( "Order ID:" , response. orderID) ;
await client. cancelOrder ( response. orderID) ;
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..." ) ;
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[]>
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>
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
POLYMARKET_API_KEY = .. .
POLYMARKET_SECRET = .. .
POLYMARKET_PASSPHRASE = .. .
PRIVATE_KEY = 0x.. . Custom Endpointsconst client = new ClobTradingClient ( walletClient, {
baseUrl: "https://clob.polymarket.com" ,
requestTimeoutMs: 15000 ,
maxRetries: 3 ,
} ) ; Signature Types
Type
Value
Use Case
EOA
0
Direct wallet (Metamask, Rabby, hardware)
POLY_PROXY
1
Polymarket Magic/Email login
const client = new ClobTradingClient ( walletClient, {
signatureType: 1 ,
funderAddress: "0x..." ,
} ) ; Error Handlingimport { 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 ) {
await client. init ( ) ;
}
}
} Testing
bun test packages/polymarket/test/unit
bun test packages/polymarket
bun test packages/polymarket --coverage
POLYMARKET_BENCH = true bun test packages/polymarket/test/sdk
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.) │
└─────────────────────────────────────────────────────────────┘
┌──────────────────┐ ┌─────────────────┐ ┌────────────────┐
│ 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 │
└──────────────────┘ └─────────────────┘ LicenseMIT © Varla