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: Get the unsigned EIP712 Create Order message
  • Step 2: Check Limit Order contract spending allowance
  • Step 3: Sign the EIP712 Create Order message
  • Step 4: Format the create order request body
  • Step 5: Post the create order

Was this helpful?

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

Create Limit Order

PreviousDeveloper GuidesNextGasless Cancel

Last updated 1 year ago

Was this helpful?

Overview

KyberSwap Limit Order enables Makers to create orders without incurring gas. To achieve this, signed Maker orders are stored off-chain but settled by the Takers on-chain. By gaslessly signing the off-chain order, a Maker pre-commits to a limit order whose parameters can't be tampered with ensuring order predicatability and security. Please refer to for a design overview.

Sequence diagram

KyberSwap exposes 2 APIs which Makers will need to call to create a new order:

In addition to the above, Makers are also able to query their active making amount to aid with token approvals:

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 the unsigned EIP712 Create Order message

To create a new limit order, the Maker must first specify the order parameters to be sent to the KyberSwap LO Service via the POST request body:

const requestBody: CreateOrderUnsignedBody = {
    chainId: ChainId.MATIC.toString(),
    makerAsset: makerAsset.address, // USDC
    takerAsset: takerAsset.address, // KNC
    maker: signerAddress,
    allowedSenders: [signerAddress], // Included so that only our account can fill this order
    makingAmount: "10000", // 0.01 USDC
    takingAmount: "20000000000000000", // 0.02 KNC
    expiredAt: Math.floor(Date.now() / 1000) + 60 * 60 // 60mins
};

Step 2: Check Limit Order contract spending allowance

KyberSwap Limit Order Contract Addresses

To get the Maker's current making amount for a specific token, KyberSwap exposes a /read-ks/api/v1/orders/active-making-amount API:

const targetPathConfig = {
    params: {
        chainId: ChainId.MATIC,
        makerAsset: makerAsset.address,
        maker: signerAddress
    }
};

Note that the new order making amount will have to be added to the current making amount. In other words, when creating a new order, the KyberSwap service checks that it has sufficient allowance across all open Maker orders.

const currentMakingAmount = await getMakerActiveAmount();
const newMakingAmount = Number(currentMakingAmount) + Number(unsignedOrderReqBody.makingAmount);

If there is insufficient spending allowance, we can then request for a higher allowance via the makerAsset 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 3: Sign the EIP712 Create Order message

Once we have the necessary allowances in place, we can then go ahead and request the signature from the Maker:

const signature = await signer.signTypedData(
    unsignedOrderReturnData.domain,
    { Order: unsignedOrderReturnData.types.Order },
    unsignedOrderReturnData.message
);

EIP712 Sign Typed Data

Step 4: Format the create order request body

With the maker-signed transaction, we can then format the request body according to the /write/api/v1/orders specs:

const requestBody: CreateOrderSignedBody = {
    ...unsignedOrderReqBody,
    salt: unsignedOrderReturnData.message.salt,
    signature: signature
};

Note that apart from appending the signature to the existing request body from our earlier API call, we are also extracting the salt that was returned.

Step 5: Post the create order

We are now ready to call the /write/api/v1/orders API with the formatted create order message:

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

Once the KyberSwap LO service receives the creation order, a new off-chain order will be created in it's orderbook from which our network of Takers will be able to query. The created orderId will also be returned as part of the response values from the /write/api/v1/orders API.

: Get the EIP712 create order message to be signed. The response of this API will need to be signed with before submitting create order request below.

: Create new order(s) by sending in order params which includes the signed EIP712 message.

: The aggregated making amount for the Maker given a specific token.

As part of the order configuration, note that the makingAmount and takingAmount are denominated in wei units and dependent on the configured in the asset's ERC20 contract. The allowedSenders parameter is optional but have been included for the purposes of this demo so that only our controlled address can fill the created order.

The makerAsset and takerAsset are defined in the file to enable convenient reuse across various operations.

Full details for each parameter can be found via the . Upon posting the above request body to /write/api/v1/orders/sign-message, the KyberSwap LO Service will return an unsigned Create Order message.

Before signing the order creation message, we will first need to ensure that the LO smart contract has sufficient . This ensures that when a Taker fills the order, the LO smart contract has the necessary approvals to transfer the specified makerAsset amount from the Maker's wallet.

Please refer to for the exact addresses for KyberSwap Limit Order for each supported chain.

exposes human-readable data for user's to view prior to signing the transaction.

Our example assumes a pure Node.js implementation and therefore uses the ethers.js function to sign the EIP712 message. Note that the type object used is per the primaryType that is returned by the KyberSwap LO Service.

For further information on how to implement this from the browser UI, you can also take reference from MetaMask's .

Note that the KyberSwap Limit Order domain is stored under for easy retrieval across various API operations.

postCreateOrdersUnsigned.ts
decimals
constants.ts
allowance to spend the Maker's ERC20 token
Limit Order Contract Addresses
getMakerActiveAmount.ts
postCreateOrder.ts
approval.ts
postCreateOrder.ts
EIP712
signTypedData()
SignTypedData V4
postCreateOrder.ts
postCreateOrder.ts
constants.ts
Off-Chain Relay, On-Chain Settlement
Sign Typed Data v4
EIP712
GitHub - KyberNetwork/ks-limit-order-API-demo: Sample implementation of KyberSwap Limit Order APIsGitHub
Logo
/write/api/v1/orders/sign-message
/write/api/v1/orders
/read-ks/api/v1/orders/active-making-amount
Get Unsigned Create Order Message API specification
Create order success response