Build a dApp

1
Last updated 26 days ago

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

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.

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 a faucet.

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

  1. Head to Node.js and install node.

  2. If you're on Mac, you can install Node using Brew.

$ /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 web application.

Clone the Repository

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

dApp Setup

1. Install Dependencies

Install the required dependencies with NPM or Yarn.

$ npm install
$ yarn 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 or Yarn.

$ npm start
$ yarn start

About 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.

// 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.

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.

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.

This is the underlying code to proceed with 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.

This is the underlying code to proceed with the market order:

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