Build your own crypto-trading platform in 15 days

Samyak Jain
Easwap
Published in
6 min readJul 26, 2018

You might have seen many trading platforms like — IDEX, Waves, Radar Relay, Kyber Swap etc. Ever wonder making one yourself? Well, then this article is for you.

In this article, I’ll give you every basic information to build your own trading platform within 15 days, of course, the design will be yours.

We will use the Kyber Network’s Liquidity Network to build a Dapp on their smart contract. I’m a big fan of Kyber Network because:

  • It’s really easy to integrate and their documentation is very easy to understand.
  • They have by far the best liquidity for onchain swapping.
  • I’ll provide much of the code for it. You just have to understand and copy paste it.
  • I haven’t learned how to integrate DEX (other than Kyber Network) and probably I won’t :P

Requirements:-

  • You must know a little bit about Front End Engineering.
  • You need to be a Dapp developer (If you’re not, it will not take more than 5 days to learn basics of it). Mostly, you must be aware of the Web3 library.
  • Briefly, go through the documentation of kyber network’s — this & this.
  • Always feel free to shoot me a message on the telegram.

Before we begin, let’s have a look at what I have developed within a month.

Easiest way to swap your ERC20 tokens. Go on try it out at easwap.com. I tried to make it as easy as possible. Just a one pager dapp with an easy to swap UX.

Okay! Dive in.

(I’m assuming you know the basics of Dapp.)

In case you don’t know the basics I prefer you to do this course. This is where I started learning the development side of ethereum.

As I said I’ll give very basic information.

Step-1:-

Add this Web3 CDN to get connected to ethereum blockchain.

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

Step-2:-

Check web3, Metamask and process related to that. (Metamask is browser extension which helps in interaction with ETH blockchain. At the time of writing this article, I saw this tweet on metamask. Give it a look).

// Check if web3 is defined or not
if (typeof web3 !== 'undefined') {
// Define web3
var web3 = new Web3(web3.currentProvider);
// check if metamask is installed or not
if (web3.currentProvider.isMetaMask === true) {
// if installed check if it's on main-net and logged in
web3.version.getNetwork((err, netId) => {
// if account is not defined means not logged-in
var account = web3.eth.accounts[0];
// if account not defined means not logged-in
if (account) {
// if netId = 1 then main-net
if (netId == 1) {
// main net
} else {
// not main-net
}
} else {
// not logged-in
}
});
} else {
// metamask not installed
}
}

Step-3:-

ABI’s of ERC20 and kyber contract function and events.

  • Get ERC20 ABI from here. (contains balanceOf, allowance, approve functions and approval event)
  • Get kyber contract ABI from here. (contains enabled, getExpectedRate, trade, maxGasPrice functions and ExecuteTrade event)

Step-4:-

Connect kyber ABI with kyber contract address to read and write functions and listen to events. we’re not connecting ERC20 contract addresses now because defining every address in needless unless you are using some functions like:- “balanceOf” to show all coins quantity.

var mainKyberAdd = ‘0x818E6FECD516Ecc3849DAf6845e3EC868087B755’;var kyberContract = web3.eth.contract(kyberMainABI).at(mainKyberAdd)

Step-4.1(optional):-

This enabled function returns value in boolean. if the callback is false that means the platform is not live currently probably cause they’re upgrading something.

I kept this optional because it rarely happens the platform is not live and even if it’s not live any transaction user do will get reverted. So no one will lose anything.

kyberContract.enabled(function (err, res) {
if (!err) {
if (!res) {
// kyber contract under construction
}
} else {
// error occured while reading function
};
});

Step-5:-

API of kyber network to get tokens details.

https://tracker.kyber.network/api/tokens/pairs

In kyber network, they have eliminated the work of convert ETH to wrapped ETH, so wherever you need to enter the token address and if the token is ETH then we have to use the address below:-

var ethAdd = “0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee”
  • API to get current gas price details. Limit of gas price in kyber trade function is 50 GWEI. So if the gas price is more than 50 GWEI set it to 50 GWEI else transaction will get reverted.
  • After getting gas price store it in a variable say gasToTrade because we’re going to need in at the time of the trade.
https://ethgasstation.info/json/ethgasAPI.jsonvar gasToTrade;

Step-6:-

