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
  • AntiSnipingAttack​
  • Struct: Data​
  • initialize()​
  • update()​
  • calcFeeProportions()​
  • BytesLib​
  • LiquidityMath​
  • getLiquidityFromQty0()​
  • getLiquidityFromQty1()​
  • getLiquidityFromQties()​
  • PathHelper​
  • Variables​
  • hasMultiplePools()​
  • numPools()​
  • decodeFirstPool()​
  • getFirstPool()​
  • skipToken()​
  • PoolAddress​
  • computeAddress()​
  • PoolTicksCounter​
  • countInitializedTicksCrossed()​
  • TokenHelper​
  • transferToken()​
  • transferEth()​

Was this helpful?

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

Elastic Peripheral Library Contracts

PreviousElastic Periphery Core ContractsNextElastic Peripheral Base Contracts

Last updated 2 years ago

Was this helpful?

AntiSnipingAttack

The motivation and explanation of the mechanism can be found . The function containing the bulk of the logic is .

Struct: Data

Field
Type
Formula Variable
Explanation

lastActionTime

uint32

timestamp of last action performed

lockTime

uint32

average start time of lock schedule

unlockTime

uint32

average unlock time of locked fees

feesLocked

uint32

locked rToken qty since last update

initialize()

Initializes values for a new position. The time variables are set to the current timestamp, while feesLocked is set to zero.

update()

Updates values for an existing position. Calculates the amount of claimable reinvestment tokens to be sent to the user and, in the case of liquidity removal, the amount of burnable reinvestment tokens as well.

Formula

claimBpsnew=min(BPS,tnow−tlockttarget)claimBps_{new} = min(BPS, \frac{t_{now}-t_{lock}}{t_{target}})claimBpsnew​=min(BPS,ttarget​tnow​−tlock​​)

claimBpscurrent=min(BPS,tnow−tlasttunlock−ttarget)claimBps_{current} = min(BPS, \frac{t_{now}-t_{last}}{t_{unlock} - t_{target}})claimBpscurrent​=min(BPS,tunlock​−ttarget​tnow​−tlast​​)

if tunlock>ttargett_{unlock} > t_{target}tunlock​>ttarget​, BPSBPSBPS otherwise feeharvestfee_{harvest}feeharvest​ and feelockfee_{lock}feelock​ updated through

tunlock=(tlock+ttarget)∗(BPS−claimBpsnew)∗feecollect+tunlock∗(BPS−claimBpscurrent)∗feelockedfeelock∗BPSt_{unlock} = \frac{(t_{lock} + t_{target}) * (BPS - claimBps_{new}) * fee_{collect} + t_{unlock} * (BPS - claimBps_{current}) * fee_{locked}}{fee_{lock} * BPS}tunlock​=feelock​∗BPS(tlock​+ttarget​)∗(BPS−claimBpsnew​)∗feecollect​+tunlock​∗(BPS−claimBpscurrent​)∗feelocked​​

  • If adding liquidity, update tlock=ceil(max(tlock,tnow−ttarget)∗L+tnow∗ΔLL+ΔL)t_{lock} = ceil(\frac{max(t_{lock}, t_{now} - t_{target})*L + t_{now} * \Delta{L}}{L + \Delta{L}})tlock​=ceil(L+ΔLmax(tlock​,tnow​−ttarget​)∗L+tnow​∗ΔL​)

  • If removing liquidity,

    • feeburn=feeharvest∗ΔLLfee_{burn} = fee_{harvest} * \frac{\Delta{L}}{L}feeburn​=feeharvest​∗LΔL​

    • feeharvestfee_{harvest}feeharvest​ -= feeburnfee_{burn}feeburn​

Field
Type
Formula Variable
Explanation

self

N.A.

stored data values for an existing position

currentLiquidity

uint128

current position liquidity

liquidityDelta

uint128

quantity change to be applied

currentTime

uint32

current block timestamp

isAddLiquidity

bool

N.A.

true = add liquidity, false = remove liquidity

feesSinceLastAction

uint256

fees accrued since last action

vestingPeriod

uint256

maximum time duration for which LP fees are proportionally burnt upon LP removals

Field
Type
Formula Variable
Explanation

feesClaimable

uint256

claimable reinvestment token amount

feesBurnable

uint256

reinvestment token amount to burn

Calculates the proportion of locked fees and claimable fees given the fee amounts and claimable fee basis points.

feeharvest=claimBpscurrentBPS∗feelocked+claimBpsnewBPS∗feecollectfee_{harvest} = \frac{claimBps_{current}}{BPS} * fee_{locked} + \frac{claimBps_{new}}{BPS} * fee_{collect}feeharvest​=BPSclaimBpscurrent​​∗feelocked​+BPSclaimBpsnew​​∗feecollect​ feelock=feelocked+feecollect−feeharvestfee_{lock} = fee_{locked} + fee_{collect} - fee_{harvest}feelock​=feelocked​+feecollect​−feeharvest​

Field
Type
Formula Variable
Explanation

currentFees

uint256

currently locked fees

nextFees

uint256

fees since last action

