RADAR RELAY V2

We’ve updated to 0x V2.See what changed.

Building a dApp (in 500 lines or less)

This tutorial walks you through using the SDK in a frontend webapp.

Prerequisites

1

A Browser Wallet

A browser wallet, such as MetaMask, is required for dApp development. The browser wallet will hold your funds and communicate with the Ethereum network.

MetaMask URL

https://metamask.io
2

Kovan Testnet Tokens

Testnet Ether and tokens allow you to test the dApp's functionality without spending real money. Kovan ETH and tokens can be requested from our faucet.

Faucet URL

https://faucet.kovan.network/
3

Node.js

The easiest way to install the dependencies for the example dApp is to download Node.js and use npm. Npm is installed with Node.js. (version 8 - LTS release recommended).

Installing Node.JS with Homebrew

$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

$ brew install node

4

The Radar Relay dApp Example

The Radar Relay dApp example is a Github repository that integrates the Radar Relay SDK in a frontend webapp.

View The Repository On Github

Clone the Repository on Github

$ git clone https://github.com/RadarRelay/sdk-dapp-example.git

dApp Setup

1

Install dependencies

Install the required dependencies with npm.

Install Dependencies

$ npm install
2

Unlock Your Browser Wallet

Ensure that your browser wallet is unlocked. This allows the dApp to fetch your Ethereum address.

3

Run the dApp

Run the dApp via NPM.

Run the dApp

$ npm start

The dApp

1

SDK Initialization

Setup SDK
Use the SdkManager to setup the SDK. This will instantiate the RadarRelay class and setup for the initialization lifecycle.

Add Event Listeners (Optional)
If you would like to perform an action during wallet / SDK initialization, you can listen for various initialization events.

In this example, we'll listen for the AccountInitialized event. This will allow us to update the UI without waiting for the rest of the SDK initialization to complete. Learn More About SDK Events

Initialize Injected Wallet
Call initialize to hook up the wallet, set the web3 provider, and spin up the classes necessary to begin trading.


SDK Initialization


  // Setup the SDK
  const rr = await SdkManager.Setup({
    type: InjectedWalletType.Metmask,
    sdkInitializationTimeoutMs: 30000
  });

  // Listen for account initialization
  rr.events.on(EventName.AccountInitialized, async () => {
    // Update balances
    await updateTokensAndTableAsync();

    // Update the active address in the UI
    watchActiveAddress();
  });

  // Initialize the SDK
  await SdkManager.InitializeAsync(rr);
2

Fetching Balances & Allowances

Once initialized, the dApp will fetch balances and allowances for any tokens in your wallet that are supported by Radar Relay.

Fetching Balances & Allowances


  export async function getAllTokenBalancesAndAllowancesAsync() {
    const tokenData = {};
    const total = rr.tokens.size;

    // Get ETH balance
    const ethBalance = await rr.account.getEthBalanceAsync();
    tokenData['ETH'] = {
      balance: ethBalance.toNumber()
    };

    // Get all token balances
    return new Promise(async resolve => {
      let current = 0;
      rr.tokens.forEach(async token => {
        const balance = await rr.account.getTokenBalanceAsync(token.address);
        if (balance.greaterThan(0)) {
          // Token has balance. Check the allowance
          const allowance = await rr.account.getTokenAllowanceAsync(token.address);
          tokenData[token.symbol] = {
            address: token.address,
            balance: balance.toNumber(),
            allowance: allowance.greaterThan(balance) ? true : false
          }
        }
        current += 1;
        if (current >= total) {
          resolve(tokenData);
        }
      });
    });
  }
3

Toggling Token Allowances

A token allowance must be set in order to trade over the 0x smart contracts. The dApp example will toggle token allowances between 0 and 2^256 (unlimited).

The awaitTransactionMined: true argument tells the code to wait for the transaction to be mined and return the transaction receipt before continuing.

Toggling Token Allowances


  if (noAllowanceSet) {
    // No allowance is set. Set to unlimited
    await rr.account.setUnlimitedTokenAllowanceAsync(name, {
      awaitTransactionMined: true
    });
  } else {
    // An allowance is set. Set to 0
    await rr.account.setTokenAllowanceAsync(name, new BigNumber(0), {
      awaitTransactionMined: true
    });
  }
4

Wrapping ETH

In order for ETH to be tradable with other tokens it must first be converted to Wrapped ETH, or WETH. Clicking the wrap button next to ETH will allow you to input an amount to wrap.

Wrapping ETH


  await rr.account.wrapEthAsync(new BigNumber(amountToWrap), {
    awaitTransactionMined: true
  });
5

Execute a Market Order

Use the base and quote token dropdowns to select a book, enter a base token amount, and press "Exchange" to execute a market order.

Execute a Market Order


  const txReceipt = await market.marketOrderAsync(orderType, new BigNumber(baseTokenAmount), {
    awaitTransactionMined: true
  });
SDK

View SDK Documentation