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

Was this helpful?

  1. Reference
  2. Legacy
  3. Integrations

Price Feed Security

PreviousSlippage Rate ProtectionNextContract Events

Last updated 2 years ago

Was this helpful?

You are referring to the Legacy version of KyberSwap docs.

For the most updated information, please refer to:

Using Kyber as an on-chain price feed

While using Kyber as an on-chain feed for token prices is viable, note that it is susceptible to price manipulation by malicious parties.

Generally, any price feed should

  • be averaged over time

  • have checks to verify that the buy / sell spread is small, and that there is no arbitrage at the time of query

We recommend that adequate measures are in place to verify the rate obtained on Kyber. We outline some of these methods below.

Check for arbitrage and the buy / sell spread

  1. Query for both buy and sell rates.

  2. Check that the spread between the buy / sell rate is within an acceptable range.

  3. Should there be arbitrage, there is a small possibility that a party is manipulating the price feed. We recommend that the transaction be reverted in these cases.

Our suggested algorithm is as follows:

  1. Get expected rate of 1 ETH equivalent worth of source tokens to the destination token

  2. Use the expected rate of (1) to calculate the expected destinations token receivable

  3. Get expected rate of the no. of destination tokens obtained in (2) to the source token

  4. Use the expected rate of (3) to calculate the number of source tokens receivable

    • If the resulting source token amount is greater than the initial source amount, arbitrage opportunity exists.

    • Otherwise, the smaller the resulting source token amount, the higher the spread.

// DISCLAIMER: The code snippet is just an example and you
// should always do your own testing. If you have questions, visit our
// https://t.me/KyberDeveloper.

// querySrcAmount = 100 * 10 ** srcDecimals (Recommend to be 1 ETH worth of tokens, in its token decimals)
// reasonableBps = a reasonable spread amount in basis points (bps)
// returns true if spread is reasonable, false if arbitrage exists, or spread is too large
function checkArbitrageAndSpread(
    uint querySrcAmount,
    ERC20 srcToken,
    ERC20 destToken,
    uint reasonableBps
) returns (bool) {
    uint buyRate;
    uint sellRate;
    //Step 1: Get expected rate of 1 ETH equivalent worth of source tokens to the destination token
    (buyRate, ) = kyberProxy.getExpectedRate(srcToken, destToken, querySrcAmount);
    //Step 2: Use the expected rate to calculate the expected destinations token receivable
    uint queryDestAmount = calcDstQty(querySrcAmount, srcToken.decimals(), destToken.decimals(), buyRate);
    //Step 3: Get expected rate dest token to the source token
    (sellRate, ) = kyberProxy.getExpectedRate(destToken, srcToken, queryDestAmount);
    //Step 4: Use the expected rate to calculate the number of source tokens receivable
    uint resultingSrcAmount = calcDstQty(queryDestAmount, destToken.decimals(), srcToken.decimals(), sellRate);
    //Step 5: Check arbitrage and spread amounts
    if (resultingSrcAmount > querySrcAmount) {
        //arbitrage opportunity exists, handle by reverting tx or return a flag
        return false;
    } else {
        //1 bps = 0.1%
        uint spreadInBps = (querySrcAmount - resultingSrcAmount) * 10000 / querySrcAmount;
        return (spreadInBps < reasonableBps);
    }
}

Note: The calcDstQty function used below

  • srcToken: USDC (6 decimals)

  • destToken: WBTC (8 decimals)

  • querySrcAmount = 180 * 10 ** 6 (180 USDC in its token decimals)

  1. A buyRate of 98426111111111 is obtained

  2. Expected dest amount is 1771669, or roughly 0.0177 WBTC tokens.

  3. A sellRate of 10151860703099732512111 is obtained

  4. Expected source amount is 179857368, or roughly 179.86 USDC tokens.

This means that if we swap 180 USDC to WBTC and back, we will obtain roughly 179.86 USDC in return. The resultingSrcAmount > querySrcAmount condition thus checks for arbitrage.

  1. We now check the spread between the buy and sell rate.

spreadInBps
    = (querySrcAmount - resultingSrcAmount) * 10000 / querySrcAmount
    ~= 7

This means that there is a 0.07% spread. For token to token swaps, we expect spreads to be higher, as ETH is used as the quote currency.

Consider using other price feeds in tandem with Kyber, if such on-chain sources are available. For example, use Maker's medianizer to obtain ETH/USD rates.

The token conversion rate returned by Kyber varies with different source token quantities. If applicable, use the actual source quantity when calling the getExpectedRate function.

Algorithm

Example

Use multiple price feeds

Use actual source quantity

Classic
Elastic
Limit Order
Aggregator
​
​
​
​
​
​