Skip to content

Latest commit

 

History

History
325 lines (232 loc) · 17.6 KB

File metadata and controls

325 lines (232 loc) · 17.6 KB

Fill Limit Order

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 Off-Chain Relay, On-Chain Settlement 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%)

Stable (0.02%)

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

{% hint style="success" %} 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. {% endhint %}

{% embed url="https://github.com/KyberNetwork/ks-limit-order-API-demo" %}

Step 1: Get orders by best rates

{% hint style="info" %} Active/Open Orders

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

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  
    }
};

getOrders.ts

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

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);

getOperatorSignature.ts

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
    }
};

getOperatorSignature.ts

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

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

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

postFillOrder.ts

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);
    }
};    

approval.ts

Step 4: Format the fill order request body

{% hint style="info" %} 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.

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

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
};

postFillOrder.ts

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

To execute the transaction, we can use our ethers.js signer instance to send the transaction with the required gas fees:

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

postFillOrder.ts

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

Sample fill order on Polygon