@cowprotocol/sdk-bridging

中文文档
4.5.3发布于 2026/11/04MITTypeScriptESM + CJS构建来源已验证近 30 天下载 4.1万

Bridging for CoW Protocol

原始使用文档
文档目录18 节
  1. Test coverage
  2. Installation
  3. Usage
  4. Multi-Provider Quote Comparison
  5. Basic Multi-Quote Usage
  6. Progressive Quote Results
  7. Advanced Multi-Quote Example
  8. Timeout Configuration
  9. Best Quote Selection
  10. Basic Best Quote Usage
  11. Progressive Best Quote Updates
  12. Error Handling with Best Quote
  13. Comparison: getBestQuote vs getMultiQuotes
  14. Provider Management
  15. Getting Available Providers
  16. Filtering Active Providers
  17. Dynamic Provider Selection Example
  18. Supported Bridge Providers

SDK Bridging

Test coverage

StatementsBranchesFunctionsLines
StatementsBranchesFunctionsLines

This package provides bridging functionality for the CoW Protocol SDK, enabling cross-chain token transfers and interactions. It integrates with various bridge providers to facilitate seamless asset movement across supported blockchain networks.

Installation

npm install @cowprotocol/sdk-bridging
or
pnpm add @cowprotocol/sdk-bridging
or
yarn add @cowprotocol/sdk-bridging

Usage

import {
  SupportedChainId,
  BridgingSdk,
  QuoteBridgeRequest,
  OrderKind,
  assertIsBridgeQuoteAndPost,
} from '@cowprotocol/sdk-bridging'
import { EthersV6Adapter } from '@cowprotocol/sdk-ethers-v6-adapter'
import { JsonRpcProvider, Wallet } from 'ethers'

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

// Initialize bridging SDK
const bridging = new BridgingSdk(adapter, options)

const parameters: QuoteBridgeRequest = {
  // Cross-chain orders are always SELL orders (BUY not supported yet)
  kind: OrderKind.SELL,

  // Sell token (and source chain)
  sellTokenChainId: SupportedChainId.ARBITRUM_ONE,
  sellTokenAddress: '0x82aF49447D8a07e3bd95BD0d56f35241523fBab1',
  sellTokenDecimals: 18,

  // Buy token (and target chain)
  buyTokenChainId: SupportedChainId.BASE,
  buyTokenAddress: '0x4200000000000000000000000000000000000006',
  buyTokenDecimals: 18,

  // Amount to sell
  amount: '120000000000000000',

  signer: adapter.signer,

  // Optional parameters
  appCode: 'YOUR_APP_CODE',
}

// Get a quote (and the post callback) for a cross-chain swap
const quoteResult = await sdk.getQuote(parameters)
// Assert that the quote result is of type BridgeQuoteAndPost
// (type for cross-chain quotes, as opposed to QuoteAndPost for single-chain quotes).
// The assertion makes typescript happy.
assertIsBridgeQuoteAndPost(quoteResult)
const { swap, bridge, postSwapOrderFromQuote } = quoteResult

// Display all data related to the swap (costs, amounts, appData including the bridging hook, etc.) 🐮
console.log('Swap info', swap)

// Display all data related to the bridge (costs, amounts, provider info, hook, and the bridging quote) ✉️
console.log('Bridge info', bridge)

// Get the buy amount after slippage in the target chain
const { buyAmount } = bridge.amountsAndCosts.afterSlippage

if (confirm(`You will get at least: ${buyAmount}, ok?`)) {
  const orderId = await postSwapOrderFromQuote()
  console.log('Order created, id: ', orderId)
}

Multi-Provider Quote Comparison

The getMultiQuotes() method allows you to get quotes from multiple bridge providers simultaneously, with support for progressive results as each provider responds.

Basic Multi-Quote Usage

import { MultiQuoteRequest } from '@cowprotocol/sdk-bridging'

const multiQuoteRequest: MultiQuoteRequest = {
  quoteBridgeRequest: parameters, // Same parameters as above
  providerDappIds: ['provider1', 'provider2'], // Optional: specify which providers to query
  advancedSettings: {
    slippageBps: 100, // 1% slippage tolerance
  },
  options: {
    totalTimeout: 15000,        // 15 seconds total timeout
    providerTimeout: 8000, // 8 seconds per provider timeout
  }
}

// Get quotes from all providers
const results = await bridgingSdk.getMultiQuotes(multiQuoteRequest)

results.forEach((result) => {
  if (result.quote) {
    console.log(`Quote from ${result.providerDappId}:`, result.quote)
  } else {
    console.log(`Error from ${result.providerDappId}:`, result.error?.message)
  }
})

Progressive Quote Results

For better user experience, you can receive quotes progressively as each provider responds:

const progressiveResults: MultiQuoteResult[] = []

