@cowprotocol/cow-sdk

中文文档
9.3.3发布于 2026/11/04(MIT OR Apache-2.0)TypeScriptESM + CJS构建来源已验证近 30 天下载 9.2万

CoW Protocol SDK - get quote, configure your order, and trade

原始使用文档
文档目录19 节
  1. 📚 Docs website
  2. 🌐 Supported Networks
  3. 🔗 Related Resources
  4. Getting Started
  5. Usage Examples
  6. Installation
  7. CoW SDK
  8. SDK Components
  9. Core
  10. Advanced
  11. v6 → v7 Migration Guide
  12. Basic Use Case
  13. Developer Attribution (UTM Tracking)
  14. Partner API
  15. Adapters
  16. Available Adapters
  17. Installation
  18. Adapter Setup Examples
  19. Low-Level SDK Usage Example

CoW SDK

📚 Docs website

🌐 Supported Networks

The SDK supports all CoW Protocol enabled networks:

  • Ethereum (1) - SupportedChainId.MAINNET
  • Gnosis Chain (100) - SupportedChainId.GNOSIS_CHAIN
  • Arbitrum One (42161) - SupportedChainId.ARBITRUM_ONE
  • Base (8453) - SupportedChainId.BASE
  • Polygon (137) - SupportedChainId.POLYGON
  • Avalanche (43114) - SupportedChainId.AVALANCHE
  • BNB (56) - SupportedChainId.BNB
  • Linea (59144) - SupportedChainId.LINEA
  • Plasma (9745) - SupportedChainId.PLASMA
  • Ink (57073) - SupportedChainId.INK
  • Robinhood Chain (4663) - SupportedChainId.ROBINHOOD (coming soon)
  • Sepolia (11155111) - SupportedChainId.SEPOLIA (Testnet)

Getting Started

Usage Examples

React Examples:

Node.js Examples:

Installation

pnpm add @cowprotocol/cow-sdk
yarn add @cowprotocol/cow-sdk

CoW SDK

Using CoW Protocol, you can perform swaps, limit orders, TWAP orders, and many other operations. The @cowprotocol/cow-sdk provides tools at different abstraction levels, allowing you to conveniently implement basic scenarios while maintaining the flexibility to control all possible cases.

In most cases, you will only need to use the Trading SDK

SDK Components

Core

  • TradingSdk - Main tool for swap and limit orders with built-in quote fetching, order signing, and posting
  • OrderSigningUtils - Utilities for signing orders and cancellations using cryptographic algorithms
  • OrderBookApi - Provides the ability to retrieve orders and trades from the CoW Protocol order book, as well as add and cancel them
  • MetadataApi - API for accessing order metadata and additional information

Advanced

v6 → v7 Migration Guide

The versions are 99% backward compatible. The only difference is that in v7 you need to set an adapter corresponding to the library you use: Viem, Ethers6, or Ethers5.

Before (v6):

import { SupportedChainId, TradingSdk, MetadataApi, OrderBookApi } from '@cowprotocol/cow-sdk'

const options = {}

const sdk = new TradingSdk({
  chainId: SupportedChainId.SEPOLIA,
  appCode: 'YOUR_APP_CODE',
}, options)

After (v7):

import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/cow-sdk'
import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
import { createPublicClient, http, privateKeyToAccount } from 'viem'
import { sepolia } from 'viem/chains'

// NEW: Instantiate and set adapter
const adapter = new ViemAdapter({
  provider: createPublicClient({
    chain: sepolia,
    transport: http('YOUR_RPC_URL')
  }),
  // You can also set `walletClient` instead of `signer` using `useWalletClient` from wagmi
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
})

const options = {}

const sdk = new TradingSdk({
  chainId: SupportedChainId.SEPOLIA,
  appCode: 'YOUR_APP_CODE',
}, options, adapter)

Most other packages (e.g., MetadataApi or BridgingSdk) have a parameter to set an adapter. You can also set an adapter using setGlobalAdapter:

import { setGlobalAdapter, CowShedSdk } from '@cowprotocol/cow-sdk'

const adapter = {...}

// Set global adapter
setGlobalAdapter(adapter)

const cowShedSdk = new CowShedSdk()

You will likely also need to bind the SDK to your app's account state. When the account or network changes in the app/wallet, it should be updated in the SDK as well. Here's an example for WAGMI (see examples/react/wagmi):

import { useAccount, usePublicClient, useWalletClient } from 'wagmi'
import { useEffect, useState } from 'react'
import { ViemAdapter, ViemAdapterOptions } from '@cowprotocol/sdk-viem-adapter'
import { tradingSdk } from '../cowSdk.ts'
import { setGlobalAdapter } from '@cowprotocol/cow-sdk'

export function useBindCoWSdkToWagmi(): boolean {
  const { chainId } = useAccount()
  const { data: walletClient } = useWalletClient()
  const publicClient = usePublicClient()

  const [isSdkReady, setIsSdkReady] = useState(false)

  /**
   * Sync Trading SDK with wagmi account state (chainId and signer)
   */
  useEffect(() => {
    if (!walletClient || !chainId) return

    setGlobalAdapter(
      new ViemAdapter({
        provider: publicClient,
        walletClient,
      } as unknown as ViemAdapterOptions),
    )

    tradingSdk.setTraderParams({ chainId })

    setIsSdkReady(true)
  }, [publicClient, walletClient, chainId])

  return isSdkReady
}

