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.Documentation Index
Fetch the complete documentation index at: https://cowswap-mintlify-seo-audit-1777280932.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
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
Environment Setup
Create a.env file in your project root:
Complete Swap Example
Understanding the Code
Import Dependencies
web3.py for Ethereum interactions and provides a simple swap_tokens function.
Configure Token Addresses
Specify Sell Amount
Web3.to_wei() for easier conversion: Web3.to_wei(50, 'ether') equals 50 tokens with 18 decimals.
Select Network
MAINNET, GNOSIS, SEPOLIA, ARBITRUM_ONE, BASE, POLYGON, AVALANCHE, and BNB.
Execute the Swap
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
Insufficient Token Balance
Insufficient Token Balance
Ensure your wallet has enough of the sell token. Account for token decimals when checking balances.
Missing Token Approval
Missing Token Approval
Before swapping, approve the CoW Protocol Vault Relayer:
Order Not Executing
Order Not Executing
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
- Explore Order Management to learn how to fetch, monitor, and cancel orders
- Investigate Advanced Features for composable orders and TWAP strategies
- Browse the API Reference for complete documentation
- Learn about Contract Interaction with CoW Protocol smart contracts
- Read the Testing Guide for how to test on Sepolia and graduate to production