currentClaimableBps

uint256

proportion of claimable / unlocked currentFees in basis points

nextClaimableBps

uint256

proportion of claimable nextFees in basis points

Field
Type
Formula Variable
Explanation

feesLockedNew

uint256

new fee amount to be locked

feesClaimable

uint256

claimable fees to be sent to user

Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. The library lets you slice and type cast bytes arrays both in memory and storage.

Contract to calculate the expected amount of liquidity given the amounts of tokens.

Params:
    uint160 lowerSqrtP     // a lower sqrt price of the position
    uint160 upperSqrtP     // a upper sqrt price of the position
    uint256 qty0           // the amount of token0 to add
Returns:
    uint128 liquidity       // amount of liquidity to receive

Get liquidity from qty0 of the first token given the price range.

Params:
    uint160 lowerSqrtP     // a lower sqrt price of the position
    uint160 upperSqrtP     // a upper sqrt price of the position
    uint256 qty1           // the amount of token1 to add
Returns:
    uint128 liquidity       // amount of liquidity to receive

Get liquidity from qty1 of the second token given the price range.

Params:
    uint160 currentSqrtP    // the current price, e.g the pool's current price
    uint160 lowerSqrtP      // a lower sqrt price of the position
    uint160 upperSqrtP      // a upper sqrt price of the position
    uint256 qty0            // the amount of token0 to add
    uint256 qty1            // the amount of token1 to add
Returns:
    uint128 liquidity       // amount of liquidity to receive

Get liquidity given the price range and amounts of 2 tokens

Functions for manipulating path data for multihop swaps

ADDR_SIZE = 20 // length of the address, i.e 20 bytes
FEE_SIZE = 2 // length of the fee, i.e 2 bytes
TOKEN_AND_POOL_OFFSET = ADDR_SIZE + FEE_SIZE// the offset of a single token address + pool fee
POOL_DATA_OFFSET = TOKEN_AND_POOL_OFFSET + ADDR_SIZE // the offset of 2 token addresses + pool fee
MULTIPLE_POOLS_MIN_LENGTH = POOL_DATA_OFFSET + TOKEN_AND_POOL_OFFSET // min length that contains at least 2 pools
Params:
    bytes path
Returns:
    bool

Return true if the path contains 2 or more pools, false otherwise

Params:
    bytes path
Returns:
    uint256

Returns the number of pools in the path.

Params:
    bytes path
Returns:
    address tokenA
    address tokenB
    uint16 fee

Return the first pool's data from the path, including tokenA, tokenB and fee.

Params:
    bytes path
Returns:
    bytes data

Return the segment corresponding to the first pool in the path.

Params:
    bytes path
Returns:
    bytes newPath

Skip a token + fee from the buffer and returns the remainder.

Provides a function for deriving a pool address from the factory, tokens, and swap fee

Params:
    address factory   // DMMv2 factory contract
    address token0    // the first token of the pool
    address token1    // the second token of the pool
    uint16 swapFee    // the fee of the pool
    bytes32 poolInitHash    // the keccake256 hash of the Pool creation code
Returns:
    address pool    // the pool address

Deterministically computes the pool address from the given data.

Params:
    IProAMMPool
    int24 nearestCurrentTickBefore
    int24 nearestCurrentTickAfter
Returns:
    uint32 initializedTicksCrossed

Count the number of initialized ticks have been crossed given the previous/current nearest initialized ticks to the current tick.

A helper contract to transfer token/ETH.

Params:
    IERC20 token
    uint256 amount
    address sender
    address receiver

Transfer an amount of ERC20 token from the sender to the receiver.

Params:
    uint256 amount
    address receiver

Transfer an amount of ETH to the receiver.

Input

Output

calcFeeProportions()

Formula

Input

Output

BytesLib

Solidity Bytes Arrays Utils @author Gonçalo Sá

LiquidityMath

getLiquidityFromQty0()

getLiquidityFromQty1()

getLiquidityFromQties()

PathHelper

Variables

hasMultiplePools()

numPools()

decodeFirstPool()

getFirstPool()

skipToken()

PoolAddress

computeAddress()

PoolTicksCounter

countInitializedTicksCrossed()

TokenHelper

transferToken()

transferEth()

tlastt_{last}tlast​
tlockt_{lock}tlock​
tunlockt_{unlock}tunlock​
feelockedfee_{locked}feelocked​
LLL
ΔL\Delta{L}ΔL
tnowt_{now}tnow​
feecollectfee_{collect}feecollect​
ttargett_{target}ttarget​
feeharvestfee_{harvest}feeharvest​
feeburnfee_{burn}feeburn​
feelockedfee_{locked}feelocked​
feecollectfee_{collect}feecollect​
claimBpscurrentclaimBps_{current}claimBpscurrent​
claimBpsnewclaimBps_{new}claimBpsnew​
feelockfee_{lock}feelock​
feeharvestfee_{harvest}feeharvest​
​
​
​
​
​
​
​
goncalo.sa@consensys.net
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
here
​
​
​
​
calcFeeProportions()
update()
Data
Data
Data