Basic Use Case

This example demonstrates the main use case of creating a swap and shows how to:

  • Get a quote
  • Verify amounts
  • Adjust swap parameters
  • Sign and post an order
import { SupportedChainId, OrderKind, TradeParameters, TradingSdk } from '@cowprotocol/cow-sdk'
import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
import { createPublicClient, http, privateKeyToAccount } from 'viem'
import { sepolia } from 'viem/chains'

// EthersV5Adapter and EthersV6Adapter are also available
// @cowprotocol/sdk-ethers-v5-adapter, @cowprotocol/sdk-ethers-v6-adapter
const adapter = new ViemAdapter({
  provider: createPublicClient({
    chain: sepolia,
    transport: http('YOUR_RPC_URL')
  }),
  // You can also set `walletClient` instead of `signer` using `useWalletClient` from wagmi
  signer: privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
})

const sdk = new TradingSdk({
  chainId: SupportedChainId.SEPOLIA,
  appCode: 'YOUR_APP_CODE',
}, {}, adapter)

const parameters: TradeParameters = {
  kind: OrderKind.SELL,
  sellToken: '0xfff9976782d46cc05630d1f6ebab18b2324d6b14',
  sellTokenDecimals: 18,
  buyToken: '0x0625afb445c3b6b7b929342a04a22599fd5dbb59',
  buyTokenDecimals: 18,
  amount: '120000000000000',
}

// Get quote
const { quoteResults, postSwapOrderFromQuote } = await sdk.getQuote(parameters)

const buyAmount = quoteResults.amountsAndCosts.afterSlippage.buyAmount

// Verify amount
if (confirm(`You will receive at least: ${buyAmount}. Proceed?`)) {
  // Sign and post order
  const orderId = await postSwapOrderFromQuote()

  console.log('Order created, ID:', orderId)
}

This example demonstrates the simplest way to trade on CoW Protocol.

For more advanced use cases, you can use additional parameters such as receiver, partiallyFillable, validTo, and others. Refer to the Trading SDK documentation for comprehensive details.

Developer Attribution (UTM Tracking)

The SDK automatically includes UTM tracking in all orders to attribute trading volume to developers. Default parameters:

{
  utmSource: 'cowmunity',
  utmMedium: '[email protected]',  // SDK version
  utmCampaign: 'developer-cohort',
  utmContent: '',
  utmTerm: 'js'
}

Customize or disable via advancedSettings.appData.metadata.utm:

// Custom UTM
await sdk.getQuote(parameters, {
  appData: {
    metadata: {
      utm: { utmContent: 'my-integration-v2' }
    }
  }
})

// Disable UTM
await sdk.getQuote(parameters, {
  appData: {
    metadata: {
      utm: {}
    }
  }
})

Note: Providing any utm field gives you full control - the SDK will not add defaults.

Tip: Use utmContent for graffiti without affecting your appCode. The appCode parameter tracks your integration on CoW Protocol's Dune dashboards, while utmContent is available for custom identifiers or experimentation - all while attributing your volume to SDK integrators' collective impact.

Partner API

Partners can use authenticated API access with higher rate limits via the Partner API gateway. Pass your API key when creating an OrderBookApi instance:

import { OrderBookApi, SupportedChainId } from '@cowprotocol/cow-sdk'

const orderBookApi = new OrderBookApi({
  chainId: SupportedChainId.MAINNET,
  apiKey: 'your-partner-api-key',
})

By default, the SDK routes requests through partners.cow.fi (prod) or partners.barn.cow.fi (staging) and includes the X-API-Key header. If you provide custom baseUrls, those take precedence over the default partner hosts, but the X-API-Key header is still sent with every request.

See the OrderBookApi documentation for more details, including usage with the Trading SDK.

Adapters

The CoW SDK supports multiple blockchain adapters to work with different Web3 libraries. You need to install and configure one of the following adapters:

Available Adapters

  • EthersV6Adapter - For ethers.js v6
  • EthersV5Adapter - For ethers.js v5
  • ViemAdapter - For viem

Installation

# For ethers v6
pnpm add @cowprotocol/sdk-ethers-v6-adapter ethers

# For ethers v5
pnpm add @cowprotocol/sdk-ethers-v5-adapter ethers@^5.7.0

# For viem
pnpm add @cowprotocol/sdk-viem-adapter viem

Adapter Setup Examples

EthersV6Adapter

import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter'
import { JsonRpcProvider, Wallet } from 'ethers'

const provider = new JsonRpcProvider('YOUR_RPC_URL')
const wallet = new Wallet('YOUR_PRIVATE_KEY', provider)
const adapter = new EthersV6Adapter({ provider, signer: wallet })

EthersV5Adapter

import { EthersV5Adapter } from '@cowprotocol/sdk-ethers-v5-adapter'
import { ethers } from 'ethers'

