Those familiar with the cryptocurrency space will know that dApp developers and crypto investors actively seek to expand and advance their blockchain projects. One popular way of doing so is by launching new tokens on various DEXs, or decentralized exchanges. With these tokens, users are able to interact with the many DEXs and dApps on different networks. Furthermore, different assets are necessary to interact with various chains and dApps (decentralized applications) in some cases. Using a DEX is a common way to acquire tokens. There is a veritable plethora of DEXes on the market, and with Moralis, you can even create your own DEX! As such, we will explain how you can create a DEX in five steps using Moralis.
Building a DEX has long been a cumbersome task. It is both resource-intensive and time-consuming, due to requiring extensive backend development. However, it’s possible to avoid most of this by using Moralis, as the platform provides a highly capable, existing backend infrastructure. As such, it’s possible to cut down the development process of all blockchain projects significantly.
Furthermore, Moralis offers a selection of great development tools that allow you to develop and deploy dApps. A few examples are Moralis Speedy Nodes, Moralis’ NFT API, native support for IPFS, and the Moralis Price API. However, these are just some of the many benefits provided by Moralis, and there is a lot more to discover with the full Moralis SDK. To learn more, be sure to visit the Moralis Blog. For example, did you know that Moralis has full support for Avalanche, want to learn NFT programming or Ethereum development?
The Moralis platform is not only great when creating a DEX but for all Web3 development projects. So, if you want to develop dApps, then sign up with Moralis right away!
What is a DEX (Decentralized Exchange)?
When transferring currencies between two accounts with the conventional financial system, an intermediary is often necessary to facilitate a transaction. Furthermore, these platforms are often referred to as centralized exchanges as they’re based on a centralized system. In contrast, a decentralized exchange, or a DEX, rather emulates the functionalities of a centralized exchange but is based on a decentralized system. What this basically means is that the backend of these exchanges exists on a blockchain.
One of the many benefits of basing a DEX on a decentralized system such as a blockchain is the possibility of eliminating intermediaries. As such, there is no need for a mediator to take custody of the funds before transferring them to another person or account. This means that the trade or exchange of tokens/currencies occurs directly between two people.
However, in a centralized exchange system, you deposit your funds, either fiat currencies or crypto, and whenever you deposit crypto into the system, you give up control over the assets, or at least from a technical standpoint. But, you still have the ability to withdraw or trade the assets. This means that you, as a user, will give up control of the private keys of your assets, and whenever you perform an action, you ask the platform to sign a transaction on your behalf.
However, a DEX avoids this issue by using smart contracts, which allow users to remain in complete control of their assets prior to making a trade. As such, DEXs are a safer way to trade crypto as we can avoid some of the pitfalls of centralization, such as a single point of failure.
How to Create a DEX with Moralis in 5 Steps
With a better understanding of what a DEX is, we can move on to the main topic of this article: ”How to Create a DEX in 5 Steps”. The best way to develop any type of dApp is to utilize the premier Web3 development platform, Moralis. We will be making a DEX from scratch that allows users to sign in with MetaMask and trade cryptocurrency pairs. The user interface (UI) of the dApp will mimic Uniswap’s UI and will look something like this once finalized:
We’ll be using Visual Studio Code as our code editor to build the dApp, and since we’re utilizing Moralis, we’ll be able to create a DEX in only five steps:
- Setting up a Moralis server.
- Installing the 1inch DEX plugin.
- Creating an HTML file.
- Assigning functions to each event.
Now, let’s get started with the first step of this tutorial by creating our own Moralis server!
Step 1: How to Create a DEX — Setting Up a Moralis Server
If you haven’t already, the first thing you need to do is sign up with Moralis. Once logged in to your account, we can initiate the process of creating a server by pressing the ”+ Create a new Server” button at the top right of the admin panel. This will provide a drop-down menu with three different alternatives, and for this tutorial, we selected the “Mainnet Server” option.
If either alternative is selected, a new window will appear where you need to input a name, select a region, and then add the desired network(s). In our case, we only selected ETH:
Once you are satisfied with your options, you can simply click the ”Add Instance” button to spin up the server. Creating the server might take a short while; however, the server will be up and running momentarily.
Step 2: How to Create a DEX — Installing the 1inch DEX Plugin
With a server up and running, the next step in the process is adding the 1inch DEX plugin to the server. To do so, we’ll need to visit the Moralis plugin store, which we can find by clicking the ”Plugins” button on the server and then clicking on ”Go to Plugin Store”.
Installing the plugin is relatively straightforward, and all we need to do is click the ”Read More” button for the correct plugin and then click the ”Install” button. Here you must choose the right server, which should be the one you set up in the previous section. The installation of the plugin might take a short while, and once finalized, the server must also reboot. However, the server will be back online in just a moment, and then we can continue the tutorial on how to create a DEX.
Step 3: How to Create a DEX — Creating an HTML File
The third step in the process of this “How to Create a DEX in 5 Steps” article is to set up an HTML file. In this case, we’ll name the file ”index.html”, and you’ll be able to find the complete code by clicking the file’s name. This file will be divided into four different sections:
- Essential imports.
- A navigation bar.
- A container.
- A modal.
Before we go further into the fourth step of this article, let’s go through the above-mentioned sections to provide you with a clearer understanding of the code.
The first things we need to implement into our code are a few essential imports. These are vital for our application to work properly, and we are, for example, including “web3.js” and “moralis.js”. Implementing these essentials is easy, and all you need to do is fetch some boilerplate code from Moralis’ GitHub page.
We went ahead and copied and pasted the code, followed by making a few adjustments. For example, we changed the title and removed everything associated with ”Jumbotron”. As such, this is what the final result looks like after the alterations:
If you look back at the UI that we presented earlier, you might notice a navigation bar. Adding a navigation bar to our HTML code is simple; all we need is to fetch a template from Bootstrap and implement it into our code. We selected the first template provided on the Bootstrap page and made a few adjustments. We mainly removed some unnecessary elements, and as a result, the final product for our code looks like this:
Next up, we’ll add the “div” container, which will contain all the content of the DEX’s UI. This section will have a few essential elements, such as the code for the fields and buttons of the application. This is what the complete “div” container looks like:
The complete “div” container contains several other “divs”, such as those with the ”swapbox” classes. There are two “swapbox classes”, and they include the HTML code for selecting the tokens, and the input fields, allowing users to specify an amount. One of the “divs” with the ”swapbox” class displays the token that the user would like to trade; meanwhile, the other indicates which token the user would like to receive in return after the trade.
After these two elements, there is also a “div” for presenting the estimated gas price and one with the button for executing the swap itself. However, it’s important to note that you can adapt all the HTML code to fit your own preferences. This means that the content doesn’t have to be structured in this way.
Whenever a user of the DEX interacts with the dApp and wants to select a token, a separate menu will open containing all the available alternatives. Therefore, we’ll also need an HTML element to display the tokens, which is where the modal “div” comes in. To create this “div”, we once again fetch a Bootstrap template and make a few changes. This is what the complete modal “div” looks like:
One part of this “div” is a button for closing the modal once it has been opened. This button has the ”modal_close” ID, which we’ll later tie to a function for closing the modal. Within the modal body, there is a “div” for a token list, which we’ll use when displaying the list of tokens to the users of the DEX. However, we’ll return to this when we go through the dApp’s functions.
Now, that’s it for the HTML code! However, if you decide to simply utilize the same code from the GitHub page, the web application will look messy. The reason for this is that we need to style the application with CSS. We won’t be getting into this process as this depends on your preferences and how you would like the interface to look. As such, we’re simply going to link to the ”style.css” file for you to take a closer look at and maybe get some inspiration.
So, now that we have the fields and buttons ready for our application, we can move on to the fourth step, which is to add some functions and logic to our dApp. However, before we create the functions of the exchange, we need to initialize Moralis. To do so, you need to fetch the server URL and application ID from the server that you created earlier. You’ll find this information by clicking the ”View Details” button for the server in question. You can then go ahead and copy this information and paste it into the code in the following manner:
With Moralis initialized, we’re also going to add three global variables. The first one represents the current trade, the second represents the currently selected side, and the final one represents the tokens. However, we’re going to explain later on why these global variables come in handy. But this is what they look like in the code:
Now, with both Moralis initialized, and the global variables added, we can move on to the first function of the dApp. We’re going to call this function ”init()”, and it will run as soon as the dApp launches.
The “init()” Function
The ”init()” function is important since it takes care of some initial tasks when the user launches the dApp. Here is an image of the entire function:
The first two lines of the function are quite vital; one makes sure that the plugins from the server are available, and the other initializes Moralis’ SDK. The third line of the function runs the ”listAvailableTokes()” function. This function fetches all the available tokens and loads this information directly when the application starts. The reason for this is efficiency, meaning that the users won’t need to wait for the dApp to fetch the alternatives when they are about to make a trade.
Finally, we also check if the user is authenticated and logged in with MetaMask. If they are, then we enable the “Swap” button.
The “login()” Function
The second function we’re taking a closer look at is the ”login()” function. This function is pretty straightforward, and it looks something like this:
The function checks if there is a user logged in or not. If the user isn’t logged in, then we can authenticate users with MetaMask. If a user is signed in, then the function simply enables the ”Swap” button.
The “openModal()” and “closeModal()” Functions
The following two functions are self-explanatory; one opens the modal while the other closes the modal. Furthermore, as you can see from the image below, the ”openModal()” function takes an argument in the form of ”side”. The dApp indicates this depending on which modal the user selects. So, depending on if they select the ”from_token_select” option or the ”to_token_select”, this variable changes. With this information, the function also changes the state of the global variable ”currentSelectSide”, indicating to the dApp where future changes should occur.
The “listAvailableTokens()” Function
Next up, we have the ”listAvailableTokes()” function, which is the one we call through the ”init()” function. This function does a variety of things, and one of them is to acquire the available tokens through Moralis’ ”getSupportedTokens()” function and then stores them in a list:
With the information acquired regarding the tokens, we have access to numerous things, such as the decimals of the tokens, the image URI, and the token symbol. We can then go through each object with a “for” loop and use this information to populate a list enabling us to display the image and the token’s symbol to users through the modal from the HTML code.
Furthermore, in the “for” loop, we also add an ”onclick” event to each token. This means that once the user clicks any of the options in the list, it will trigger the ”selectToken()” function. However, we haven’t created this function yet, so we’ll do so in the next section.
The “selectToken()” Function
In this section, we’re briefly going to look at the ”selectToken()” function that is called whenever the user selects a token from the modal. Once triggered, the function passes the address as an argument and then closes the modal.
After calling ”closeModal()”, the function also adds the selection to the global object ”currentTrade”. This occurs twice, first when the user decides which token they would like to trade and then for the token they would like to receive in return.
Finally, the function calls two additional functions: ”renderInterface()” and ”getQuote()”, which we are going to look at in the following two sections.
The “renderInterface()” Function
The ”renderInterface” function renders the token image and the symbol once the user selects a token. As observed in the image, it does this for both the ”from_token_select” and ”to_token_select” elements depending on which the user interacts with. This is what the function looks like:
The “getQuote()” Function
Next up, we’re going to implement the ”getQuote()” function. This function aims to get the quote of the tokens and automatically display the amount the user will receive if they proceed with a trade. This is what the function looks like, and we are going to go through the most critical elements:
First and foremost, the function checks if the user has selected the preferred token that they’d like to trade and receive and that a ”from_amount” value exists. If either of these elements is missing, then the function will return until the user inputs everything.
If the user has inputted all the info, then a new variable called ”amount” is created, which converts the inputted amount based on the decimals of the selected token. With the proper amount, the function then, in turn, calls the 1inch ”quote()” function. It is possible to fetch this function from the plugin store. Then we assign the appropriate addresses along with the “amount” variable previously converted.
With the quote at hand, the function then sets both the estimated gas price along with ”to_amount”. As such, this will automatically display both the gas price and the amount the user will receive from the trade.
The “trySwap()” Function
To send tokens, the 1inch plugin must receive an allowance for the smart contracts so that the swap can take place. For this reason, the ”trySwap()” function checks if the user has provided an allowance before calling the ”doSwap()” function. Moreover, this is what the function looks like:
The first thing the function does is fetch the user’s wallet address and convert the inputted amount (just as the previous function). If the user wants to trade ETH, then there is no allowance needed. As such, the function then checks if the currency symbol is equal to ”ETH”. If it isn’t, then the function checks if the user has provided an allowance, which is done by calling the ”hasAllowance()” function. This function will then return a boolean which is either true or false.
If the user hasn’t provided an allowance, then the ”approve()” function is called, which gets an allowance from the user that enables the swap. As you can see from the image, there is a need to supply the token and the user’s wallet address.
The “doSwap()” Function
Finally, we have the ”doSwap()” function, which executes the actual transfer. As you can see from the ”trySwap()” function, this function will execute as soon as the user gives an allowance. Here is the function:
Here we simply call the 1inch Moralis ”swap()” function with a few parameters. The user address and the amount are passed as arguments when calling the ”doSwap()” function, and the other information is fetched from the selected tokens.
Furthermore, there is a new property here which is slippage. In the code above, it’s set to 1%, which is generally the standard. Lastly, once the swap is completed, the users will be alerted through the ”trySwap()” function.
Step 5: How to Create a DEX — Assigning Functions to Each Event
The ”onclick” events are pretty straightforward; once a button is clicked, a function will execute. The ”onblur” event, on the other hand, might be somewhat trickier to wrap one’s head around. This event means that the ”getQuote()” function will trigger once the user removes the focus from the ”from_amount” field. As such, once they’re done typing in the amount and moving the focus away from this input field, the quote will be displayed in the ”to_amount” field.
Now, this covers all the basic elements of how to create a DEX; all that remains is for you to style the dApp according to your own preferences using CSS.
How to Create a DEX — Summary
As we’ve been using Moralis throughout this tutorial, we’ve demonstrated the power of the platform as we were able to create a DEX in just five simple steps:
- Setting up a Moralis server.
- Installing the 1inch DEX plugin.
- Creating an HTML file.
- Assigning functions to each event.
This clearly showcases the power of Moralis, and throughout the coding process, we used some of the phenomenal ready-to-use functions available through the 1inch DEX plugin. By using the tools of the platform, we’ve significantly shortened the development time of this DEX. As such, you know how to create a DEX from scratch in just five steps!
Furthermore, creating a DEX is only one of the many instances in which the Moralis platform comes in handy. The platform offers a variety of great development tools along with the already managed backend infrastructure, making Moralis the ultimate middleware for Web3 development.
Moreover, if you want to learn more about the potential of working with Moralis, then check out the Moralis blog. Here you’ll find great articles showcasing the power of working with the platform. For example, there are guides on how to add a fiat gateway to dApps and how to create your own NFT game.
With all these benefits, it’s a no-brainer to sign up with Moralis. Joining the platform is entirely free, and it only takes a couple of seconds, so don’t hesitate!