Overview
The OrderBookApi class provides direct access to the CoW Protocol OrderBook API. It handles quotes, order submission, order retrieval, cancellations, and trading data with built-in rate limiting, retries, and error handling.
Installation
npm install @cowprotocol/sdk-order-book
# or
pnpm add @cowprotocol/sdk-order-book
# or
yarn add @cowprotocol/sdk-order-book
Constructor
new OrderBookApi ( context ?: PartialApiContext )
API configuration options Show PartialApiContext properties
Chain ID (e.g., 1 for Mainnet, 100 for Gnosis Chain)
env
'prod' | 'staging'
default: "prod"
Environment to use
Partner API key for authenticated access with higher rate limits
Custom API endpoint URLs per chain
Rate limiter configuration
Exponential backoff configuration for retries
Basic Setup
import { OrderBookApi , SupportedChainId } from '@cowprotocol/sdk-order-book'
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
env: 'prod' ,
})
Quote Methods
getQuote
Get a quote for an order before signing and submitting.
async getQuote (
requestBody : OrderQuoteRequest ,
contextOverride ?: PartialApiContext
): Promise < OrderQuoteResponse >
requestBody
OrderQuoteRequest
required
Quote request parameters Show OrderQuoteRequest properties
Receiver address (can be same as from)
Sell amount (for sell orders)
Buy amount (for buy orders)
signingScheme
SigningScheme
default: "eip712"
Signing scheme (eip712, ethsign, presign, eip1271)
Order expiration timestamp
priceQuality
'fast' | 'optimal'
default: "optimal"
Quote price quality
Hydrated quote ready for signing Show OrderQuoteResponse properties
Quote details with all order parameters
Example
const quoteRequest = {
sellToken: '0xA0b86a33E6417b528874E10EB3a95beb4F25A0E3' , // GNO
buyToken: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2' , // WETH
from: '0x123...' ,
receiver: '0x123...' ,
sellAmountBeforeFee: '1000000000000000000' , // 1 GNO
kind: 'sell' ,
}
const { quote } = await orderBookApi . getQuote ( quoteRequest )
console . log ( 'Quote:' , quote )
Order Management Methods
sendOrder
Submit a signed order to the order book.
async sendOrder (
requestBody : OrderCreation ,
contextOverride ?: PartialApiContext
): Promise < string >
Signed order data Show OrderCreation properties
Example
import { OrderSigningUtils } from '@cowprotocol/sdk-order-signing'
// After getting a quote and signing it
const signingResult = await OrderSigningUtils . signOrder (
quote ,
chainId ,
signer
)
const orderId = await orderBookApi . sendOrder ({
... quote ,
... signingResult ,
})
console . log ( 'Order submitted:' , orderId )
getOrder
Retrieve order details by UID.
async getOrder (
orderUid : string ,
contextOverride ?: PartialApiContext
): Promise < EnrichedOrder >
Complete order information Show EnrichedOrder properties
Order status (open, fulfilled, cancelled, expired)
Example
const order = await orderBookApi . getOrder (
'0xd64389693b6cf89ad6c140a113b10df08073e5ef...'
)
console . log ( 'Order status:' , order . status )
console . log ( 'Sell amount:' , order . sellAmount )
getOrders
Get all orders for a specific owner.
async getOrders (
request : GetOrdersRequest ,
contextOverride ?: PartialApiContext
): Promise < Array < EnrichedOrder >>
Query parameters Show GetOrdersRequest properties
Example
const orders = await orderBookApi . getOrders ({
owner: '0x123...' ,
limit: 10 ,
offset: 0 ,
})
console . log ( `Found ${ orders . length } orders` )
orders . forEach ( order => {
console . log ( `Order ${ order . uid } : ${ order . status } ` )
})
getOrderMultiEnv
Attempt to get an order from multiple environments (prod/staging).
async getOrderMultiEnv (
orderUid : string ,
contextOverride ?: PartialApiContext
): Promise < EnrichedOrder >
Order found in any environment
Example
// Will check prod first, then staging
const order = await orderBookApi . getOrderMultiEnv (
'0xd64389693b6cf89ad6c140a113b10df08073e5ef...'
)
sendSignedOrderCancellations
Cancel one or more orders (off-chain).
async sendSignedOrderCancellations (
requestBody : OrderCancellations ,
contextOverride ?: PartialApiContext
): Promise < void >
requestBody
OrderCancellations
required
Signed cancellation request Show OrderCancellations properties
Array of order UIDs to cancel
This is a “soft cancel” and may not prevent execution if the order is already being processed.
Example
import { OrderSigningUtils } from '@cowprotocol/sdk-order-signing'
const orderUids = [ '0xd64389...' , '0xa12345...' ]
const cancellationSigning = await OrderSigningUtils . signOrderCancellations (
orderUids ,
chainId ,
signer
)
await orderBookApi . sendSignedOrderCancellations ({
... cancellationSigning ,
orderUids ,
})
console . log ( 'Orders cancelled' )
Trading Data Methods
getTrades
Get all trades for an owner or order.
async getTrades (
request : GetTradesRequest ,
contextOverride ?: PartialApiContext
): Promise < Array < Trade >>
Query parameters (must specify owner OR orderUid) Show GetTradesRequest properties
Example
// Get all trades for an owner
const trades = await orderBookApi . getTrades ({
owner: '0x123...' ,
limit: 20 ,
})
// Get trades for a specific order
const orderTrades = await orderBookApi . getTrades ({
orderUid: '0xd64389...' ,
})
console . log ( `Found ${ trades . length } trades` )
getTxOrders
Get all orders from a settlement transaction.
async getTxOrders (
txHash : string ,
contextOverride ?: PartialApiContext
): Promise < Array < EnrichedOrder >>
Settlement transaction hash
Orders settled in the transaction
Example
const orders = await orderBookApi . getTxOrders (
'0xabc123...'
)
console . log ( `Transaction included ${ orders . length } orders` )
Price & Data Methods
getNativePrice
Get the native price of a token.
async getNativePrice (
tokenAddress : string ,
contextOverride ?: PartialApiContext
): Promise < NativePriceResponse >
Native price (e.g., ETH price on Ethereum)
Example
const price = await orderBookApi . getNativePrice (
'0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' // USDC
)
console . log ( 'Native price:' , price )
getTotalSurplus
Get total surplus earned by a user.
async getTotalSurplus (
address : string ,
contextOverride ?: PartialApiContext
): Promise < TotalSurplus >
Total surplus information
Example
const surplus = await orderBookApi . getTotalSurplus ( '0x123...' )
console . log ( 'Total surplus:' , surplus )
App Data Methods
getAppData
Retrieve full app data for a given hash.
async getAppData (
appDataHash : string ,
contextOverride ?: PartialApiContext
): Promise < AppDataObject >
Example
const appData = await orderBookApi . getAppData (
'0x0000000000000000000000000000000000000000000000000000000000000000'
)
console . log ( 'App data:' , appData )
uploadAppData
Upload app data to the OrderBook.
async uploadAppData (
appDataHash : string ,
fullAppData : string ,
contextOverride ?: PartialApiContext
): Promise < AppDataObject >
Full app data content (JSON string)
Example
const fullAppData = JSON . stringify ({
version: '1.0.0' ,
appCode: 'My App' ,
metadata: {},
})
const result = await orderBookApi . uploadAppData (
appDataHash ,
fullAppData
)
Competition & Analytics Methods
getSolverCompetition
Get solver competition details for an auction.
async getSolverCompetition (
auctionIdOrTxHash : number | string ,
contextOverride ?: PartialApiContext
): Promise < SolverCompetitionResponse >
Auction ID or transaction hash
competition
SolverCompetitionResponse
Solver competition data
Example
// By auction ID
const competition = await orderBookApi . getSolverCompetition ( 12345 )
// By transaction hash
const competition2 = await orderBookApi . getSolverCompetition ( '0xabc...' )
getOrderCompetitionStatus
Get competition status while order is open.
async getOrderCompetitionStatus (
orderUid : string ,
contextOverride ?: PartialApiContext
): Promise < CompetitionOrderStatus >
Utility Methods
getVersion
Get API version.
async getVersion (
contextOverride ?: PartialApiContext
): Promise < string >
getOrderLink
Generate API endpoint URL for an order.
getOrderLink (
orderUid : string ,
contextOverride ?: PartialApiContext
): string
Full API URL to get the order
Example
const url = orderBookApi . getOrderLink ( '0xd64389...' )
console . log ( 'Order URL:' , url )
Partner API Usage
For authenticated access with higher rate limits:
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
apiKey: 'your-partner-api-key' ,
env: 'prod' ,
})
This automatically routes requests through:
Production: https://partners.cow.fi
Staging: https://partners.barn.cow.fi
Custom Configuration
Rate Limiting
import { RateLimiterOpts } from 'limiter'
const limiterOpts : RateLimiterOpts = {
tokensPerInterval: 5 ,
interval: 'second' ,
}
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
limiterOpts ,
})
Retry Configuration
import { BackoffOptions } from 'exponential-backoff'
const backoffOpts : BackoffOptions = {
numOfAttempts: 5 ,
maxDelay: Infinity ,
jitter: 'none' ,
}
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
backoffOpts ,
})
Custom Endpoints
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
baseUrls: {
[SupportedChainId. MAINNET ]: 'https://your-custom-endpoint.com' ,
},
})
Error Handling
import { OrderBookApiError } from '@cowprotocol/sdk-order-book'
try {
const order = await orderBookApi . getOrder ( orderUid )
} catch ( error ) {
if ( error instanceof OrderBookApiError ) {
console . error ( 'API error:' , error . response . status , error . message )
} else {
console . error ( 'Unexpected error:' , error )
}
}
See Also