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
        • Add Your Favourite Tokens
        • Get Crypto With Fiat
        • Bridge Your Assets Across Multiple Chains
        • Swap Between Different Tokens Across 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: Get orders by best rates
  • Step 2: Get the Operator signature for the target order
  • Step 3: Check Limit Order contract spending allowance
  • Step 4: Format the fill order request body
  • Step 5: Post the encode data request
  • Step 6: Execute the fill order transaction on-chain

Was this helpful?

  1. KyberSwap Solutions
  2. Limit Order
  3. Developer Guides

Fill Limit Order

PreviousHard CancelNextContracts

Last updated 5 months ago

Was this helpful?

Overview

Takers are able to fill any signed Maker order within the KyberSwap Limit Order order books by executing the fill order on-chain. By utilizing KyberSwap Limit Order APIs, Takers gain access to slippage-free liquidity sources which are secured via on-chain settlement.

Please refer to for more detail on this design.

Limit Order protocol fees

To support the continued development of the Limit Orders feature, KyberSwap will charge variable taker fees for orders filled on the following chains:

  • Ethereum (ChainID: 1)

  • BSC (ChainID: 56)

  • Arbitrum (ChainID: 42161)

  • Polygon (ChainID: 137)

  • Optimism (ChainID: 10)

  • Avalanche (ChainID: 43114)

  • Fantom (ChainID: 250)

  • Base (ChainID: 8453)

  • ZkSync (ChainID: 324)

  • Linea (ChainID: 59144)

  • Mantle (ChainID: 5000)

  • Scroll (ChainID: 534352)

  • Blast (ChainID: 81457)

The fees charged will be according to the most exotic token in the trading pair. The section below lists the fees whereby the highest fee category will apply based on the classification of the input and output tokens. There are 4 categories of tokens with an additional special category for trades involving KNC.

Super stable (0.01%)

  • Ethereum (ChainID: 1)

    • USDC:

    • USDT:

    • DAI:

  • BSC (ChainID: 56)

    • USDT:

    • USDC:

    • DAI:

    • BUSD:

  • Arbitrum (ChainID: 42161)

    • USDT:

    • USDC:

    • DAI:

  • Polygon (ChainID: 137)

    • USDT:

    • USDC:

    • DAI:

  • Optimism (ChainID: 10)

    • USDT:

    • USDC:

    • DAI:

  • Avalanche (ChainID: 43114)

    • USDT:

    • USDC:

    • DAI.e:

    • USDT.e:

    • USDC.e:

  • Fantom (ChainID: 250)

    • fUSDT:

    • USDC:

    • DAI:

Stable (0.02%)

  • Ethereum (ChainID: 1)

    • MAI:

    • BOB:

    • MIM:

  • BSC (ChainID: 56)

    • MAI:

    • BOB:

    • MIM:

  • Arbitrum (ChainID: 42161)

    • MAI:

    • MIM:

  • Polygon (ChainID: 137)

    • MAI:

    • BOB:

    • MIM:

  • Optimism (ChainID: 10)

    • MAI:

    • BOB:

  • Avalanche (ChainID: 43114)

    • MAI:

    • YUSD:

    • MIM:

  • Fantom (ChainID: 250)

    • MAI:

    • MIM:

Normal (0.1%)

  • Top 200 tokens by market cap (identified via multiple on and off-chain services), excluding tokens under the super stable, stable, and KNC categories.

Exotic (0.3%)

  • All remaining tokens not covered in the super stable, stable, normal, and KNC categories.

High Volatility (0.5%)

  • Tokens that have been added in the Token Catalog from 2 weeks to 1 month.

Super High Volatility (1%)

  • Tokens that have been added in the Token Catalog for less than 2 weeks.

KNC (0.1%)

  • Trades to and from KNC will be charged a flat 0.1% fee.

Limit Order fees structure

The fee token is determined based on the following logic, in order of priority (from top to bottom):

  1. Token Catalog Availability (Rare Case):

    • If the taker token (takerAsset) is not listed in the token catalog:

    → The maker token (makerAsset) will be the fee token.

    • If the maker token (makerAsset) is not listed in the token catalog:

    → The taker token (takerAsset) will be the fee token.

If both token are in the token catalog, move to 2 & 3

  1. Whitelist Priority:

  • If the maker token is whitelisted and the taker token is not: → The maker token will be the fee token.

  • If the taker token is whitelisted and the maker token is not → The taker token will be the fee token.

  1. Token Ranking:

