NAV
Im token logo imToken API Documentation DApp-SDK Tokenlon-Onboarding Tokenlon-MMSK Tokenlon-MMProxy Tokenlon-JSSDK Tokenlon-Open-API
typescript
  • Introduction
  • Provider
  • detect imToken
  • callAPI
  • API
  • Wallet Connect
  • debug
  • multi-language support
  • deeplink
  • example
  • English

    Introduction

    This documentation aims to help developers of decentralized application (DApp) to leverage the imToken DApp SDK.

    In general, DApps need a host environment and the user's wallet to interact with. Just like for example Metamask, imToken is providing this environment within the imToken wallet app.

    The imToken DApp browser lets your DApp interact in even more complex ways, than for would be possible with other tools like Metamask.

    Provider

    imToken currently support Ethereum and EOS DApps.

    DApp browser has the compatibility of Metamask, your DApp should naturally work with imToken if it is compatible with Metamask as well.

    DApp browser also support Scatter, you can develop your EOS DApp with ScatterJS,and run inside imToken DApp browser.

    ⚠️ note: for ScatterJS, right now, we noly support `scatterjs-core` version <= 2.3.8.

    The interaction between DApp browser and DApp is base on EIP1102 ,DApp must implement EIP1102 to get user account and send transaction.

    ⚠️ DApp browser do not inject web3 into dapp page any more, we just inject a simple `provider`, DApp should enable it first to get full provider features:

    👉 You can also check the related documentation of metamask

    window.addEventListener("load", async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        window.web3 = new Web3(ethereum);
        try {
          // Request account access if needed
          await ethereum.enable();
          // Acccounts now exposed
          web3.eth.sendTransaction({
            /* ... */
          });
        } catch (error) {
          // User denied account access...
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        window.web3 = new Web3(web3.currentProvider);
        // Acccounts always exposed
        web3.eth.sendTransaction({
          /* ... */
        });
      }
    });
    

    detect imToken

    you can detect imToken browser by !!window.imToken or window.ethereum.isImToken, it returns true if current browser is imToken DApp browser.

    callAPI

    We provide a serie of methods that enhance the capacity of your DApp. Each method has an apiName. Please use as follows:

    imToken.callAPI(apiName, options, callback)

    Params Type Description
    apiName string name of the method which you want to invoke, you will see the available apiNames below
    options object options depend on the specific method
    callback function callback of method

    The callback function follows the style of NodeJS. The first param passed to the callback function is always an error object (if no error occurred, it is null), the error object always has a message property. The second param is the successful result returned by API call.

    callAPI

    imToken.callAPI(apiName, params, (error, result) => {
      if (error) {
        alert(error.message);
      } else {
        alert(result);
      }
    });
    

    Another way to call a method is by using callPromisifyAPI. This will do the same things as callAPI, and may be useful if you want to call the API with Promise style:

    callPromisifyAPI

    imToken
      .callPromisifyAPI(apiName, params)
      .then((result) => alert(result))
      .catch((error) => {
        alert(error.message);
      });
    

    API

    transaction

    web3.eth.sendTransaction

    About send transaction, Please read Web3 Documentation first.

    The most common operation of a DApp is to send a transaction, which has the method web3.eth.sendTransaction in web3.js. The DApp browser listens to this method being invoked by the DApp and displays relevant information to the user. Users then type in their password for approval, send the transaction and get the txHash if the transaction succeeded or an error if failed.

    error handle

    The DApp browser only handles a part of errors (such as a password error). Most transaction errors will be returned to the DApp itself. Therefore, DApps should always handle the error and display the message to users directly. imToken handles the i18n of the error message, which is why the DApp can simply use the alert message in most cases.

    gas

    We recommend that DApps should always set gas and gasPrice when sending transactions, because the DApp developer usually knows the accurate value. If you don't set a gas param, imToken uses web3.eth.estimateGas to estimate a value of gas.

    transaction.signTransaction

    signTransaction only signs the transaction, but doesn't send. It directly returns the signature.

    ⚠️ Deprecated: API has been removed in version 2.1.5.

    transaction.signTransaction

    var params = {
      to: "0x0fa38abec02bd4dbb87f189df50b674b9db0b468",
      from: web3.eth.defaultAccount,
      value: "1250000000000000",
      memo: "buy a cup of coffee",
      feeCustomizable: true,
    };
    
    imToken.callAPI("transaction.tokenPay", params, function (err, signature) {
      if (err) {
        alert(err.message);
      } else {
        alert(signature);
      }
    });
    

    get the current orientation state of APP,return 'LANDSCAPE' or 'PORTRAIT'

    navigator.getOrientation

    imToken.callAPI('navigator.getOrientation', function(err, result) {
      console.log(result)
    })
    

    set the orientation of APP,

    navigator.setOrientation, param is 'landscape' or 'portrait'

    imToken.callAPI('navigator.setOrientation', 'landscape')
    

    Close the current DApp window.

    navigator.closeDapp

    imToken.callAPI('navigator.closeDapp')
    

    Navigate to the previous history of the current webpage, like history.go(-1). If there is no previous record, the method closes the current DApp window.

    navigator.goBack

    imToken.callAPI('navigator.goBack')
    

    Configure navigation style,2.5.0 and above are avaliable.

    Property Meaning Option values Default value
    orientation Divice direction landscape/portrait portrait
    navigationStyle navigation style default/transparent default
    navigatorColor navigation background color Any color like you write in CSS white

    When navigationStyle was set transparent, navigatorColor won't take effect.

    To bring a better user experience, we suggest - Game DApps set navigationStyle transparent - Other DApps set navigation background color as your DApp's theme color

    navigator.configure

    imToken.callAPI('navigator.configure', {
      navigatorColor: '#008cd5',
    })
    

    Navigate to a special screen.

    navigator.routeTo

    imToken.callAPI('navigator.routeTo', {
      screen: 'DappView',
      passProps: {
        title: 'DApp API Examples',
        url: 'https://consenlabs.github.io/dapp-sdk-doc/index.html',
      },
    })
    

    native

    native.alert

    Displays a native alert dialog to show a message, like window.alert.

    Params Type Required Default Description
    message string true null message to show

    native.alert

    imToken.callAPI('native.alert', 'winner winner, chicken dinner!')
    

    native.toast

    Displays a native toast to show a message

    Params Type Required Default Description
    message string true null message content
    type string false info message type['info', 'warnning', 'success']
    align string false top ['top', 'center', 'bottom']
    model string false banner message UI['banner', 'alert']
    duration number false 1500 message duration

    native.toast

    imToken.callAPI('native.toast', {
      type: 'info',
      message: 'hello world',
      align: 'top',
      model: 'banner',
      duration: 1000 * 1,
    })
    

    native.confirm

    Displays a native confirm dialog, like window.confirm. If the user clicked the cancel button, an error will be returned to the callback function.

    Params Type Required Default Description
    title string true null dialog title
    message string true null dialog content
    cancelText string true null cancel button text
    confirmText string true null confirm button text

    native.confirm

    imToken.callAPI('native.confirm', {
      title: 'quick question',
      message: 'is Javascript the worst language?',
      cancelText: 'no',
      confirmText: 'yes',
    }, function(err, result) {
      if(err) {
        console.log('no')
      } else {
        console.log('yes')
      }
    })
    

    native.selectPicture

    Select a picture from library or take a photo. It will return image data in base64 (jpeg default).

    Params Type Required Default Description
    maxWidth number false null response will be corpped
    maxHeight number false null response will be corpped
    allowsEditing boolean false false enables built-in iOS functionality to resize the image after selection
    quality number false 1 quality of image, range of value is 0 to 1

    response:

    property Type Description
    data string base64 data, default prefix 'data:image/jpeg;base64,'
    width number image width
    height number image height
    fileSize number file size (b)

    native.selectPicture

    imToken.callAPI('native.selectPicture',{
      maxWidth: 400,
      maxHeight: 200
    }, function (err, ret) {
      if(err) {
        alert(err.message)
      } else {
        document.getElementById('imgContainer').src = ret.data
      }
    })
    

    native.setClipboard

    Sets a text to the user's clipboard.

    Params Type Required Default Description
    text string true null text to set

    native.setClipboard

    imToken.callAPI('native.setClipboard', 'are you ok?')
    

    native.share

    Opens the native share component.

    Params Type Required Default Description
    title string true null title
    message string true null content
    url string true null link. If you want to share an image, set url to base64 data

    native.share

    imToken.callAPI('native.share', {
        title: 'dapp example',
        message: 'this is example of dapp sdk',
        url: location.href,
      }, function (err, ret) {
        if(err) {
          alert(err.message)
        } else {
          alert('share success!')
        }
      })
    

    native.scanQRCode

    Opens a scanner to scan a QRCode. Returns string content of the QRCode.

    native.scanQRCode

    imToken.callAPI('native.scanQRCode', function (err, text) {
        if(err) {
          alert(err.message)
        } else {
          alert(text)
        }
      })
    

    user

    user.showAccountSwitch

    Open a wallet selector modal. Returns a wallet address.

    If user cancels, it will return an error with message 'User canceled operation'

    user.showAccountSwitch

    imToken.callAPI('user.showAccountSwitch', { chainType: null }, function(err, address){
      if(err) {
        alert(err.message)
      } else {
        alert(address)
      }
    })
    

    it will display a wallets selector on the user's device, after the user selected, it returns the selected wallet address.

    if you only want to display bitcoin wallet addresses in the wallet selector, you can change the chainType value from null to 'BITCOIN'.

    device

    device.getCurrentLanguage

    Gets the user's current language setting. If your DApp should support multiple languages, this information may be useful, but we have added the locale parameter to the DApp's url. In most cases you do not need to call this API.

    Available locale:

    device.getCurrentLanguage

    imToken.callAPI('device.getCurrentLanguage', function(err, language) {
      if(err) {
        alert(err)
      } else {
        alert(language)
      }
    })
    

    device.getCurrentCurrency

    Gets the user's current currency setting.

    Available currencies:

    device.getCurrentCurrency

    imToken.callAPI('device.getCurrentCurrency', function(err, currency) {
      if(err) {
        alert(err)
      } else {
        alert(currency)
      }
    })
    

    others

    wallet_addEthereumChain

    An API for adding Ethereum chains to wallet applications. This API is similar to the official interface of ethereum, you can also refer ethereum EIP 3085 for more information.

    ⚠️ Note: API only works on versions higher than 2.8.4.

    Property Meaning Option values Default value
    chainId a 0x-prefixed hexadecimal string string null
    chainName a human-readable name for the chain string null
    nativeCurrency the native currency of the chain NativeCurrency {}
      nativeCurrency.name nativeCurrency fields string null
      nativeCurrency.symbol nativeCurrency fields string null
      nativeCurrency.decimals nativeCurrency fields number null
    rpcUrls one or more URLs pointing to RPC endpoints string[] []
    blockExplorerUrls one or more URLs pointing to block explorer web sites for the chain string[] []

    wallet_addEthereumChain

    type EthereumChain = {
      chainId: string;
      chainName: string;
      nativeCurrency: {
        name: string;
        symbol: string; // 2-6 characters long
        decimals: number; // 18
      };
      rpcUrls: string[];
      blockExplorerUrls?: string[];
    };
    const chain: EthereumChain = {
      chainId: "0x64",
      chainName: "xDAI Chain",
      rpcUrls: ["https://dai.poa.network"],
      iconUrls: [
        "https://xdaichain.com/fake/example/url/xdai.svg",
        "https://xdaichain.com/fake/example/url/xdai.png",
      ],
      nativeCurrency: {
        name: "xDAI",
        symbol: "xDAI",
        decimals: 18,
      },
    };
    
    window.ethereum.request({
      method: "wallet_addEthereumChain",
      params: [chain],
    });
    

    error code

    error code Description
    1001 user canceled the operation

    Wallet Connect

    <img src="https://walletconnect.org/static/banner-08401b4515705be60764f906ed1f3845.png" /

    The DApp Browser mentioned earlier is that DApp runs in the browser of imToken wallet. if DApp runs in PC, Native APP or system browser, You need to use Wallet Connect to connect with imToken.

    ImToken version 2.5.8 has implemented the support of wallet connect, so that users can connect The DApp in PC browser and imToken wallet by scanning qrcode, and use DApp in PC browser by imToken.

    The mobile DApp that implements Wallet Connect can also call imToken via deeplink to complete the signature.

    For the development document of Wallet Connect, please refer to the official document https://docs.walletconnect.org/quick-start/dapps .

    If you want to accurately invoke the imToken wallet through deeplink, you need to add imtokenv2://wc?uri=prefix, for example:

    imtokenv2://wc?uri=wc:00e46b69-d0cc-4b3e-b6a2-cee442f97188@1?bridge=https%3A%2F%2Fbridge.walletconnect.org&key=91303dedf64285cbbaf9120f6e9d160a5c8aa3deb67017a3874cd272323f48ae
    

    debug

    You can add an param url ___debug to your DApp url (like: https://ens.token.im/?___debug=1), it will inject an console panel into your page,you can find a vConsole button in the bottom right corner of page, it will open a panel after click (like chrome developer panel).

    multi-language support

    When user open a DApp, we set the accept-language http request header of the url request, the value is depend on imToken APP language, such as:

    Accept-Language: zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,*;q=0.6

    We recommend you detect this value first, otherwise you can detect language form url, we will and a locale params to it (like : https://ens.token.im/?locale=en-US)

    deeplink

    Open a DApp page via deeplink.

    imtokenv2://navigate?screen=DappView&url=https://token.im
    

    encodeURIComponent is required for queryString parameter following navigate.

    example

    You can find the API example here. Feel free to test the examples within your imToken App.