> For the complete documentation index, see [llms.txt](https://docs.fly.trade/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.fly.trade/developers/for-agents.md).

# For Agents

## Fly Trade EVM Swap API — Agent Reference

### Overview

Base URL: `https://api.fly.trade`

Execute a token swap on EVM networks in 3 steps:

1. GET `/aggregator/quote` → receive `quoteId` + pricing
2. GET `/aggregator/transaction` → receive transaction payload
3. Sign and submit transaction to the network

**Shortcut:** Use GET `/aggregator/quote/transaction` to get both quote and transaction in one call (no gas estimation).

### Decision Tree for Agent Use

```
Want to swap tokens?
│
├─ Standard swap (user pays gas in native token)
│   ├─ Need gas estimate?  → Step 1 (quote) + Step 2 (transaction, estimateGas=true) + Step 3
│   └─ No gas estimate needed? → Combined /quote/transaction + Step 3
│
└─ Calling from a smart contract?
    └─ GET /quote/transaction (estimateGas=false, fromAddress=CONTRACT) → forward data as calldata
```

***

### Supported Networks

Use the `network` string (not chain ID) in all requests.

| `network` value | Chain             |
| --------------- | ----------------- |
| `ethereum`      | Ethereum Mainnet  |
| `polygon`       | Polygon           |
| `bsc`           | BNB Smart Chain   |
| `arbitrum`      | Arbitrum One      |
| `optimism`      | Optimism          |
| `base`          | Base              |
| `avalanche`     | Avalanche C-Chain |
| `blast`         | Blast             |
| `manta`         | Manta Pacific     |
| `scroll`        | Scroll            |
| `fantom`        | Fantom            |
| `polygonzk`     | Polygon zkEVM     |
| `zksync`        | zkSync Era        |
| `linea`         | Linea             |
| `sonic`         | Sonic             |
| `megaeth`       | MegaETH           |
| `fogo`          | Fogo              |
| `stable`        | Stable            |
| `plasma`        | Plasma            |
| `monad`         | Monad             |
| `hyperevm`      | HyperEVM          |
| `eclipse`       | Eclipse           |
| `unichain`      | Unichain          |
| `berachain`     | Berachain         |
| `abstract`      | Abstract          |
| `ink`           | Ink               |
| `taiko`         | Taiko             |
| `metis`         | Metis             |
| `solana`        | Solana            |
| `morph`         | Morph             |
| `zerogravity`   | 0g                |
| `katana`        | Katana            |
| `tempo`         | Tempo             |
| `telos`         | Telos             |
| `pharos`        | Pharos            |

Full list: GET `/token-manager/networks` or check Swagger at `https://api.fly.trade/swagger`.

***

### These 5 endpoints cover most agent use cases:

#### Step 1 — Get Quote

**GET** `/aggregator/quote`&#x20;

Fetches a quote estimating the output amount you'll receive for swapping a given input asset. Use this to preview the exchange rate, fees, and expected output before committing to a transaction.

#### Required Parameters

| Parameter          | Type    | Description                                                                                                                                                   |
| ------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `network`          | string  | Network name (e.g. `ethereum`)                                                                                                                                |
| `fromTokenAddress` | string  | The token address of the token to sell. Use `0x0000000000000000000000000000000000000000` for native token (ETH/MATIC/BNB)                                     |
| `toTokenAddress`   | string  | Token to buy. Use `0x0000000000000000000000000000000000000000` for native token (ETH/MATIC/BNB)                                                               |
| `sellAmount`       | string  | The amount of the token to sell.                                                                                                                              |
| `slippage`         | number  | Max slippage. `0.005` = 0.5%, `0.01` = 1%                                                                                                                     |
| `fromAddress`      | string  | Wallet address sending the swap                                                                                                                               |
| `toAddress`        | string  | Wallet address receiving tokens                                                                                                                               |
| `gasless`          | boolean | Always set `gasless: false`. This ensures the user pays gas in the native token. Gasless transactions are deprecated and will be removed in a future release. |

#### Optional Parameters

| Parameter          | Type   | Description                                            |
| ------------------ | ------ | ------------------------------------------------------ |
| `affiliateAddress` | string | Address to receive affiliate fee                       |
| `affiliateFee`     | number | Fee percentage. `0.01` = 1%. Deducted from `fromToken` |

#### Example Request

````bash
GET https://api.fly.trade/aggregator/quote?network=ethereum&fromTokenAddress=0x0000000000000000000000000000000000000000&toTokenAddress=0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48&fromAddress=0xff270dc360ef80314c7d6b2564fe76eaf3979b1a&toAddress=0xff270dc360ef80314c7d6b2564fe76eaf3979b1a&sellAmount=1000000000000000000&slippage=0.005&gasless=false```
````

#### Response Schema (Standard Swap)

```json
{
  "id": "8de05661-09d6-4b82-ab63-1e32ee1fa297",   // ← save as quoteId
  "amountOut": "1956398549",                        // expected output in smallest unit
  "targetAddress": "0xa6e941eab67569ca4522f70d343714ff51d571c4",  // router address (use for ERC-20 approval)
  "fees": [
    { "type": "gas", "value": "0.0150" }
  ],
  "resourceEstimate": {
    "gasLimit": "191157"
  }
}
```

#### Critical Constraints

* **Quote expires in 5 minutes.** After expiry, the `quoteId` is invalid. Fetch a new quote.
* **Single-use.** Each `quoteId` can only be used once with `/aggregator/transaction`. If consumed or expired, fetch a new quote.
* **ERC-20 approval required** before executing. The spender is `targetAddress` from the quote response.

***

### Step 2 — Get Transaction Payload

**GET** `/aggregator/transaction`

#### Required Parameters

| Parameter | Type   | Description                         |
| --------- | ------ | ----------------------------------- |
| `quoteId` | string | The `id` value returned from Step 1 |

#### Optional Parameters

| Parameter     | Type    | Default | Description                                                                                                                                                        |
| ------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `estimateGas` | boolean | `true`  | When `true`, validates token approval and balance before returning. Fails with `"Couldn't estimate gas"` if checks fail. Set to `false` for contract integrations. |

#### Example Request

```bash
GET https://api.fly.trade/aggregator/transaction?quoteId=8de05661-09d6-4b82-ab63-1e32ee1fa297
```

#### Response Schema

```json
{
  "from": "0xff270dc360ef80314c7d6b2564fe76eaf3979b1a",
  "to": "0xa6e941eab67569ca4522f70d343714ff51d571c4",   // router contract
  "data": "0x73fc4457...",                               // encoded calldata
  "chainId": 1,
  "type": 2,                                             // EIP-1559 (type 2) or legacy (type 0)
  "gasLimit": "314086",
  "maxFeePerGas": "228922087",                           // present for EIP-1559 chains
  "maxPriorityFeePerGas": "190605439",                   // present for EIP-1559 chains
  "value": "10000000000000000"                           // ETH value in wei (0 for ERC-20 swaps)
}
```

> **Note:** Some chains return legacy format with `gasPrice` instead of `maxFeePerGas`/`maxPriorityFeePerGas`. Ensure your signer/library handles both.

***

### Alternative: Combined Quote + Transaction (Single Request)

**GET** `/aggregator/quote/transaction`

Accepts all parameters from `/aggregator/quote`. `fromAddress` and `toAddress` are **required**. Gas is not estimated.

#### Example Request

````bash
GET https://api.fly.trade/aggregator/quote/transaction?network=base&fromTokenAddress=1&toTokenAddress=2&sellAmount=3&slippage=1&gasless=false&toAddress=111&fromAddress=111```
````

#### Response Schema

```json
{
  "quote": {
    "id": "...",
    "amountOut": "...",
    "targetAddress": "...",
    "fees": [...],
    "resourceEstimate": { "gasLimit": "..." }
  },
  "transaction": {
    "from": "...",
    "to": "...",
    "data": "...",
    "chainId": 1,
    "type": 2,
    "gasLimit": "...",
    "maxFeePerGas": "...",
    "maxPriorityFeePerGas": "...",
    "value": "..."
  }
}
```

***

### Step 3 — Execute the Transaction

Submit the transaction object from Step 2 directly to the network using any EVM-compatible library.

**TypeScript (ethers.js):**

```typescript
const tx = await signer.sendTransaction({
  to: transaction.to,
  data: transaction.data,
  value: transaction.value,
  gasLimit: transaction.gasLimit,
  // For EIP-1559:
  maxFeePerGas: transaction.maxFeePerGas,
  maxPriorityFeePerGas: transaction.maxPriorityFeePerGas,
  // For legacy chains, use gasPrice instead
});
const receipt = await tx.wait();
```

***

### ERC-20 Token Approval

Before swapping an ERC-20 token, the `fromAddress` must approve the router contract (`targetAddress` from the quote) to spend the token.

```typescript
const token = new ethers.Contract(fromTokenAddress, [
  'function allowance(address owner, address spender) view returns (uint256)',
  'function approve(address spender, uint256 amount) returns (bool)'
], signer);

const allowance = await token.allowance(userAddress, routerAddress);
if (allowance.lt(sellAmount)) {
  const approveTx = await token.approve(routerAddress, ethers.constants.MaxUint256);
  await approveTx.wait();
}
```

***

### Smart Contract Integration

When calling from a contract, always set `estimateGas=false` or use the combined `/aggregator/quote/transaction` endpoint with `fromAddress` set to your **contract address**.

```typescript
// Get transaction data targeting your contract as sender
const url = new URL('https://api.fly.trade/aggregator/quote/transaction');
url.searchParams.set('fromAddress', CONTRACT_ADDRESS);
url.searchParams.set('estimateGas', 'false');
// ... other params

const { transaction } = await fetch(url.toString()).then(r => r.json());

// Pass transaction.data as calldata to your contract
await mySwapContract.executeSwap(fromToken, amountIn, transaction.data, { value: 0 });
```

**Contract requirements:**

* Approve the Fly router for ERC-20 tokens before calling
* Forward `transaction.data` as calldata to the router (`targetAddress`)
* Forward the correct `msg.value` for native token swaps
