Portal provides a built-in swap functionality that allows users to exchange tokens directly from their wallet.
Token Swaps
The swap method allows you to exchange one token for another on supported chains.
Basic Swap
import 'package:portal_flutter/portal_flutter.dart';
final portal = Portal();
// Perform a swap on Base
final result = await portal.swap(
swapsApiKey: 'YOUR_SWAPS_API_KEY',
chainId: 'eip155:8453', // Base mainnet
sellToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // Native ETH
buyToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC on Base
amount: '1000000000000000', // 0.001 ETH in wei
);
if (result.success) {
print('Swap successful!');
print('Transaction hash: ${result.transactionHash}');
} else {
print('Swap failed');
}
You’ll need a Swaps API key to use this feature. Contact the Portal team to obtain one.
Swap Parameters
| Parameter | Description |
|---|
swapsApiKey | Your API key for the swaps service |
chainId | The chain ID in CAIP-2 format |
sellToken | Token address to sell (use 0xEeee... for native token) |
buyToken | Token address to buy |
amount | Amount to sell in the smallest unit (wei for ETH) |
Example: Swap USDC to ETH
final result = await portal.swap(
swapsApiKey: 'YOUR_SWAPS_API_KEY',
chainId: 'eip155:8453',
sellToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
buyToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // Native ETH
amount: '10000000', // 10 USDC (6 decimals)
);
Supported Chains
Token swaps are available on the following chains:
- Ethereum Mainnet (
eip155:1)
- Base (
eip155:8453)
- Arbitrum (
eip155:42161)
- Optimism (
eip155:10)
- Polygon (
eip155:137)
Always verify token addresses before performing swaps. Incorrect addresses may result in loss of funds.
Error Handling
try {
final result = await portal.swap(
swapsApiKey: 'YOUR_SWAPS_API_KEY',
chainId: 'eip155:8453',
sellToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE',
buyToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
amount: '1000000000000000',
);
if (result.success) {
print('Swap completed: ${result.transactionHash}');
}
} on PortalException catch (e) {
print('Swap failed: ${e.message}');
print('Error code: ${e.code}');
}
Related Documentation