To get the quantity of ETH of user’s account.

  • account (user’s eth address)
web3.eth.getBalance(account, function (err, res) {
if (!err) {
ethQtyInWei = res;
} else {
console.log(err);
};
});

Connect tokens ABI with token contract address to read and write functions.

  • the balanceOf function is to get the user’s token qty.
  • tokensAbi is already defined in step-3.
  • coinAddress (particular token address)
  • account (user’s eth address)
var coinContract = web3.eth.contract(tokensAbi).at(coinAddress);
coinContract.balanceOf(account, function (err, res) {
if (!err) {
var coinQty = String(res);
} else {
// error getting balance
};
});

Step-7:-

This function will give the expected rate of two coins that the user is going to swap.

  • oneNum is one token converted to it’s lowest unit. Like:- eth=10¹⁸ Wei, dgx=10⁹ (10 to the power of no of decimals of the token).
  • maxRateInWei is maxed qty of token which can get in swapping.
  • slippageRateInWei is min qty user will accept in case of sudden changes. (it is 97% of maxTwoRateInWei).
  • We are going to use maxTwoRateInWei and slippageRateInWei at the time of trading in the end.
kyberContract.getExpectedRate(coinOneAdd, coinTwoAdd, oneNum, function (err, res) {
if (!err) {
maxRateInWei = String(res[0]);
slippageRateInWei = String(res[1]);
} else {
console.log(err);
};
});

step-8:- (I’m assuming you know the basic information of ERC20 functions)

  • Checking ERC20 allowance on kyber address before trading.
  • if already allowed then go directly for trading else approve.
  • if not then run approve function for allowance.
  1. mainKyberAdd (Address which you’re giving allowance in our case it’ll be same as the address in step-4).
  2. allowanceAmount (maximum it could be “2²⁵⁶-1”. I prefer keeping it “2²⁵⁵”. So that user don’t have to allow it again ever).
  3. srcAmount (Quantity of token which user is going to swap).

See the below code here for better understanding.

coinContract.allowance(account, mainKyberAdd, function (err, res) {
if (!err) {
if (String(res) < srcAmount) {
coinContract.approve(mainKyberAdd, allowanceAmount, function (err, res) {
if (!err) {
// start trading
} else {
console.log(err);
};
})
} else {
// start trade function from kyber contract
}
} else {
console.log(err);
};
})

Step-8.1:-(optional)

To get information if approve is completed or not. Use Approval event.

coinContract.Approval({}, 'latest').watch(function (err, event) {
if (!err) {
console.log(event);
}
});

Step-9:-

Finally, trade.

  • src (address of token which user is going to swap).
  • srcAmount (Quantity of token which user is going to swap).
  • dest (address of token which user is going to get).
  • account (user’s address).
  • maxRateInWei & slippageRateInWei(rate we are getting in step-7).
  • walletId (this will be ‘0’ unless you’re part of Kyber’s fee-sharing program).
  • setGasPrice (Maximum gas price that can be set is 50 GWEI if it’s more than 50 GWEI then the transaction will get reverted, so you have to check it by calling API in step-5.1 in case if the price is more than 50 GWEI, set it 50GWEI).
  • gasToTrade (we’ve defined it in step-5).
var setGasPrice = {gasPrice: gasToTrade}
mainKyberContract.trade(src, srcAmount, dest, account, maxRateInWei, slippageRateInWei, walletId, setGasPrice, function (err, res) {
if (!err) {
// transaction successful
} else {
console.log(err);
};
});

Step-9.1:-(optional)

You can get the maximum gas price by calling this function.

mainKyberContract.maxGasPrice(function (err, res) {
if (!err) {
var maxGasPrice = String(res);
} else {
console.log(err);
};
});

Step-9.2:- (optional)

To get information if the trade is completed or not. Use ExecuteTrade event.

mainKyberContract.ExecuteTrade({}, 'latest').watch(function (err, event) {
if (!err) {
console.log(event);
}
});

Yay!! you created your own trading platform. Easy huh!!

let me know if something is missing.

Get connected for updates on Easwap:- twitter and telegram

--

--

Samyak Jain
Easwap
Editor for

Co-founder InstaDApp, MakerScan Alerts and Buidling Easwap. ETHSF and ETHINDIA finalists