# Cross chain swap

## Architecture diagram

<figure><img src="/files/qE2MHONQJDvRAxHB9n4l" alt="" width="375"><figcaption><p>Architecture diagram - cross chain swap</p></figcaption></figure>

## Overview of Cross-Chain Swap Flow

Magpie provides two execution options for cross-chain swaps:

### **Self-Execution**

Users execute the transaction themselves and cover gas costs.

### **Gasless Transaction**

Magpie executes the transaction on behalf of the user and covers the gas fees, so no gas payment is required in the native currency.

Each cross-chain swap involves two main steps:

1. **Quote-In**: Get an estimated swap amount and route on the source chain.
2. **Transaction Execution**: Complete the swap by either self-execution or letting Magpie handle it.

## Step-by-Step Cross-Chain Swap Process

### Step 1: Get a Quote-In

In this step, you retrieve a quote that provides details for the cross-chain swap on the source chain, including the estimated output amount and swap route.

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

#### **Required Parameters**

* **fromTokenAddress**: Address of the token on the source chain that you want to swap from.
  * If you want to use a native token, please use this address `0x0000000000000000000000000000000000000000`
* **toTokenAddress**: Address of the token on the destination chain that you want to receive.
  * If you want to use a native token, please use this address `0x0000000000000000000000000000000000000000`
* **amount**: The amount of `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 on the destination chain.
* **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-in?fromTokenAddress=0x...&toTokenAddress=0x...&amount=1000000000000000000&slippage=0.005&fromAddress=0x...&toAddress=0x...&gasless=true&affiliateAddress=0xPartnerAddress&affiliateFeeInPercentage=0.01
```

#### **Response**:

This request returns a `quote-id` and details such as `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 Cross-Chain Transaction

Based on the `gasless` option chosen in Step 1, there are two ways to execute the transaction:

1. **Self-Execution** (`gasless = false`): Users retrieve transaction data and broadcast it themselves.
2. **Gasless Transaction** (`gasless = true`): Magpie executes the transaction on behalf of the user.

***

### Self-Execution Path

If `gasless` is set to `false`, users execute the cross-chain transaction on-chain themselves.

* **Endpoint**: `/aggregator/transaction-in`
* **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-in`
* **Method**: `POST`&#x20;

#### **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 monitor the swap status through the following endpoints:

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

***

### Additional Endpoints: Get Distribution

To check the route and distribution of the swap on both source and destination chains, use the following endpoints with the `quote-id` from Step 1:

* **Source Chain Distribution**: `/aggregator/distribution-in`
* **Destination Chain Distribution**: `/aggregator/distribution-out`

#### **Example Request for Source Chain Distribution**:

```
GET /aggregator/distribution-in?quote-id=YOUR_QUOTE_ID
```

#### **Example Request for Destination Chain Distribution**:

```
GET /aggregator/distribution-out?quote-id=YOUR_QUOTE_ID
```


---

# Agent Instructions: 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/developers/api-reference/cross-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.
