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
  • Router​
  • Struct: ExactInputSingleParams​
  • Struct: ExactInputParams​
  • Struct: ExactOutputSingleParams​
  • Struct: ExactOutputParams​
  • swapCallback()​
  • swapExactInputSingle()​
  • swapExactInput()​
  • swapExactOutputSingle()​
  • swapExactOutput()​
  • BasePositionManager​
  • Struct: MintParams​
  • Struct: IncreaseLiquidityParams​
  • Struct: RemoveLiquidityParams​
  • Struct: BurnRTokenParams​
  • createAndUnlockPoolIfNecessary()​
  • mint()​
  • addLiquidity()​
  • removeLiquidity()​
  • burnRTokens()​
  • AntiSnipAttackPositionManager​

Was this helpful?

  1. Reference
  2. Legacy
  3. KyberSwap Elastic
  4. Contracts

Elastic Periphery Core Contracts

PreviousElastic Core LibrariesNextElastic Peripheral Library Contracts

Last updated 1 year ago

Was this helpful?

Router

The Router contract to handle swapping.

Struct: ExactInputSingleParams

Contains data for swap exact input with a single pool.

ExactInputSingleParams
    address tokenIn;     // source token to swap
    address tokenOut;    // dest token to receive
    uint16 fee;          // fee of the pool to swap
    address recipient;   // the recipient of tokenOut
    uint256 deadline;    // deadline for the transaction
    uint256 amountIn;    // the amount of tokenIn to swap
    uint256 minAmountOut;// min acceptable amount of tokenOut
    uint160 limitSqrtP;  // the limit of sqrt price, partial swap if price reaches the limitation

Struct: ExactInputParams

Contains data for swap exact input with one or multiple pools.

ExactInputParams
    bytes path;           // contains data to identify list of pools to use for the swap
    address recipient;    // the recipient of token out
    uint256 deadline;     // deadline for the transaction
    uint256 amountIn;     // the amount of token in to swap
    uint256 minAmountOut; // the min acceptable amount of token out

Contains data for swap to an exact amount out of token out, using only one pool.

ExactOutputSingleParams:
    address tokenIn;    // source token to swap
    address tokenOut;   // dest token to receive
    uint16 fee;         // fee of the pool
    address recipient;  // the recipient of tokenOut
    uint256 deadline;   // deadline for the transaction
    uint256 amountOut;  // the amount of tokenOut to expect
    uint256 maxAmountIn;// the max amount of tokenIn that is allowed to use
    uint160 limitSqrtP; // the limit of sqrt price, partial swap if price reaches the limitation

Contains data for swap to an exact amount out of token out using one or multiple pools.

ExactOutputParams
    bytes path;
    address recipient;
    uint256 deadline;
    uint256 amountOut;
    uint256 maxAmountIn;
Params:
    int256 deltaQty0
    int256 deltaQty1
    bytes data

Callback function that is be triggerred by the pool when swapping tokens. Either deltaQty0 or deltaQty1 must be positive. Positive value means the pool (also the caller) is expecting to receive that amount of token.

Params:
    ExactInputSingleParams params
Returns:
    uint256 amountOut

Given the params of ExactInputSingleParams, it uses only one pool to swap exact an amountIn of tokenIn to tokenOut and return the amount of tokenOut from the swap. It calls the swap function in the pool contract, the pool will transfer the tokenOut to the Router, and expect to receive the corresponding tokenIn in the swap callback function.

Params:
    ExactInputParams params
Returns:
    uint256 amountOut

Given the params of ExactInputParams, it uses only one or multiple pools that can be decoded from the path. It calls the swap function in each pool contract that is decoded from the path param, and uses callback to handle transferring tokens.

Flow:

  • Swap path: tokenIn -> token0 -> token1 -> ... -> tokenOut.

  • Call the first pool to borrow token0 to the Router, then transfer tokenIn from user's wallet to the first pool.

  • Call the second pool to borrow token1 to the Router, then transfer token0 from the Router to the second pool.

  • Repeat the action until the last pool, and transfer tokenOut directly to the recipient.

Params:
    ExactOutputSingleParams params
Returns:
    uint256 amountIn

Given the params of ExactOutputSingleParams, it uses only one pool to swap to get exact amountOut of tokenOut (or stop if price limit reaches).

  • Call the swap function in the pool contract.

  • The pool transfers the tokenOut to the recipient, and make the swap callback.

  • The Router transfer the corresponding tokenIn from user's wallet to the pool. The required amount of tokenIn should not be greater than maxAmountIn.

Params:
    ExactOutputParams params
Returns:
    uint256 amountIn

Given the params of ExactOutputParams, it uses one or multiple pools that can be decoded from the path. It calls the swap function in each pool contract that is decoded from the path param, and uses callback to handle transferring tokens. The list of pools in the path params should be in the reverse order, i.e the last pool first since we don't know the exact amount of token in to be used.