const provider = new ethers.providers.JsonRpcProvider('YOUR_RPC_URL')
const wallet = new ethers.Wallet('YOUR_PRIVATE_KEY', provider)
const adapter = new EthersV5Adapter({ provider, signer: wallet })

ViemAdapter

import { ViemAdapter } from '@cowprotocol/sdk-viem-adapter'
import { http, createPublicClient, privateKeyToAccount } from 'viem'
import { sepolia } from 'viem/chains'

const account = privateKeyToAccount('YOUR_PRIVATE_KEY' as `0x${string}`)
const transport = http('YOUR_RPC_URL')
const provider = createPublicClient({ chain: sepolia, transport })

// You can also set `walletClient` instead of `signer` using `useWalletClient` from wagmi
const adapter = new ViemAdapter({ provider, signer: account })

Low-Level SDK Usage Example

This example demonstrates low-level API usage with a practical scenario: exchanging 0.4 GNO for WETH on the Gnosis Chain network.

We will perform the following operations:

  1. Get a quote
  2. Sign the order
  3. Send the order to the order book
  4. Get the data of the created order
  5. Get trades for the order
  6. Cancel the order (signing + sending)

Try it live: https://codesandbox.io/p/devbox/cow-sdk-example-forked-x63k52

import { OrderBookApi, OrderSigningUtils, SupportedChainId, OrderQuoteSideKindSell, SigningScheme, setGlobalAdapter } from '@cowprotocol/cow-sdk'
import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter'
import { JsonRpcProvider, Wallet } from 'ethers'

const account = 'YOUR_WALLET_ADDRESS'
const chainId = 100 // Gnosis Chain
const provider = new JsonRpcProvider('YOUR_RPC_URL')
const wallet = new Wallet('YOUR_PRIVATE_KEY', provider)
const adapter = new EthersV6Adapter({ provider, signer: wallet })

setGlobalAdapter(adapter)

const receiver = account

const quoteRequest = {
  sellToken: '0x6a023ccd1ff6f2045c3309768ead9e68f978f6e1', // WETH on Gnosis Chain
  buyToken: '0x9c58bacc331c9aa871afd802db6379a98e80cedb', // GNO on Gnosis Chain
  from: account,
  receiver,
  sellAmountBeforeFee: (0.4 * 10 ** 18).toString(), // 0.4 WETH
  kind: OrderQuoteSideKindSell.SELL,
}

const orderBookApi = new OrderBookApi({ chainId: SupportedChainId.GNOSIS_CHAIN })

async function main() {
  const { quote } = await orderBookApi.getQuote(quoteRequest)

  const orderData = {
    ...quote,
    // Add fee to sellAmount for sell orders
    sellAmount: (BigInt(quote.sellAmount) + BigInt(quote.feeAmount)).toString(),
    receiver,
    feeAmount: "0",
  };

  const orderSigningResult = await OrderSigningUtils.signOrder(orderData, chainId, adapter.signer)

  const orderId = await orderBookApi.sendOrder({
    ...orderData,
    ...orderSigningResult,
    signingScheme: SigningScheme.EIP712,
  })

  const order = await orderBookApi.getOrder(orderId)

  const trades = await orderBookApi.getTrades({ orderId })

  const orderCancellationSigningResult = await OrderSigningUtils.signOrderCancellations([orderId], chainId, adapter.signer)

  const cancellationResult = await orderBookApi.sendSignedOrderCancellations({
    ...orderCancellationSigningResult,
    orderUids: [orderId],
  })

  console.log('Results:', { orderId, order, trades, orderCancellationSigningResult, cancellationResult })
}

版本与发布记录

@cowprotocol/cow-sdk 共发布 324 个版本,首次发布于 2022/04/04;过去 12 个月发布了 73 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
9.3.3latest2026/11/046 天前
9.3.22026/11/046 天前
9.3.12026/11/037 天前
9.3.02026/10/2615 天前
9.2.222026/10/2318 天前
9.2.212026/10/1328 天前

其他发布通道:next → 7.0.1-beta.0。

关于 @cowprotocol/cow-sdk 的常见问题

@cowprotocol/cow-sdk 是什么?

CoW Protocol SDK - get quote, configure your order, and trade

如何安装 @cowprotocol/cow-sdk?

在项目目录运行 npm install @cowprotocol/cow-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:cross-fetch(^3.x)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@cowprotocol/cow-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cowprotocol/cow-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cowprotocol/cow-sdk 可以商用吗?

@cowprotocol/cow-sdk 使用 (MIT OR Apache-2.0) 许可。可在 MIT、Apache-2.0 中任选其一遵守。选择 MIT 时,宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cowprotocol/cow-sdk 的下载量有多少?

根据 npm 官方下载统计,@cowprotocol/cow-sdk 在 2026/10/11 – 2026/11/09 这 30 天内被下载 92,450 次,日均约 3,082 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cowprotocol/cow-sdk 还在维护吗?

最新版本 9.3.3 发布于 2026/11/04(6 天前);至今共发布 324 个版本,其中过去 12 个月发布了 73 个;首次发布于 2022/04/04。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。