Skip to main content
This guide walks through creating and executing a token swap on CoW Protocol using the Python SDK, learning how to swap tokens with built-in MEV protection and gasless trading.
CoW Protocol employs batch auctions to protect traders from MEV and provides the best execution prices by aggregating liquidity across multiple DEXs.

Prerequisites

Before starting, ensure you have:
  • The CoW Protocol Python SDK installed
  • A wallet with test tokens (Sepolia testnet)
  • Your wallet’s private key
  • Approval for the CoW Protocol Vault Relayer to spend your tokens
You must approve the CoW Protocol Vault Relayer contract before executing a swap.

Environment Setup

Create a .env file in your project root:
Add .env to .gitignore to prevent accidentally committing your private key.
Install the required package:

Complete Swap Example

Understanding the Code

Import Dependencies

The SDK uses web3.py for Ethereum interactions and provides a simple swap_tokens function.

Configure Token Addresses

Always use checksummed addresses to avoid errors via Web3.to_checksum_address().

Specify Sell Amount

Amounts are specified in the token’s smallest unit. Use Web3.to_wei() for easier conversion: Web3.to_wei(50, 'ether') equals 50 tokens with 18 decimals.

Select Network

Supported networks include: MAINNET, GNOSIS, SEPOLIA, ARBITRUM_ONE, BASE, POLYGON, AVALANCHE, and BNB.

Execute the Swap

The function handles quote retrieval, order creation and signing, orderbook submission, and returns the order UID and explorer URL.

Advanced Options

Slippage Tolerance protects against price changes between order creation and execution. A 1% slippage means accepting up to 1% less than the quoted amount.

Working with Safe Wallets

To create orders from a Safe wallet:
When using a Safe wallet, the order uses pre-signature validation. The account parameter should be one of the Safe owners signing the transaction.

Fetching Order Information

After creating an order, fetch its details using the OrderBook API:

Common Issues

Ensure your wallet has enough of the sell token. Account for token decimals when checking balances.
Before swapping, approve the CoW Protocol Vault Relayer:
Orders may take time to execute using batch auctions. Check the order status via the explorer URL returned by swap_tokens(). Orders expire if they don’t find a match within their validity period.

Next Steps

Last modified on March 17, 2026