Skip to main content

Overview

The CoW Protocol Python SDK provides a high-level swap_tokens function that enables you to execute token swaps with built-in MEV protection through batch auctions. This guide covers the complete swap workflow including token approval and order execution.

Prerequisites

Before swapping tokens, ensure you have:
  • An Ethereum account with a private key
  • Sufficient balance of the token you want to sell
  • Token approval for the CoW Protocol Vault Relayer

Token Approval Flow

Before calling swap_tokens, you must approve the CowContractAddress.VAULT_RELAYER to spend your sell token. The swap will fail without proper approval.
1

Import Required Modules

2

Approve Token Spending

Grant the Vault Relayer permission to spend your tokens:
3

Execute the Swap

Once approval is complete, you can execute the swap.

Basic Token Swap

Here’s a complete example of swapping tokens:

Advanced Configuration

The swap_tokens function accepts several optional parameters for advanced use cases:

Function Parameters

Return Value

The function returns a CompletedOrder object with:

How It Works

1

Quote Request

The function requests a quote from the OrderBook API with your sell amount and tokens.
2

Order Construction

Creates an Order object with sell/buy amounts (with slippage protection), validity period, token balances configuration, and app data metadata.
3

Order Signing

Signs the order using EIP-712 typed data. For regular accounts: ECDSA signature. For Safe addresses: PreSign signature.
4

Order Submission

Posts the signed order to the OrderBook API for solvers to execute.

After the Swap

When swap_tokens returns a CompletedOrder, the order has been submitted to the CoW Protocol orderbook. Solvers now compete in batch auctions to find the best execution path for your trade.

Monitoring Order Status

You can poll the order status using the OrderBookApi:

Order Status Values

Cancelling an Order

If your order has not yet been filled, you can request cancellation:
For a complete guide on querying, tracking, and cancelling orders, see Managing Orders.

Supported Chains

The SDK supports swapping on the following networks:
  • Ethereum MainnetChain.MAINNET
  • Gnosis ChainChain.GNOSIS
  • Arbitrum OneChain.ARBITRUM_ONE
  • BaseChain.BASE
  • Sepolia TestnetChain.SEPOLIA
Use Chain.SEPOLIA for testing without spending real funds. Get testnet tokens from Sepolia faucets.

Error Handling

Common Issues

Next Steps

Last modified on March 17, 2026