@cowprotocol/sdk-composable

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

TypeScript composable features for CoW Protocol SDK

原始使用文档
文档目录22 节
  1. Test coverage
  2. Installation
  3. Read TWAP history
  4. Core Components
  5. ConditionalOrderFactory
  6. Multiplexer
  7. ConditionalOrder
  8. JIT Poller
  9. Usage
  10. Conditional Order Types
  11. TWAP (Time-Weighted Average Price)
  12. DCA (Dollar Cost Averaging) — WIP
  13. Stop-Loss Orders — WIP
  14. Advanced Features
  15. Merkle Tree Management
  16. Order Validation
  17. Context Dependencies
  18. Order Registry Management
  19. Smart Contract Integration
  20. ComposableCoW Integration
  21. Proof Generation and Storage
  22. Complete TWAP Setup

SDK Composable

Test coverage

StatementsBranchesFunctionsLines
StatementsBranchesFunctionsLines

This package provides advanced conditional and programmable order functionality for the CoW Protocol. It enables the creation, management, and execution of sophisticated trading strategies through conditional orders that execute automatically when specified conditions are met.

Installation

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

Read TWAP history

import { ProgrammaticOrderApi } from '@cowprotocol/sdk-composable'
import { SupportedChainId } from '@cowprotocol/sdk-config'

const api = new ProgrammaticOrderApi()
const { items: twaps } = await api.getTwapOrders({
  resolvedOwner: '0x...',
  chainId: SupportedChainId.GNOSIS_CHAIN,
})
const { items: parts } = await api.getTwapPartOrders(
  {
    eventId: twaps[0].eventId,
    chainId: SupportedChainId.GNOSIS_CHAIN,
  },
  {
    offset: 0,
    limit: 10,
    direction: 'desc',
  },
)

Both methods return QueryPage<T> and accept optional QueryOptions (offset, limit, direction). Parent results include execution totals and indexed part counts; pass the returned eventId to fetch parts.

Core Components

ConditionalOrderFactory

Registry-based factory for creating different types of conditional orders:

import { ConditionalOrderFactory } from '@cowprotocol/sdk-composable'

const factory = new ConditionalOrderFactory(registry, adapter)
const conditionalOrder = factory.fromParams(orderParams)

Multiplexer

Manages batches of conditional orders using merkle trees:

import { Multiplexer } from '@cowprotocol/sdk-composable'

const multiplexer = new Multiplexer(chainId, orders, root, location)
const proofs = multiplexer.dumpProofsAndParams()

ConditionalOrder

Base class for implementing custom conditional order types:

import { ConditionalOrder } from '@cowprotocol/sdk-composable'

class CustomOrder extends ConditionalOrder<DataType, StaticType> {
  // Implement custom conditional logic
}

JIT Poller

The package exports utilities needed to integrate with a deployed ComposableCowPoller. The Poller moves sell tokens just in time from a funding account (often an EOA) to the ComposableCoW order owner/trader. This avoids requiring the trader account to be prefunded for the full schedule, reducing setup friction and idle capital.

The package exposes two Poller APIs: the low-level ComposableCowPoller below only reads state and encodes calldata, while ComposableCowPollerSdk adds signing and transaction submission through the configured adapter.

import { ComposableCowPoller, type ComposableCowPollerSchedule } from '@cowprotocol/sdk-composable'
import { setGlobalAdapter } from '@cowprotocol/sdk-common'

setGlobalAdapter(adapter)

const poller = new ComposableCowPoller(pollerAddress)
const schedule: ComposableCowPollerSchedule = {
  handler,
  authEpoch,
  funder,
  owner,
  salt,
  staticInput,
}
const scheduleId = poller.getScheduleId(schedule)

// Submit this calldata to pollerAddress from schedule.funder.
const registerCalldata = poller.encodeRegister(schedule)

// Anyone may submit this calldata to pollerAddress when the next order part needs funding.
const pollFundsCalldata = poller.encodePollFunds(scheduleId)

// Or authorize registration for submission by another account.
const deadline = Math.floor(Date.now() / 1000) + 15 * 60
const typedData = poller.getRegisterTypedData({ chainId, schedule, deadline })
const signature = await adapter.signer.signTypedData(typedData.domain, typedData.types, typedData.message)
const signedRegisterCalldata = poller.encodeRegisterWithSignature(schedule, deadline, signature)

// Direct revocation must be submitted by schedule.funder.
const revokeCalldata = poller.encodeRevoke(schedule)

