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 Maker orders
  • Step 2: Get the target orderId to cancel
  • Step 3: Get the unsigned EIP712 Cancel Order message
  • Step 4: Sign the EIP712 Cancel Order message
  • Step 5: Format the cancel order request body
  • Step 6: Post the gasless cancel order

Was this helpful?

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

Gasless Cancel

PreviousCreate Limit OrderNextHard Cancel

Last updated 1 year ago

Was this helpful?

Overview

In addition to , KyberSwap Limit Order Makers have the option to cancel their orders without incurring gas. As Taker order fulfilment requires both a Maker and KyberSwap Operator signature, Makers are able to cancel their orders gaslessly by instructing the KyberSwap Operator to cancel their orders.

Please refer to for more details on this design.

Sequence Diagram

KyberSwap exposes 2 APIs which Makers will need to call to gaslessly cancel their order:

In addition to the above, Makers are also able to query their active order(s) to aid with filtering orders to cancel:

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 Maker orders

Active/Open Orders

We can use the /read-ks/api/v1/orders to get the list of "active" or "open" Maker orders:

const targetPathConfig = {
    params: {
        chainId: ChainId.MATIC,
        maker: signerAddress,
        status: "active"
    }
};

In this case, the above query will return all of the Maker active orders from which we can then filter for our target order to cancel.

Step 2: Get the target orderId to cancel

For our purposes, we will just take the first order which matches our makerAsset and takerAsset pair:

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

Step 3: Get the unsigned EIP712 Cancel Order message

To get the unsigned Cancel Order message, we will send the following request to the /write/api/v1/orders/cancel-sign endpoint:

const requestBody: CancelOrderUnsignedBody = {
    chainId: ChainId.MATIC.toString(),
    maker: signerAddress,
    orderIds: [targetOrderId]
};

Step 4: Sign the EIP712 Cancel Order message

Based on the response above, we can then proceed to request the Maker's signature:

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

EIP712 Sign Typed Data

Step 5: Format the cancel order request body

With the maker-signed transaction, we can then append the signature to the request body to be sent to /write/api/v1/orders/cancel:

const requestBody: CancelOrderSignedBody = {
    ...unsignedOrderReqBody,
    signature: signature
};

Step 6: Post the gasless cancel order

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

const {data} = await axios.post(
    LimitOrderDomain+targetPath,
    requestBody,
    {headers: {Origin: 'https://kyberswap.com'}}
);

Note that we have included an Origin header parameter as a means to authenticate the request.

Once the KyberSwap LO Service receives the gasless cancel order, the KyberSwap Operator will no longer sign the orderIds that were requested to be gaslessly cancelled. In rare cases where the KyberSwap Operator had recently signed the target orderId (i.e. when target order is close to the market price), Makers might need to wait up till a maximum of 5 minutes for the Operator signature to lapse before their order is cancelled.

Hard Cancel

For Makers who would like to immediately cancel their orders without waiting for the Operator signature to lapse, KyberSwap Limit Orders also offers a Hard Cancel option. By paying a small prioritization gas fee, Makers can cancel their orders immediately on-chain.

The cancelled orderId as well as any operator signature expiry timestamp will be returned as part of the response values from the /write/api/v1/orders/cancel API.

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

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

: Get all orders created by a Maker address filtered by the order status.

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 you can specify more than a single orderId to be cancelled by adding to the orderIds array. Once submitted, the KyberSwap LO Service will return an unsigned Cancel Order message.

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 .

Please refer to for more info.

Create Limit Order developer guide
getMakerOrders.ts
postCancelOrderUnsigned.ts
postCancelOrderUnsigned.ts
EIP712
postCancelOrder.ts
EIP712
signTypedData()
SignTypedData V4
postCancelOrder.ts
postCancelOrder.ts
Hard Cancel
gasless order creation
Gasless Cancellation
Sign Typed Data v4
GitHub - KyberNetwork/ks-limit-order-API-demo: Sample implementation of KyberSwap Limit Order APIsGitHub
/write/api/v1/orders/cancel-sign
/write/api/v1/orders/cancel
/read-ks/api/v1/orders
Logo
Gasless cancel order success response