> 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/flycn/developers/api-reference/on-chain-swap.md).

# On chain swap

## Architecture diagram

<figure><img src="/files/3qSL1MzeeX5CPrjCl91I" alt="" width="375"><figcaption><p>Architecture diagram - on-chain swap</p></figcaption></figure>

## Overview of On-Chain Swap Flow

There are two methods to execute a swap: gasless and self-execution.

### **Self-Execution**

The user executes the transaction and covers gas costs themselves.

### **Gasless Transaction**

Magpie executes the transaction on behalf of the user, covering the gas fees, so the user doesn’t need to hold or pay gas in the native currency.

## Step-by-Step Swap Process

### Step 1: Get a Quote

In this step, you will retrieve a quote that contains details of the swap, including the estimated output amount, swap route, and other necessary transaction parameters.

* **Endpoint**: `/aggregator/quote`
* **Method**: `GET`

**Required Parameters**

* **fromTokenAddress**: Address of the token you want to swap from.
  * If you want to use a native token, please use this address `0x0000000000000000000000000000000000000000`
* **toTokenAddress**: Address of the token you want to swap to.
  * If you want to use a native token, please use this address `0x0000000000000000000000000000000000000000`
* **amount**: The amount of the `fromToken` in the smallest unit (e.g., wei for ETH).
* **slippage**: Allowed slippage percentage (e.g., `0.005` for 0.5%).
* **fromAddress**: Wallet address initiating the swap.
* **toAddress**: Wallet address receiving the swapped tokens.
* **gasless**: Set `true` to let Magpie handle gas costs (gasless mode), or `false` if you will cover the gas cost.
* **enableRFQ**: Optional parameter to enable RFQ protocols. Default is `false`&#x20;

> Affiliate Fee: API consumer can implement their own affiliate fees and define their affiliate address, the fees will be deducted from their user from the from asset (asset sold by their user) and distributed to the affiliate address in the same transaction. They can set an affiliate fee by including **affiliateAddress** and **affiliateFeeInPercentage** in the quote request. **affiliateFeeInPercentage** is the percentage fee, such as 0.01 for 1%.

#### **Example Request**:

```
GET /aggregator/quote?fromTokenAddress=0x...&toTokenAddress=0x...&amount=1000000000000000000&slippage=0.005&fromAddress=0x...&toAddress=0x...&gasless=true&affiliateAddress=0xPartnerAddress&affiliateFeeInPercentage=0.01
```

#### **Response**:

This will return a `quote-id` and details like `toTokenAmount` (estimated output) and fees.

***

### Step 2: Approve tokens

If you are swapping a token that is not the native token, you must first grant approval for the transaction. This requires calling the `approve` function on the token contract associated with the `fromTokenAddress` that you intend to swap.

When retrieving a quote via the endpoint, the response includes `targetAddress`. This address must be used as the spender when granting approval.

***

### Step 3: Execute the Transaction

Based on the `gasless` option chosen in Step 1, there are two paths for transaction execution:

1. **Self-Execution** (`gasless = false`): The user retrieves transaction data and broadcasts the transaction themselves.
2. **Gasless Transaction** (`gasless = true`): Magpie executes the transaction on behalf of the user, covering the gas fees.

***

### Self-Execution Path

If `gasless` is set to `false`, you will need to execute the transaction on-chain by following these steps:

* **Endpoint**: `/aggregator/transaction`
* **Method**: `GET`

#### **Parameters**:

* **quoteId**: Use the `quote-id` from Step 1 to retrieve the transaction data.

***

### Gasless Transaction Path

If `gasless` is set to `true`, Magpie will execute the transaction on behalf of the user.

* **Endpoint**: `/user-manager/execute-swap`
* **Method**: `POST`

#### **Parameters**:

* **networkName:** The target network, where the transaction takes place.
* **quoteId**: The `quote-id` from Step 1 is required to execute the swap.
* **swapSignature**: Signed quote using EIP-712
* **permitSignature**: Signed approval using EIP-2612
* **permitDeadline**: The time at which the signature expires (unix time)

#### Generating swapSignature

To generate a `swapSignature` using Ethers v5, follow these steps:

1. Obtain Parameters: Retrieve the `message` parameter from the response of quote API.
2. Generate the Signature: `const signature = await signer._signTypedData(domain, types, message);`&#x20;

Magpie handles the swap and covers the gas fees. No additional action or gas payment is required from the user.

***

#### Checking Swap Status

After initiating a swap, you can track its status using the following endpoints:

* **Get Swap Details**
  * **Endpoint**: `/user-manager/swap`
  * **Method**: `GET`
  * Use this endpoint to retrieve the details of a completed swap.
* **Get Swap Status**
  * **Endpoint**: `/user-manager/status-counts`
  * **Method**: `GET`
  * This endpoint provides the count of swaps in `pending`, `error`, or other states based on the wallet address.

***

**Additional Endpoint: Get Distributions**

You can check the route and distribution of the swap using the quote-id from Step 1.Endpoint: /aggregator/distributionsMethod: GETAvailable Networks: Magpie supports swaps on networks like Ethereum, Polygon, Avalanche, and others (BSC, Arbitrum, zkSync, etc.).

**Example Request:**

```
GET /aggregator/distributions?quote-id=YOUR_QUOTE_ID
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.fly.trade/flycn/developers/api-reference/on-chain-swap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
