Skip to main content
The settlement module provides utilities for encoding settlements, managing trades, and building settlement transactions.

Classes

SettlementEncoder

A class for building settlement calldata.
class SettlementEncoder {
  constructor(domain: TypedDataDomain);
  
  readonly domain: TypedDataDomain;
  get tokens(): string[];
  get trades(): Trade[];
  get interactions(): [Interaction[], Interaction[], Interaction[]];
  
  encodeTrade(order: Order, signature: Signature, execution?: Partial<TradeExecution>): void;
  signEncodeTrade(order: Order, owner: Signer, scheme: EcdsaSigningScheme, execution?: Partial<TradeExecution>): Promise<void>;
  encodeInteraction(interaction: InteractionLike, stage?: InteractionStage): void;
  clearingPrices(prices: Prices): BigNumberish[];
  encodedSettlement(prices: Prices): EncodedSettlement;
  static encodedSetup(...interactions: InteractionLike[]): EncodedSettlement;
}

Constructor

new SettlementEncoder(domain: TypedDataDomain)
domain
TypedDataDomain
required
The EIP-712 domain used for signing orders. Contains the chain ID and settlement contract address.

Properties

domain
TypedDataDomain
The domain used for signing orders.
tokens
string[]
Array of token addresses used in the settlement.
trades
Trade[]
Array of encoded trades in the settlement.
interactions
[Interaction[], Interaction[], Interaction[]]
Three arrays of interactions for pre-settlement, intra-settlement, and post-settlement stages.

Methods

encodeTrade
Encodes a trade from a signed order.
encodeTrade(
  order: Order,
  signature: Signature,
  execution?: Partial<TradeExecution>
): void
order
Order
required
The order to encode.
signature
Signature
required
The signature for the order.
execution
Partial<TradeExecution>
Execution details. Required for partially fillable orders.
For partially fillable orders, you must specify executedAmount. For fill-or-kill orders, this is optional and defaults to 0.
signEncodeTrade
Signs an order and encodes it as a trade in one step.
async signEncodeTrade(
  order: Order,
  owner: Signer,
  scheme: EcdsaSigningScheme,
  execution?: Partial<TradeExecution>
): Promise<void>
order
Order
required
The order to sign and encode.
owner
Signer
required
The Ethers.js signer that will sign the order.
scheme
EcdsaSigningScheme
required
The signing scheme: SigningScheme.EIP712 or SigningScheme.ETHSIGN.
execution
Partial<TradeExecution>
Execution details for the trade.
encodeInteraction
Encodes an interaction to be executed during settlement.
encodeInteraction(
  interaction: InteractionLike,
  stage?: InteractionStage
): void
interaction
InteractionLike
required
The interaction to encode.
stage
InteractionStage
The execution stage: PRE, INTRA (default), or POST.
clearingPrices
Returns a clearing price vector for the current settlement tokens.
clearingPrices(prices: Prices): BigNumberish[]
prices
Prices
required
Object mapping token addresses to their clearing prices.
prices
BigNumberish[]
Array of prices corresponding to the token array.
encodedSettlement
Returns the complete encoded settlement parameters.
encodedSettlement(prices: Prices): EncodedSettlement
prices
Prices
required
Object mapping token addresses to their clearing prices.
settlement
EncodedSettlement
A tuple containing [tokens, prices, trades, interactions].
encodedSetup (static)
Creates an encoded settlement that only performs setup interactions.
static encodedSetup(...interactions: InteractionLike[]): EncodedSettlement
interactions
InteractionLike[]
required
Setup interactions to encode.
settlement
EncodedSettlement
An encoded settlement with only the provided interactions.
Use this method to set up the settlement contract’s allowances or perform other preparatory operations.

TokenRegistry

A class for tracking tokens when encoding settlements.
class TokenRegistry {
  get addresses(): string[];
  index(token: string): number;
}
Tokens in settlements are referenced by index rather than address to reduce calldata size and gas costs.

Methods

index
Retrieves the token index for a token address, adding it if necessary.
index(token: string): number
token
string
required
The token address to get the index for.
index
number
The zero-based index of the token in the registry.

Types

Trade

Encoded trade parameters for settlement.
interface Trade {
  sellTokenIndex: BigNumberish;
  buyTokenIndex: BigNumberish;
  receiver: string;
  sellAmount: BigNumberish;
  buyAmount: BigNumberish;
  validTo: number;
  appData: string;
  feeAmount: BigNumberish;
  flags: BigNumberish;
  executedAmount: BigNumberish;
  signature: BytesLike;
}

