> ## Documentation Index
> Fetch the complete documentation index at: https://docs.portalhq.io/llms.txt
> Use this file to discover all available pages before exploring further.

# swap

> Execute a token swap.

## Function Signature

```dart theme={null}
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

| Parameter | Type | Required | Description |
| - | - | - | - |
| `swapsApiKey` | `String` | Yes | Your swaps API key |
| `chainId` | `String` | Yes | The chain ID in CAIP-2 format |
| `buyToken` | `String` | Yes | Token address to buy |
| `sellToken` | `String` | Yes | Token address to sell |
| `amount` | `String` | Yes | Amount to sell (in smallest unit) |

## Returns

**`PortalSwapResult`** - An object containing:

| Property | Type | Description |
| - | - | - |
| `success` | `bool` | Whether the swap was successful |
| `transactionHash` | `String?` | The transaction hash |

## Example

```dart theme={null}
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

| Code | Description |
| - | - |
| `NOT_INITIALIZED` | Portal was not initialized |
| `SWAP_FAILED` | The swap operation failed |
| `INSUFFICIENT_BALANCE` | Not enough tokens to swap |
| `INVALID_API_KEY` | The swaps API key is invalid |

## Related

* [Perform swaps guide](https://docs.portalhq.io/sdks/flutter/guide/perform-swaps.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.