Skip to main content

Function Signature

Future<PortalSwapResult> swap({
  required String swapsApiKey,
  required String chainId,
  required String buyToken,
  required String sellToken,
  required String amount,
})

Description

Execute a token swap on supported chains. This method handles the entire swap process including finding the best route and executing the transaction.

Parameters

ParameterTypeRequiredDescription
swapsApiKeyStringYesYour swaps API key
chainIdStringYesThe chain ID in CAIP-2 format
buyTokenStringYesToken address to buy
sellTokenStringYesToken address to sell
amountStringYesAmount to sell (in smallest unit)

Returns

PortalSwapResult - An object containing:
PropertyTypeDescription
successboolWhether the swap was successful
transactionHashString?The transaction hash

Example

import 'package:portal_flutter/portal_flutter.dart';

final portal = Portal();

final result = await portal.swap(
  swapsApiKey: 'YOUR_SWAPS_API_KEY',
  chainId: 'eip155:8453', // Base
  sellToken: '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', // ETH
  buyToken: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913', // USDC
  amount: '1000000000000000', // 0.001 ETH in wei
);

if (result.success) {
  print('Swap successful: ${result.transactionHash}');
}

Native Token Address

Use the following address for native tokens (ETH, MATIC, etc.):
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE

Errors

CodeDescription
NOT_INITIALIZEDPortal was not initialized
SWAP_FAILEDThe swap operation failed
INSUFFICIENT_BALANCENot enough tokens to swap
INVALID_API_KEYThe swaps API key is invalid