If both tokens are either whitelisted or not whitelisted, the fee token is based on the higher-ranked token:

  • Each token’s ranking using its CMC Rank or CGK Rank is calculated (marketcap ranking).

  • The token with the better (higher) ranking will be the fee token.

Example: If makerAssetRanking > takerAssetRanking, use makerAsset as the fee token; otherwise, use takerAsset.

Sequence Diagram

KyberSwap exposes 2 API options for Takers looking to fill orders on-chain:

In order to fill an order, Takers will first have to request an Operator signature via:

In addition to the above, Takers are also able to query active or open order(s) to aid with filtering orders to fill:

TypeScript Example

Limit Order API Demo

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

Step 1: Get orders by best rates

Active/Open Orders

We can use the /read-partner/api/v1/orders to get the list of "active" or "open" orders by token pair:

const targetPathConfig = {
    params: {
        chainId: ChainId.MATIC,
        makerAsset: makerAsset.address, // USDC
        takerAsset: takerAsset.address  // KNC  
    }
};

Step 2: Get the Operator signature for the target order

For the purposes of this guide, we will be taking the first returned order to fill:

const orders = await getOrders();
const targetOrders = orders.filter(order => 
    order.maker.toLowerCase() == signerAddress.toLowerCase() &&
    order.makerAsset.toLowerCase() == makerAsset.address.toLowerCase() &&
    order.takerAsset.toLowerCase() == takerAsset.address.toLowerCase()
);
const targetOrderId = Number(targetOrders[0].id);

With our target orderId, we can then request for the Operator signature by calling /read-partner/api/v1/orders/operator-signature with the following parameters:

const targetPathConfig = {
    params: {
        chainId: ChainId.MATIC.toString(),
        orderIds: targetOrderId
    }
};

For each orderId requested, the KyberSwap LO Service will return an operatorSignature which will be required as part of the fill order transaction.

Step 3: Check Limit Order contract spending allowance

const orders = await getOrders();
const targetOrder = orders.filter(order => order.id == targetOrderId.toString());
const takingAmount = Number(targetOrder[0].takingAmount)/2;

If there is insufficient spending allowance, we can then request for a higher allowance via the takerAsset ERC20 token contract using our getTokenApproval() helper function:

if (Number(limitOrderContractAllowance) < spendingAmount) {
    console.log(`Insufficient allowance, getting approval for ${await tokenContract.symbol()}...`);
    try {
        // Call the ERC20 approve method
        const approvalTx = await tokenContract.approve(
            spenderAddress, 
            BigInt(spendingAmount), 
            {maxFeePerGas: 100000000000, maxPriorityFeePerGas: 100000000000}
            );

        // Wait for the approve tx to be executed
        const approvalTxReceipt = await approvalTx.wait();
        console.log(`Approve tx executed with hash: ${approvalTxReceipt?.hash}`);

    } catch(error) {
        console.log(error);
    }
};    

Step 4: Format the fill order request body

Filling Batch Orders

For simplicity, the example below fills a single order using /read-ks/api/v1/encode/fill-order-to. KyberSwap Limit Orders exposes another /read-ks/api/v1/encode/fill-batch-orders-to API which enables Takers to get the encoded data to batch fill orders.

By filling multiple orders in a single on-chain tx, batch fill orders are more efficient. The only difference between the 2 APIs is the formatting of orderIds and operatorSignatures when preparing the requestBody for the respective API.

To get the encoded data, we will then need to format the /read-ks/api/v1/encode/fill-order-to request body. Note the operatorSignature that was returned in step 2:

const requestBody: FillOrderBody = {
    orderId: Number(targetOrderId),
    takingAmount: takingAmount.toString(),
    thresholdAmount: '0',
    target: signerAddress,
    operatorSignature: operatorSignature[0].operatorSignature
};

Step 5: Post the encode data request

With the fill order prepared, we can then request the encoded data via /read-ks/api/v1/encode/fill-order-to:

const {data} = await axios.post(
    LimitOrderDomain+targetPath,
    requestBody
);

This will return the fill order encoded data which will be used as the calldata when executing the transaction on-chain.

Step 6: Execute the fill order transaction on-chain

const fillOrderTx = await signer.sendTransaction({
    data: data.data.encodedData,
    to: limitOrderContract,
    from: signerAddress,
    maxFeePerGas: 100000000000,
    maxPriorityFeePerGas: 100000000000
});

: Encode the fill order data to be sent on-chain. This API can be used to fill a single order.

