Building a de-centralised crypto exchange

Victor Yeo
3 min readJul 10, 2021

--

In this article, i describe the ways to create a prototype of de-centralised crypto exchange using Ethereum blockchain, solidity (smart contracts), nodeJS (backend) and ReactJS (frontend).

In this prototype of de-centralised crypto exchange (DEX), there will be a token contract and a swap contract. The token contract is used to create an ERC20 token. The swap contract is used to buy the tokens with ethers, and sell the tokens for getting back the ethers.

The smart contracts can be deployed with “truffle migrate” or “truffle deploy”. In this example, we use nodeJS web3 code to deploy the smart contract. Firstly, we deploy the token contract. Secondly, we pass the address of the token contract to the constructor of swap contract, and then deploy the swap contract. After that, we transfer the total token supply to the swap contract (to fund the swap contract).

In the backend code, the Rest APIs to buy token, sell token , and get token balance are created.

In the frontend code, the UI is equipped with buy page and sell page. The pages are toggled by clicking Buy button and Sell button.

In the figure below, the user enters 1 ether to buy 100 tokens.

DEX buy token UI

After the Swap button is clicked, ReactJS calls the Rest APIs using http fetch. For the action of buying tokens, ReactJS calls the backend buy token Rest API. The API will call the swap contract buyTokens method, which calls token contract transfer method to send tokens to the buyer.

In the figure below, the user sells 100 tokens for getting back 1 ether.

DEX sell token UI

Again, after the Swap button is clicked, ReactJS calls the Rest APIs using http fetch. For the action of selling tokens, ReactJS calls the backend sell token Rest API. The API will call the swap contract sellTokens method, which calls token contract transferFrom method to transfer tokens from seller to the swap contract.

To send ether back to the seller, we use:

(bool success, ) = msg.sender.call.value(etherAmount)(“”);require(success, “Transfer failed.”);

Since December 2019, in solidity, <address>.call.value is preferred over <address>.transfer because transfer is taking a dependency on fixed amount of 2300 gas.
See the links below for further information on the solidity transfer issue.

Lastly, the smart contract test code is executed using “truffle test”. Truffle uses Mocha and Chai for testing. The test code is written in javascript.

The source code can be found at https://github.com/victoryeo/crypto_dex

--

--

No responses yet