const multiQuoteRequest: MultiQuoteRequest = {
  quoteBridgeRequest: parameters,
  options: {
    // Receive quotes as they arrive
    onQuoteResult: (result) => {
      progressiveResults.push(result)

      if (result.quote) {
        console.log(`✅ Quote received from ${result.providerDappId}`)
        // Update UI immediately with the new quote
        displayQuoteInUI(result)
      } else {
        console.log(`❌ Error from ${result.providerDappId}: ${result.error?.message}`)
      }
    },
    totalTimeout: 20000,       // 20 seconds total timeout
    providerTimeout: 5000 // 5 seconds per provider timeout
  }
}

// This will return all results once completed (or timed out)
const finalResults = await bridgingSdk.getMultiQuotes(multiQuoteRequest)

console.log(`Received ${finalResults.filter(r => r.quote).length} successful quotes out of ${finalResults.length} providers`)

Advanced Multi-Quote Example

// Example with React state management
const [quotes, setQuotes] = useState<MultiQuoteResult[]>([])
const [isLoading, setIsLoading] = useState(false)

const fetchQuotes = async () => {
  setIsLoading(true)
  setQuotes([])

  try {
    const results = await bridgingSdk.getMultiQuotes({
      quoteBridgeRequest: parameters,
      options: {
        onQuoteResult: (result) => {
          // Add quote to state as it arrives
          setQuotes(prev => [...prev, result])

          if (result.quote) {
            // Optional: Auto-select best quote
            if (isBestQuote(result)) {
              selectQuote(result)
            }
          } else {
            // Handle errors
            console.error(`Provider ${result.providerDappId} failed:`, result.error?.message)
            // Update UI to show provider is unavailable
            setProviderStatus(prev => ({
              ...prev,
              [result.providerDappId]: 'error'
            }))
          }
        },
        totalTimeout: 30000,       // 30 seconds total timeout
        providerTimeout: 10000 // 10 seconds per provider timeout
      }
    })

    console.log('All quotes completed:', results)
  } catch (error) {
    console.error('Multi-quote failed:', error)
  } finally {
    setIsLoading(false)
  }
}

// Helper function to determine best quote
const isBestQuote = (result: MultiQuoteResult): boolean => {
  if (!result.quote) return false

  const currentBest = quotes.find(q => q.quote)
  if (!currentBest?.quote) return true

  // Compare buy amounts after slippage
  return result.quote.bridge.amountsAndCosts.afterSlippage.buyAmount >
         currentBest.quote.bridge.amountsAndCosts.afterSlippage.buyAmount
}

Timeout Configuration

The getMultiQuotes() method supports two types of timeouts for fine-grained control:

const results = await bridgingSdk.getMultiQuotes({
  quoteBridgeRequest: parameters,
  options: {
    // Global timeout: Maximum time to wait for all providers to complete
    totalTimeout: 30000,        // 30 seconds (default)

    // Individual provider timeout: Maximum time each provider has to respond
    providerTimeout: 15000, // 15 seconds (default)

    onQuoteResult: (result) => {
      // Handle progressive results
      console.log(`Received result from ${result.providerDappId}`);
    }
  }
});

How timeouts work:

  • providerTimeout: Each provider has this amount of time to complete their quote request. If exceeded, that provider returns a timeout error.
  • totalTimeout: The total time to wait for all providers. After this time, any remaining providers are marked as timed out.
  • Providers that complete within their individual timeout but after the global timeout will still be included in the final results.

Best Quote Selection

The getBestQuote() method provides an optimized way to get only the best quote from multiple providers, with progressive updates as better quotes are found. This is perfect for applications that only need the single best result.

Basic Best Quote Usage

import { MultiQuoteRequest } from '@cowprotocol/sdk-bridging'

// Get the best quote from all available providers
const bestQuote = await bridgingSdk.getBestQuote({
  quoteBridgeRequest: parameters, // Same parameters as above
  providerDappIds: ['provider1', 'provider2'], // Optional: specify which providers to query
  advancedSettings: {
    slippageBps: 100, // 1% slippage tolerance
  },
  options: {
    totalTimeout: 15000,       // 15 seconds total timeout
    providerTimeout: 8000,     // 8 seconds per provider timeout
  }
})

if (bestQuote?.quote) {
  console.log(`Best quote from ${bestQuote.providerDappId}:`, bestQuote.quote)
  const { buyAmount } = bestQuote.quote.bridge.amountsAndCosts.afterSlippage
  console.log(`You will receive: ${buyAmount} tokens`)
} else if (bestQuote?.error) {
  console.log('All providers failed, first error:', bestQuote.error.message)
} else {
  console.log('No quotes available')
}

Progressive Best Quote Updates

For real-time updates, you can receive notifications each time a better quote is found:

let currentBest: MultiQuoteResult | null = null

