Skip to main content

Crate cow_rs

Crate cow_rs 

Source
Expand description

cow-rs — Rust SDK for the CoW Protocol (façade crate).

This is the Layer 6 façade of the workspace — it re-exports every layered cow-* crate under one ergonomic entry point and contains no logic of its own. Users who want tighter tree-shaking can depend on the individual cow-* crates directly.

Two naming conventions are exposed in parallel:

Both forms reach the same underlying crates.

LayerClean nameLegacy aliasCrate
L0primitivescow_primitives
L0chainsconfigcow_chains
L0errorcow_errors
L1typescow_types
L2signingorder_signingcow_signing
L2app_datacow_app_data
L2permit, erc20, ethflow, weiroll, cow_shed, settlementrespective cow-* crates
L3httpcow_http
L4orderbookorder_bookcow_orderbook
L4subgraph, onchainrespective cow-* crates
L5trading, composable, bridging, flash_loansrespective cow-* crates

§Quick start — TradingSdk

use alloy_primitives::U256;
use cow_rs::{OrderKind, SupportedChainId, TradeParameters, TradingSdk, TradingSdkConfig};

let sdk = TradingSdk::new(
    TradingSdkConfig::prod(SupportedChainId::Sepolia, "MyApp"),
    "0xdeadbeef...",
)?;
let result = sdk
    .post_swap_order(TradeParameters {
        kind: OrderKind::Sell,
        sell_token: "0xfFf9976782d46CC05630D1f6eBAb18b2324d6B14".parse()?,
        sell_token_decimals: 18,
        buy_token: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238".parse()?,
        buy_token_decimals: 6,
        amount: U256::from(100_000_000_000_000_u64),
        slippage_bps: Some(50),
        receiver: None,
        valid_for: None,
        valid_to: None,
        partially_fillable: None,
        partner_fee: None,
    })
    .await?;
println!("order: {}", result.order_id);

Re-exports§

pub use trading_swap_quoter::TradingSwapQuoter;
pub use settlement::reader::AllowListReader;
pub use settlement::reader::SettlementReader;
pub use traits::CowSigner;
pub use traits::IpfsClient;
pub use traits::OrderbookClient;
pub use traits::RpcProvider;
pub use cow_primitives as primitives;
pub use cow_http as http;
pub use cow_chains as chains;
pub use cow_signing as signing;
pub use cow_orderbook as orderbook;

Modules§

app_data
CoW Protocol order app-data — metadata schema and hash generation.
bridging
Cross-chain bridge aggregator and provider abstractions.
browser_wallet
EIP-1193 browser wallet adapter and WASM bindings.
common
Common utility functions ported from the TypeScript SDK common package.
composable
CoW Protocol composable (conditional) orders.
config
Chain configuration, contract addresses and endpoints.
cow_shed
CoW Shed proxy contract helpers.
cross_chain_post
post_cross_chain_order — post-time orchestration for a hook-based bridge order.
erc20
ERC-20 and EIP-2612 calldata builders.
error
Unified error type for the SDK.
ethflow
EthFlow native-currency order encoding.
flash_loans
Flash loan orchestration helpers.
onchain
JSON-RPC eth_call reader for on-chain state queries.
order_book
CoW Protocol orderbook API client and types.
order_signing
EIP-712 order signing, EIP-1271, and OrderUid computation.
permit
EIP-2612 permit utilities.
prelude
Curated prelude of the most commonly used items.
settlement
Settlement encoding and contract interaction layer for CoW Protocol.
subgraph
CoW Protocol subgraph GraphQL client.
trading
High-level trading SDK.
trading_swap_quoter
TradingSwapQuoter — newtype wrapper that adapts cow_trading::TradingSdk to the cow_bridging::SwapQuoter trait.
traits
Injectable trait abstractions for testing and composition.
types
Protocol enums and primitive constants.
wasm
wasm-bindgen exports (WASM-only).
weiroll
Weiroll script builder and encoding.

Structs§

