NAV
Im token logo imToken API Documentation DApp-SDK Tokenlon-Onboarding Tokenlon-MMSK Tokenlon-MMProxy Tokenlon-JSSDK Tokenlon-Open-API
  • Introduction
  • Install JS SDK
  • Set up the JS SDK
  • Market API
  • Tokenlon Data API
  • Tokenlon Trade API
  • Tokenlon Chain API
  • Errors
  • English

    Introduction

    Welcome to the Tokenlon-jsSDK. This document is the only one about the Tokenlon-Jssdk. Updated features should be reflected in the documentation.

    Tokenlon JavaScript SDK (JS SDK) is a set of trading tools developed using JavaScript. You can use the tool to directly connect to the Tokenlon trading API and start trading on Tokenlon programmatically.

    With this document, you will know how to access the services provided by Tokenlon via the JS SDK. For example, get a quote for ETH and fill an order.

    Install JS SDK

    This section contains instructions for installing the JS SDK.

    System Requirements

    Download

    Please download JS SDK latest version manually.

    Check

    After downloading, please check whether the downloaded zip file sha256 is consistent with the latest version (shasum -a 256 /path/to/ file) to ensure that the file is the original version.

    Install dependencies

    After checking, unzip the downloaded zip file, and move the unzipped tokenlon-jssdk folder to your project ’s file directory, and enter the tokenlon-jssdk file directory through the terminal cd YOUR_RELATIVE_PATH/tokenlon-jssdk

    After reaching the file directory, install the dependent packages by yarn install

    Set up the JS SDK

    This section contains instructions for setting up the JS SDK.

    Initialization

    Go back to your project directory and create a JavaScript test file test.js

    cd your_project_path /tokenlon-jssdk && touch test.js

    Copy the following initial code to the test.js file.

    const JssdkClient = require('YOUR_RELATIVE_PATH/tokenlon-jssdk').default
    const { genPersonalSign, genSignRawTransaction } = JssdkClient
    // If you are using TypeScipt, please replace the upper two lines with the below line
    // import JssdkClient, { genPersonalSign, genSignRawTransaction } from 'YOUR_RELATIVE_PATH/tokenlon-jssdk'
    
    const personalSignFn = genPersonalSign('YOUR PRIVATE KEY')
    const signRawTransactionFn = genSignRawTransaction('YOUR PRIVATE KEY')
    
    const jssdkClient = JssdkClient({
      debug: false,
      address: 'YOUR ADDRESS',
      providerUrl: 'PROVIDER URL',
      personalSignFn,
      signRawTransactionFn,
    })
    

    Configure

    In the initial code, you could modify the attributes according to your needs and fill in the information required for trading through the API.

    debug

    Turn on or off the debug mode, the default is false. Note that if set to true, the JS SDK will access the test environment of Tokenlon. Accordingly, providerUrl also needs to be set to the kovan node address.

    address

    Your address to trade

    providerUrl

    Link to your Ethereum node. If you don't have one, you could apply through https://infura.io/.

    personalSignFn

    personalSignFn method accept message as parameter, and need to return the signed string

    signRawTransactionFn

    signRawTransactionFn method accept a parameter and its structure is interface SignRawTransactionFnParams, and it need to return the signed string, and you should notice that the signed string can be used to broadcast transaction by using eth_sendRawtransaction.

    parameter interface

    interface SignRawTransactionFnParams {
      to: string
      data: string
      from: string
      nonce: string
      gasLimit: string
      gasPrice: string
      value: string
    }
    

    parameter example

    {
      to: '0xdd974d5c2e2928dea5f71b9825b8b646686bd200',
      data:
       '0x095ea7b300000000000000000000000041f8d14c9475444f30a80431c68cf24dc9a8369a0000000000000000000000000000000000000000000000056bc75e2d63100000',
      from: '0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36',
      nonce: '0x9bd',
      gasLimit: '0x186a0',
      gasPrice: '0x12a05f200',
      value: '0x0',
    }
    

    the returned signed string example

    '0xf8ac8209c085012a05f200830186a094dd974d5c2e2928dea5f71b9825b8b646686bd20080b844095ea7b300000000000000000000000041f8d14c9475444f30a80431c68cf24dc9a8369affffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1ba0035b6dc663577dbe878aaaef80721ca5855226227fb9c835f6e4366365ff23e0a071ebc0e28c4f59298ed3d2c41da6de97b7e948a9a2a23f1fc8833d9dadc78fc2'
    

    More info

    About the implementations of personalSignFn and signRawTransactionFn:

    1. Experienced developers can refer to gen.ts to implement their own
    2. Or developers can also use this two methods genPersonalSign ('YOUR PRIVATE KEY'), genSignRawTransaction ('YOUR PRIVATE KEY') provided by tokenlon-jssdk for convenient generation.
    3. Teams or individuals with higher security requirements can use KMS for wallet management    - GCP KMS: https://cloud.google.com/kms    - AWS KMS: https://amazonaws-china.com/kms    - Cosmos KMS: https://github.com/tendermint/kms

    Market API

    This interface is the JavaScript implementation of the Tokenlon Open API. For detailed API documentation check the Tokenlon Open API documentation

    getPairs

    example call

    const pairs = await jssdkClient.getPairs()
    console.log('pairs', pairs)
    

    example result

    [
      "ELF_ETH",
      "ETH_TUSD",
      "ETH_USDT",
      "KNC_ETH",
      "MANA_ETH",
      "OMG_ETH",
      "OMG_USDT",
      "SNT_ETH",
      "TUSD_USDT",
      "USDC_ETH",
      "USDC_TUSD",
      "USDC_USDT",
      "ZRX_ETH",
      "ZRX_USDT"
    ]
    

    getTicker

    example call

    const ticker = await jssdkClient.getTicker({
      pairs: 'ETH_USDT',
      period: '1M',
    })
    console.log('ticker', JSON.stringify(ticker, null, 2))
    

    example result

    {
      "timestamp": 1579593604,
      "period": "1M",
      "pairs": "ETH_USDT",
      "lastTimestamp": 1579228568,
      "last": 165.35,
      "high": 167.2000379,
      "low": 143.29,
      "ask": 166.6300080649,
      "mid": 166.5550040324,
      "bid": 166.48,
      "vol": 21.19617002,
      "txs": 67,
      "wallet": 10,
      "change": 0.0226
    }
    

    Must use the response of getPairs API as pairs parameter.

    getTickerHistory

    example call

    const tickerHistory = await jssdkClient.getTickerHistory({
      pairs: 'KNC_ETH',
      beginTimestamp: now - 86400 * 30,
      endTimestamp: now,
    })
    console.log('tickerHistory', JSON.stringify(tickerHistory, null, 2))
    

    example result

    [
      {
        "date": "2020-01-16",
        "period": "24H",
        "pairs": "KNC_ETH",
        "last": 0.001557100002,
        "high": 0.00168504,
        "low": 0.00126427,
        "vol": 359.91195154,
        "txs": 14,
        "wallet": 5
      },
      // ...
    ]
    

    getTradeCap

    example call

    const tradeCap = await jssdkClient.getTradeCap({
      currency: 'USD',
      period: '24H',
    })
    console.log('tradeCap', JSON.stringify(tradeCap, null, 2))
    

    example result

    {
      "timestamp": 1579593345,
      "period": "24H",
      "vol": 12.6222969804,
      "txs": 6,
      "wallet": 2,
      "currency": "USD"
    }
    

    getTradeCapHistory

    example call

    const tradeCapHistory = await jssdkClient.getTradeCapHistory({
      currency: 'USD',
      beginTimestamp: now - 86400 * 7,
      endTimestamp: now,
    })
    console.log('tradeCapHistory', JSON.stringify(tradeCapHistory, null, 2))
    

    example result

    [
      {
        "date": "2020-01-21",
        "period": "24H",
        "vol": 12.6222969804,
        "txs": 6,
        "wallet": 2,
        "currency": "USD"
      },
      // ...
    ]
    

    Tokenlon Data API

    getTokens

    example call

    const tokens = await jssdkClient.getTokens()
    console.log('tokens', JSON.stringify(tokens, null, 2))
    

    example result

    [
      {
        "symbol": "ETH",
        "contractAddress": "0x0000000000000000000000000000000000000000",
        "decimal": 18,
        "precision": 4,
        "minTradeAmount": 1e-7,
        "maxTradeAmount": 10,
        "opposites": [
          "KNC",
          "USDT"
        ]
      },
      // ...
    ]
    

    Parameter

    none

    Return Token Item

    Name Type Description
    symbol String
    contractAddress String
    decimal Number
    precision Number
    minTradeAmount Number The default minimum tradable amount of the system
    maxTradeAmount Number The default minimum tradable amount of the system
    opposites String[] Supported Token Symbol

    getOrderState

    example call

    const orderState = await jssdkClient.getOrderState('0x21755702165de6d55dbab44eeb92d3d4a31a8182ee315c50f86c5db790fdd4fd')
    

    example result

    {
      "status": "success",
      "order": {
        "from": "0x974afc6906cdeb17f163b7a5a2d2a59aa488b94e",
        "to": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
        "fromToken": {
          "symbol": "KNC",
          "contractAddress": "0x25570c5f2058efc52ff34e47631f41b5f6595d42",
          "decimal": 18,
          "precision": 4,
          "minTradeAmount": 1e-7,
          "maxTradeAmount": 50000
        },
        "toToken": {
          "symbol": "ETH",
          "contractAddress": "0x0000000000000000000000000000000000000000",
          "decimal": 18,
          "precision": 4,
          "minTradeAmount": 1e-7,
          "maxTradeAmount": 10
        },
        "fromTokenAmountUnit": "0.01",
        "toTokenAmountUnit": "0.00001452",
        "executeTxHash": "0x21755702165de6d55dbab44eeb92d3d4a31a8182ee315c50f86c5db790fdd4fd",
        "txHash": "0xd8054f86c9f76eec3304f99ebcb1c68ef71eb99b8854d4f5d2d729e038af8bd4",
        "status": "success",
        "blockNumber": 15867119,
        "timestamp": 1578020919,
        "finishedTimestamp": 1578020931,
        "feeFactor": 30,
        "feeTokenSymbol": "ETH",
        "feeTokenAmountUnit": "0.00000004356",
        "actualTokenSymbol": "ETH",
        "actualTokenUnit": "0.00001447644"
      }
    }
    

    Parameter

    The executeTxHash field of the trade order,see trade API for details

    Return Order

    Name Type Description
    from String
    to String
    fromToken Object user's outgoing Token, for details see above
    toToken Object user's incoming Token, for details see above
    fromTokenAmountUnit String user's outgoing Token amount
    toTokenAmountUnit String user's projected incoming Token amount (excluding service fee)
    executeTxHash String Unique identifier obtained after order transaction
    txHash String the order's on-chain txHash
    status String order status, see below
    blockNumber Number block height at the time the order was mined
    timestamp Number time when the transaction was submitted to the system
    finishedTimestamp Number time of the final completion of the transaction
    feeFactor Number fee 30 means 30/10000=0.3% (a rate of 3/1000)
    feeTokenSymbol String Token symbol of the service fee
    feeTokenAmountUnit String amount of the service fee
    actualTokenSymbol String actual name of Token received
    actualTokenUnit String actual Token amount received by user (including fee)

    status of the order:

    status description
    unbroadcast order hasn't been broadcasted to the chain by the worker yet
    pending order is being packaged
    success order already mined on-chain
    failed order failed on-chain
    timeout order timeout on-chain
    invalid order invalid
    abandoned order not accepted yet

    getOrdersHistory

    example call

    const ordersHistory = await jssdkClient.getOrdersHistory({
      page: 1,
      perpage: 10,
    })
    console.log('ordersHistory', JSON.stringify(ordersHistory, null, 2))
    

    example result

    [
      {
        "from": "0x974afc6906cdeb17f163b7a5a2d2a59aa488b94e",
        "to": "0xd7a0d7889577ef77c11ab5cc00817d1c9ade6b36",
        "fromToken": {
          "symbol": "KNC",
          "logo": "https://aws-v2-cdn.token.im/app-mainnet-production/exchange-pairs/kyber.png",
          "contractAddress": "0x25570c5f2058efc52ff34e47631f41b5f6595d42",
          "decimal": 18,
          "precision": 4,
          "minTradeAmount": 1e-7,
          "maxTradeAmount": 50000
        },
        "toToken": {
          "symbol": "ETH",
          "logo": "https://v2-cdn.token.im/app-mainnet-production/tokens/icons/eth%403x.png",
          "contractAddress": "0x0000000000000000000000000000000000000000",
          "decimal": 18,
          "precision": 4,
          "minTradeAmount": 1e-7,
          "maxTradeAmount": 10
        },
        "fromTokenAmountUnit": "8.14157458",
        "toTokenAmountUnit": "0.011",
        "executeTxHash": "0xd0271b7f7202f7f7a4968745b7f2e1456f23591e5567948e7edc226c831d34fa",
        "txHash": "0x2f516d0eab28d460197bf188964d5058a8d25e1823a2e4676b2c0e028a8245ba",
        "status": "success",
        "blockNumber": 16258131,
        "timestamp": 1579589963,
        "finishedTimestamp": 1579589975,
        "feeFactor": 30,
        "feeTokenSymbol": "ETH",
        "feeTokenAmountUnit": "0.000033",
        "actualTokenSymbol": "ETH",
        "actualTokenUnit": "0.010967"
      },
      // ...
    ]
    

    Parameter

    Name Type Description
    page Number
    perpage Number

    Return

    order[],order array. with array items same as order above.

    Tokenlon Trade API

    getQuote

    example call

    const quoteResult = await jssdkClient.getQuote({
      base: 'ETH',
      quote: 'KNC',
      side: 'BUY',
      amount: 0.011,
    })
    

    example result

    {
      base: 'ETH',
      quote: 'KNC',
      side: 'BUY',
      amount: 0.12,
      quoteAmount: 39.792548182,
      quoteId: '3--TD-200303-100712-VHMpwdH',
      price: 331.60456818333336,
      feeSymbol: 'ETH',
      feeAmount: 0.0024,
      transferTokenSymbol: 'KNC',
      transferTokenAmount: 39.792548182,
      receiveTokenSymbol: 'ETH',
      receiveTokenAmount: 0.1176,
      priceExcludeFee: 338.37200835034014,
      timestamp: 1583230034,
      minAmount: 0.000309419,
      maxAmount: 4.5127910248,
    }
    

    Parameter

    Name Type Description
    base String
    quote String
    side String 'BUY' or 'SELL'
    amount Number always refers to base Token amount

    More info:

    1. base is base currency in a trading pair, quote is quote currency in a trading pair. like ETH/USDT, base is ETH, quote is USDT
    2. Examples
      1. the price of ETH/USDT pair and with side BUY param, maybe 250 (1ETH = 250 USDT), represent if you want to buy 1 ETH, you need pay 250 USDT
      2. the price of ETH/USDT pair and with side SELL param, maybe 200 (1ETH = 200 USDT), represent if you want to sell 1 ETH, you may only got 200 USDT
    3. Because of that Tokenlon is a RFQ mode, you can't find display content about side BUY or SELL in our web or APP pages. But it is hidden within APIs. So, we support trading pairs which looks like USDT/ETH too(We suggest that you need not to process these abnormal trading pairs, you only need to follow trading pairs which is normal and easy to handle).
      1. The price of USDT/ETH side BUY may be 0.005 (1 USDT = 0.005 ETH), which means that buying one USDT requires 0.005ETH; that is, buying 200 USDT requires 1 ETH; equivalent to selling one 1ETH, you can get 200 USDT; Price equivalent to ETH/USDT SELL is 200 (1ETH = 200 USDT)
      2. The price of USDT/ETH side SELL may be 0.004 (1 USDT = 0.004 ETH), which means that if you sell one USDT, you can get 0.004 ETH; that is, if you sell 250 USDT, you can get 1 ETH; it is equivalent to buying one 1 ETH, requires 250USDT; the price equivalent to ETH/USDT BUY is 250 (1ETH = 250 USDT)
    4. How does base/quote, side correspond to our Tokenlon UI?
      1. ETH -> USDT. When the user enters the amount of ETH, it means that the user wants to sell ETH. The corresponding relationship at this time is {base: 'ETH', quote: 'USDT', side: 'SELL', amount: inputAmount }
      2. ETH -> USDT. When the user enters the amount of USDT, it means that the user wants to buy USDT. The corresponding relationship at this time is {base: 'USDT', quote: 'ETH', side: 'BUY', amount: inputAmount}
      3. USDT -> ETH. When the user enters the amount of ETH, it means that the user wants to purchase ETH. The corresponding relationship at this time is {base: 'ETH', quote: 'USDT', side: 'BUY', amount: inputAmount}
      4. USDT -> ETH. When the user enters the USDT amount, it means that the user wants to sell USDT. The corresponding relationship at this time is {base: 'USDT', quote: 'ETH', side: 'SELL', amount: inputAmount }

    Return

    Name Type Description
    base String
    quote String
    side String 'BUY' or 'SELL'
    amount Number always refers to base Token amount
    quoteAmount Number corresponding quote Token amount
    quoteId String the unique identifier before order is submitted, used for trade API
    price Number quoteAmount / baseAmount = price
    feeSymbol String fee asset symbol
    feeAmount Number the amount of the fee
    transferTokenSymbol String the symbol of the transfered out token
    transferTokenAmount Number the amount of the transfered out token
    receiveTokenSymbol String the symbol of the received token
    receiveTokenAmount Number the amount of the received token
    priceExcludeFee Number the price that exclude fee amount
    timestamp Number order return time. please note that the order needs to be within 10s for the trade to be valid
    minAmount Number The minimum amount that base token can be traded and it is returned by the market maker
    maxAmount Number The maximum amount that base token can be traded and it is returned by the market maker

    trade

    example call

    const tradeResult = await jssdkClient.trade(quoteResult.quoteId)
    

    example result

    {
      "success": true,
      "message": null,
      "txHash": null,
      "executeTxHash": "0x140e519ffb81ce2bf23a55ba213b12193e0547d880637c909fafb4e13005ced8"
    }
    

    Parameter

    quoteId,returns for getQuote API

    Return

    Name Type Description
    success Boolean
    message String error message
    txHash String only when the user trades the order and outgoing token is ETH this returns a value; when the outgoing token is erc20 token, this returns null, because of the transaction will be broadcasted by tokenlon system after a while
    executeTxHash String Unique identifier returned after the order transaction is submitted

    More info:

    1. Only when the user trades the order and outgoing token is ETH that need user to pay gas
    2. gasPrice is automatically adapted according to the value of the order
    3. Considering the timeliness and accuracy of order transactions, the configuration of gasPrice is not supported currently.
    4. When the user trades the order and outgoing token is erc20 token, the transaction will be broadcasted by tokenlon system, and also the gas is paied by tokenlon system.

    Tokenlon Chain API

    getBalance

    example call

    const balance = await jssdkClient.getBalance('ETH')
    

    example result

    4.06410224837175
    

    Parameter

    Token Symbol String

    Return

    Token Balance Number

    getBalances

    example call

    const balances = await jssdkClient.getBalances()
    

    example result

    [
      {
        "symbol": "ETH",
        "balance": 4.06410224837175
      },
      {
        "symbol": "KNC",
        "balance": 965.450009029981
      },
      {
        "symbol": "USDT",
        "balance": 0.848815
      }
    ]
    

    getAllowance

    example call

    const allowance = await jssdkClient.getAllowance('KNC')
    

    example result

    1.157920892373162e+59
    

    Parameter

    Token Symbol String

    Return

    This Token's authorized amount

    isAllowanceEnough

    example call

    const allowance = await jssdkClient.isAllowanceEnough('KNC')
    

    example result

    true
    

    Parameter

    Token Symbol String

    Return

    Whether the Token's authorized amount exceeds the balance

    setAllowance

    example call

    const allowanceTx = await jssdkClient.setAllowance('KNC', 100)
    

    example result

    '0xb6c02a4d7f137762196934f761a671807ac2c94fc46d8f99a0f19668f7f3e7c3'
    

    Parameter

    Token Symbol String and desired authorized amount

    Return

    The authorized trade's txHash

    setUnlimitedAllowance

    example call

    const unlimitedAllowanceTx = await jssdkClient.setUnlimitedAllowance('KNC')
    

    example result

    '0x36a6f49af84309a7c878a4e266c00e8f69eea81c8b20f3a9c0d322de56adf8cb'
    

    Parameter

    Token Symbol String

    Return

    The txHash of setting the unlimited allowance

    closeAllowance

    example call

    const closeAllowanceTx = await jssdkClient.closeAllowance('KNC')
    

    example result

    '0x36a6f49af84309a7c878a4e266c11e8f69eea81c8b20f3a9c0d322de56adf8cb'
    

    Parameter

    Token Symbol String

    Return

    The txHash of closing the authorization

    Errors

    Name Description
    UNSUPPORTED_TRADE_PAIR not supported trading pair
    REQUEST_5S_TIMEOUT order request exceeded 5s no return
    LESS_THAN_SYSTEM_MIN_TRADE_AMOUNT less than the minimum Token trade amount
    GREATER_THAN_SYSTEM_MAX_TRADE_AMOUNT more than the maximum Token trade amount
    LESS_THAN_MM_MIN_TRADE_AMOUNT smaller than the market maker's minimum Token trade amount
    GREATER_THAN_MM_MAX_TRADE_AMOUNT greater than the market maker's maximum Token trade amount
    CAN_NOT_RESOLVE_EXCHANGE trade currently not supported
    NO_DATA_RESPONSED no order data returned
    INVALID_QUOTE_ID_PARAM quoteId parameter error
    QUOTE_DATA_10S_EXPIRED order with corresponding quoteId exceeded 10s
    PARAMS_ERROR parameter error
    TOKEN_NOT_FOUND Token not supported
    NONCE_CONFLICT conflicting nonce
    CONNECT_FAILED connection failed
    ALREADY_CONNETING already connected
    BALANCE_NOT_ENOUGH insufficient balance
    ALLOWANCE_NOT_ENOUGH insufficient authorized amount
    SIGNATURE_FAILED Counterparty order signature error
    SANITY_FAILED Counterparty price is unreasonable
    BALANCE_FAILED Counterparty balance is insufficient
    PERMIT_CHECK_FAILED The wallet is prohibited from trading. Please contact bd@tokenlon.im or WeChat(tokenlonsupport)
    ESCAPE_DEALT_ORDER Your order failed. To avoid failing again, please a period of time before trading again. If you have any questions, please contact bd@tokenlon.im or the official WeChat account tokenlonsupport
    LONG_TIME_HOLD The wallet is prohibited from trading. Please contact bd@tokenlon.im or WeChat(tokenlonsupport)
    FROM_UPBIT The wallet is prohibited from trading. Please contact bd@tokenlon.im or WeChat(tokenlonsupport)
    SLP_FAILED Counterparty price is abnormal