const bestQuote = await bridgingSdk.getBestQuote({
  quoteBridgeRequest: parameters,
  options: {
    // Called whenever a better quote is found
    onQuoteResult: (result) => {
      currentBest = result
      console.log(`🚀 New best quote from ${result.providerDappId}!`)

      if (result.quote) {
        const buyAmount = result.quote.bridge.amountsAndCosts.afterSlippage.buyAmount
        console.log(`Better quote found: ${buyAmount} tokens`)

        // Update UI immediately with the new best quote
        updateBestQuoteInUI(result)
      }
    },
    totalTimeout: 20000,      // 20 seconds total timeout
    providerTimeout: 5000     // 5 seconds per provider timeout
  }
})

console.log('Final best quote:', bestQuote)

Error Handling with Best Quote

When all providers fail, getBestQuote() returns the first provider's error:

const bestQuote = await bridgingSdk.getBestQuote({
  quoteBridgeRequest: parameters,
  options: {
    onQuoteResult: (result) => {
      // Only called for successful quotes that are better than current best
      console.log(`✅ Better quote from ${result.providerDappId}`)
    }
  }
})

if (bestQuote?.quote) {
  // Success: we have the best available quote
  console.log('Best quote found:', bestQuote.quote)
} else if (bestQuote?.error) {
  // All providers failed, this is the first error encountered
  console.error('All providers failed:', bestQuote.error.message)
  console.log('Failed provider:', bestQuote.providerDappId)
} else {
  // This should never happen, but good to handle
  console.log('No quote or error returned')
}

Comparison: getBestQuote vs getMultiQuotes

FeaturegetBestQuote()getMultiQuotes()
ReturnsSingle best resultArray of all results
Progressive CallbacksOnly for better quotesFor all results (success & error)
Error HandlingReturns first error if all failReturns all errors in array
PerformanceOptimized for best result onlyReturns complete data set
Use CaseWhen you only need the best quoteWhen you need to compare all options

Choose getBestQuote() when:

  • You only need the single best quote
  • You want real-time updates as better quotes are found
  • You want to minimize callback overhead (only called for improvements)

Choose getMultiQuotes() when:

  • You need to display all available options to users
  • You want to analyze all provider responses
  • You need to show provider-specific errors or statuses

Provider Management

The BridgingSdk provides methods to manage which bridge providers are actively used for quotes and operations.

Getting Available Providers

Use getAvailableProviders() to retrieve the list of currently active providers:

// Get all active providers
const providers = bridgingSdk.getAvailableProviders()

providers.forEach((provider) => {
  console.log(`Provider: ${provider.info.name}`)
  console.log(`Dapp ID: ${provider.info.dappId}`)
  console.log(`Networks: ${provider.info.supportedChains.join(', ')}`)
})

Filtering Active Providers

Use setAvailableProviders() to dynamically filter which providers should be used for bridge operations:

// Initially, all configured providers are available
const allProviders = bridgingSdk.getAvailableProviders()
console.log(`Total providers: ${allProviders.length}`)

// Filter to use only specific providers
bridgingSdk.setAvailableProviders(['across', 'hop-protocol'])

// Now only the specified providers will be used
const filteredProviders = bridgingSdk.getAvailableProviders()
console.log(`Active providers: ${filteredProviders.length}`)

// Reset to use all providers again
bridgingSdk.setAvailableProviders([])
const resetProviders = bridgingSdk.getAvailableProviders()
console.log(`Reset to all providers: ${resetProviders.length}`)

Dynamic Provider Selection Example

// Example: Let users select their preferred bridge providers
const [selectedProviders, setSelectedProviders] = useState<string[]>([])

// Function to update active providers based on user selection
const updateActiveProviders = (providerIds: string[]) => {
  bridgingSdk.setAvailableProviders(providerIds)
  setSelectedProviders(providerIds)

  console.log(`Updated to use ${providerIds.length} provider(s)`)
}

// Get quotes only from selected providers
const getQuotesFromSelectedProviders = async () => {
  // The SDK will automatically use only the providers set via setAvailableProviders
  const quote = await bridgingSdk.getQuote(parameters)
  // Or for multi-provider quotes
  const multiQuotes = await bridgingSdk.getMultiQuotes({
    quoteBridgeRequest: parameters
    // No need to specify providerDappIds, setAvailableProviders already filtered them
  })

  return quote
}

Supported Bridge Providers

  • Additional bridge providers are being integrated
  • More details will be available as development progresses

版本与发布记录

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

版本发布日期距今
4.5.3latest2026/11/046 天前
4.5.22026/11/046 天前
4.5.12026/11/037 天前
4.5.02026/10/2615 天前
4.4.202026/10/2318 天前
4.4.192026/10/1328 天前

其他发布通道:next → 0.4.7-rc.0。

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

@cowprotocol/sdk-bridging 是什么?

Bridging for CoW Protocol

如何安装 @cowprotocol/sdk-bridging?

在项目目录运行 npm install @cowprotocol/sdk-bridging,或使用 pnpm add / yarn add / bun add。

@cowprotocol/sdk-bridging 支持 TypeScript 吗?

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

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

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

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

@cowprotocol/sdk-bridging 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

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

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

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

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