Amounts
Amounts at a specific stage of the fee pipeline.
ApiContext
The CoW Protocol API context.
AppDataDoc
Root document for CoW Protocol order app-data (schema v1.14.0).
AppDataInfo
Full app-data information derived from an AppDataDoc.
AppDataObject
Response from GET /api/v1/app_data/{appDataHash} and PUT /api/v1/app_data/{appDataHash}.
Auction
A batch auction returned by GET /api/v1/auction.
BlockInfo
Block information used for conditional order validation.
BridgingSdk
High-level cross-chain bridge aggregator.
BuildAppDataParams
Parameters for building the app-data document for a trade.
Bundle
Aggregate price bundle — contains the current ETH/USD price.
ChainContract
An on-chain contract reference with an optional creation block.
ChainContracts
Well-known contracts on an EVM chain.
ChainRpcUrls
RPC URL configuration for an EVM chain.
ChainTokenInfo
Token info used in chain metadata.
CidComponents
Parsed components of an IPFS Content Identifier (CID).
CompetitionAuction
The set of order UIDs and reference prices that make up a competition auction.
CompetitionOrderStatus
Response from GET /api/v1/orders/{UID}/status.
ConditionalOrderFactory
Instantiates conditional orders from ConditionalOrderParams.
ConditionalOrderParams
ABI-encoded parameters identifying a conditional order on-chain.
CowHook
A single CoW Protocol pre- or post-settlement interaction hook.
CowShedCall
A single call to be executed by the CowShed proxy contract.
CowShedHookParams
Parameters for a CowShed execution bundle.
CowShedSdk
High-level helper for building CowShed proxy interactions.
CowSwapConfig
Configuration for the CoW Protocol swap executor.
DailyTotal
Full per-day protocol statistics entity from the subgraph.
DailyVolume
Per-day volume snapshot.
EncodedInteraction
An encoded interaction ready for inclusion in a settlement.
Erc20PermitInfo
EIP-712 domain metadata for an ERC-20 token that implements EIP-2612.
EthFlowOrderData
Parameters for a native-currency sell order submitted through the EthFlow contract.
EthFlowTransaction
Ready-to-send transaction for submitting a native-currency order.
EthflowData
Additional data present on EthFlow (native sell) orders.
EvmCall
An EVM call with a target address, calldata, and value.
EvmChainInfo
Metadata for an EVM chain.
FlashLoanParams
Parameters for a flash loan pre-interaction hook.
FlashLoanSdk
Helper for building flash loan pre-interaction hooks.
GatData
Parameters for a GoodAfterTime (GAT) conditional order.
GatOrder
A GoodAfterTime conditional order ready for submission to ComposableCow.
GetOrdersRequest
Query parameters for GET /api/v1/account/{owner}/orders.
GetTradesRequest
Query parameters for GET /api/v2/trades.
GpV2OrderStruct
Raw on-chain GPv2Order.DataStruct as emitted by the GPv2Settlement contract.
HourlyTotal
Full per-hour protocol statistics entity from the subgraph.
HourlyVolume
Per-hour volume snapshot.
InteractionData
A single on-chain interaction (pre- or post-settlement hook).
Ipfs
IPFS connection parameters for upload/fetch operations.
IpfsConfig
IPFS configuration for reading and writing app data.
IpfsUploadResult
Result of uploading metadata to IPFS (legacy).
LimitOrderAdvancedSettings
Advanced overrides for limit order submission.
LimitTradeParameters
Parameters for a limit order (fixed price, no slippage).
LimitTradeParametersFromQuote
Simplified limit order parameters derived directly from a quote response.
Metadata
Metadata container — all fields are optional.
MetadataApi
High-level facade mirroring MetadataApi from the TypeScript SDK.
Multiplexer
Manages a set of conditional orders and computes their Merkle root.
NetworkFee
Network fee expressed in both currencies.
NonEvmChainInfo
Metadata for a non-EVM chain (e.g. Bitcoin, Solana).
OnchainOrderData
On-chain placement metadata for orders submitted directly on-chain (as opposed to the off-chain API).
OnchainReader
Reads on-chain state from an Ethereum node via JSON-RPC eth_call.
OnchainTokenInfo
Aggregate on-chain token information gathered in a single round of concurrent eth_call requests.
Order
A full order record returned by GET /api/v1/orders/{uid}.
OrderBookApi
Async HTTP client for the CoW Protocol orderbook REST API.
OrderCancellations
Request body for DELETE /api/v1/orders — batch cancellation of orders.
OrderCreation
Request body for POST /api/v1/orders — a signed order ready to submit.
OrderDomain
The EIP-712 domain for CoW Protocol orders.
OrderFlags
Order flags extracted from a bitfield.
OrderInteractionHooks
Pre- and post-settlement interaction hooks.
OrderInteractions
Pre- and post-settlement interaction hooks attached to an order.
OrderPostingResult
The result of a successful order submission.
OrderProof
Merkle inclusion proof for a single conditional order.
OrderQuoteRequest
Request body for POST /api/v1/quote.
OrderQuoteResponse
Response from POST /api/v1/quote.
OrderRefund
Refund claim for a CoW Protocol order.
OrderTypedData
The full EIP-712 typed data envelope for a CoW Protocol order.
OrderUid
The unique order identifier returned by POST /api/v1/orders.
OrderUidParams
Parameters extracted from a 56-byte order UID.
PairDaily
Per-day statistics for a token pair.
PairHourly
Per-hour statistics for a token pair.
PartnerFeeCost
Partner fee cost component.
PartnerFeeEntry
A single partner fee policy entry (schema v1.14.0).
PartnerFeeResult
Result of partner-fee calculation.
PermitHookData
Pre-interaction hook data that CoW Protocol appends to an order to trigger an EIP-2612 permit call before settlement.
PermitInfo
Core parameters for an EIP-2612 permit operation.
PostTradeAdditionalParams
Additional parameters for posting orders.
ProofStruct
On-chain Proof argument passed to ComposableCow::setRoot.
ProofWithParams
Proof and params bundled for watchtower export.
ProtocolFeeAmountParams
Parameters for get_protocol_fee_amount.
ProtocolFeeCost
Protocol fee cost component.
ProtocolOptions
Protocol-level options for overriding CoW Protocol contract addresses and environment.
Quote
Quote-level slippage settings embedded in app-data.
QuoteAmounts
Sell and buy amounts at a particular fee stage.
QuoteAmountsAndCosts
Full fee and amount breakdown for a quoted trade, mirroring the CoW SDK’s QuoteAmountsAndCosts structure.
QuoteAmountsAndCostsParams
Parameters for get_quote_amounts_and_costs.
QuoteAmountsAndCostsResult
Complete breakdown of quote amounts at every fee stage.
QuoteBridgeRequest
Request for a cross-chain bridge quote.
QuoteBridgeResponse
A bridge quote from a single provider.
QuoteCosts
All cost components of a quote.
QuoteData
The core quote amounts returned by the orderbook.
QuoteFeeComponent
A single fee component: absolute amount and its BPS rate.
QuoteNetworkFee
Network fee expressed in both sell and buy currency.
QuoteOrderParams
Order parameters needed by the quote-amount calculations.
QuoteResults
The result of a successful quote, bundled with posting capability.
QuoteResultsWithSigner
Quote results bundled with the signer that produced them.
QuoteSide
The directional “side” of a quote request.
QuoterParameters
Trader information extracted from swap parameters.
RateLimiter
A shared token-bucket rate limiter.
ReplacedOrder
Links this order to a previously submitted order it supersedes.
RetryPolicy
Exponential-backoff retry policy for transient HTTP failures.
SettlementEncoder
Orchestrates building a complete GPv2Settlement.settle() calldata payload.
SignOrderCancellationParams
Parameters for signing a single order cancellation.
SignOrderCancellationsParams
Parameters for signing multiple order cancellations in bulk.
SignOrderParams
Parameters for signing a CoW Protocol order.
SigningResult
The result of signing an order — signature bytes and the scheme used.
SimulationResult
Result of simulating a settlement transaction via eth_call.
SlippageToleranceRequest
Request parameters for a slippage tolerance suggestion.
SlippageToleranceResponse
Response from a slippage tolerance suggestion.
SolverCompetition
Solver competition response from GET /api/v1/solver_competition/{auctionId}.
SolverExecution
Per-solver execution amounts within the competition.
SolverSettlement
A single solver’s proposed settlement within a competition.
StopLossData
Parameters for a stop-loss conditional order.
StopLossOrder
A stop-loss conditional order ready to be submitted to ComposableCow.
SubgraphApi
GraphQL client for the CoW Protocol subgraph.
SubgraphBlock
Block information returned by the subgraph _meta field.
SubgraphMeta
Top-level subgraph indexing metadata returned by the _meta field.
SubgraphOrder
An order indexed by the subgraph.
SubgraphPair
A trading pair (two tokens) indexed by the subgraph.
SubgraphSettlement
An on-chain batch settlement transaction.
SubgraphToken
An ERC-20 token indexed by the subgraph.
SubgraphTrade
A single trade executed within a batch settlement.
SubgraphUser
A trader address indexed by the subgraph.
SwapAdvancedSettings
Advanced overrides for swap and quote operations.
SwapQuoteOutcome
Minimal swap-quote response returned by a SwapQuoter. Carries just enough to build the outer QuoteBridgeResponse and upstream app-data attribution.
SwapQuoteParams
Minimal swap-quote request passed from the bridging orchestrator to a SwapQuoter. Mirrors the subset of TradeParameters the bridging layer needs for the intermediate hop.
TestConditionalOrderParams
Parameters for creating a test conditional order.
ThemedImage
A themed image with light and dark variants.
TokenDailyTotal
Per-day volume and price statistics for a specific token.
TokenHourlyTotal
Per-hour volume and price statistics for a specific token.
TokenInfo
Minimal token metadata used for order size calculations.
TokenRegistry
A registry mapping asset ticker symbols to their ERC-20 token metadata.
TokenTradingEvent
A price-changing event for a token (used to reconstruct OHLC data).
Total
Protocol-wide singleton accumulator entity from the subgraph.
TotalSurplus
Response from GET /api/v1/users/{address}/total_surplus.
Totals
Protocol-wide aggregate statistics.
Trade
A single trade event returned by GET /api/v1/trades or GET /api/v2/trades.
TradeFlags
Trade flags: order flags plus a signing scheme.
TradeParameters
Parameters for requesting a swap quote.
TradeSimulator
Simulates settlement execution to estimate gas costs and detect reverts.
TradingAppDataInfo
App-data document and its keccak256 hash.
TradingSdk
High-level CoW Protocol trading interface.
TradingSdkConfig
Configuration for TradingSdk.
TradingTransactionParams
A raw Ethereum transaction object produced by the CoW SDK on-chain helpers.
TwapData
Parameters for a Time-Weighted Average Price (TWAP) order.
TwapOrder
A TWAP order ready to be submitted to ComposableCow.
TwapStruct
On-chain TwapStruct representation with per-part amounts.
UniswapPool
A Uniswap pool entity indexed by the CoW Protocol subgraph.
UniswapToken
A Uniswap token entity indexed by the CoW Protocol subgraph.
UnsignedOrder
An unsigned CoW Protocol order ready to be hashed and signed.
Utm
UTM campaign tracking parameters.
ValidationResult
Result of validating an AppDataDoc against its schema.
WebUrl
A named URL.
WeirollCommand
A single command in a Weiroll script (32-byte packed encoding).
WeirollContractRef
A Weiroll-compatible contract reference with a default call mode.
WeirollPlanner
Builder that accumulates commands and state slots into a Weiroll script.
WeirollScript
A complete Weiroll script ready for on-chain execution.
Widget
Widget integration metadata.

