Execute A Swap With The Aggregator API

Interacting With KyberSwap Aggregator Router Contract

Overview

Disclaimer: the calldatas returned in any API responses are provided as is and as available. By using the calldata provided by our API to execute any swap, you acknowledge that you have independently reviewed and verified all transaction details and that you accept and assume full responsibility for all risks, including potential loss of funds, arising from such transactions

KyberSwap maintains a single API specification for all EVM chains:

Sequence diagram

APIv1 sequence diagram

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 are 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.

Single Request Model

While the [V1] APIs provide more performant queries, we understand that some integrators might prioritize a single request model over the dual request required in [V1]. For example, instead of querying rates and requesting for encoded data separately, both functions can be completed in a single request with slightly longer response times via our non-versioned API.

In such cases, integrators can still use our non-versioned API whose call parameters are similar except for an additional required to field that denotes the recipient of the swapped tokens. Please see Non-versioned API swap flow for more details.

TypeScript Example

Step 1: Query Swap Route

Integrators can easily query for superior rates by passing in the following required parameters into the [V1] Get Swap Route API:

const targetPathConfig = {
    params: {
        tokenIn: tokenIn.address,
        tokenOut: tokenOut.address,
        amountIn: Number(1*10**tokenIn.decimals).toString()
    }
};

V1Get.ts

Note that the full list of available parameters as well as their usage can be found on the specification page.

For each of the token swaps queried, the [V1] GET API will return a data object consisting of:

  • routeSummary -> An object containing the routing data in human readable format. The API will only return the route with the best rate as determined by the KyberSwap Aggregator algorithm.

  • routerAddress -> The address of the router contract which facilitates the swap

Step 2: Encode Preferred Swap Route

Upon finding a favourable route, we can then go ahead and encode the selected route by including the routeSummary in the request body of [V1] Post Swap Route For Encoded Data. Encoding the swap route via the API abstracts away the complexity of interacting with the contract directly.

const requestBody = {
    routeSummary: routeSummary,
    sender: signerAddress,
    recipient: signerAddress,
    slippageTolerance: 10 //0.1%
}

V1Post.ts

Note that the [V1] POST API requires the sender and recipient to be appended to the routeSummary in order to configure the parties to the swap. In most cases, these would usually be the address that is executing the swap.

It is highly recommended that a slippageTolerance (in bips) is set to ensure that the swap proceeds smoothly within the boundaries set. Refer to slippage for more info regarding it's causes and effects on swap rates.

The encoded data for the selected swap route will be returned as a hexstring under the data object.

Step 3: Execute Swap Transaction On-Chain

To execute the swap, we will leverage the ethers.js library. For simplicity, we will hard code a private key under /src/libs/signer.ts that will allow us to programatically interact with the EVM from the backend.

With a configured signer, we can then execute the transaction on-chain by paying the necessary gas fees:

const executeSwapTx = await signer.sendTransaction({
    data: encodedSwapData,
    from: signerAddress,
    to: routerContract,
    maxFeePerGas: 1000000000000,
    maxPriorityFeePerGas: 1000000000000        
});

V1Swap.ts

A tx hash will be returned once the swap tx has been successfully executed:

Last updated

Was this helpful?