Flow:

  • Origial swap path: tokenIn -> token0 -> token1 -> ... -> tokenN -> tokenOut.

  • Reverse swap path: tokenOut -> tokenN -> ... -> token1 -> token0 -> tokenIn.

  • Consider as we are swapping from amountOut of tokenOut to tokenIn.

Inherit from an ERC721 contract, it stores all positions of all liquidity providers and mint corresponding NFT.

Users can use the PositionManager to create & unlock pool, mint new position, add/remove liquidity to/from an existing position and burn their reinvestment tokens to receive back the LP fees.

It also inherits from Multicall contract, thus, users can make multiple function/method calls to the PositionManager in a single transaction.

All reinvestment tokens will be held in the contract, thus, it blocks anyone from transferring reinvestment tokens out. As a result, the contract can not support pools with any reinvestment tokens.

Params for the first time adding liquidity, mint new nft to sender

MintParams
    address token0; // the token0 of the pool
    address token1; // token1 of the pool, must make sure that token0 < token1
    uint16 fee; // the pool's fee in bps
    int24 tickLower; // the position's lower tick
    int24 tickUpper; // the position's upper tick
    int24[2] ticksPrevious; // the nearest tick that has been initialized and lower than or equal to the tickLower and tickUpper, use to help insert the tickLower and tickUpper if haven't initialized
    uint256 amount0Desired; // the desired amount for token0
    uint256 amount1Desired; // the desired amount for token1
    uint256 amount0Min; // min amount of token 0 to add
    uint256 amount1Min; // min amount of token 1 to add
    address recipient; // the owner of the position
    uint256 deadline; // time that the transaction will be expired

Params for adding liquidity to the existing position

IncreaseLiquidityParams
    uint256 tokenId // id of the position to increase its liquidity
    uint256 amount0Desired // the desired amount for token0
    uint256 amount1Desired // the desired amount for token1
    uint256 amount0Min // min amount of token 0 to add
    uint256 amount1Min // min amount of token 1 to add
    uint256 deadline // time that the transaction will be expired

Params for remove liquidity from the existing position

RemoveLiquidityParams
    uint256 tokenId // id of the position to remove its liquidity
    uint256 amount0Min // min amount of token 0 to receive
    uint256 amount1Min // min amount of token 1 to receive
    uint256 deadline // time that the transaction will be expired

Burn the rTokens to get back token0 + token1 as fees

BurnRTokenParams
    uint256 tokenId // id of the position to burn r token
    uint256 amount0Min // min amount of token 0 to receive
    uint256 amount1Min // min amount of token 1 to receive
    uint256 deadline // time that the transaction will be expired
Params:
    address token0;
    address token1;
    uint16 fee;
    uint160 currentSqrtP
Returns:
    address pool // deployed pool given the set of params

Use this function to create & unlock a pool if needed given (token0, token1, fee) params and the initial sqrt price. Required: token0 < token1

Params:
    MintParams params
Returns:
    uint256 tokenId;
    uint128 liquidity,
    uint256 amount0,
    uint256 amount1

Call the _addLiquidity function in the LiquidityHelper contract with the data from *params. It mints a new NFT token represents the position to the recipient, stores the position data and pool information.

Params:
    IncreaseLiquidityParams params
Returns:
    uint128 liquidity,
    uint256 amount0,
    uint256 amount1,
    uint256 additionalRTokenOwed

Call the _addLiquidity function in the LiquidityHelper contract with the data from params to add more liquidity to a given position (i.e tokenId). Calculate and update the additional reinvestment tokens that the position should have earned.

Params:
    RemoveLiquidityParams params
Returns:
    uint256 amount0,
    uint256 amount1,
    uint256 additionalRTokenOwed

Call the burn function in the pool contract with the data from params to remove liquidity and get back 2 tokens. Calculate and update the additional reinvestment tokens that the position should have earned.

Params:
    BurnRTokenParams params
Returns:
    uint256 rTokenQty,
    uint256 amount0,
    uint256 amount1

Call the burnRTokens function in the pool contract to burn all reinvestment tokens from the position and get back 2 tokens. Return the amount of reinvestment tokens to burn and expected amounts of 2 tokens to receive

Overriding functions for the inherited ERC721 and permit contracts.

Inherits BasePositionManager and adds the anti-sniping attack feature into addLiquidity and removeLiquidity functions.

Reinvestment tokens of a position will be locked and vested to prevent LPs from adding then removing liquidity within a small period of time.

Struct: ExactOutputSingleParams

Struct: ExactOutputParams

swapCallback()

swapExactInputSingle()

swapExactInput()

swapExactOutputSingle()

swapExactOutput()

BasePositionManager

Struct: MintParams

Struct: IncreaseLiquidityParams

Struct: RemoveLiquidityParams

Struct: BurnRTokenParams

createAndUnlockPoolIfNecessary()

mint()

addLiquidity()

removeLiquidity()

burnRTokens()

Functions: tokenURI(), getApproved(), _approve(), _getAndIncrementNonce()

AntiSnipAttackPositionManager

The motivation, mechanism and formula for Anti-Sniping Attack can be found . The will be of interest as well.

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
here
AntiSnipingAttack library