Enums§

AdditionalTargetChainId
Chains where you can buy tokens using bridge functionality but that are not directly supported by CoW Protocol for selling.
BridgeError
Errors specific to bridging operations.
ChainInfo
A chain on the network – either an EVM chain or a non-EVM chain.
CompetitionOrderStatusKind
Fine-grained lifecycle state of an order within the current batch auction.
ConditionalOrderKind
A conditional order decoded from on-chain ConditionalOrderParams.
CowError
Errors that can occur when interacting with the CoW Protocol SDK.
DurationOfPart
Duration constraint for each individual TWAP part.
EcdsaSigningScheme
ECDSA-only signing schemes (EIP-712 or EIP-191).
Env
Orderbook API environment.
EvmChains
All EVM chains supported by CoW Protocol or available for bridging.
FlashLoanProvider
Supported flash loan providers.
InteractionStage
The three interaction stages in a CoW Protocol settlement.
IsValidResult
Result of validating a conditional order.
NonEvmChains
All non-EVM chains available for bridging only.
OrderClass
Order class assigned by the orderbook.
OrderClassKind
High-level classification of the order’s intent.
OrderKind
Whether to sell an exact input amount or buy an exact output amount.
OrderStatus
Lifecycle state of an order on the orderbook.
PartnerFee
Partner fee attached to a CoW Protocol order (schema v1.14.0).
PollResult
Result returned when polling a conditional order for tradability.
PriceQuality
Quote price-quality hint passed to the orderbook.
ProofLocation
Where the Merkle proof for a conditional order is stored / communicated.
QuoteStrategy
Strategy variant for quote retrieval.
Referrer
Partner referral tracking information.
RefundType
The contract path to use for an order refund.
SigningScheme
Signing scheme for a CoW Protocol order.
SupportedChainId
Chains supported by the CoW Protocol orderbook.
TargetChainId
A chain ID that is either a SupportedChainId or an AdditionalTargetChainId.
TokenBalance
The ERC-20 balance source/destination for sellToken and buyToken.
TwapStartTime
Start time specification for a TWAP order.
ValidationError
A specific constraint violation found when validating an AppDataDoc.
WeirollCommandFlags
Flags that modify the execution mode of a Weiroll command.