TradeExecution

Details about how an order was executed.
interface TradeExecution {
  executedAmount: BigNumberish;
}
executedAmount
BigNumberish
required
For partially fillable sell orders: amount of sell tokens to trade. For partially fillable buy orders: amount of buy tokens to trade. Ignored for fill-or-kill orders.

TradeFlags

Combination of order flags and signing scheme.
interface TradeFlags extends OrderFlags {
  signingScheme: SigningScheme;
}

InteractionStage

Enum specifying when an interaction should execute.
enum InteractionStage {
  PRE = 0,
  INTRA = 1,
  POST = 2
}
PRE
0
Before any trading occurs. Used for operations like EIP-2612 permits.
INTRA
1
After sell amounts are transferred in, before buy amounts are transferred out. Used for AMM interactions.
POST
2
After all trading has completed.

EncodedSettlement

Complete encoded settlement parameters.
type EncodedSettlement = [
  tokens: string[],
  clearingPrices: BigNumberish[],
  trades: Trade[],
  interactions: [Interaction[], Interaction[], Interaction[]]
];

Prices

Mapping of token addresses to clearing prices.
type Prices = Record<string, BigNumberish | undefined>;

Functions

encodeTrade

Encodes a trade to be used with the settlement contract.
function encodeTrade(
  tokens: TokenRegistry,
  order: Order,
  signature: Signature,
  execution: TradeExecution
): Trade

encodeTradeFlags

Encodes trade flags as a bitfield.
function encodeTradeFlags(flags: TradeFlags): number

decodeTradeFlags

Decodes trade flags from a bitfield.
function decodeTradeFlags(flags: BigNumberish): TradeFlags

encodeOrderFlags

Encodes order flags as a bitfield.
function encodeOrderFlags(flags: OrderFlags): number

decodeOrderFlags

Decodes order flags from a bitfield.
function decodeOrderFlags(flags: BigNumberish): OrderFlags

encodeSigningScheme

Encodes a signing scheme as a bitfield.
function encodeSigningScheme(scheme: SigningScheme): number

decodeSigningScheme

Decodes a signing scheme from a bitfield.
function decodeSigningScheme(flags: BigNumberish): SigningScheme

encodeSignatureData

Encodes signature data for settlement.
function encodeSignatureData(sig: Signature): string

decodeSignatureOwner

Decodes the owner address from a signature.
function decodeSignatureOwner(
  domain: TypedDataDomain,
  order: Order,
  scheme: SigningScheme,
  sig: BytesLike
): string

decodeOrder

Decodes an order from a settlement trade.
function decodeOrder(trade: Trade, tokens: string[]): Order

Example Usage

import {
  SettlementEncoder,
  domain,
  Order,
  OrderKind,
  SigningScheme,
} from "@cowprotocol/contracts";
import { Wallet } from "ethers";

// Create settlement encoder
const settlementDomain = domain(1, "0x9008D19f58AAbD9eD0D60971565AA8510560ab41");
const encoder = new SettlementEncoder(settlementDomain);

// Define orders
const order1: Order = {
  sellToken: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2", // WETH
  buyToken: "0x6B175474E89094C44Da98b954EedeAC495271d0F", // DAI
  sellAmount: "1000000000000000000",
  buyAmount: "3000000000000000000000",
  validTo: Math.floor(Date.now() / 1000) + 3600,
  appData: 1,
  feeAmount: "5000000000000000",
  kind: OrderKind.SELL,
  partiallyFillable: false,
};

// Sign and encode the trade
const wallet = new Wallet(privateKey);
await encoder.signEncodeTrade(order1, wallet, SigningScheme.EIP712);

// Add more trades...

// Define clearing prices
const prices = {
  "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2": "3000000000000000000000", // 3000 DAI per WETH
  "0x6B175474E89094C44Da98b954EedeAC495271d0F": "1000000000000000000", // 1 DAI (base unit)
};

// Get encoded settlement
const settlement = encoder.encodedSettlement(prices);
const [tokens, clearingPrices, trades, interactions] = settlement;

console.log("Tokens:", tokens);
console.log("Prices:", clearingPrices);
console.log("Trades:", trades.length);
Order refunds are deprecated post-London hardfork (EIP-3529) as the refunded amount is less than the gas cost. The functionality is kept for test coverage but should not be used in production.

Build docs developers (and LLMs) love