NAV
Im token logo imToken API Documentation Tokenlon-SDK DApp-SDK
typescript
  • Introduction
  • Installation
  • Configuration
  • Features
  • Tokenlon
  • Basics
  • Others
  • English

    Introduction

    Tokenlon-SDK Designed and achieved by the imToken team. It is based on the 0x protocol and 0x.js ,providing APIs for developers to create automated trading, out of DApps.

    Installation

    yarn add tokenlon-sdk

    or

    npm install tokenlon-sdk

    Configuration

    server url

    web3 provider url

    wallet config

    wallet config

    {
      "address": "0x20F0C6e79A763E1Fe83DE1Fbf08279Aa3953FB5f",
      "privateKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    }
    

    An Object with the wallet's address and privateKey.

    Notice:

    1. The Wallet address must be approved by imToken to be able to get responses from the imToken server;
    2. Place orders, fill orders, and cancel orders are all performed by this wallet. It is therefore necessary to have the corresponding tokens in the wallet, during the running period.

    The private key will be used to process the signature when Tokenlon-SDK is initialized or running:

    1. The signature timestamp will be sent to the imToken server to obtain a JWT Token (JSON Web Token) as the request header for each request. During this process, the backend verifies whether the signed address passes the audit;
    2. Placing, filling, cancelling Orders and other smart contract calls are done through the Tokenlon-SDK. After that, web3 will broadcast the transaction.

    zeroEx config

    testnet(kovan)

    {
      "networkId": 42,
      "gasLimit": 150000,
      "etherTokenContractAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
      "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
      "tokenTransferProxyContractAddress": "0x087Eed4Bc1ee3DE49BeFbd66C662B434B15d49d4"
    }
    

    mainnet

    {
      "networkId": 1,
      "gasLimit": 250000,
      "exchangeContractAddress": "0x12459c951127e0c374ff9105dda097662a027093",
      "etherTokenContractAddress": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
      "tokenTransferProxyContractAddress": "0x8da0d80f5007ef1e431dd2127178d224e32c2ef4"
    }
    
    1. The networkId is fixed as either test network and main network. When the gasLimit is insufficient, an internal gasLimit should be set for the transaction to avoid an out of gas error.
    2. etherTokenContractAddress is the 0x WETH Token contract address, exchangeContractAddress is the 0x exchange contract address, and tokenTransferProxyContractAddress is the 0x TokenTransferProxy contract address.

    For details see: 0xproject.com/docs/0xjs.

    gasPriceAdaptor

    Supportting fast, safeLow, average these three options.

    Will send a request to ethgasstation API to get the corresponding field, and process out gasPrice for onChain APIs

    onChain APIs

    tokenlon.deposit
    tokenlon.withdraw
    tokenlon.setAllowance
    tokenlon.setUnlimitedAllowance
    tokenlon.fillOrder
    tokenlon.fillOrKillOrder
    tokenlon.batchFillOrders
    tokenlon.batchFillOrKill
    tokenlon.fillOrdersUpTo
    tokenlon.cancelOrder
    tokenlon.batchCancelOrders
    
    tokenlon.zeroExWrapper.token.setAllowanceAsync
    tokenlon.zeroExWrapper.token.transferAsync
    tokenlon.zeroExWrapper.token.transferFromAsync
    tokenlon.zeroExWrapper.token.setUnlimitedAllowanceAsync
    tokenlon.zeroExWrapper.token.setProxyAllowanceAsync
    tokenlon.zeroExWrapper.token.setUnlimitedProxyAllowanceAsync
    tokenlon.zeroExWrapper.etherToken.depositAsync
    tokenlon.zeroExWrapper.etherToken.withdrawAsync
    tokenlon.zeroExWrapper.exchange.fillOrderAsync
    tokenlon.zeroExWrapper.exchange.cancelOrderAsync
    tokenlon.zeroExWrapper.exchange.fillOrKillOrderAsync
    tokenlon.zeroExWrapper.exchange.batchFillOrdersAsync
    tokenlon.zeroExWrapper.exchange.batchFillOrKillAsync
    tokenlon.zeroExWrapper.exchange.fillOrdersUpToAsync
    tokenlon.zeroExWrapper.exchange.batchCancelOrdersAsync
    

    onChainValidate

    Example

    const baseQuote = { base: 'SNT', quote: 'WETH' }
    const orders = [
      {
        side: 'BUY',
        price: 0.0002,
        amount: 10000,
      },
      {
        side: 'SELL',
        price: 0.00022,
        amount: 10000,
      },
      // ...
    ]
    

    onChainValidate = true

    for (let o of orders) {
      try {
        // If order is invalid, it will thorw error
        await tokenlon.placeOrder({
          ...baseQuote,
          ...o,
        })
      } catch (e) {}
    }
    

    onChainValidate = false

    const checkBalanceEnough = (price, side, balanceStack) => {
      const { baseBalance, quoteBalance } = balanceStack
      return side === 'BUY' ? quoteBalance >= price * amount : baseBalance >= amount
    }
    
    const baseBalance = await tokenlon.getTokenBalance(baseQuote.base)
    const quoteBalance = await tokenlon.getTokenBalance(baseQuote.quote)
    
    for (let o of orders) {
      // If the allowance and balance are exactly enough (Here only checked the balance)
      // we can avoid request balance and allowance again and again inside tokenlon.placeOrder
      if (checkBalanceEnough(o.price, o.side, { baseBalance, quoteBalance })) {
        await tokenlon.placeOrder({
          ...baseQuote,
          ...o,
        })
      }
    }
    
    

    Default value: true

    This method will do validations (of balance, allowance, fillable amount, cancelable amount) to avoid specific invalid operations when calling place, fill or cancel calls.

    However, during this process of verification, a lot of web3 requests are made. When network delay is serious and the web3 node is unstable, it will affect the efficiency of placing, filling or cancelling orders.

    Therefore, version v0.2 (and higher) provides the onChainValidate config, which is suitable for developers with high requirements regarding the efficiency of placing orders, filling orders, and cancelling orders.

    Includes the interface:

    1. tokenlon.utils.getSignedOrderBySimpleOrderAsync (Internal calls tokenlon.zeroExWrapper.exchange.validateOrderFillableOrThrowAsync)
    2. tokenlon.placeOrder (Internal calls tokenlon.utils.getSignedOrderBySimpleOrderAsync)
    3. tokenlon.fillOrder (Internal calls tokenlon.zeroExWrapper.exchange.validateFillOrderThrowIfInvalidAsync)
    4. tokenlon.fillOrKillOrder (Internal calls tokenlon.zeroExWrapper.exchange.validateFillOrKillOrderThrowIfInvalidAsync)
    5. tokenlon.batchFillOrders (Internal loop calls tokenlon.zeroExWrapper.exchange.validateFillOrderThrowIfInvalidAsync)
    6. tokenlon.batchFillOrKill (Internal loop calls tokenlon.zeroExWrapper.exchange.validateFillOrKillOrderThrowIfInvalidAsync)
    7. tokenlon.cancelOrder (Internal calls tokenlon.zeroExWrapper.exchange.validateCancelOrderThrowIfInvalidAsync)
    8. tokenlon.batchCancelOrders (Internal loop calls tokenlon.zeroExWrapper.exchange.validateCancelOrderThrowIfInvalidAsync)

    Initialization

    Configuration parameters: GlobalConfig.

    Initialization

    import { createTokenlon } from 'tokenlon-sdk'
    
    const config = {
      wallet,
      onChainValidate: true, // default is true
      gasPriceAdaptor: 'average',
      server: {
        url: serverUrl,
      },
      web3: {
        providerUrl,
      },
      zeroEx: zeroExConfig,
    }
    
    const run = async () => {
      const tokenlon = await createTokenlon(config)
      // do something
    }
    
    run()
    

    Features

    No need to deal with decimals

    Example call

    const balance = await tokenlon.getTokenBalance('ZRX')
    console.log(balance) // 10000
    

    When an Ethereum smart contract is called and the corresponding quantity is passed, the amount actually needs to be processed by the corresponding Token's decimal.

    The decimal value of ETH, for example, is 18. When you are transferring 1 ETH, the amount parameter passed on the chain is 1000000000000000000.

    Different Tokens may be have different decimals. Therefore, after getting the token information of both sides of the trading pair, it is still necessary to take the token's decimal and perform conversions for both, which increasing the complexity of a transfer.

    To simplify this process,Tokenlon-SDK provides a simple interface that encapsulates decimal processing for developers. When a developer calls the Tokenlon-SDK APIs, the passed parameters/returns are all amounts you actually want.

    In the example, 10,000 obtained is indeed 10,000 ZRX in the current wallet.

    Simple parameters

    0x order format

    {
      "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
      "maker": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
      "taker": "0x0000000000000000000000000000000000000000",
      "makerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "takerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
      "feeRecipient": "0x0000000000000000000000000000000000000000",
      "makerTokenAmount": "20000000000000000000",
      "takerTokenAmount": "22220000000000000",
      "makerFee": "0",
      "takerFee": "0",
      "expirationUnixTimestampSec": "1552032476",
      "salt": "43681724269174499411415138645444720680939661042486674370470466081321366610686",
      "ecSignature": {
          "v": 27,
          "r": "0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570",
          "s": "0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52"
      }
    }
    

    0x is a decentralized exchange protocol based on a model of makers and takers, see 0x protocol for details. However, the format of defining and transmitting orders rather hard to grasp for most people, especially new users.

    In this list, you first need to use makerTokenAddress and takerTokenAddress to identify the corresponding trading pair. Once the pair is identified, you then get the traded Tokens' decimal, to process makerTokenAmount and takerTokenAmount. Then process the price and according to buy or sell side decide whether to fill this order. Again, the fill amounts decimal need to be processed.

    Similarly, the placing of orders is a series of complicated reverse operations.

    Therefore, the Tokenlon API encapsulates this part of the operation within easy commands. Whether it is placing, filling orders or batch filling orders, you only ever need to use simple parameters within the interface. Just like on traditional exchanges.

    tokenlon place order parameters

    {
      "base": "SNT",
      "quote": "WETH",
      "amount": 20,
      "price": 0.001111,
      "side": "SELL"
    }
    

    tokenlon fill order parameters

    {
      "side": "BUY",
      "price": 0.00034,
      "amount": 0.01,
      "expirationUnixTimestampSec": 1551170972,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"10000000000000000\",\"takerTokenAmount\":\"3400000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1551170972\",\"salt\":\"15447773907054777000000000000000000000000000000000000000000000000000000000000\",\"ecSignature\":{\"v\":27,\"r\":\"0xc09abbc4b49cdf61c2f0dedf38ed8f618071f70d179280e389e2cb90a500892e\",\"s\":\"0x54a5a7a70253dd7e023ffab04183f8073a50bc8d9683fe37357cd0d89e38a04d\"}}"
    }
    

    Use privateKey to sign and send transactions

    For security reasons and potential misoperation, tools like metamask require the user to enter a password each time an user sends a transfer/contract call, unlock the private key, and then sign and broadcast transactions.

    A quantitative trading robot or automated trading program shouldn't be reminded to enter the password every time the privateKey needs to be signed.

    Therefore, the Tokenlon API partially encapsulates 0x.js and overwrites 0x.js. It is no longer needed to enter the password to unlock the privateKey; instead the privateKey is directly obtained by the developer in the configuration to sign and broadcast transactions.

    This makes an automated trading program built on 0x protocol become possible.

    Tokenlon

    Supported pairs and tokens

    tokenlon.getPairs

    Example call

    await tokenlon.getPairs()
    

    Example response

    [
      {
        "id": 458,
        "market": "Tokenlon",
        "base": {
            "symbol": "SNT",
            "contractAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
            "decimal": 18
        },
        "quote": {
            "symbol": "WETH",
            "contractAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
            "decimal": 18
        },
        "infoUrl": "",
        "tags": [
            "HOT"
        ],
        "relayFee": {
            "relayRecipient": "",
            "makerFee": "",
            "takerFee": ""
        },
        "instantExEnabled": true,
        "marketEnabled": true,
        "tradingEnabled": true,
        "anchored": false,
        "protocol": "0x",
        "rank": 101,
        "precision": 8,
        "quoteMinUnit": 0.0001
      }
      // ...
    ]
    

    Gets a list of all supported pairs on Tokenlon.

    Returns

    Result Type Description
    array Promsise<Pair.ExchangePair[]> pair list

    tokenlon.getPairInfo

    Example call

    await tokenlon.getPairInfo({ base: 'SNT', quote: 'WETH' })
    

    Example response

    {
      "id": 458,
      "market": "Tokenlon",
      "base": {
          "symbol": "SNT",
          "contractAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
          "decimal": 18
      },
      "quote": {
          "symbol": "WETH",
          "contractAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
          "decimal": 18
      },
      "infoUrl": "",
      "tags": [
          "HOT"
      ],
      "relayFee": {
          "relayRecipient": "",
          "makerFee": "",
          "takerFee": ""
      },
      "instantExEnabled": true,
      "marketEnabled": true,
      "tradingEnabled": true,
      "anchored": false,
      "protocol": "0x",
      "rank": 101,
      "precision": 8,
      "quoteMinUnit": 0.0001
    }
    

    A syntactic sugar of the tokenlon.getPairs interface, to fetch information of a token.

    Arguments

    Params Type Required Default Description
    baseQuote Tokenlon.BaseQuote true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Pair.ExchangePair> detailed information of a pair

    tokenlon.getTokenInfo

    Example call

    await tokenlon.getTokenInfo('SNT')
    

    Example response

    {
      "symbol": "SNT",
      "contractAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "decimal": 18
    }
    

    A syntactic sugar of the tokenlon.getPairs interface, to fetch information of a token.

    Arguments

    Params Type Required Default Description
    tokenName string true - tokenName must be capital letters

    Returns

    Result Type Description
    object Promise<Pair.ExchangePairToken> The detail information of a token

    ETH and WETH Token

    tokenlon.deposit

    await tokenlon.deposit(2)
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Deposits ETH into the Wrapped ETH smart contract and issues the equivalent number of wrapped ETH tokens to the depositor address. These wrapped ETH tokens can be used in 0x trades and are redeemable 1-to-1 for ETH.

    Arguments

    Params Type Required Default Description
    amount number true - unit amount
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    Example call

    tokenlon.withdraw

    Example call

    // 将2个WETH转换为2个ETH
    await tokenlon.withdraw(2)
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Withdraws ETH to the withdrawer's address from the wrapped ETH smart contract in exchange for the equivalent number of wrapped ETH tokens.

    Arguments

    Params Type Required Default Description
    amount number true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    Balance and allowance

    tokenlon.getTokenBalance

    Example call

    // get currently configured wallet's ETH balance
    await tokenlon.getTokenBalance('ETH')
    
    // get 0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36 wallet's WETH token balance
    await tokenlon.getTokenBalance('WETH', '0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36')
    

    Example response

    109.98084968041424
    

    Retrieves an owner's ETH / ERC20 token balance.

    Arguments

    Params Type Required Default Description
    tokenName string true - tokenName must be capital letters
    address string false config.wallet.address which wallet address

    Returns

    Result Type Description
    amount Promise<number> -

    tokenlon.getAllowance

    Example call

    // Get current wallet's amount of WETH that is approved to 0x proxy's address
    await tokenlon.getAllowance('WETH')
    
    // Get 0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36's amount of WETH that is approved to 0x proxy's address
    await tokenlon.getAllowance('SNT', '0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36')
    

    Example response

    5.78960446186581e+58
    

    Retrieves the owner's allowance in units set to the spender's address.

    Arguments

    Params Type Required Default Description
    tokenName string true - tokenName must be capital letters
    address string false current configured config.wallet.address which wallet address

    Returns

    Result Type Description
    amount Promise<number> -

    tokenlon.setAllowance

    Example call

    await tokenlon.setAllowance('WETH', 10)
    

    返回数据格式

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Sets the spender's allowance to a specified number of Units on behalf of the owner address. Equivalent to the ERC20 spec method approve.

    Arguments

    Params Type Required Default Description
    tokenName string true - tokenName must be capital letters
    amount number true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    tokenlon.setUnlimitedAllowance

    Example call

    await tokenlon.setUnlimitedAllowance('WETH')
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Sets the spender's allowance to an unlimited number of baseUnits(UNLIMITED_ALLOWANCE_IN_BASE_UNITSnew BigNumber(2).pow(256).minus(1)) on behalf of the owner address. Equivalent to the ERC20 spec method approve. Setting an unlimited allowance will lower the gas cost for filling orders involving tokens that forego updating allowances set to the max amount (e.g ZRX, WETH).

    Arguments

    Params Type Required Default Description
    tokenName string true - tokenName must be capital letters

    Returns

    Result Type Description
    object Promise<string> string is txHash

    Trade info

    tokenlon.getOrderBook

    Example call

    await tokenlon.getOrderBook({
      base: 'SNT',
      quote: 'WETH',
    })
    

    Example response

    {
      "asks": [
        {
          "side": "SELL",
          "price": 0.00034,
          "amount": 0.01,
          "amountTotal": 0.01,
          "isMaker": true,
          "expirationUnixTimestampSec": 1551170972,
          "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"10000000000000000\",\"takerTokenAmount\":\"3400000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1551170972\",\"salt\":\"15447773907054777000000000000000000000000000000000000000000000000000000000000\",\"ecSignature\":{\"v\":27,\"r\":\"0xc09abbc4b49cdf61c2f0dedf38ed8f618071f70d179280e389e2cb90a500892e\",\"s\":\"0x54a5a7a70253dd7e023ffab04183f8073a50bc8d9683fe37357cd0d89e38a04d\"}}"
        }
        // ...
      ],
      "bids": [
        {
          "side": "BUY",
          "price": 0.000255,
          "amount": 100,
          "amountTotal": 200,
          "isMaker": false,
          "expirationUnixTimestampSec": 1551342565,
          "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0x75eb52e0265b80d5eac78e714b85ea9e199013aa\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"takerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"25500000000000000\",\"takerTokenAmount\":\"100000000000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1551342565\",\"salt\":\"76669967321507220000000000000000000000000000000000000000000000000000000000000\",\"ecSignature\":{\"v\":27,\"r\":\"0x8afe8a8e4f7d18b65ae8e28ded6dcea22a80b7997b73d75d93b4b04a4dcca3e9\",\"s\":\"0x5abe9f4928b0b9ad1e46083c406adbfd9441897e39ab2eb82869653a39e2d5ab\"}}"
        }
        // ...
      ]
    }
    

    Fetches the order book by submitting base and quote token names. amount is the remaining amount that can be traded,amountTotal is the order original total base amount before any other operations.

    Arguments

    Params Type Required Default Description
    baseQuote Tokenlon.BaseQuote true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Tokenlon.OrderBookResult> isMaker shows whether this order is placed by the current wallet config.wallet

    tokenlon.getOrders

    Example call

    await tokenlon.getOrders({
      base: 'SNT',
      quote: 'WETH',
      page: 1,
      perpage: 20,
    })
    

    Example response

    [
      {
        "side": "BUY",
        "price": 0.001111,
        "amount": 20,
        "amountTotal": 100,
        "expirationUnixTimestampSec": 1552031755,
        "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"takerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"22220000000000000\",\"takerTokenAmount\":\"20000000000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552031755\",\"salt\":\"48847617304836587184218437964024195445423260754840613284444648760400900578804\",\"ecSignature\":{\"v\":28,\"r\":\"0xeafa23489bf35b57bc693fbf590c99dd4239722a2edfcc852653bae858ee987b\",\"s\":\"0x7d04686e0859ac1c6885da811302c863b2fd321dcacc45cda565c7b318865114\"}}"
      },
      {
        "side": "SELL",
        "price": 0.001111,
        "amount": 20,
        "amountTotal": 20,
        "expirationUnixTimestampSec": 1552032476,
        "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
      },
      ...
    ]
    

    Gets the currently configured wallet's placed orders through base, quote token names.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.GetOrdersParams true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Tokenlon.OrderBookItem[]> order list

    tokenlon.getOrder

    Example call

    await tokenlon.getOrder(rawOrder)
    

    Example response

    {
      "side": "BUY",
      "price": 0.001111,
      "amount": 90,
      "amountTotal": 200,
      "expirationUnixTimestampSec": 1552031755,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"takerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"22220000000000000\",\"takerTokenAmount\":\"20000000000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552031755\",\"salt\":\"48847617304836587184218437964024195445423260754840613284444648760400900578804\",\"ecSignature\":{\"v\":28,\"r\":\"0xeafa23489bf35b57bc693fbf590c99dd4239722a2edfcc852653bae858ee987b\",\"s\":\"0x7d04686e0859ac1c6885da811302c863b2fd321dcacc45cda565c7b318865114\"}}",
      "trades": [{
        "id": 8,
        "price": 0.00016421,
        "amount": 110.12356129346568,
        "timestamp": 1527057048,
        "txHash": "0xae6e54b9006d8f812ac18e804980d84605abf65c36aac7188e133c22db045171"
      }]
    }
    

    Gets order details and trade history (if available) by rawOrder.

    Arguments

    Params Type Required Default Description
    rawOrder string true - The rawOrder string

    Returns

    Result Type Description
    object Promise<Tokenlon.OrderDetail> The different between tokenlon.getOrders and this API, is that this response order has trades field

    tokenlon.getMakerTrades

    Example call

    const now = Math.floor(Date.now() / 1000)
    await tokenlon.getMakerTrades({
      base: 'SNT',
      quote: 'WETH',
      page: 1,
      perpage: 20,
      // Acquire transaction records for pending orders in the past year
      timeRange: [now - 365 * 86400, now]
    })
    

    Example response

    [
      {
        "id": 21555,
        "price": 0.00016421,
        "amount": 110.12356129346568,
        "tradeType": "bid",
        "side": "BUY",
        "timestamp": 1527056944,
        "amountRemaining": 70.7103761,
        "expirationUnixTimestampSec": "1527060545",
        "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"takerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"feeRecipient\":\"0x6f7ae872e995f98fcd2a7d3ba17b7ddfb884305f\",\"makerTokenAmount\":\"40053744052658000\",\"takerTokenAmount\":\"200278734200000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1527076156\",\"salt\":\"14369837435448330357568565681144815538872002803647102464670480132035762359371\",\"ecSignature\":{\"v\":28,\"r\":\"0x1a08f7e01676e039c80895f2265a3e1818cc8a0ab58281e6c5c0ac8d7c8977c2\",\"s\":\"0x746ad6346b4a426ecb623cc3aef8a23ac3335219799781ddeb21f163cd6c2a1d\"}}",
        "trades": [
          {
            "id": 8,
            "price": 0.00016421,
            "amount": 110.12356129346568,
            "timestamp": 1527057048,
            "txHash": "0xae6e54b9006d8f812ac18e804980d84605abf65c36aac7188e133c22db045171"
          }
        ]
      }
    ]
    

    Get the pending order of the current wallet by base and quote . timeRange represents an interval of time, an array, the first being the start timestamp, and the second being the end timestamp.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.TradesParams true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Tokenlon.MakerTradesItem[]> -

    tokenlon.getTakerTrades

    Example call

    const now = Math.floor(Date.now() / 1000)
    await tokenlon.getTakerTrades({
      base: 'SNT',
      quote: 'WETH',
      page: 1,
      perpage: 20,
      timeRange: [now - 365 * 86400, now]
    })
    

    Example response

    [
      {
        "id": 38,
        "price": 5000.2500125,
        "amount": 100.1393671,
        "tradeType": "ask",
        "side": "SELL",
        "timestamp": 1527075768,
        "amountRemaining": 0,
        "txHash": "0x2aa141defef4c279db1a03f84dfee077f175e21244d1b1f3388e4c112e700cff",
        "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"takerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"feeRecipient\":\"0x6f7ae872e995f98fcd2a7d3ba17b7ddfb884305f\",\"makerTokenAmount\":\"40053744052658000\",\"takerTokenAmount\":\"200278734200000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1527076156\",\"salt\":\"14369837435448330357568565681144815538872002803647102464670480132035762359371\",\"ecSignature\":{\"v\":28,\"r\":\"0x1a08f7e01676e039c80895f2265a3e1818cc8a0ab58281e6c5c0ac8d7c8977c2\",\"s\":\"0x746ad6346b4a426ecb623cc3aef8a23ac3335219799781ddeb21f163cd6c2a1d\"}}"
      }
    ]
    

    Gets the transaction record of the current wallet via base and quote . timeRange represents an interval of time, an array, the first being the start timestamp, and the second being the end timestamp.

    It should be noted that getMakerTrades is consistent with the getMakerTrades parameter, but the returned data structure is different.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.TradesParams true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Tokenlon.TakerTradesItem[]> -

    Place order

    tokenlon.placeOrder

    Example call

    await tokenlon.placeOrder({
      base: 'SNT',
      quote: 'WETH',
      amount: 20,
      price: 0.001111,
      side: 'BUY',
      expirationUnixTimestampSec: 1552032476,
    })
    

    Example response

    {
      "isMaker": true,
      "base": "SNT",
      "quote": "WETH",
      "amount": 20,
      "price": 0.001111,
      "side": "BUY",
      "expirationUnixTimestampSec": 1552032476,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
    }
    

    Use the current configured wallet to generate a 0x form order and send it to the imToken server by using the parameters of the class's traditional exchange order.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.SimpleOrderWithBaseQuote true - base, quote must be capital letters

    Returns

    Result Type Description
    object Promise<Tokenlon.OrderBookItem> placed order info

    Fill order

    Inside Tokenlon-SDK fill order APIs, smart contract calls, and the order and txHash will be sent to the imToken server. This portion of the order is marked in advance and the order will be not be returned, to reduce the incidence of competitions.

    After txHash is mined, the server will update the real order amount, and order status.

    tokenlon.fillOrder

    Example call

    await tokenlon.fillOrder({
      "side": "BUY",
      "base": "SNT",
      "quote": "WETH",
      "price": 0.001111,
      "amount": 20,
      "expirationUnixTimestampSec": 1552032476,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
    })
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Fills an order.

    It verifies whether the transaction's side, price, base and quote match the rawOrder.

    For example, if rawOrder represents a SELL order, then fillOrder needs to set side to BUY, to buy this SELL order.

    If the amount of fillOrder and rawOrder don't match, the final result will still be a rawOrder with the set price, and the quantity of the trade will simply be the remaining available amount that can be filled`.

    Take a look at the function at: 0x.js fillOrderAsync

    Arguments

    Params Type Required Default Description
    Params Tokenlon.FillOrderParams true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    tokenlon.batchFillOrders

    Example call

    await tokenlon.batchFillOrders([{
      "side": "BUY",
      "base": "SNT",
      "quote": "WETH",
      "price": 0.001111,
      "amount": 20,
      "expirationUnixTimestampSec": 1552032476,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
    }])
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Batch fill orders. The batched version of tokenlon.fillOrder, which batches fill orders in only one smart contract call txHash, suitable for situations where you want to fill multiple orders, while altogether increasing speed and reducing miner's fees.

    Take a look at the function at: 0x.js batchFillOrdersAsync

    Arguments

    Params Type Required Default Description
    Params Tokenlon.FillOrderParams[] true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    tokenlon.fillOrKillOrder

    Example call

    await tokenlon.fillOrKillOrder({
      "side": "BUY",
      "base": "SNT",
      "quote": "WETH",
      "price": 0.001111,
      "amount": 20,
      "expirationUnixTimestampSec": 1552032476,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
    })
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Same parameters and functions as tokenlon.fillOrder, with the difference, that it attempts to fill a specific amount of an order. If the entire amount specified cannot be filled, the fill order is abandoned.

    The applicable scenario is, for example, a list of only 1,000 tokenlon.fillOrder , but because of the price preference, if you use tokenlon.fillOrder , you are not sure what the final volume will be. And if the final transaction is only 100, its corresponding value earned may not be enough to consume the value of ETH miner's fees. Using tokenlon.fillOrKillOrder avoids this problem. If you want to trade 1,000 SNTs that cannot be satisfied, follow-up operations will not be performed.

    Take a look at the function at: 0x.js fillOrKillOrderAsync

    Arguments

    Params Type Required Default Description
    Params Tokenlon.FillOrderParams true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    tokenlon.batchFillOrKill

    Example call

    await tokenlon.batchFillOrKill([{
      "side": "BUY",
      "base": "SNT",
      "quote": "WETH",
      "price": 0.001111,
      "amount": 20,
      "expirationUnixTimestampSec": 1552032476,
      "rawOrder": "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}"
    }])
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    Batches tokenlon.fillOrKillOrder. Ends up with just one smart contract call txHash, altogether increasing speed and reducing miner fees. Order will either be atomically filled (each to the specified fillAmount) or aborted.

    Take a look at this function at: 0x.js batchFillOrKillAsync

    Arguments

    Params Type Required Default Description
    Params Tokenlon.FillOrderParams[] true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    tokenlon.fillOrdersUpTo

    Example call

    await tokenlon.fillOrdersUpTo({
      "side": "BUY",
      "base": "SNT",
      "quote": "WETH",
      "amount": 20,
      "rawOrders": [
        "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}",
        // ...
      ]
    })
    

    Example response

    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    

    For a series of rawOrders, sets an amount and starts filling orders until the quantity amount is satisfied. Similar to the market order function of a traditional centralized exchange.

    If amount is too large, and exceeds the quantity of these orders passed. The final deal is the sum of all the deals that can be traded.

    If amount is too small, orders will be issued in order, from order one, order two, and so on until the amount is satisfied. Taking into account the price, this interface will order these orders internally (pay price from high to low, sell order price from low to high), meet the corresponding quantity at the best price.

    Pay attention:

    rawOrders must be same side and same pair.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.FillOrdersUpTo true - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> string is txHash

    Cancel order

    tokenlon.cancelOrder

    Example call

    await tokenlon.cancelOrder(
      "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}",
      false
    )
    

    Example response

    // onChain = true
    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    
    // onChain = false
    "ok"
    

    Cancels an order.

    The parameter onChain indicates whether this order is cancelled via a smart contract transaction, thus, ensuring that the order will never be traded or a request to the imToken server.

    If onChain is set to true, the cancelOrder method sends a tx on the Ethereum blockchain (consuming miner fees) so that the 0x protocol's smart contract marks the order as cancelled. See 0x.js cancelOrderAsync for reference. In addition, the method calls tokenlon.server.cancelOrdersWithHash, passing the relevant txHash to the server for checking. If the txHash's transaction went through with the right amount, this order will be considered canceled.

    If onChain is set to false, it will not send an on-chain tx, but only use tokenlon.server.cancelOrders to send a cancellation request to the server. The relevant order will then no longer appear in the list of getOrderBook and token 2.0 orders. Besides, the opts paramater will not be processed any more.

    Recommend: Considering the miner fees (for onChain=true) and the fact that the order is actually not cancelled (for onChain=false) but only hidden (and therefore still trade-able), we recommended to place orders (via tokenlon.placeOrder) with timestamps to automatically expire, and aim to use the cancel API method as little as possible.

    Notice: The 0x protocol allows you to cancel a specific amount, say 10,000 SNT. If you for example cancel 1,000 SNT through the API, 9,000 SNT will remain for trading. However, for convenient development, tokenlon.cancelOrder doesn't include this parameters, but uniformly cancels all orders (excluding the transaction volume).

    Arguments

    Params Type Required Default Description
    schema string true - -
    onChain boolean false - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> onChain=true string is txHash; and onChain=false the string is 'ok'

    tokenlon.batchCancelOrders

    await tokenlon.batchCancelOrders([
      "{\"exchangeContractAddress\":\"0x90fe2af704b34e0224bf2299c838e04d4dcf1364\",\"maker\":\"0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36\",\"taker\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAddress\":\"0xf26085682797370769bbb4391a0ed05510d9029d\",\"takerTokenAddress\":\"0xd0a1e359811322d97991e03f863a0c30c2cf029c\",\"feeRecipient\":\"0x0000000000000000000000000000000000000000\",\"makerTokenAmount\":\"20000000000000000000\",\"takerTokenAmount\":\"22220000000000000\",\"makerFee\":\"0\",\"takerFee\":\"0\",\"expirationUnixTimestampSec\":\"1552032476\",\"salt\":\"43681724269174499411415138645444720680939661042486674370470466081321366610686\",\"ecSignature\":{\"v\":27,\"r\":\"0x85cd3b0768be4a283243de114d12686bd94d560909b7a5da145f4bf9af81d570\",\"s\":\"0x0dd82fc0aa7b8d90e855e814a18995ec326d35bb3b2c319eff03882139a78a52\"}}",
      // ...
    ], false)
    

    Example response

    // onChain = true
    "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea"
    
    // onChain = false
    "ok"
    

    Bulk withdrawals,tokenlon.cancelOrder, will eventually result in only one smart contract call txHash. Fill multiple orders, while altogether increasing speed and reducing miner's fees.

    onChain parameter is equal to the same parameter in tokenlon.cancelOrder.

    Arguments

    Params Type Required Default Description
    schemas string[] true - -
    onChain boolean false - -
    opts Tokenlon.TxOpts fasle - gasPrice is a number, and its gasPrice, gasLimit will be used to send transaction at the end.

    Returns

    Result Type Description
    object Promise<string> onChain=true string is txHash; and onChain=false the string is 'ok'

    Basics

    Utils

    The following auxiliary methods are mainly used in special scenarios, such as docking with other 0x-based exchanges, and arbitrage. The order forms of most other exchanges mostly maintain the 0x order format.

    Therefore, the methods provided here are mainly used to deal with the situation where the developer needs to handle the data structure on his own.

    tokenlon.utils.getSimpleOrderWithBaseQuote

    Example call

    tokenlon.getSimpleOrderWithBaseQuote({
      exchangeContractAddress: '0x90fe2af704b34e0224bf2299c838e04d4dcf1364',
      maker: '0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f',
      taker: '0x0000000000000000000000000000000000000000',
      makerTokenAddress: '0xf26085682797370769bbb4391a0ed05510d9029d',
      takerTokenAddress: '0xd0a1e359811322d97991e03f863a0c30c2cf029c',
      feeRecipient: '0x0000000000000000000000000000000000000000',
      makerTokenAmount: '10000000000000000',
      takerTokenAmount: '1940000000000',
      makerFee: '0',
      takerFee: '0',
      expirationUnixTimestampSec: '1549361646',
      salt: '42214642756128894000000000000000000000000000000000000000000000000000000000000',
      ecSignature: {
        v: 28,
        r: '0x60dcd418568f7fa56104fb6c9ac66eeb6443994a082eeebf8376ebd400430b78',
        s: '0x06dbdf8b6b92c93e96b79c5fafe70f3caff21b338efc1ad00ec7025120ea4841',
      },
    })
    

    Example response

    {
      "side": "SELL",
      "base": "SNT",
      "quote": "WETH",
      "amount": 0.01,
      "price": 0.000194,
      "expirationUnixTimestampSec": 1549361646,
    }
    

    Converted 0x order format to simple order format similar to traditional exchange.

    This 0x format order corresponding to other exchanges can be used as a more comprehensible method for determining whether or not to perform related operations.

    Arguments

    Params Type Required Default Description
    order DexOrderBNToString true - -

    Returns

    Result Type Description
    simpleOrderWithBaseQuote Tokenlon.SimpleOrderWithBaseQuote -

    tokenlon.utils.getSignedOrderBySimpleOrderAsync

    Example call

    await tokenlon.utils.getSignedOrderBySimpleOrderAsync({
      base: 'SNT',
      quote: 'WETH',
      amount: 20,
      price: 0.001111,
      side: 'BUY',
    })
    

    Example response

    {
      "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
      "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
      "taker": "0x0000000000000000000000000000000000000000",
      "makerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "takerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
      "feeRecipient": "0x0000000000000000000000000000000000000000",
      "makerTokenAmount": "10000000000000000",
      "takerTokenAmount": "1940000000000",
      "makerFee": "0",
      "takerFee": "0",
      "expirationUnixTimestampSec": "1549361646",
      "salt": "42214642756128894000000000000000000000000000000000000000000000000000000000000",
      "ecSignature": {
        "v": 28,
        "r": "0x60dcd418568f7fa56104fb6c9ac66eeb6443994a082eeebf8376ebd400430b78",
        "s": "0x06dbdf8b6b92c93e96b79c5fafe70f3caff21b338efc1ad00ec7025120ea4841"
      }
    }
    

    Convert traditional exchanges' order format to the 0x order format.

    Uses the interface ZeroEx.generatePseudoRandomSalt to generate salt and sign the processed order and salt via the purse privateKey configured to generate ecSignature.

    The tokenlon.placeOrder internally calls this method to place orders.

    After using this method, you get a 0x format order, which you can use with tokenlon.server.placeOrder to place an order to the imToken server. (The equivalent of these two steps is tokenlon.placeOrder). And you can place this order to other 0x based exchange too.

    Note : This utils method returns Promise.

    Arguments

    Params Type Required Default Description
    Params Tokenlon.SimpleOrderWithBaseQuote true - base, quote must be capital letters

    Returns

    Result Type Description
    simpleOrderWithBaseQuote Promise<DexOrderBNToString> -

    tokenlon.utils.orderBNToString

    Converts 0x format order's BigNumber field to string.

    Arguments

    Params Type Required Default Description
    Params Dex.SignedDexOrder true - base, quote must be capital letters

    Returns

    Result Type Description
    DexOrderBNToString DexOrderBNToString -

    tokenlon.utils.orderStringToBN

    Converts 0x format order's string field to BigNumber.

    Arguments

    Params Type Required Default Description
    Params DexOrderBNToString true - base, quote must be capital letters

    Returns

    Result Type Description
    Params Dex.SignedDexOrder true

    Wrapped zeroEx

    As mentioned in 'using a privateKey to sign and send transaction', in order to not enter a password, we encapsulate 0x.js in APIs for signing.

    If the developer has a deeper understanding of the 0x protocol and wants to make more advanced customizations, the Tokenlon APIs may not meet the corresponding requirements. Therefore, Tokenlon also provides basic methods that cover 0x.js. Developers can make selective calls depending on their own situation.

    The covered methods as follows:

    tokenlon.zeroExWrapper.token

    tokenlon.zeroExWrapper.token.setAllowanceAsync
    tokenlon.zeroExWrapper.token.transferAsync
    tokenlon.zeroExWrapper.token.transferFromAsync
    
    // Because these methods called this.setAllowanceAsync, so they are covered too.
    tokenlon.zeroExWrapper.token.setUnlimitedAllowanceAsync
    tokenlon.zeroExWrapper.token.setProxyAllowanceAsync
    tokenlon.zeroExWrapper.token.setUnlimitedProxyAllowanceAsync
    

    tokenlon.zeroExWrapper.etherToken

    tokenlon.zeroExWrapper.etherToken.depositAsync
    tokenlon.zeroExWrapper.etherToken.withdrawAsync
    

    tokenlon.zeroExWrapper.exchange

    tokenlon.zeroExWrapper.exchange.fillOrderAsync
    tokenlon.zeroExWrapper.exchange.cancelOrderAsync
    tokenlon.zeroExWrapper.exchange.fillOrKillOrderAsync
    tokenlon.zeroExWrapper.exchange.batchFillOrdersAsync
    tokenlon.zeroExWrapper.exchange.batchFillOrKillAsync
    tokenlon.zeroExWrapper.exchange.fillOrdersUpToAsync
    tokenlon.zeroExWrapper.exchange.batchCancelOrdersAsync
    

    The difference to note is, that these methods have a built-in private key to sign and broadcast transaction, that preserves the location and structure of the original API parameters, but ignores some non-essential parameters internally.

    For example, parameters shouldValidate, takerAddress remain, but will not be processed.

    The consideration in this respect is that the original 0x.js just does some verification with these two parameters. Tokenlon-SDK, in the initial configuration, sets onChainValidate. Besides, takerAddress sets the wallet address.

    Covering other than the above signature, 0x.js calls its internal assert.isSenderAddressAsync in multiple places to determine if it is current wallet that signs the broadcast transaction, and Tokenlon-SDK does not call its internal web3Wrapper to initiate the creation of web3 accounts, thus rewriting assert.isSenderAddressAsync and removing the web3Wrapper.isSenderAddressAvailableAsync(senderAddressHex) judgment.

    The effect of the overriding operation can be described as minimal.

    For other uncovered methods, developers can still use the form of 0x.js, and the API parameters and functions remain the same.

    The detail 0x.js API can see this 0x.js API

    Backend interface interaction

    Basic implementation of the back-end JSON RPC interface, part of the Tokenlon API. Developers can interact with other APIs to interact with other decentralized exchanges through the wrapped-0x API.

    Note: This part of the interface uses the 0x order form.

    For detailed description see imToken JSONRPC API (coming soon).

    Obtaining the JWT Token and bringing the JWT Token in the request header, has been built into each interface, so the developer does not need to consider this part.

    tokenlon.server.getPairList

    Example call

    await tokenlon.server.getPairList()
    

    Example response

    [
      {
        "id": 458,
        "market": "Tokenlon",
        "base": {
            "symbol": "SNT",
            "contractAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
            "decimal": 18
        },
        "quote": {
            "symbol": "WETH",
            "contractAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
            "decimal": 18
        },
        "infoUrl": "",
        "tags": [
            "HOT"
        ],
        "relayFee": {
            "relayRecipient": "",
            "makerFee": "",
            "takerFee": ""
        },
        "instantExEnabled": true,
        "marketEnabled": true,
        "tradingEnabled": true,
        "anchored": false,
        "protocol": "0x",
        "rank": 101,
        "precision": 8,
        "quoteMinUnit": 0.0001
      },
      // ...
    ]
    

    Returns

    Result Type Description
    array Promsise<Pair.ExchangePair[]> Pair list

    tokenlon.server.getOrderBook

    Example call

    await tokenlon.server.getOrderBook({
      baseTokenAddress: '0xf26085682797370769bbb4391a0ed05510d9029d',
      quoteTokenAddress: '0xd0a1e359811322d97991e03f863a0c30c2cf029c',
    })
    

    Example response

    {
      "bids": [
        {
          "orderId": 359828,
          "protocol": "0x",
          "rate": 0.000255,
          "amountRemaining": "0.00000000473965",
          "tradeType": "bid",
          "payload": {
            "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
            "maker": "0x75eb52e0265b80d5eac78e714b85ea9e199013aa",
            "taker": "0x0000000000000000000000000000000000000000",
            "makerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
            "takerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
            "feeRecipient": "0x0000000000000000000000000000000000000000",
            "makerTokenAmount": "25500000000000000",
            "takerTokenAmount": "100000000000000000000",
            "makerFee": "0",
            "takerFee": "0",
            "expirationUnixTimestampSec": "1551342565",
            "salt": "76669967321507220000000000000000000000000000000000000000000000000000000000000",
            "ecSignature": {
              "v": 27,
              "r": "0x8afe8a8e4f7d18b65ae8e28ded6dcea22a80b7997b73d75d93b4b04a4dcca3e9",
              "s": "0x5abe9f4928b0b9ad1e46083c406adbfd9441897e39ab2eb82869653a39e2d5ab"
            }
          }
        }
        // ...
      ],
      "asks": [
        {
          "orderId": 557090,
          "protocol": "0x",
          "rate": 0.00024984,
          "amountRemaining": "200.12808197",
          "tradeType": "ask",
          "payload": {
            "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
            "maker": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
            "taker": "0x0000000000000000000000000000000000000000",
            "makerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
            "takerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
            "feeRecipient": "0x0000000000000000000000000000000000000000",
            "makerTokenAmount": "200128081970000000000",
            "takerTokenAmount": "49999999999384800",
            "makerFee": "0",
            "takerFee": "0",
            "expirationUnixTimestampSec": "1522837661",
            "salt": "57928698160066632789044452941960007163066608846099684516946268760498144549884",
            "ecSignature": {
              "v": 28,
              "r": "0x3fff53fb44a1cacd022eb413b8f4534d07bdef80cf18c5049c4224de9970b026",
              "s": "0x2bd054d4b40435ab2ed45d5065d619ce442c7b6a512ce1351c145e63cffb4952"
            }
          }
        }
        // ...
      ]
    }
    

    Get the order list through baseTokenAddress, quoteTokenAddress and the corresponding contractAddressget.

    Arguments

    Params Type Required Default Description
    Params Server.GetOrderBookParams true - -

    Returns

    Result Type Description
    object Promsise<Server.OrderBookResult> -

    tokenlon.server.placeOrder

    Example call

    await tokenlon.server.placeOrder({
      "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
      "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
      "taker": "",
      "makerTokenAddress": "0x739e78d6bebbdf24105a5145fa04436589d1cbd9",
      "takerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "feeRecipient": "0x0000000000000000000000000000000000000000",
      "makerTokenAmount": "1000000000000000",
      "takerTokenAmount": "10000000000000000000",
      "makerFee": "0",
      "takerFee": "0",
      "expirationUnixTimestampSec": "1514539440",
      "salt": "99392977337186991769370078621467871065903823087405146848913118809902183766712",
      "ecSignature": {
        "v": 27,
        "r": "0x9e9e325635110ab6c7cbf44984959028c108f91c21495f5281e2d8a2bd59c658",
        "s": "0x1e3df4c2cd7719ca0a432a172da51be050b84100ecbe1c2686b4f266329a62e8"
      }
    })
    

    Example response

    "ok"
    

    Send 0x format orders to the imToken server.

    Arguments

    Params Type Required Default Description
    order DexOrderBNToString true - -

    Returns

    Result Type Description
    object Promsise<string> -

    tokenlon.server.fillOrder

    Example call

    await tokenlon.server.fillOrder({
      order: {
        "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
        "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
        "taker": "",
        "makerTokenAddress": "0x739e78d6bebbdf24105a5145fa04436589d1cbd9",
        "takerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
        "feeRecipient": "0x0000000000000000000000000000000000000000",
        "makerTokenAmount": "1000000000000000",
        "takerTokenAmount": "10000000000000000000",
        "makerFee": "0",
        "takerFee": "0",
        "expirationUnixTimestampSec": "1514539440",
        "salt": "99392977337186991769370078621467871065903823087405146848913118809902183766712",
        "ecSignature": {
          "v": 27,
          "r": "0x9e9e325635110ab6c7cbf44984959028c108f91c21495f5281e2d8a2bd59c658",
          "s": "0x1e3df4c2cd7719ca0a432a172da51be050b84100ecbe1c2686b4f266329a62e8"
        }
      },
      txHash: "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea",
      amount: "1000000000000000",
    })
    

    Example response

    "ok"
    

    Send a fill order request to imToken server, but getOrderBook won't return and display the imToken 2.0 order list.

    When the back-end queries, the transaction on the chain corresponding to the txHash, will update the latest order amount and order status.

    Notice:

    Parameter's amount needs to pass decimal.

    Arguments

    Params Type Required Default Description
    Params Server.FillOrderParams true - -

    Returns

    Result Type Description
    object Promsise<string> -

    tokenlon.server.batchFillOrders

    Example call

    await tokenlon.server.batchFillOrders({
      txHash: "0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea",
      orders: [
        {
          order: {
            "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
            "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
            "taker": "",
            "makerTokenAddress": "0x739e78d6bebbdf24105a5145fa04436589d1cbd9",
            "takerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
            "feeRecipient": "0x0000000000000000000000000000000000000000",
            "makerTokenAmount": "1000000000000000",
            "takerTokenAmount": "10000000000000000000",
            "makerFee": "0",
            "takerFee": "0",
            "expirationUnixTimestampSec": "1514539440",
            "salt": "99392977337186991769370078621467871065903823087405146848913118809902183766712",
            "ecSignature": {
              "v": 27,
              "r": "0x9e9e325635110ab6c7cbf44984959028c108f91c21495f5281e2d8a2bd59c658",
              "s": "0x1e3df4c2cd7719ca0a432a172da51be050b84100ecbe1c2686b4f266329a62e8"
            }
          },
          amount: "1000000000000000",
        }
      ]
      // ...
    })
    

    Example response

    "ok"
    

    Send a batch order request to the imToken server, but getOrderBook won't return and display the imToken 2.0 order list.

    When the back-end queries the txHash corresponding transaction on the chain, it will update the latest order availability amount and order status.

    Notice:

    Parameter's amount needs to pass decimal.

    Arguments

    Params Type Required Default Description
    Params Server.BatchFillOrdersParams true - -

    Returns

    Result Type Description
    object Promsise<string> -

    tokenlon.server.cancelOrders

    Example call

    const orderHashs = rawOrders.map(rawOrder => ZeroEx.getOrderHashHex(tokenlon.utils.orderStringToBN(JSON.parse(rawOrder))))
    await tokenlon.server.cancelOrders(orderHashs)
    

    Example response

    "ok"
    

    Sends a cancel order request to imToken server, but getOrderBook won't return and display the imToken 2.0 order list.

    Arguments

    Params Type Required Default Description
    orderHashs string[] true - -

    Returns

    Result Type Description
    object Promsise<string> -

    tokenlon.server.cancelOrdersWithHash

    Example call

    const cancerOrderItems = rawOrders.map(rawOrder => {
      return {
        orderHash: ZeroEx.getOrderHashHex(tokenlon.utils.orderStringToBN(JSON.parse(rawOrder))),
        txHash: '0x702767ddd0da65d58691d7157e12d379d8135d7e670183880d5877610d1aebea',
      }
    })
    await tokenlon.server.cancelOrdersWithHash(cancerOrderItems)
    

    Example response

    "ok"
    

    Sends an order cancellation request to the imToken server. The difference between tokenlon.server.cancelOrders and this method is, that this one needs txHash. If txHash is found, the server updates the order.

    Arguments

    Params Type Required Default Description
    orderHashs Server.CancelOrderItem[] true - -

    Returns

    Result Type Description
    object Promsise<string> -

    tokenlon.server.getOrders

    Example call

    const baseContractAddress = '0x7606bd550f467546212649a9c25623dfca88dcd7'
    const quoteContractAddress = '0xd0a1e359811322d97991e03f863a0c30c2cf029c'
    
    await tokenlon.server.getOrders({
      maker: '0xd7a0D7889577ef77C11Ab5CC00817D1c9adE6B36',
      tokenPair: [baseContractAddress, quoteContractAddress],
      page: 1,
      perpage: 20,
    })
    

    Example response

    [
      {
        "orderId": 558227,
        "protocol": "0x",
        "rate": 0.022152,
        "amountRemaining": "2.25713254",
        "tradeType": "bid",
        "payload": {
          "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
          "maker": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
          "taker": "0x0000000000000000000000000000000000000000",
          "makerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
          "takerTokenAddress": "0x7606bd550f467546212649a9c25623dfca88dcd7",
          "feeRecipient": "0x0000000000000000000000000000000000000000",
          "makerTokenAmount": "50000000026080000",
          "takerTokenAmount": "2257132540000000000",
          "makerFee": "0",
          "takerFee": "0",
          "expirationUnixTimestampSec": "1522846664",
          "salt": "4725486074876887493600134161853933784321096497136367356999342811313686135929",
          "ecSignature": {
            "v": 28,
            "r": "0xa7b9c69a81fcb86ae5e947c76ac76e788ebfe43f407c494f6c05f547a58f6eda",
            "s": "0x777ef39a414ddfe9bae5754c3668f52a64f97b07f0b2e10bc3cb0df524b08b92"
          }
        }
      }
    ]
    

    Get a list of current wallet orders.

    Arguments

    Params Type Required Default Description
    Params Server.GetOrdersParams true - -

    Returns

    Result Type Description
    object Promise<Server.OrderBookItem[]> placed order list

    tokenlon.server.getOrder

    Example call

    const orderHash = ZeroEx.getOrderHash(JSON.parse(rawOrder))
    
    await tokenlon.server.getOrder(orderHash)
    

    Example response

    {
      "orderId": 21555,
      "protocol": "0x",
      "rate": 0.00016421,
      "amountRemaining": "70.7103761",
      "tradeType": "bid",
      "onchainType": "expired",
      "payload": {
          "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
          "maker": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
          "taker": "0x0000000000000000000000000000000000000000",
          "makerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
          "takerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
          "feeRecipient": "0x6f7ae872e995f98fcd2a7d3ba17b7ddfb884305f",
          "makerTokenAmount": "180833937390000000000",
          "takerTokenAmount": "29694740858811900",
          "makerFee": "0",
          "takerFee": "0",
          "expirationUnixTimestampSec": "1527060545",
          "salt": "84381538164926307902569989902765324966525654257663591646793613516330182861192",
          "ecSignature": {
              "v": 28,
              "r": "0xb3df635d08f8e7024808aa64c4889f0e366053a4c13ef3467730a8e0efcb8159",
              "s": "0x4dda482ac979cc15f8dcc5deb9f32819af1c0ac8f38c38c28d992d4fa9046989"
          }
      },
      "trades": [
        {
          "id": 8,
          "price": 0.00016421,
          "amount": 110.12356129346568,
          "timestamp": 1527057048,
          "txHash": "0xae6e54b9006d8f812ac18e804980d84605abf65c36aac7188e133c22db045171"
        }
      ]
    }
    

    Get order detail info and its trades (if available ) by orderHash.

    Arguments

    Params Type Required Default Description
    orderHash string true - -

    Returns

    Result Type Description
    object Promise<Server.OrderDetail> The different between tokenlon.server.getOrders and this API, is that this response order has trades field

    tokenlon.server.getMakerTrades

    Example call

    const now = Math.floor(Date.now() / 1000)
    await tokenlon.getMakerTrades({
      "baseTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "quoteTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
      "page": 1,
      "perpage": 20,
      "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
      timeRange: [now - 365 * 86400, now]
    })
    

    Example response

    [
      {
        "id": 21555,
        "price": 0.00016421,
        "amount": 110.12356129346568,
        "tradeType": "bid",
        "timestamp": 1527056944,
        "amountRemaining": 70.7103761,
        "expirationUnixTimestampSec": "1527060545",
        "payload": {
          "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
          "maker": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
          "taker": "0x0000000000000000000000000000000000000000",
          "makerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
          "takerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
          "feeRecipient": "0x6f7ae872e995f98fcd2a7d3ba17b7ddfb884305f",
          "makerTokenAmount": "180833937390000000000",
          "takerTokenAmount": "29694740858811900",
          "makerFee": "0",
          "takerFee": "0",
          "expirationUnixTimestampSec": "1527060545",
          "salt": "84381538164926307902569989902765324966525654257663591646793613516330182861192",
          "ecSignature": {
            "v": 28,
            "r": "0xb3df635d08f8e7024808aa64c4889f0e366053a4c13ef3467730a8e0efcb8159",
            "s": "0x4dda482ac979cc15f8dcc5deb9f32819af1c0ac8f38c38c28d992d4fa9046989"
          }
        },
        "trades": [
          {
            "id": 8,
            "price": 0.00016421,
            "amount": 110.12356129346568,
            "timestamp": 1527057048,
            "txHash": "0xae6e54b9006d8f812ac18e804980d84605abf65c36aac7188e133c22db045171"
          }
        ]
      }
    ]
    

    Use baseTokenAddress, quoteTokenAddress to get a maker wallet's offers. timeRange represents the time interval as an array. The first item is the start time, the second item is the end time.

    tokenlon.getMakerTrades interface is based on this.

    Arguments

    Params Type Required Default Description
    Params Server.MakerTradesParams true - -

    Returns

    Result Type Description
    object Promise<Server.MakerTradesItem[]> -

    tokenlon.server.getTakerTrades

    Example call

    const now = Math.floor(Date.now() / 1000)
    await tokenlon.getTakerTrades({
      "baseTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
      "quoteTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
      "page": 1,
      "perpage": 20,
      "taker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
      timeRange: [now - 365 * 86400, now]
    })
    

    Example response

    [
      {
        "id": 38,
        "price": 5000.2500125,
        "amount": 100.1393671,
        "tradeType": "ask",
        "timestamp": 1527075768,
        "amountRemaining": 0,
        "txHash": "0x2aa141defef4c279db1a03f84dfee077f175e21244d1b1f3388e4c112e700cff",
        "payload": {
          "exchangeContractAddress": "0x90fe2af704b34e0224bf2299c838e04d4dcf1364",
          "maker": "0x20f0c6e79a763e1fe83de1fbf08279aa3953fb5f",
          "taker": "0x0000000000000000000000000000000000000000",
          "makerTokenAddress": "0xd0a1e359811322d97991e03f863a0c30c2cf029c",
          "takerTokenAddress": "0xf26085682797370769bbb4391a0ed05510d9029d",
          "feeRecipient": "0x6f7ae872e995f98fcd2a7d3ba17b7ddfb884305f",
          "makerTokenAmount": "40053744052658000",
          "takerTokenAmount": "200278734200000000000",
          "makerFee": "0",
          "takerFee": "0",
          "expirationUnixTimestampSec": "1527076156",
          "salt": "14369837435448330357568565681144815538872002803647102464670480132035762359371",
          "ecSignature": {
            "v": 28,
            "r": "0x1a08f7e01676e039c80895f2265a3e1818cc8a0ab58281e6c5c0ac8d7c8977c2",
            "s": "0x746ad6346b4a426ecb623cc3aef8a23ac3335219799781ddeb21f163cd6c2a1d"
          }
        }
      }
    ]
    

    Use baseTokenAddress, quoteTokenAddress to get a take wallet's offers. timeRange represents the time interval as an array. The first item is the start time, the second item is the end time.

    Attention: Note that the taker, maker parameters within tokenlon.server.getTakerTrades and tokenlon.server.getMakerTrades are not consistent and returns different data structure.

    Arguments

    Params Type Required Default Description
    Params Server.TakerTradesParams true - -

    Returns

    Result Type Description
    object Promise<Server.TakerTradesItem[]> -

    Others

    Types

    type Side

    type Side = 'BUY' | 'SELL'
    

    type Wallet

    type Wallet = {
      address: string
      privateKey: string;
    }
    

    type GasPriceAdaptor

    type GasPriceAdaptor = 'safeLow' | 'average' | 'fast'
    

    type GlobalConfig

    type GlobalConfig = {
      server: {
        url: string;
      }
      web3: {
        providerUrl: string;
      }
      wallet: Wallet
      onChainValidate?: boolean
      gasPriceAdaptor: GasPriceAdaptor
      zeroEx: {
        gasLimit: number
        networkId: number
        exchangeContractAddress: undefined | string
        etherTokenContractAddress: string
        tokenTransferProxyContractAddress: undefined | string
        zrxContractAddress?: undefined | string
        tokenRegistryContractAddress?: undefined | string
        orderWatcherConfig?: {
          cleanupJobIntervalMs: undefined | number
          eventPollingIntervalMs: undefined | number
          expirationMarginMs: undefined | number
          orderExpirationCheckingIntervalMs: undefined | number;
        };
      };
    }
    

    type SimpleOrder

    type SimpleOrder = {
      side: Side
      price: number
      amount: number
      expirationUnixTimestampSec?: number;
    }
    

    type DexOrderBNToString

    type DexOrderBNToString = {
      maker: string
      taker: string
      makerTokenAddress: string
      takerTokenAddress: string
      exchangeContractAddress: string
      expirationUnixTimestampSec: string
      feeRecipient: string
      makerFee: string
      makerTokenAmount: string
      takerFee: string
      takerTokenAmount: string
      salt: string
      ecSignature: ECSignature;
    }
    

    namespace Pair

    namespace Pair {
      type ExchangePairToken = {
        symbol: string
        logo: string
        contractAddress: string
        decimal: number;
      }
      type ExchangePair = {
        id: number | string
        market: string
        marketLogo?: string
        base: ExchangePairToken
        quote: ExchangePairToken
        tags: string[]
        rate?: number
        protocol: string
        addedTimestamp?: number
        index?: number
        infoUrl?: string
        price?: number
        change?: number
        anchored?: boolean
        precision: number
        rank?: number
        quoteMinUnit?: number
        marketUrl?: string;
      }
    }
    

    namespace Dex

    namespace Dex {
      type ECSignatureBuffer = {
        v: number
        r: Buffer
        s: Buffer;
      }
      type GetSimpleOrderParams = {
        amountRemaining?: string
        order: DexOrderBNToString
        pair: Pair.ExchangePair;
      }
      type GenerateDexOrderWithoutSaltParams = {
        simpleOrder: SimpleOrder
        pair: Pair.ExchangePair
        config: GlobalConfig;
      }
      type DexOrderWithoutSalt = {
        exchangeContractAddress: string,
        expirationUnixTimestampSec: BigNumber.BigNumber
        feeRecipient: string
        maker: string
        makerFee: BigNumber.BigNumber
        makerTokenAddress: string
        makerTokenAmount: BigNumber.BigNumber
        taker: string
        takerFee: BigNumber.BigNumber
        takerTokenAddress: string
        takerTokenAmount: BigNumber.BigNumber;
      }
      interface DexOrder extends DexOrderWithoutSalt {
        salt: BigNumber.BigNumber
      }
      interface SignedDexOrder extends DexOrder {
        ecSignature: ECSignature
      }
    
      interface TranslateOrderBookToSimpleParams {
        orderbookItems: Server.OrderBookItem[]
        pair: Pair.ExchangePair
        wallet?: {
          address: string;
        }
      }
    }
    

    namespace Server

    namespace Server {
      type Transformer = {
        (data: any): any;
      }
    
      type RequestParams = {
        [propName: string]: any;
      }
    
      type RequestConfig = {
        url: string
        method: string
        baseURL?: string
        transformRequest?: Transformer | Transformer[]
        transformResponse?: Transformer | Transformer[]
        headers?: any
        params?: any
        paramsSerializer?: (params: any) => string
        data?: any
        timeout?: number
        withCredentials?: boolean
        responseType?: string
        xsrfCookieName?: string
        xsrfHeaderName?: string
        onUploadProgress?: (progressEvent: any) => void
        onDownloadProgress?: (progressEvent: any) => void
        maxContentLength?: number
        validateStatus?: (status: number) => boolean;
      }
    
      type tradeType = 'ask' | 'bid'
    
      type GetTokenParams = {
        timestamp: number
        signature: string;
      }
    
      type GetOrderBookParams = {
        baseTokenAddress: string
        quoteTokenAddress: string;
      }
    
      type OrderBookItem = {
        rate: number
        tradeType?: tradeType
        amountRemaining: string
        payload: DexOrderBNToString;
      }
    
      type OrderBookResult = {
        bids: OrderBookItem[]
        asks: OrderBookItem[];
      }
    
      type CancelOrderItem = {
        orderHash: string
        txHash: string;
      }
    
      type FillOrderItem = {
        order: DexOrderBNToString
        amount: string;
      }
      interface FillOrderParams extends FillOrderItem {
        txHash: string
      }
    
      type BatchFillOrdersParams = {
        txHash: string
        orders: FillOrderItem[];
      }
    
      type GetOrdersParams = {
        maker: string
        page?: number
        perpage?: number
        tokenPair?: string[];
      }
    
      type GetTradesParams = {
        timeRange: number[]
        baseTokenAddress: string
        quoteTokenAddress: string
        page: number
        perpage: number;
      }
    
      interface MakerTradesParams extends GetTradesParams {
        maker: string
      }
    
      interface TakerTradesParams extends GetTradesParams {
        taker: string
      }
    
      type TradesDetailItem = {
        id: number
        price: number
        amount: number
        timestamp: number;
      }
    
      interface MakerTradesDetailItem extends TradesDetailItem {
        txHash: string
      }
    
      interface MakerTradesItem extends TradesDetailItem {
        tradeType: tradeType
        amountRemaining: number
        expirationUnixTimestampSec: string
        payload: DexOrderBNToString
        trades: MakerTradesDetailItem[]
      }
    
      interface TakerTradesItem extends TradesDetailItem {
        tradeType: tradeType
        payload: DexOrderBNToString
        txHash: string
      }
    
      interface OrderDetail extends OrderBookItem {
        trades: MakerTradesDetailItem[]
      }
    }
    

    namespace Tokenlon

    namespace Tokenlon {
      type makerTaker = {
        maker: string
        taker: string;
      }
    
      type BaseQuote = {
        base: string
        quote: string;
      }
    
      interface GetOrdersParams extends BaseQuote {
        page?: number
        perpage?: number
      }
    
      interface OrderBookItem extends SimpleOrder {
        amountTotal: number
        rawOrder: string
        isMaker: boolean
      }
    
      interface OrderBookResult {
        asks: OrderBookItem[]
        bids: OrderBookItem[]
      }
    
      interface SimpleOrderWithBaseQuote extends SimpleOrder {
        base: string
        quote: string
      }
    
      interface FillOrderParams extends SimpleOrderWithBaseQuote {
        rawOrder: string
        [propName: string]: any
      }
    
      interface TradesParams extends BaseQuote {
        page: number
        perpage: number
        timeRange?: [number, number]
      }
    
      interface MakerTradesItem {
        tradeType: Server.tradeType
        trades: Server.MakerTradesDetailItem[]
        amountRemaining: number
        expirationUnixTimestampSec: string
    
        side: Side
        rawOrder: string
      }
    
      interface TakerTradesItem {
        tradeType: Server.tradeType
        id: number
        price: number
        amount: number
        timestamp: number
        txHash: string
    
        side: Side
        rawOrder: string
      }
    
      interface OrderDetail extends OrderBookItem {
        trades: Server.MakerTradesDetailItem[]
      }
    
      interface FillOrdersUpTo {
        base: string
        quote: string
        side: string
        amount: number
        rawOrders: string[]
      }
    
      interface TxOpts {
        gasPrice?: number
        gasLimit?: number
      }
    }
    

    Errors

    Note:

    Tokenlon is based on 0x.js. 0x.js's built-in error types are listed on: ZeroExError

    enum TokenlonError {
      InvalidOrders = 'INVALID_ORDERS',
      UnsupportedPair = 'UNSUPPORTED_PAIR',
      UnsupportedToken = 'UNSUPPORTED_TOKEN',
      WalletDoseNotExist = 'WALLET_DOSE_NOT_EXIST',
      InvalidContractName = 'INVALID_CONTRACT_NAME',
      InvalidContractMethod = 'INVALID_CONTRACT_METHOD',
      InvalidSideWithOrder = 'INVALID_SIDE_WITH_ORDER',
      InvalidWalletPrivateKey = 'INVALID_WALLET_PRIVATE_KEY',
      InvalidGasPriceAdaptor = 'INVALID_GAS_PRICE_ADAPTOR',
      EthDoseNotHaveApprovedMethod = 'ETH_DOSE_NOT_HAVE_APPROVED_METHOD',
      InvalidPriceWithToBeFilledOrder = 'INVALID_PRICE_WITH_TO_BE_FILLED_ORDER',
      OrdersMustBeSamePairAndSameSideWithFillOrdersUpTo = 'ORDERS_MUST_BE_SAME_PAIR_AND_SAME_SIDE_WITH_FILLORDERSUPTO',
    }