Constants§

ACROSS_DEPOSIT_EVENT_INTERFACE
Alias for ACROSS_FUNDS_DEPOSITED_TOPIC matching the TypeScript ACROSS_DEPOSIT_EVENT_INTERFACE export.
ATTESTATION_PREFIX_CONST
Near Intents attestation prefix constant.
ATTESTATOR_ADDRESS
Near Intents attestator address.
ATTESTION_VERSION_BYTE
Near Intents attestation version byte.
BARN_ETH_FLOW
The staging (barn) EthFlow contract address.
BTC_CURRENCY_ADDRESS
Sentinel address for BTC native currency.
BUY_ETH_ADDRESS
Marker address to indicate that an order is buying Ether (native currency).
COMPOSABLE_COW
The ComposableCow factory contract address.
COMPOSABLE_COW_ADDRESS
ComposableCow factory contract — same address on all supported chains.
COW_TRADE_EVENT_INTERFACE
Alias for COW_TRADE_EVENT_SIGNATURE matching the TypeScript COW_TRADE_EVENT_INTERFACE export.
CURRENT_BLOCK_TIMESTAMP_FACTORY_ADDRESS
CurrentBlockTimestampFactory contract address.
DEFAULT_FEE_SLIPPAGE_FACTOR_PCT
Default fee-based slippage multiplier: 50 % of the quoted fee amount.
DEFAULT_IPFS_READ_URI
Default IPFS gateway used when none is provided.
DEFAULT_IPFS_WRITE_URI
Default IPFS write URI (Pinata).
DEFAULT_QUOTE_VALIDITY
Default order TTL in seconds (30 minutes).
DEFAULT_RETRY_STATUS_CODES
HTTP status codes that the upstream TypeScript SDK retries on. Mirrors STATUS_CODES_TO_RETRY in packages/order-book/src/request.ts.
DEFAULT_SLIPPAGE_BPS
Default slippage in basis points (0.5 %).
DEFAULT_VOLUME_SLIPPAGE_BPS
Default volume-based slippage in basis points (0.5 %).
DEPLOYER_CONTRACT
The CREATE2 deployer contract address.
EIP1271_MAGICVALUE
Value returned by a call to isValidSignature if the signature was verified successfully (EIP-1271).
ETH_FLOW_DEFAULT_SLIPPAGE_BPS
Default slippage for ETH flow (native-currency sell) orders, in basis points.
ETH_FLOW_PROD
The production EthFlow contract address.
ETH_FLOW_STAGING
The staging (barn) EthFlow contract address.
EVM_NATIVE_CURRENCY_ADDRESS
The standard address used to represent native currency on EVM chains.
EXTENSIBLE_FALLBACK_HANDLER
The ExtensibleFallbackHandler contract address.
GAS_LIMIT_DEFAULT
Fallback gas limit for smart-contract wallet interactions (150 000 gas).
GAT_HANDLER_ADDRESS
GoodAfterTime handler contract address.
HUNDRED_THOUSANDS
Scale factor: 100 000.
LAST_DAYS_VOLUME_QUERY
GraphQL query for daily volume snapshots over the last N days.
LAST_HOURS_VOLUME_QUERY
GraphQL query for hourly volume snapshots over the last N hours.
LATEST_APP_DATA_VERSION
Latest app-data schema version this crate targets.
LIMIT_CONCURRENT_REQUESTS
Maximum concurrent requests to the CoW Protocol API.
MAX_FREQUENCY
Maximum allowed part_duration in seconds (1 year).
MAX_SLIPPAGE_BPS
Maximum allowed suggested slippage (100 %).
MAX_UINT32
Maximum u32 value as a U256 (2^32 - 1 = 4 294 967 295).
MAX_UINT256
Maximum U256 value (2^256 - 1).
MAX_VALID_TO_EPOCH
Maximum valid-to epoch value (u32::MAX).
NATIVE_CURRENCY_ADDRESS
The sentinel address used to represent the native currency (ETH, xDAI, AVAX, …).
ONE
U256 one.
ONE_HUNDRED_BPS
One hundred basis points expressed as a U256 (100 * 100 = 10 000).
ORDER_PRIMARY_TYPE
EIP-712 primary type for CoW Protocol orders.
ORDER_TYPE_HASH
Pre-computed EIP-712 type hash for a Gnosis Protocol v2 order.
ORDER_UID_LENGTH
The byte length of an order UID (32 bytes order digest + 20 bytes owner + 4 bytes validTo).
PERMIT_GAS_LIMIT
Estimated gas required for a single EIP-2612 permit call.
PRE_SIGNED
Marker value indicating a presignature is set.
RAW_CHAINS_FILES_PATH
CDN path for chain data.
RAW_FILES_PATH
Base CDN path for SDK files.
SALT
The deterministic deployment salt.
SETTLEMENT_CONTRACT
The CoW Protocol GPv2Settlement contract address.
SETTLEMENT_CONTRACT_STAGING
The staging CoW Protocol GPv2Settlement contract address.
SOL_NATIVE_CURRENCY_ADDRESS
Sentinel address for SOL native currency.
STOP_LOSS_HANDLER_ADDRESS
StopLoss handler contract address (Ethereum mainnet).
TOKEN_LIST_IMAGES_PATH
CDN path for token list images.
TOTALS_QUERY
GraphQL query for protocol-wide aggregate statistics.
TWAP_HANDLER_ADDRESS
Default TWAP handler contract address.
VAULT_ACTIONS
The Balancer V2 Vault function names used by GPv2Settlement.
VAULT_RELAYER
The CoW Protocol Vault Relayer contract address.
VAULT_RELAYER_STAGING
The staging CoW Protocol Vault Relayer contract address.
WEIROLL_ADDRESS
The default Weiroll executor contract address deployed across supported chains.
ZERO
U256 zero.
ZERO_ADDRESS
The zero address (0x0000…0000).
ZERO_HASH
The 32-byte zero hash.

