> For the complete documentation index, see [llms.txt](https://docs.kyberswap.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.kyberswap.com/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/developer-guides/execute-a-swap-with-the-aggregator-api.md).

# Execute A Swap With The Aggregator API

Interacting With KyberSwap Aggregator Router Contract

## Overview

As the KyberSwap Aggregator has been deployed on Solana, KyberSwap maintains 2 different API specifications:

* [Swap API for EVM chains](/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/aggregator-api-specification/evm-swaps.md)
* [Swap API for Solana](/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/aggregator-api-specification/solana-swaps.md)

This guide focuses on calling the Aggregator APIs for [EVM chains](/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/aggregator-api-specification/evm-swaps.md) but the same principles apply to the [Solana](/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/aggregator-api-specification/solana-swaps.md) variant.&#x20;

To execute a swap, the router (`MetaAggregationRouterV2`) contract requires the encoded swap data to be included as part of the transaction. This encoded swap data as well as other swap metadata is returned as part of the API response. As such, developers are expected to call the swap API prior to sending a transaction to the router contract.

{% hint style="info" %}

#### Backwards compatibility

Following feedback on the initial `[V1]` API, KyberSwap has implemented a more performant `[V2]` API which improves the response time for getting a route via offloading encoding requirements to the post method.

**Please refer to** [**Upgrading From APIv1 To APIv2**](/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/developer-guides/upgrading-from-apiv1-to-apiv2.md) **for further details on the motivation behind the upgrade as well as the relevant changes to swap flow and parameters.**

Please use the `[V2]GET` API for more efficient route queries. The returned route can then be reused in the `[V2]POST` body to get the encoded swap data. The `[V1]GET` and `[V2]GET` remains backwards compatible with the main change being the queried path.
{% endhint %}

## Web3.js example

### Swap Params Response[​](https://docs.kyberswap.com/Aggregator/implement-a-swap#swap-params-response) <a href="#swap-params-response" id="swap-params-response"></a>

| Parameter Name  | Type   | Required | Description                            |
| --------------- | ------ | -------- | -------------------------------------- |
| inputAmount     | string |          | hex string represents the input amount |
| routerAddress   | string |          | ERC20 contract address of the router   |
| encodedSwapData | string |          | hex data to be used in transaction     |
| ...             |        |          |                                        |

{% hint style="info" %}
The response parameters have been slightly altered in the `[V2]POST` API. The relevant parameter keys are provided below (`[V1]` -> `[V2]`):

* `inputAmount` -> `amountIn`
* `encodedSwapData` -> `data`
  {% endhint %}

The Encoded Swap API response includes `inputAmount` and `encodedSwapData` above to be used as data to interact with our smart contract. By using the `encodedSwapData`, you don't have to care about the logic behind the encoding process. The next section will explain client usage

### Web3js Client Integration[​](https://docs.kyberswap.com/Aggregator/implement-a-swap#web3js-client-integration) <a href="#web3js-client-integration" id="web3js-client-integration"></a>

Web3.js integration is relatively straightforward but to avoid transaction failure due to gas, we recommend performing a gas estimation call.

#### Initial web3 context[​](https://docs.kyberswap.com/Aggregator/implement-a-swap#initial-web3-context) <a href="#initial-web3-context" id="initial-web3-context"></a>

```javascript
const { account, chainId, library } = useActiveWeb3React()
```

#### Estimate gas[​](https://docs.kyberswap.com/Aggregator/implement-a-swap#estimate-gas) <a href="#estimate-gas" id="estimate-gas"></a>

*Note: The value of the transaction is the `inputAmount` if the input token is a native token, and 0 otherwise*

```javascript
const amountIn = tokenIn == ETHER ? response.InputAmount : 0

const estimateGasOption = {
        from: account,
        to: trade.routerAddress,
        data: trade.encodedSwapData,
        value: BigNumber.from(amountIn),
      }
      
const gasEstimate = await library
        .getSigner()
        .estimateGas(estimateGasOption)
        .then(response => {
          return response
        })
```

#### Execute transaction call[​](https://docs.kyberswap.com/Aggregator/implement-a-swap#execute-transaction-call) <a href="#execute-transaction-call" id="execute-transaction-call"></a>

Using the `gasEstimate` function above to combine with the transaction object

*Note: The value of the transaction is the `inputAmount` if the input token is a native token, and 0 otherwise*

```javascript
const amountIn = tokenIn == ETHER ? response.InputAmount : 0

const sendTransactionOption = {
    from: account,
    to: api.routerAddress,
    data: api.encodedSwapData,
    gasLimit: gasEstimate,
    gasPrice: gasPrice,
    ...(trade.inputAmount.currency instanceof Token
          ? {}
          : { value: BigNumber.from(inputAmount) }),
}

library
    .getSigner()
    .sendTransaction(sendTransactionOption)
```


---

# 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, and the optional `goal` query parameter:

```
GET https://docs.kyberswap.com/~/changes/1kQEhDNzHMDf7SwOE6Yu/kyberswap-solutions/kyberswap-aggregator/developer-guides/execute-a-swap-with-the-aggregator-api.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
