KyberSwap Docs
  • Introduction to KyberSwap
  • Getting Started
    • Quickstart
      • FAQ
    • Supported Exchanges And Networks
    • Foundational Topics
      • Decentralized Finance
        • Tokens
        • Stablecoins
        • DEX/DeFi Aggregator
        • Slippage
        • Price Impact
        • Zap
        • Maximal Extractable Value (MEV)
      • Decentralized Technologies
        • Wallets
        • Dapps
        • RPC
        • Oracles
        • On-Chain vs Off-Chain Data
      • Other Valuable Resources
  • KyberSwap Solutions
    • KyberSwap Interface
      • User Guides
        • Connect Your Wallet
        • Switching Networks
        • Instantly Swap At Superior Rates
        • Swap At Your Preferred Rates
        • Cross-chain Swap
        • Add Your Favourite Tokens
        • Get Crypto With Fiat
        • Bridge Your Assets Across Multiple Chains
      • Profiles
        • Profile Creation
        • Profile Customization
        • Sync Profile Across Devices
      • Notifications
        • Notification Center
    • KyberSwap Aggregator
      • Concepts
        • Dynamic Trade Routing
      • User Guides
        • Instantly Swap At Superior Rates
      • Developer Guides
        • Execute A Swap With The Aggregator API
        • Upgrading To APIv1
      • Aggregator API Specification
        • EVM Swaps
        • Permit
      • Contracts
        • Aggregator Contract Addresses
      • DEX IDs
      • Subgraphs
      • FAQ
    • KyberSwap Zap as a Service
      • KyberSwap Zap as a Service (ZaaS) API
        • ZaaS HTTP API
        • ZaaS GRPC API
      • KyberSwap Zap Liquidity Widget
      • Zap Fee Model
      • Zap's Supported Chains/Dexes
      • Zap's Deployed Contract Addresses
      • Zap's DEX IDs
    • KyberSwap Widget
      • Developer Guides
        • Integrating The KyberSwap Widget
        • Customizing The KyberSwap Widget
      • iFrame Alternative
      • Widget/iFrame Fee
    • KyberSwap Liquidity Widget
      • Integrating The KyberSwap Liquidity Widget
    • Limit Order
      • Concepts
        • Off-Chain Relay, On-Chain Settlement
        • Gasless Cancellation
      • User Guides
        • Swap At Your Preferred Rates
        • Update Limit Orders
        • Cancel Limit Orders
      • Developer Guides
        • Create Limit Order
        • Gasless Cancel
        • Hard Cancel
        • Fill Limit Order
      • Contracts
        • Limit Order Contract Addresses
      • Limit Order API Specification
        • General APIs
        • Maker APIs
        • Taker APIs
      • FAQ
    • KyberSwap OnChain Price Service
    • Fee Schedule
  • Governance
    • KyberDAO
      • User Guides
        • Participating in KyberDAO
        • Staking
        • Voting
        • Stake KNC And Enjoy Gas Savings
      • Fees to KyberDAO
      • KyberDAO Operator MultiSig
      • Contracts
        • KyberDAO Contract Repo
        • KyberDAO Contract Addresses
      • FAQ - Others
    • KNC Token
      • KNC Tokenomics & Utility
      • Gas Refund Program
      • KNC Contract Addresses
  • Security
    • Audits
  • Reference
    • Legacy
      • KyberSwap Classic
        • Concepts
          • Programmable Pricing Curves
          • Dynamic Auto-Adjusting Fees
          • Virtual Balances
          • Protocol Fees
        • Contracts
          • Classic Contract Repo
          • Classic Contract Addresses
          • Classic Contract Farming Addresses
      • KyberSwap Elastic
        • Concepts
          • Concentrated Liquidity
          • Reinvestment Curve
          • Tick-Range Mechanism
          • Pool Process Flows
          • Anti-Sniping Mechanism
          • Tick-Based Farming
          • Elastic Zap
          • TWAP Oracle
          • Elastic APR Calculations
        • Contracts
          • Elastic Contract Repo
          • Elastic Contract Addresses
          • Elastic Farming Contract Addresses
          • Elastic Zap Contract Addresses
          • Elastic Core Contracts
          • Elastic Core Libraries
          • Elastic Periphery Core Contracts
          • Elastic Peripheral Library Contracts
          • Elastic Peripheral Base Contracts
        • Subgraphs
      • Whitepapers
      • Audits
      • KyberAI
        • KyberScore
        • Concepts
        • On-Chain Indicators
          • Number Of Trades
          • Trading Volume
          • Netflow To Whale Wallets
          • Netflow To CEX
          • Number Of Transfers
          • Volume Of Transfers
          • Number Of Holders
          • Top Holders
        • Technical Indicators
          • Live Charts
          • Support & Resistance Levels
          • Live Trades
          • Funding Rate On CEX
          • Liquidations On CEX
        • Liquidity Analysis
      • Elastic Legacy
        • Elastic Legacy Contract Repo
        • Elastic Legacy Contract Addresses
        • Elastic Legacy Farming Contract Addresses
        • Remove Elastic Legacy Liquidity
      • Protocol
        • Overview
        • Smart Contract Architecture
        • Trust and Security Model
      • Integrations
        • Getting Started
        • Use Cases
        • Integration Types
        • Smart Contracts
        • Ethers JS
        • RESTful API
        • Slippage Rate Protection
        • Price Feed Security
        • Contract Events
        • Platform Fees
      • Reserves
        • Getting Started
          • Overview
          • Why Develop On Kyber
          • Create New Reserve
          • Existing Reserves
          • Customising Existing Reserves
        • Development Guides
          • Fed Price Reserve
          • Automated Price Reserve
          • Reserves with Ganache
          • Orderbook Reserve
        • Operations
          • Listing Policies
          • Reserve IDs
          • Reserve Rebates
          • Sanity Rates
      • Addresses
        • Introduction
        • Mainnet
        • Kovan
        • Rinkeby
        • Ropsten
      • API/ABI
        • Introduction
        • RESTful API
          • RESTful API Overview
          • RESTful API
        • Core Smart Contracts
          • IKyberNetworkProxy
          • KyberNetworkProxy
          • IKyberNetwork
          • ISimpleKyberProxy
          • IKyberMatchingEngine
          • KyberMatchingEngine
          • IKyberHint
          • KyberHintHandler
          • IKyberHintHandler
          • IKyberFeeHandler
          • IKyberStaking
          • KyberStaking
          • IKyberDao
          • KyberDao
          • IKyberStorage
          • KyberStorage
          • IKyberHistory
          • KyberHistory
          • IKyberReserve
          • KyberReserve
          • ConversionRates
          • LiquidityConversionRates
          • EpochUtils
          • IEpochUtils
          • KyberFeeHandler
        • Contract ABIs
          • ABIs
        • Code Snippets
          • Token Quantity Conversion
        • Misc Contracts
          • KyberNetwork
          • ConversionRatesInterface
          • PermissionGroups
          • SanityRates
          • Withdrawable
          • OrderbookReserveInterface
          • OrderbookReserveLister
    • KyberSwap Operator MultiSig
    • Permitable Tokens
    • Third-Party Integrations
    • KyberSwap Analytics
    • KyberSwap App
    • GitHub
    • KyberSwap Analytics
    • KyberSwap Blog
    • Kyber Network Press Kit
  • Socials
    • X
    • Discord
    • Telegram
    • LinkedIn
    • Reddit
    • Instagram
    • Tik Tok
  • Support
    • KyberSwap Help Center
    • Complaints Handling Process