: Encode the fill batch order data to be sent on-chain. This API can be used to fill multiple orders.

: Get the KyberSwap Operator to sign the target orders so that it can be filled.

: Returns orders for the queried token pair sorted by best rates in descending order.

To proceed with this guide, users must have created an Active or Open Limit Order. Please refer to the for instructions on how to achieve this programmatically.

Note that the returned orders will be sorted according to the in descending order. The makerAsset and takerAsset are defined in the file to enable convenient reuse across various operations.

Before executing the fill order, we will first need to ensure that the LO smart contract has sufficient . In this example, we will be filling half of the Maker order requested takingAmount:

The Fill Batch Orders API requires the order of the orderIds array to match their corresponding operatorSignatures. Full code example can be found on .

To execute the transaction, we can use our to send the transaction with the required gas fees:

A transaction hash will be returned once the cancel order has been executed. You can copy this hash into a scanner (i.e. ) and see that your transaction has been successfully completed by the network.

Create Limit Order developer guide
getOrders.ts
getOperatorSignature.ts
getOperatorSignature.ts
allowance to spend the taker's ERC20 token
postFillOrder.ts
approval.ts
postFillBatchOrders.ts
postFillOrder.ts
ethers.js signer instance
postFillOrder.ts
PolygonScan
Off-Chain Relay, On-Chain Settlement
0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
0xdac17f958d2ee523a2206206994597c13d831ec7
0x6b175474e89094c44da98b954eedeac495271d0f
0x55d398326f99059ff775485246999027b3197955
0x8ac76a51cc950d9822d68b83fe1ad97b32cd580d
0x1af3f329e8be154074d8769d1ffa4ee058b1dbc3
0xe9e7cea3dedca5984780bafc599bd69add087d56
0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9
0xaf88d065e77c8cC2239327C5EDb3A432268e5831
0xDA10009cBd5D07dd0CeCc66161FC93D7c9000da1
0xc2132d05d31c914a87c6611c10748aeb04b58e8f
0x2791bca1f2de4661ed88a30c99a7a9449aa84174
0x8f3Cf7ad23Cd3CaDbD9735AFf958023239c6A063
0x94b008aa00579c1307b0ef2c499ad98a8ce58e58
0x7f5c764cbc14f9669b88837ca1490cca17c31607
0xda10009cbd5d07dd0cecc66161fc93d7c9000da1
0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7
0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E
0xd586E7F844cEa2F87f50152665BCbc2C279D8d70
0xc7198437980c041c805A1EDcbA50c1Ce5db95118
0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664
0x049d68029688eabf473097a2fc38ef61633a3c7a
0x04068DA6C83AFCFA0e13ba15A6696662335D5B75
0x8D11eC38a3EB5E956B052f67Da8Bdc9bef8Abf3E
0x8D6CeBD76f18E1558D4DB88138e2DeFB3909fAD6
0xB0B195aEFA3650A6908f15CdaC7D92F8a5791B0B
0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3
0x3F56e0c36d275367b8C502090EDF38289b3dEa0d
0xB0B195aEFA3650A6908f15CdaC7D92F8a5791B0B
0xfE19F0B51438fd612f6FD59C1dbB3eA319f433Ba
0x3F56e0c36d275367b8C502090EDF38289b3dEa0d
0xFEa7a6a0B346362BF88A9e4A88416B77a57D6c2A
0xa3Fa99A148fA48D14Ed51d610c367C61876997F1
0xB0B195aEFA3650A6908f15CdaC7D92F8a5791B0B
0x49a0400587A7F65072c87c4910449fDcC5c47242
0xdFA46478F9e5EA86d57387849598dbFB2e964b02
0xB0B195aEFA3650A6908f15CdaC7D92F8a5791B0B
0x5c49b268c9841AFF1Cc3B0a418ff5c3442eE3F3b
0x111111111111ed1D73f860F57b2798b683f2d325
0x130966628846BFd36ff31a822705796e8cb8C18D
0xfB98B335551a418cD0737375a2ea0ded62Ea213b
0x82f0B8B456c1A451378467398982d4834b6829c1
constants.ts
/read-ks/api/v1/encode/fill-order-to
/read-ks/api/v1/encode/fill-batch-orders-to
/read-partner/api/v1/orders/operator-signature
/read-partner/api/v1/orders
best rates
GitHub - KyberNetwork/ks-limit-order-API-demo: Sample implementation of KyberSwap Limit Order APIsGitHub
Logo
Sample fill order on Polygon