// Or authorize revocation for submission by another account.
const revokeAuthorization = {
  handler: schedule.handler,
  authEpoch: schedule.authEpoch,
  funder: schedule.funder,
  owner: schedule.owner,
  salt: schedule.salt,
}
const revokeDeadline = Math.floor(Date.now() / 1000) + 15 * 60
const revokeTypedData = poller.getRevokeTypedData({
  chainId,
  ...revokeAuthorization,
  deadline: revokeDeadline,
})
const revokeSignature = await adapter.signer.signTypedData(
  revokeTypedData.domain,
  revokeTypedData.types,
  revokeTypedData.message,
)
const signedRevokeCalldata = poller.encodeRevokeWithSignature(revokeAuthorization, revokeDeadline, revokeSignature)

Install the CowShed package to derive a Poller-compatible account:

npm install @cowprotocol/sdk-cow-shed

Configure CowShedSdk with the Composable CoW factory. It must match poller.getCowShedFactoryAddress().

import {
  COW_SHED_FACTORY_FOR_COMPOSABLE_COW,
  COW_SHED_IMPLEMENTATION_FOR_COMPOSABLE_COW,
  COW_SHED_LATEST_VERSION,
  CowShedSdk,
} from '@cowprotocol/sdk-cow-shed'

const cowShedSdk = new CowShedSdk(adapter, {
  factoryAddress: COW_SHED_FACTORY_FOR_COMPOSABLE_COW[COW_SHED_LATEST_VERSION],
  implementationAddress: COW_SHED_IMPLEMENTATION_FOR_COMPOSABLE_COW[COW_SHED_LATEST_VERSION],
})
const cowShed = cowShedSdk.getCowShedAccount(chainId, funder)

Register from the funder's own CowShed by including the Poller call in a signed bundle. The schedule owner must equal that CowShed. Refresh the epoch for this schedule ID before signing.

const shedSchedule = { ...schedule, owner: cowShed }
const { authEpoch: shedAuthEpoch } = await poller.getSchedule(poller.getScheduleId(shedSchedule))

const registration = await cowShedSdk.signCalls({
  chainId,
  signer,
  calls: [
    {
      target: pollerAddress,
      callData: poller.encodeRegisterFromShed({ ...shedSchedule, authEpoch: shedAuthEpoch }),
      value: 0n,
      isDelegateCall: false,
      allowFailure: false,
    },
  ],
})

Revoke from the funder's own CowShed by including the Poller call in a signed bundle. Use the original schedule identity and refresh its epoch before signing. Revocation does not require the schedule owner to equal the CowShed.

const { authEpoch: revokeAuthEpoch } = await poller.getSchedule(scheduleId)

const revocation = await cowShedSdk.signCalls({
  chainId,
  signer,
  calls: [
    {
      target: pollerAddress,
      callData: poller.encodeRevokeFromShed({ ...schedule, authEpoch: revokeAuthEpoch }),
      value: 0n,
      isDelegateCall: false,
      allowFailure: false,
    },
  ],
})

Use ComposableCowPollerSdk to sign or submit transactions through the configured adapter. Its poller property exposes the same low-level calldata and read methods shown above. Using that schedule, choose either the direct flow or the signature flow below; do not run both for the same registration.

import { ComposableCowPollerSdk } from '@cowprotocol/sdk-composable'

const pollerSdk = new ComposableCowPollerSdk({ chainId, pollerAddress, signer }, adapter)
const deadline = Math.floor(Date.now() / 1000) + 15 * 60

// Direct flow: use the SDK signer, or the adapter signer when none was configured.
const transaction = await pollerSdk.register({ schedule })
await transaction.wait()

// Signature flow: keep the intended schedule and refresh only its replay-protection epoch.
const { authEpoch } = await pollerSdk.poller.getSchedule(scheduleId)
const currentSchedule = { ...schedule, authEpoch }
const authorization = await pollerSdk.signRegister({ schedule: currentSchedule, deadline })
// authorization.calldata is ready for a hook or relayed transaction.
// authorization.typedData and authorization.signature are also available for inspection.

// Alternatively, submit the authorization now with a relayer signer.
const relayedTransaction = await pollerSdk.registerWithSignature({
  schedule: currentSchedule,
  deadline,
  signature: authorization.signature,
  signer: relayerSigner,
})
await relayedTransaction.wait()

signRevoke follows the same signature flow and signs the supplied schedule identity and authEpoch. Refresh only authEpoch with pollerSdk.poller.getSchedule(scheduleId) immediately before signing; an inactive schedule retains its epoch but not its other fields.

For registration from CowShed, pass the cowShedSdk configured above. The SDK uses its configured signer, the adapter signer when none is configured, or a per-call signer override. That signer must be the schedule's funder, and the schedule owner must be its CowShed.

const registrationSchedule = { ...schedule, owner: cowShed }
const { authEpoch: registrationEpoch } = await pollerSdk.poller.getSchedule(
  pollerSdk.poller.getScheduleId(registrationSchedule),
)
const shedRegistrationParams = {
  cowShedSdk,
  schedule: { ...registrationSchedule, authEpoch: registrationEpoch },
  deadline: BigInt(Math.floor(Date.now() / 1000) + 15 * 60),
}

