Expand description
§cow-sdk-orderbook
Typed CoW Protocol orderbook client with chain and environment-aware endpoint resolution, explicit request policy, and deterministic response decoding.
⚠️ Alpha —
0.1.0-alpha. Pre-release and not security-audited; the public API may change before0.1.0. It is published as a pre-release, so Cargo selects it only when you opt in (cow-sdk-orderbook = "0.1.0-alpha.10"). Review it yourself before relying on it with real funds.
This crate owns the canonical request builders, typed wire DTOs, response
transforms, and retry policy for the CoW Protocol orderbook REST API. It is used
internally by the cow-sdk-trading
orchestration surface and is exposed directly when you only need the typed
transport layer without the higher-level trading flow. Because it transports
already-signed orders, it depends on no signing crate: you get the typed quote,
post, and query surface without compiling the ECDSA signing stack. Transport
configuration is policy-visible: HTTP timeout, retry rules, and user-agent
defaults are explicit.
§What it provides
- Quoting with fail-closed echo verification —
quote()validates the request, POSTs/api/v1/quote, and rejects any response that altered a request-determined field before it can be signed. - Order submission and cancellation —
send_order()andsend_cancellations()over typedOrderCreation/OrderCancellations. - Order and trade reads with EthFlow normalization —
order(),order_multi_env()(404-fallback across environments),orders(),tx_orders(), andtrades(). - Status, pricing, and surplus —
order_competition_status(),native_price(),total_surplus(), andversion(). - Content-addressed app-data —
app_data()andupload_app_data(), the latter with two-stage keccak256 hash verification (client precheck + server echo). - Solver competition —
solver_competition()andsolver_competition_by_tx_hash(). - A typed rejection taxonomy and retry verdict —
OrderbookRejectionmaps every servererrorTypeto a typed variant (with a forward-compatibleUnknownfallback) and anOrderbookRejectionCategoryaction partition;OrderbookError::is_retryable()mirrors the SDK’s own transport retry decision andbackoff_hint()surfaces the server’sRetry-After. - Hardened transport — an instance-scoped rate limiter shared across clones, SSRF host validation on base-URL overrides, a response-size cap, and credential and PII redaction so error output never leaks upstream bytes (ADR 0025).
§Install
[dependencies]
cow-sdk-orderbook = "0.1.0-alpha.10"§Minimal example
Build the client with the typestate builder, then request a sell-side quote.
build() is zero-config on every target: native uses the default reqwest
transport, wasm32 uses the browser fetch transport. Inject your own with
.transport(...) on either.
use cow_sdk_orderbook::{
Address, Amount, CowEnv, OrderQuoteRequest, OrderQuoteSide, OrderbookApi,
SupportedChainId,
};
let orderbook = OrderbookApi::builder()
.chain(SupportedChainId::Mainnet)
.env(CowEnv::Prod)
.build()?;
// Sell-side quote for 1 WETH -> USDC.
let weth = Address::new("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")?;
let usdc = Address::new("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")?;
let from = Address::new("0x76b0340e50BD9883D8B2CA5fd9f52439a9e7Cf58")?;
let request = OrderQuoteRequest::new(
weth,
usdc,
from,
OrderQuoteSide::sell(Amount::from_units(1, 18)?),
);
let quote = orderbook.quote(&request).await?;
println!("quoted buy amount: {}", quote.quote.buy_amount);§Feature flags
| Feature | Default | Enables |
|---|---|---|
tracing | off | Wraps every client method in a tracing span carrying chain, environment, endpoint, and method fields, and enables cow-sdk-core’s tracing. |
§Where this fits
This crate is the typed REST transport layer. It does not sign or hold keys (it
transports already-signed payloads — signing lives in
cow-sdk-signing and the alloy signer
adapters), it does not write canonical app-data JSON (that is
cow-sdk-app-data; upload_app_data
hashes the bytes you give it), and it does not orchestrate swaps or send on-chain
transactions (that is cow-sdk-trading).
Most consumers reach it through the cow-sdk
facade as cow_sdk::orderbook.
§Where to next
§License
Licensed under GPL-3.0-or-later. See the workspace
LICENSE
file for the full text.
Typed CoW Protocol orderbook transport models, request policy, and response
transforms.
Construct an OrderbookApi with its typestate builder — chain then
environment then build — and call typed methods such as quote,
send_order, and order. Failures surface as OrderbookError;
rejected submissions carry a categorized OrderbookRejection. On native
targets build uses the default reqwest transport; on wasm32 inject a
browser transport with transport(...) before build. A runnable request
example is in the crate README.
§Parity-scope invariant: quote fee/gas fields are not public builder setters
The cow-protocol services backend rejects orders that carry a non-zero
order-level fee, so the submission path always wires "feeAmount": "0"
and no public builder on this crate exposes a fee_amount(...) setter.
The orderbook’s quote-cost estimates (feeAmount, gasAmount, gasPrice,
sellTokenPrice) are likewise read-only on QuoteData (ADR 0021): they
are populated only from the /quote response and surfaced through
accessors, never through public setters. Because these types expose no
fee_amount(...), gas_amount(...), gas_price(...), or
sell_token_price(...) setter, attempting to set them does not compile.
The runtime witness in tests/fee_amount_is_not_a_public_builder_setter.rs
proves the submission path always wires "feeAmount": "0".
Re-exports§
pub use api::OrderbookApi;pub use builder::ChainIdSet;pub use builder::ChainIdUnset;pub use builder::EnvSet;pub use builder::EnvUnset;pub use builder::OrderbookApiBuilder;pub use builder::TransportSet;pub use builder::TransportUnset;pub use error::HashMismatchStage;pub use error::OrderbookError;pub use error::QuoteEchoField;pub use rejection::OrderbookRejection;pub use rejection::OrderbookRejectionCategory;pub use rejection::parse_rejection;pub use request::HttpMethod;pub use request::OrderbookApiError;pub use request::ResponseBody;pub use transform::transform_order;pub use transform::transform_orders;pub use types::ApiContextOverride;pub use types::AppDataObject;pub use types::AuctionPrices;pub use types::CompetitionAuction;pub use types::CompetitionOrderStatus;pub use types::CompetitionOrderStatusKind;pub use types::EcdsaSigningScheme;pub use types::EnvBaseUrlOverrides;pub use types::EthflowData;pub use types::ExecutedAmounts;pub use types::ExecutedProtocolFee;pub use types::FeePolicy;pub use types::InteractionData;pub use types::NativePriceResponse;pub use types::OnchainOrderData;pub use types::Order;pub use types::OrderCancellations;pub use types::OrderClass;pub use types::OrderCreation;pub use types::OrderInteractions;pub use types::OrderQuoteRequest;pub use types::OrderQuoteResponse;pub use types::OrderQuoteSide;pub use types::OrderStatus;pub use types::OrdersQuery;pub use types::PriceQuality;pub use types::QuoteAppData;pub use types::QuoteData;pub use types::QuoteSigningScheme;pub use types::QuoteValidity;pub use types::SellAmount;pub use types::SigningScheme;pub use types::SigningSchemeNotEcdsa;pub use types::SolverCompetitionOrder;pub use types::SolverCompetitionResponse;pub use types::SolverExecution;pub use types::SolverSettlement;pub use types::StoredOrderQuote;pub use types::TotalSurplus;pub use types::Trade;pub use types::TradesQuery;pub use types::default_verification_gas_limit;
Modules§
- api
- High-level orderbook client with chain/env-aware endpoint resolution.
- builder
- Typestate-checked construction surface for
OrderbookApi. Typestate builder forOrderbookApi. - error
- Typed orderbook client errors.
- rejection
- Typed rejection taxonomy and wire-envelope parser for orderbook non-2xx responses. Typed classification of CoW Protocol orderbook rejection responses.
- request
- Request execution policy, retry rules, and low-level transport helpers.
- transform
- Orderbook response normalization helpers.
- types
- Public wire DTOs and builder-style request models for the orderbook API. Public wire DTOs and builder-style request models for the orderbook API.
Structs§
- Address
- Validated EVM address.
- Amount
- Canonical non-negative
uint256quantity. - ApiContext
- API routing context used by transport-owning crates.
- AppData
Hash - Validated 32-byte app-data hash.
- Order
Uid - Validated
CoWorder UID. - Orderbook
Binding - Runtime binding captured from an orderbook client for quote-derived workflows.
- Quote
Amounts AndCosts - Stepwise quote amounts and cost components across the quote lifecycle.
Enums§
- BuyToken
Destination - Destination to which the
buyAmountis transferred upon order fulfillment. - CowEnv
- Supported
CoWdeployment environments. - External
Host Policy - Host validation policy for SDK-owned external service endpoints.
- Host
Policy Error - Sanitized host-policy failure for SDK-owned service endpoint construction.
- Order
Kind - Sell or buy side of a trade.
- Sell
Token Source - Source from which the
sellAmountis drawn upon order fulfillment. - Supported
Chain Id - Supported
CoWProtocol chain ids with explicit API configuration.
Constants§
- NATIVE_
CURRENCY_ ADDRESS - The EIP-7528 native-asset sentinel (
0xeeee…eeee): the addressCoWProtocol uses to represent the chain’s native currency, e.g. as the sell token for native-currency (EthFlow) sells.
Traits§
- Orderbook
Client - Minimal orderbook capability required by trading and composable consumers.
Type Aliases§
- ApiBase
Urls - Redacting mapping from numeric chain id to API base URL.
- Transaction
Hash - Transaction hash alias.