Overview
The TradingSdk class provides a comprehensive interface for interacting with CoW Protocol’s trading functionality. It simplifies order creation, quote fetching, order management, and token approvals.
Installation
npm install @cowprotocol/sdk-trading
# or
pnpm add @cowprotocol/sdk-trading
# or
yarn add @cowprotocol/sdk-trading
Constructor
new TradingSdk (
traderParams ?: Partial < TraderParameters > ,
options ?: Partial < TradingSdkOptions > ,
adapter ?: AbstractProviderAdapter
)
traderParams
Partial<TraderParameters>
Default trader parameters to use for all operations Chain ID for the network (e.g., 1 for Mainnet, 100 for Gnosis Chain)
Unique application identifier for order tracking
Wallet signer (can be provided per-operation instead)
options
Partial<TradingSdkOptions>
SDK configuration options Enable detailed logging of trading steps
Custom OrderBookApi instance (useful for Partner API)
Provider adapter (ViemAdapter, EthersV5Adapter, or EthersV6Adapter)
Basic Setup
import { TradingSdk , SupportedChainId } from '@cowprotocol/sdk-trading'
import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
import { createPublicClient , http , privateKeyToAccount } from 'viem'
import { sepolia } from 'viem/chains'
const adapter = new ViemAdapter ({
provider: createPublicClient ({
chain: sepolia ,
transport: http ( 'YOUR_RPC_URL' )
}),
signer: privateKeyToAccount ( 'YOUR_PRIVATE_KEY' as `0x ${ string } ` )
})
const sdk = new TradingSdk (
{
chainId: SupportedChainId . SEPOLIA ,
appCode: 'YOUR_APP_CODE' ,
},
{
enableLogging: true ,
},
adapter
)
Methods
postSwapOrder
Create a market order by fetching a quote and posting it in a single call.
async postSwapOrder (
params : TradeParameters ,
advancedSettings ?: SwapAdvancedSettings
): Promise < OrderPostingResult >
Trade parameters Order type: SELL (sell exact amount) or BUY (buy exact amount)
Amount in atoms (smallest unit of token)
Slippage tolerance in basis points (50 = 0.5%)
Order validity duration in seconds (default 30 minutes)
Address to receive bought tokens (defaults to order creator)
Whether order can be partially filled
Partner fee configuration
Advanced trading settings quoteRequest
Partial<OrderQuoteRequest>
Override quote request parameters (signingScheme, priceQuality, etc.)
Order metadata (hooks, referrer, etc.)
Unique order identifier (UID)
Example
import { OrderKind } from '@cowprotocol/sdk-trading'
const params = {
kind: OrderKind . SELL ,
sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14' ,
sellTokenDecimals: 18 ,
buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59' ,
buyTokenDecimals: 18 ,
amount: '1000000000000000000' , // 1 token
slippageBps: 200 , // 2%
validFor: 1200 , // 20 minutes
}
const { orderId } = await sdk . postSwapOrder ( params )
console . log ( 'Order created:' , orderId )
getQuote
Get a quote for a trade and optionally post it later.
async getQuote (
params : TradeParameters ,
advancedSettings ?: SwapAdvancedSettings
): Promise < QuoteAndPost >
Quote information including amounts, costs, and order data Original trade parameters
Suggested slippage based on market conditions
Detailed breakdown of amounts, fees, and costs Amounts before network costs
Amounts after network costs
Final amounts after slippage tolerance
Order parameters ready for signing
Raw quote response from API
Order metadata information
EIP-712 typed data for signing
postSwapOrderFromQuote
() => Promise<OrderPostingResult>
Function to post the order using the fetched quote
Example
const { quoteResults , postSwapOrderFromQuote } = await sdk . getQuote ( params )
const buyAmount = quoteResults . amountsAndCosts . afterSlippage . buyAmount
console . log ( 'You will receive at least:' , buyAmount )
if ( confirm ( 'Accept this quote?' )) {
const { orderId } = await postSwapOrderFromQuote ()
console . log ( 'Order created:' , orderId )
}
getQuoteOnly
Get a quote without requiring a wallet connection. Useful for displaying quotes before users connect.
async getQuoteOnly (
params : TradeParameters & { owner: string },
advancedSettings ?: SwapAdvancedSettings
): Promise < QuoteResults >
Address to quote for (doesn’t need to be connected)
Example
const quoteResults = await sdk . getQuoteOnly ({
owner: '0x1234...' , // Any valid address
kind: OrderKind . SELL ,
sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14' ,
sellTokenDecimals: 18 ,
buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59' ,
buyTokenDecimals: 18 ,
amount: '1000000000000000000' ,
})
console . log ( 'Quote:' , quoteResults . amountsAndCosts )
postLimitOrder
Create a limit order with specific buy and sell amounts.
async postLimitOrder (
params : LimitTradeParameters ,
advancedSettings ?: LimitOrderAdvancedSettings
): Promise < OrderPostingResult >
params
LimitTradeParameters
required
Limit order parameters Exact sell amount in atoms
Desired buy amount in atoms
ID of quote to use for the limit order
Exact expiration timestamp (Unix seconds)
Example
const params = {
kind: OrderKind . BUY ,
sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14' ,
sellTokenDecimals: 18 ,
buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59' ,
buyTokenDecimals: 18 ,
sellAmount: '1000000000000000000' , // 1 token
buyAmount: '500000000000000000' , // 0.5 token
}
const { orderId } = await sdk . postLimitOrder ( params )
console . log ( 'Limit order created:' , orderId )
postSellNativeCurrencyOrder
Create an order to sell native currency (ETH, xDAI, etc.) using EthFlow.
async postSellNativeCurrencyOrder (
params : TradeParameters ,
advancedSettings ?: SwapAdvancedSettings
): Promise < OrderPostingResult >
Use the special native currency address 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE as the sellToken.
Example
const params = {
kind: OrderKind . SELL ,
sellToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE' , // Native ETH
sellTokenDecimals: 18 ,
buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59' ,
buyTokenDecimals: 18 ,
amount: '100000000000000000' , // 0.1 ETH
}
const { orderId , txHash } = await sdk . postSellNativeCurrencyOrder ( params )
console . log ( 'Native currency order:' , orderId , txHash )
getOrder
Retrieve details of an existing order.
async getOrder ( params : { orderUid: string }): Promise < EnrichedOrder >
Complete order information including status, amounts, and execution details
Example
const order = await sdk . getOrder ({ orderUid: '0xd64389...' })
console . log ( 'Order status:' , order . status )
console . log ( 'Sell amount:' , order . sellAmount )
console . log ( 'Buy amount:' , order . buyAmount )
offChainCancelOrder
Cancel an order off-chain (soft cancel - fast and free).
async offChainCancelOrder ( params : { orderUid: string }): Promise < boolean >
True if cancellation was successful
Off-chain cancellation may not work if the order is already being executed.
Example
const success = await sdk . offChainCancelOrder ({ orderUid: '0xd64389...' })
if ( success ) {
console . log ( 'Order cancelled successfully' )
}
onChainCancelOrder
Cancel an order on-chain (hard cancel - requires gas but guaranteed).
async onChainCancelOrder ( params : { orderUid: string }): Promise < string >
Transaction hash of the cancellation
Example
const txHash = await sdk . onChainCancelOrder ({ orderUid: '0xd64389...' })
console . log ( 'Cancellation transaction:' , txHash )
getCowProtocolAllowance
Check current token allowance for CoW Protocol.
async getCowProtocolAllowance ( params : {
tokenAddress: string
owner : string
}): Promise < bigint >
ERC-20 token contract address
Example
const allowance = await sdk . getCowProtocolAllowance ({
tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' , // USDC
owner: '0x123...' ,
})
console . log ( 'Current allowance:' , allowance . toString ())
approveCowProtocol
Approve CoW Protocol to spend tokens.
async approveCowProtocol ( params : {
tokenAddress: string
amount : bigint
}): Promise < string >
ERC-20 token contract address
Transaction hash of approval
Example
import { parseUnits } from 'viem'
const txHash = await sdk . approveCowProtocol ({
tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' , // USDC
amount: parseUnits ( '1000' , 6 ), // 1000 USDC
})
console . log ( 'Approval transaction:' , txHash )
getPreSignTransaction
Get pre-sign transaction for smart contract wallets.
async getPreSignTransaction ( params : {
orderUid: string
account : string
}): Promise < { to : string ; data : string } >
Smart contract wallet address
transaction
{ to: string, data: string }
Transaction to execute for pre-signing
Example
const preSignTx = await sdk . getPreSignTransaction ({
orderUid: '0xd64389...' ,
account: '0xSmartContractWallet...' ,
})
console . log ( 'Execute this transaction:' , preSignTx )
setTraderParams
Update default trader parameters.
setTraderParams ( params : Partial < TraderParameters > ): TradingSdk
params
Partial<TraderParameters>
required
New trader parameters to merge with existing ones
Example
sdk . setTraderParams ({
chainId: SupportedChainId . MAINNET ,
env: 'prod' ,
})
Smart Contract Wallet Support
For smart contract wallets (like Safe), use the PRESIGN signing scheme:
import { SigningScheme } from '@cowprotocol/sdk-trading'
const params = {
// ... trade parameters
}
const advancedSettings = {
quoteRequest: {
signingScheme: SigningScheme . PRESIGN ,
},
}
const { orderId } = await sdk . postSwapOrder ( params , advancedSettings )
const preSignTx = await sdk . getPreSignTransaction ({
orderUid: orderId ,
account: '0xSmartContractWallet...' ,
})
// Execute preSignTx with your smart contract wallet
Partner API Integration
To use the Partner API with higher rate limits:
import { OrderBookApi } from '@cowprotocol/sdk-order-book'
const orderBookApi = new OrderBookApi ({
chainId: SupportedChainId . MAINNET ,
apiKey: 'your-partner-api-key' ,
})
const sdk = new TradingSdk (
{ chainId: SupportedChainId . MAINNET , appCode: 'YOUR_APP' },
{ orderBookApi },
adapter
)
Error Handling
try {
const { orderId } = await sdk . postSwapOrder ( params )
console . log ( 'Order created:' , orderId )
} catch ( error ) {
if ( error . message . includes ( 'insufficient allowance' )) {
// Handle allowance error
await sdk . approveCowProtocol ({ tokenAddress , amount })
} else if ( error . message . includes ( 'slippage' )) {
// Handle slippage error
console . error ( 'Price moved too much' )
} else {
console . error ( 'Order creation failed:' , error )
}
}
See Also