Powered by GitBook
On this page
  • Overview
  • Sequence diagram
  • TypeScript Example
  • Step 1: Query Swap Route
  • Step 2: Encode Preferred Swap Route
  • Step 3: Execute Swap Transaction On-Chain

Was this helpful?

  1. KyberSwap Solutions
  2. KyberSwap Aggregator
  3. Developer Guides

Execute A Swap With The Aggregator API

Interacting With KyberSwap Aggregator Router Contract

PreviousDeveloper GuidesNextUpgrading To APIv1

Last updated 2 months ago

Was this helpful?

Overview

KyberSwap maintains a single API specification for all EVM chains:

KyberSwap Aggregator APIv1

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

For integrators who have previously integrated with the non-versioned API, please refer to for further details on the motivation behind the upgrade as well as the relevant changes to swap flow and parameters.

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

While both versions of the API remains backwards compatible, only the [V1] APIs will continue to receive updates and hence developers are highly encouraged to implement the latest [V1] APIs to avoid any disruptions as the non-versioned API is eventually deprecated.

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.

TypeScript Example

Aggregator API Demo

The code snippets in the guide below have been extracted from our demo GitHub repo which showcases the full end-to-end Aggregator operations in a TypeScript environment.

Step 1: Query Swap Route

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

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

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

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.

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

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        
});

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

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

Integrators can easily query for superior rates by passing in the following required parameters into the API:

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

Upon finding a favourable route, we can then go ahead and encode the selected route by including the routeSummary in the request body of . Encoding the swap route via the API abstracts away the complexity of interacting with the contract directly.

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

To execute the swap, we will leverage the 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.

V1Get.ts
specification page
V1Post.ts
slippage
ethers.js
V1Swap.ts
Swap API specs for EVM chains
Upgrading To APIv1
[V1] Get Swap Route
[V1] Post Swap Route For Encoded Data
non-versioned API
GitHub - KyberNetwork/ks-aggregator-api-demo: Sample implementation of KyberSwap Aggregator APIsGitHub
Logo
Non-versioned API swap flow
APIv1 sequence diagram
Sample swap on Polygon