Traits§

BridgeProvider
Trait implemented by cross-chain bridge providers (Across, Bungee, NEAR Intents, …).
SwapQuoter
Trait implemented by any “thing that can quote an intermediate swap”.

Functions§

additional_target_chain_info
Return the ChainInfo for an AdditionalTargetChainId.
adjust_eth_flow_limit_order_params
Adjust limit-order parameters for ETH-flow by replacing the sell token with the wrapped native currency.
adjust_eth_flow_order_params
Adjust trade parameters for ETH-flow orders by replacing the sell token with the wrapped native currency for the given chain.
all_additional_target_chain_ids
Return all chain IDs for additional target chains (bridge-only).
all_additional_target_chains
Return chain info for all additional target chains (bridge-only).
all_chain_ids
Return all known chain IDs as TargetChainId values.
all_chains
Return chain info for all known chains (both supported and bridge-only).
all_supported_chain_ids
Return all supported chain IDs as a Vec.
all_supported_chains
Return chain info for all supported chains.
api_base_url
Return the orderbook API base URL (no trailing slash) for chain in env.
api_url
Return the orderbook API base URL for a chain and environment.
app_data_hex_to_cid_legacyDeprecated
Convert an appDataHex to a CIDv1 string using the legacy encoding.
appdata_hex
Serialise doc to canonical JSON with sorted keys, then return keccak256(json_bytes).
appdata_hex_to_cid
Convert an appDataHex value (the 32-byte keccak256 stored in the order struct) into a CIDv1 string.
appdata_json
Return the canonical JSON string for doc with all object keys sorted alphabetically and no extraneous whitespace.
apply_percentage
Apply a percentage value to value.
apply_settings_to_limit_trade_parameters
Apply LimitOrderAdvancedSettings overrides to limit order parameters.
assert_cid
Validate that a CID string is non-empty.
balance_to_string
Reverse-map a keccak256-hashed token-balance string back to its name.
bps_to_percentage
Convert basis points to a percentage value.
build_app_data
Build app-data for a trade, including slippage, order class, and optional partner fee.
build_app_data_doc
Build the 0x-prefixed app-data hex string with the given app_code and Metadata.
build_app_data_doc_full
Build the canonical JSON app-data document together with its keccak256 hash.
build_eip2612_nonces_calldata
Build calldata for EIP-2612.nonces(address owner).
build_eip2612_version_calldata
Build calldata for EIP-2612.version() — a 4-byte selector-only call.
build_erc20_allowance_calldata
Build calldata for ERC20.allowance(address owner, address spender).
build_erc20_approve_calldata
Build calldata for ERC20.approve(address spender, uint256 amount).
build_erc20_balance_of_calldata
Build calldata for ERC20.balanceOf(address account).
build_erc20_decimals_calldata
Build calldata for ERC20.decimals() — a 4-byte selector-only call.
build_erc20_name_calldata
Build calldata for ERC20.name() — a 4-byte selector-only call.
build_erc20_transfer_calldata
Build calldata for ERC20.transfer(address to, uint256 amount).
build_erc20_transfer_from_calldata
Build calldata for ERC20.transferFrom(address from, address to, uint256 amount).
build_eth_flow_transaction
Build a complete EthFlowTransaction for contract_address.
build_order_app_data
Build the 0x-prefixed app-data hex string for an order identified by app_code.
build_order_typed_data
Build a complete OrderTypedData envelope for order on chain_id.
build_permit_calldata
ABI-encode the permit(address,address,uint256,uint256,uint256,uint8,bytes32,bytes32) call.
build_permit_hook
Sign and build a PermitHookData ready for attachment to a CoW Protocol order.
calculate_gas_margin
Add a 20 % safety margin to a gas estimate.
calculate_unique_order_id
Calculate a unique order ID for ETH-flow orders.
cancellations_hash
Compute the EIP-712 struct hash for a batch of order cancellations.
cid_to_appdata_hex
Extract the digest from a CIDv1 string and return it as 0x-prefixed hex.
composable_cow
Return the ComposableCow contract address for chain.
composable_cow_contract_address
Return the ComposableCow contract address for a given chain.
compute_order_uid
Compute the CoW Protocol order UID (56-byte hex string).
cow_protocol_settlement_contract_address
Return the CoW Protocol settlement contract address for a given chain.
cow_protocol_vault_relayer_address
Return the CoW Protocol Vault Relayer address for a given chain.
cow_protocol_vault_relayer_address_staging
Return the staging CoW Protocol Vault Relayer address for a given chain.
create_calldata
Encode calldata for ComposableCow::create.
create_set_domain_verifier_tx
Encode a setDomainVerifier(bytes32 domain, address verifier) call.
create_strategies
Create all available quote strategies.
create_test_conditional_order
Create a test ConditionalOrderParams with optional overrides.
create_weiroll_contract
Create a WeirollContractRef for a standard CALL contract.
create_weiroll_delegate_call
Build a Weiroll delegate-call EvmCall by running a planner callback.
create_weiroll_library
Create a WeirollContractRef for a Weiroll library (DELEGATECALL).
create_with_context_calldata
Encode calldata for ComposableCow::createWithContext.
data_to_struct
Convert TwapData (user-facing, total amounts) into a TwapStruct (per-part amounts).
decode_cid
Decode raw CID bytes into their constituent CidComponents.
decode_gat_static_input
ABI-decode a 448-byte staticInput buffer into a GatData.
decode_order_flags
Decode order flags from a bitfield.
decode_params
ABI-decode a hex string into ConditionalOrderParams.
decode_signature_owner
Extract the owner (verifier) address from an EIP-1271 packed signature.
decode_signing_scheme
Decode a SigningScheme from a trade-flags bitfield.
decode_stop_loss_static_input
ABI-decode a 416-byte staticInput buffer into a StopLossData.
decode_trade_flags
Decode trade flags from a bitfield.
decode_twap_static_input
ABI-decode a 320-byte staticInput buffer into TwapData.
decode_twap_struct
ABI-decode a 320-byte staticInput buffer into the raw TwapStruct.
default_token_formatter
Default token formatter: produces "{amount}@{address}".
define_read_only
Apply a mutation to a value and return it — a porting convenience for builder-style field assignments.
deterministic_deployment_address
Compute the deterministic CREATE2 deployment address for a contract.
domain_separator
Compute the EIP-712 domain separator for CoW Protocol on chain_id.
domain_separator_from
Compute the EIP-712 domain separator from a custom OrderDomain.
eip1271_result
Build a SigningResult for an EIP-1271 smart-contract-wallet order.
encode_eth_flow_create_order
Encode the EthFlow.createOrder(order, quoteId) calldata.
encode_gat_struct
ABI-encode a GatData struct into the staticInput bytes expected by the on-chain GoodAfterTime handler.
encode_order_flags
Encode order flags as a single byte bitfield.
encode_params
ABI-encode ConditionalOrderParams into a 0x-prefixed hex string.
encode_signing_scheme
Encode a SigningScheme into its flag bits.
encode_stop_loss_struct
ABI-encode a StopLossData struct into the 416-byte staticInput bytes expected by the on-chain StopLoss handler.
encode_trade_flags
Encode trade flags (order flags + signing scheme) as a single byte bitfield.
encode_twap_struct
ABI-encode a TwapStruct into the 320-byte staticInput bytes expected by the on-chain TWAP handler.
eth_flow_for_env
Return the EthFlow contract address for chain in a given environment.
ethflow_refund_calldata
Build calldata for CoWSwapEthFlow.invalidateOrder(bytes orderUid).
extensible_fallback_handler
Return the ExtensibleFallbackHandler contract address for chain.
extensible_fallback_handler_contract_address
Return the ExtensibleFallbackHandler contract address for a given chain.
extract_digest
Extract the multihash digest from a CID string and return it as 0x-prefixed hex.
extract_order_uid_params
Extract order UID parameters from a 56-byte hex-encoded string.
fetch_doc_from_app_data_hex
Fetch an AppDataDoc from IPFS using a hex appData value.
fetch_doc_from_app_data_hex_legacyDeprecated
Fetch an AppDataDoc from IPFS using the legacy CID derivation method.
fetch_doc_from_cid
Fetch an AppDataDoc from IPFS by its CIDv1.
format_epoch
Format a Unix timestamp as an RFC 3339 / ISO 8601 date-time string.
from_struct_to_order
Decode a raw on-chain GpV2OrderStruct into a typed UnsignedOrder.
generate_app_data_from_doc
Compute the keccak256 hash and full JSON string from an app-data document value.
generate_order_id
Generate the order ID (UID) for a given order, chain, and owner.
get_app_data_info
Derive the full AppDataInfo from a document.
get_app_data_info_legacyDeprecated
Derive AppDataInfo using the legacy method.
get_app_data_schema
Get the app-data schema for a given version.
get_block_info
Get block information (number and timestamp) for constructing conditional orders.
get_cache_key
Compute a cache key for a bridge request.
get_chain_info
Return the chain info for a given chain ID, or None if the chain is not known.
get_default_slippage_bps
Return the default slippage tolerance in basis points for a given chain and flow type.
get_default_utm_params
Return the default UTM parameters embedded in orders by the CoW Protocol SDK.
get_domain
Return the EIP-712 OrderDomain for the CoW Protocol on chain_id.
get_domain_verifier
Alias for get_domain_verifier_calldata.
get_domain_verifier_calldata
Get the domain verifier address for a Safe from the ExtensibleFallbackHandler.
get_eth_flow_cancellation
Build an on-chain cancellation transaction for an ETH-flow order.
get_eth_flow_contract
Resolve the ETH-flow contract address for a given chain and environment.
get_is_eth_flow_order
Return true if sell_token is the native currency sentinel address.
get_is_valid_result
Check whether an IsValidResult represents a valid state.
get_order_deadline_from_now
Compute the absolute Unix timestamp at which an order expires.
get_order_to_sign
Build an UnsignedOrder from limit-order parameters and a quote context.
get_order_typed_data
Build the EIP-712 typed data for an order, ready for signing.
get_partner_fee_bps
Extract the first volumeBps value from an optional PartnerFee.
get_protocol_fee_amount
Derive the absolute protocol-fee amount from the quote response.
get_quote_amounts_after_partner_fee
Calculate the partner-fee amount and adjust quote amounts accordingly.
get_quote_amounts_after_slippage
Apply slippage tolerance to amounts after all fees.
get_quote_amounts_and_costs
Calculate all quote-amount stages and costs from a /quote API response.
get_quote_raw
Fetch a raw order quote directly from the orderbook API.
get_quote_with_signer
Get a quote using a specific signer.
get_quote_without_signer
Fetch a full QuoteResults for an arbitrary owner address — no signer required.
get_settlement_cancellation
Build an on-chain cancellation transaction for a settlement order.
get_settlement_contract
Resolve the settlement contract address for a given chain and environment.
get_slippage_percent
Compute the slippage percentage from absolute slippage amounts.
get_static
Look up a value by key in a static registry of (key, value) pairs.
get_trade_parameters_after_quote
Restore the original sell token in trade parameters after an ETH-flow quote.
get_trader
Extract the trader’s account address from swap parameters.
get_wrapped_token_for_chain
Return the wrapped native currency for chain, or None if unknown.
grant_role_calldata
ABI-encode grantRole(bytes32 role, address account) calldata.
hash_order
Compute the EIP-712 struct hash for order.
hash_order_cancellation
Compute the EIP-712 signing hash for a single order cancellation.
hash_order_cancellations
Compute the EIP-712 signing hash for a batch of order cancellations.
hash_typed_data
Compute the EIP-712 typed data hash: keccak256("\x19\x01" || domainSep || structHash).
hashify
Convert a numeric app-data value to a zero-padded 32-byte hash.
implementation_address_slot
Build eth_getStorageAt calldata to read the EIP-1967 implementation address.
import_schema
Import (look up) an app-data schema by version string.
invalidate_order_calldata
Build calldata for GPv2Settlement.invalidateOrder(bytes orderUid).
is_additional_target_chain
Check if a chain ID is a bridge-only target chain.
is_btc_chain
Check if a chain ID represents Bitcoin.
is_chain_deprecated
Check if a chain is deprecated (no new trading; chain remains for history/Explorer).
is_chain_under_development
Check if a chain is under development.
is_composable_cow
Returns true if address is the canonical ComposableCow factory address.
is_eth_flow_order
Returns true if order is an EthFlow (native sell) order.
is_eth_flow_order_data
Check whether on-chain data is present, indicating an EthFlow order.
is_evm_chain
Check if a chain ID represents an EVM chain (including bridge-only ones like Optimism).
is_evm_chain_info
Check if a ChainInfo represents an EVM chain.
is_extensible_fallback_handler
Returns true if address is the canonical ExtensibleFallbackHandler contract.
is_non_evm_chain
Check if a chain ID represents a non-EVM chain (Bitcoin, Solana).
is_non_evm_chain_info
Check if a ChainInfo represents a non-EVM chain.
is_supported_chain
Check if a chain ID is directly supported by CoW Protocol for trading.
is_target_chain_id
Check if a chain ID is either a supported chain or a bridge target.
is_valid_abi
Returns true if hex is a plausibly valid ABI-encoded ConditionalOrderParams.
is_zk_sync_chain
Check if a chain is zkSync-based.
kind_to_string
Reverse-map a keccak256-hashed order-kind string back to its name.
map_address_to_supported_networks
Map an address to all supported networks.
map_all_networks
Map a value across all target chains (supported + additional), returning a Vec of (TargetChainId, T) pairs.
map_quote_amounts_and_costs
Apply a mapping function to every amount in a QuoteAmountsAndCosts.
map_supported_networks
Map a value across all supported chains, returning a Vec of (SupportedChainId, T) pairs.
merge_app_data_doc
Deep-merge other into base and return the result.
normalize_buy_token_balance
Normalize the buy token balance, converting External to Erc20.
normalize_order
Normalize an UnsignedOrder for EIP-712 hashing, filling defaults.
order_explorer_link
Build a CoW Protocol Explorer link for an order.
order_hash
Compute the EIP-712 struct hash for order.
order_id
Compute the on-chain order ID from ConditionalOrderParams.
owner_address_slot
Build eth_getStorageAt calldata to read the EIP-1967 admin/owner address.
pack_order_uid_params
Pack order UID parameters into a 56-byte hex-encoded string.
parse_cid
Parse a CID string into its constituent CidComponents.
percentage_to_bps
Convert a percentage value to basis points (rounded).
permit_digest
Compute the EIP-712 signing digest for a Permit struct.
permit_domain_separator
Compute the EIP-712 domain separator for a token that implements EIP-2612.
permit_type_hash
Compute keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)").
pin_json_in_pinata_ipfs
Upload an AppDataDoc to IPFS via the Pinata pinning service.
post_co_w_protocol_trade
Post a signed order to the CoW Protocol orderbook.
post_cow_protocol_trade
Post a signed order to the CoW Protocol orderbook.
post_sell_native_currency_order
Post a native-currency sell order via the ETH-flow contract.
presign_result
Build a SigningResult for a pre-sign order.
remove_calldata
Encode calldata for ComposableCow::remove(bytes32 id).
required_vault_role_calls
Generate all grantRole calls needed to authorize an account on the Balancer Vault.
required_vault_role_selectors
Return the function selectors for the Vault methods that require authorization.
resolve_order_book_api
Resolve an OrderBookApi for the given chain and environment.
resolve_signer
Resolve a signer from an optional hex private key.
resolve_slippage_suggestion
Resolve the slippage suggestion for a trade.
revoke_role_calldata
ABI-encode revokeRole(bytes32 role, address account) calldata.
safe_call_best_quote_callback
Safely invoke a “best quote” callback, catching panics.
safe_call_progressive_callback
Safely invoke a “progressive quote” callback, catching panics.
set_pre_signature_calldata
Build calldata for GPv2Settlement.setPreSignature(bytes orderUid, bool signed).
set_root_calldata
Encode calldata for ComposableCow::setRoot.
set_root_with_context_calldata
Encode calldata for ComposableCow::setRootWithContext.
settlement_contract
Return the production settlement contract address for chain.
settlement_contract_for_env
Return the settlement contract address for chain in a given environment.
settlement_refund_calldata
Build calldata for GPv2Settlement.freeFilledAmountStorage(bytes orderUid).
sign_order
Sign order using EIP-712 typed data and return the encoded SigningResult.
sign_order_cancellation
Sign a single order cancellation using EIP-712 typed data.
sign_order_cancellations
Sign one or more order cancellations using EIP-712 typed data.
sign_permit
Sign an EIP-2612 permit and return the raw 65-byte r ‖ s ‖ v signature.
signing_digest
Compute the final signing digest: "\x19\x01" ‖ domainSep ‖ orderHash.
stringify_deterministic
Serialise doc to a deterministic JSON string with all object keys sorted alphabetically at every nesting level.
struct_to_data
Convert a TwapStruct (per-part, on-chain view) back into TwapData.
suggest_slippage_bps
Suggest a slippage tolerance for a trade, combining fee- and volume-based components.
suggest_slippage_from_fee
Compute the fee-based slippage component.
suggest_slippage_from_volume
Compute the volume-based slippage component.
supported_chain_info
Return the ChainInfo for a SupportedChainId.
swap_params_to_limit_order_params
Convert TradeParameters + a raw quote response into LimitTradeParametersFromQuote.
tradable_supported_chain_ids
Return chain IDs where new trading is allowed (excludes deprecated chains).
tradable_supported_chains
Return chain info for tradable supported chains (excludes deprecated).
transform_data_to_struct
Transform raw contract data bytes into a ConditionalOrderParams struct.
transform_order
Enrich an Order by computing its total_fee field.
transform_struct_to_data
Transform a ConditionalOrderParams struct back into ABI-encoded hex.
unsigned_order_for_signing
Convert an UnsignedOrder into a form suitable for on-chain signing.
upload_app_data_to_pinata
Upload an AppDataDoc to IPFS via the Pinata pinning service.
upload_metadata_doc_to_ipfs_legacyDeprecated
Upload an AppDataDoc to IPFS via Pinata using the legacy method.
validate_app_data_doc
Validate an AppDataDoc against all CoW Protocol app-data rules.
vault_relayer
Return the vault relayer contract address for chain.
vault_relayer_for_env
Return the vault relayer contract address for chain in a given environment.
vault_role_hash
Compute the Balancer Vault action-ID hash for a given vault and function selector.
wrapped_native_currency
Return the wrapped native currency TokenInfo for chain.

Type Aliases§

AddressPerChain
Per-chain address mapping for supported chains.
ApiBaseUrls
Per-chain base URL mapping for supported chains.