Overview
The CoW Protocol Python SDK provides a high-levelswap_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
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
Theswap_tokens function accepts several optional parameters for advanced use cases:
Function Parameters
Return Value
The function returns aCompletedOrder 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
Whenswap_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 theOrderBookApi:
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 Mainnet —
Chain.MAINNET - Gnosis Chain —
Chain.GNOSIS - Arbitrum One —
Chain.ARBITRUM_ONE - Base —
Chain.BASE - Sepolia Testnet —
Chain.SEPOLIA
Error Handling
Common Issues
Next Steps
- Learn about Managing Orders to track and cancel swaps
- Explore App Data to add custom metadata
- Check Contract Interaction for advanced signing scenarios