// Sign only: hand this factory transaction to a relayer or hook.
const signedRegistration = await pollerSdk.signRegisterFromShed(shedRegistrationParams)
// signedRegistration includes cowShedAccount, signedMulticall and gasLimit.

// Alternative: sign and submit now; the resolved signer pays transaction gas.
const shedRegistrationTx = await pollerSdk.registerFromShed(shedRegistrationParams)
await shedRegistrationTx.wait()

Choose one of these flows. Both sign a CowShed bundle with a single Poller call. The factory creates the CowShed if needed and executes registration from it. They accept CowShed's nonce, deadline, signingScheme, gasLimit, and defaultGasLimit options. Without a gas override, CowShed estimates gas; failures reject the call unless a fallback is supplied. For bundles containing other calls, use pollerSdk.poller.encodeRegisterFromShed with cowShedSdk.signCalls.

For revocation from CowShed, keep the original schedule identity, including its owner even when it differs from the CowShed. The resolved signer must be the funder. Refresh the epoch before signing:

const { authEpoch: revocationEpoch } = await pollerSdk.poller.getSchedule(scheduleId)
const shedRevocationParams = {
  cowShedSdk,
  handler: schedule.handler,
  funder: schedule.funder,
  owner: schedule.owner,
  salt: schedule.salt,
  authEpoch: revocationEpoch,
  deadline: BigInt(Math.floor(Date.now() / 1000) + 15 * 60),
}

// Sign only: return the factory bundle for a relayer or hook.
const signedRevocation = await pollerSdk.signRevokeFromShed(shedRevocationParams)

// Alternative: sign and submit now; the resolved signer pays transaction gas.
const shedRevocationTx = await pollerSdk.revokeFromShed(shedRevocationParams)
await shedRevocationTx.wait()

Choose one flow. signRevokeFromShed returns cowShedAccount, signedMulticall, and gasLimit without submitting. Both methods accept the same signer and CowShed options as registration. For a bundle containing other calls, use pollerSdk.poller.encodeRevokeFromShed with cowShedSdk.signCalls.

The schedule fields are:

  • handler: the registered conditional order's handler.
  • authEpoch: the schedule ID's current replay-protection epoch; it starts at zero and increments on revocation.
  • funder: the account from which the Poller draws sell tokens.
  • owner: the ComposableCoW conditional-order owner that receives those tokens.
  • salt: the registered conditional order's salt.
  • staticInput: the registered conditional order's encoded static input.

The low-level ComposableCowPoller only encodes these transactions; its consumer owns signing, gas policy, submission, and confirmation. Submit direct registration and revocation calldata to pollerAddress from schedule.funder, or submit signedRegisterCalldata or signedRevokeCalldata through a relayer. Signed registration calldata contains the schedule, deadline, and signature. Signed revocation calldata contains the handler, funder, owner, salt, authEpoch, deadline, and signature. Replay protection is scoped to the schedule ID through authEpoch. Use poller.getComposableCowAddress() and poller.getSchedule(scheduleId) to read Poller state.

Usage

import { ConditionalOrderFactory, Multiplexer, ConditionalOrder, ProofLocation } from '@cowprotocol/sdk-composable'
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 })

// Create a conditional order factory
const registry = {
  twap: TWAPOrderFactory,
  dca: DCAOrderFactory, // WIP: not implemented
  // ... other order types
}

const factory = new ConditionalOrderFactory(registry, adapter)

// Create conditional orders
const twapOrder = factory.fromParams({
  handler: TWAP_HANDLER_ADDRESS,
  salt: '0x...',
  staticInput: encodedTWAPData,
})

// Create multiplexer for batch management
const orders = {
  order1: twapOrder,
  // ... more orders
}

const multiplexer = new Multiplexer(SupportedChainId.MAINNET, orders, merkleRoot, ProofLocation.PRIVATE)

// Generate proofs for off-chain storage
const proofs = multiplexer.dumpProofsAndParams()

Conditional Order Types

TWAP (Time-Weighted Average Price)

Execute trades over time to achieve better average prices:

const twapOrder = new TWAPOrder({
  handler: TWAP_HANDLER,
  sellToken: '0x...',
  buyToken: '0x...',
  sellAmount: '1000000000000000000',
  numOfParts: 10,
  timeInterval: 3600, // 1 hour intervals
  startTime: Math.floor(Date.now() / 1000),
  span: 0, // Execute indefinitely
})

DCA (Dollar Cost Averaging) — WIP

DCAOrder is not implemented or exported yet.

Regularly buy or sell assets at predetermined intervals:

const dcaOrder = new DCAOrder({
  handler: DCA_HANDLER,
  sellToken: '0x...', // USDC
  buyToken: '0x...', // ETH
  sellAmount: '100000000', // $100 USDC
  timeInterval: 86400, // Daily
  numOfParts: 30, // For 30 days
})

Stop-Loss Orders — WIP

StopLossOrder is not implemented or exported yet.

Automatically sell when price drops below threshold:

const stopLossOrder = new StopLossOrder({
  handler: STOP_LOSS_HANDLER,
  sellToken: '0x...', // ETH
  buyToken: '0x...', // USDC
  sellAmount: '1000000000000000000', // 1 ETH
  strikePrice: '2000000000', // Trigger at $2000
})

Advanced Features

Merkle Tree Management

// Create multiplexer with multiple orders
const multiplexer = new Multiplexer(
  SupportedChainId.MAINNET,
  conditionalOrders,
  undefined, // Will generate merkle root
  ProofLocation.PRIVATE,
)

// Get merkle root for on-chain storage
const root = multiplexer.getOrGenerateTree().root

// Generate proofs for specific orders
const proofs = multiplexer.dumpProofsAndParams((order) => {
  return order.isActive // Only include active orders
})

Order Validation

// Check if conditional order is valid
const validationResult = await conditionalOrder.isValid({
  owner: userAddress,
  ctx: contextData,
})

if (validationResult.isValid) {
  // Order can be executed
  const tradeableOrder = await conditionalOrder.poll({
    owner: userAddress,
    proof: merkleProof,
    provider: provider,
  })
}

Context Dependencies

// Orders that depend on external data
const conditionalOrder = new PriceBasedOrder({
  handler: PRICE_HANDLER,
  // ... order parameters
})

// Get context dependency (e.g., price oracle)
const contextDependency = conditionalOrder.getContextDependency()

// Poll with off-chain input
const [orderData, signature] = await ConditionalOrder.poll(
  owner,
  proofWithParams,
  chainId,
  provider,
  async (owner, params) => {
    // Fetch off-chain data (prices, etc.)
    return await fetchOffChainInput(params)
  },
)

Order Registry Management

// Register custom order types
const registry = {
  'custom-twap': CustomTWAPOrder,
  'limit-order': LimitOrder,
  'bracket-order': BracketOrder,
}

const factory = new ConditionalOrderFactory(registry, adapter)

// Register new order type dynamically
Multiplexer.registerOrderType('new-order-type', NewOrderClass)

Smart Contract Integration

ComposableCoW Integration

// Set merkle root on ComposableCoW contract
const composableCowContract = adapter.getContract(COMPOSABLE_COW_CONTRACT_ADDRESS[chainId], ComposableCowABI)

// Set root with context
await composableCowContract.setRootWithContext(root, contextFactory, contextData)

Proof Generation and Storage

// Generate proofs for watchtowers/indexers
const proofsData = multiplexer.dumpProofs((order) => {
  // Filter criteria for proof inclusion
  return order.status === 'active'
})

// Store proofs off-chain (IPFS, etc.)
await uploadProofs(proofsData)

// Verify proofs on-chain when executing
const isValidProof = multiplexer.getOrGenerateTree().verify(proof, leafData)

Complete TWAP Setup

// 1. Create TWAP order
const twapOrder = new TWAPOrder({
  sellToken: WETH_ADDRESS,
  buyToken: USDC_ADDRESS,
  sellAmount: parseEther('10'), // 10 WETH
  numOfParts: 24, // 24 parts
  timeInterval: 3600, // 1 hour intervals
  startTime: Math.floor(Date.now() / 1000),
})

// 2. Create multiplexer
const multiplexer = new Multiplexer(SupportedChainId.MAINNET)
multiplexer.addOrder('twap-1', twapOrder)

// 3. Set root on ComposableCoW
const root = multiplexer.getOrGenerateTree().root
await composableCowContract.setRoot(root)

// 4. Generate proofs for watchtower
const proofs = multiplexer.dumpProofsAndParams()
await storeProofsOffChain(proofs)

Note: This package enables advanced trading strategies through programmable conditional orders. It's designed for sophisticated users who need automated execution of complex trading logic. Most basic trading needs can be addressed with the Trading SDK.

版本与发布记录

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

版本发布日期距今
1.8.14latest2026/11/046 天前
1.8.132026/11/046 天前
1.8.122026/11/037 天前
1.8.112026/10/2615 天前
1.8.102026/10/2615 天前
1.8.92026/10/2318 天前

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

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

@cowprotocol/sdk-composable 是什么?

TypeScript composable features for CoW Protocol SDK

如何安装 @cowprotocol/sdk-composable?

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

@cowprotocol/sdk-composable 支持 TypeScript 吗?

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

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

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

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

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

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

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

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

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