Blockchain

How to Swap Tokens on Uniswap with Ethers.js?

Uniswap has become one of the most renowned trading protocols for Ethereum. It has become a successful decentralized exchange and a unicorn in every sense with promising value advantages. Centralized exchanges have been dominating the backbone of the cryptocurrency landscape for years with the assurance of fiat on-ramps, deep liquidity, customer support, and faster transactions.

However, swapping token on Uniswap comes with many other advantages, such as accessibility, lower trading fees, privacy, and security. Decentralized exchanges provide unique benefits which ensure that they are viable alternatives to centralized exchanges. Uniswap is a leading decentralized exchange, which was introduced in 2018 and has a unique model underlying its design.

Uniswap utilizes the Automated Market Maker model and serves an important role in designing and developing decentralized exchanges. As of now, Uniswap enjoys a massive user base with its user-friendly interface, an extensive assortment of token listings, and substantial liquidity. Did you know that you can swap tokens on Uniswap with ether.js library?

Most of you would interact with Uniswap through the front-end user interface for swapping tokens. However, some users prefer to swap tokens programmatically through server-side scripts or smart contracts. The following guide will help you find out how to swap tokens on Uniswap with the help of ethers.js library.

Excited to build your skill in Ethereum development by leveraging the ethers.js library? Enroll now in the Ethers.Js Blockchain Developer Course

Important Things to Know Before Swapping Tokens on Uniswap with Ethers.js

Before you find answers to “How do you swap coins on Uniswap?” through a programmatic approach, you should fulfill the important prerequisites. First of all, you would need comprehensive knowledge of the working mechanism of smart contracts. You should also learn about the functionalities of Node.js and Ethers.js libraries. At the same time, you must ensure that you have installed the latest version of the libraries. On top of that, you must be familiar with the workings of Rinkeby test ETH and an effective code editor.

Fundamentals of Uniswap

Anyone interested in learning how to swap tokens programmatically on Uniswap must learn about the fundamentals of the decentralized exchange. It is the leading decentralized exchange in the market, which utilizes an Automated Market Maker or AMM for facilitating trading. The guides to swapping token with ether.js on Uniswap assume examples with Uniswap V2 version, although Uniswap V3 is the latest version. The decentralized exchange arrived in 2018 and has been pushing the boundaries in DeFi with multiple value advantages.

With the Uniswap V3 version, you can find a resilient liquidity-centric design, which allows liquidity providers to achieve more efficiency on their capital. In addition, the Uniswap V3 version offers variable fee structures for different unique pairs or tokens. Initially, the Uniswap protocol was deployed on the Ethereum blockchain only. 

However, it has become a popular addition to other chains, such as Optimism, Polygon, and Arbitrum. Why should you take the example of Uniswap V2 for token swap on ether.js when you have Uniswap V3? The answer would point to the fact that V2 is still relevant in the crypto and blockchain ecosystem. Most of the DeFi protocols utilize the same AMM architecture as Uniswap V2, thereby offering the advantages of interoperability.

Excited to learn the basic and advanced concepts of ethereum technology? Enroll now in Ethereum Technology Course

How to Set Up Uniswap for the Token Swap with Ether.js?

After learning about the important prerequisites and fundamentals of Uniswap, you should learn about the steps for setting up Uniswap. The best approach for swapping token on Uniswap with the ether.js library would involve learning about how to use Uniswap for developers. Uniswap has V2 contracts in two distinct repositories, such as Core and Periphery.

It also provides a comprehensive SDK for development on Uniswap and interaction with the protocol. The core contracts focus on creation of pairs or liquidity pools alongside maintaining a record of the balances. On the other hand, periphery contracts help in interaction with core contracts. Here is an outline of the components involved in the distinct categories of smart contract systems on Uniswap. 

The core contracts on Uniswap include one-factor contracts and other pairs of contracts. It is important to note that the Factory contract could create many other pair contracts and serve as a registry for different markets. The markets created by the factory contract are pairs that include a unique token pair. The primary objective of the pairs focuses on working as automated market makers and maintaining track of token balances in one pool. Furthermore, the pair contracts also emit data for building decentralized price oracles. 

Periphery contracts include different domain-centric smart contracts, which help in ensuring interactions with the core contracts. The guides for a token swap on ether.js with Uniswap would help you find the importance of Periphery contracts. The two categories of Periphery contracts include library and router contracts. Library contract offers features that can help in fetching data and price of tokens with convenience. Router contracts utilize the library and offer support for all the basic requirements of a front-end that can offer liquidity management and trading functionality.

Build your identity as a certified blockchain expert with 101 Blockchains’ Blockchain Certifications designed to provide enhanced career prospects.

Understand the Working of Uniswap Router 

The right approach for setting up Uniswap for developers would involve an in-depth understanding of the Router contract. The answers to “How do you swap coins on Uniswap?” would draw attention to the Router contract. It can help in swapping tokens with the help of code. How? Prior to successful calling of any swap method, the user should approve the router for swapping ‘N’ number of tokens. Generally, protocols would request an infinite approval amount for lower transaction costs. However, there is no need for such an approach as you can also approve a particular amount according to your requirements.

The structure of an ‘approve ()’ function looks like the following example.

function approve(address usr, uint wad) external returns (bool) 

    allowance(msg.sender)(usr) = wad;

    emit Approval(msg.sender, usr, wad);

    return true;


The ideal options to swap tokens on Uniswap with ether.js library could be quite confusing. You can use different swap methods for the router smart contract. The common methods used for swapping tokens on Uniswap include ‘swapExactTokensForTokens’ and ‘swapExactETHForTokens,’ which have different functions.

The ‘swapExactTokensForTokens’ function could help you in situations where you want to swap the exact number of input tokens as the number of output tokens. In this method, the first path element serves as the input token, while the last serves as the output token. 

function swapTokensForExactTokens(

  uint amountOut, // Given an input asset amount, returns the maximum output amount of the other asset

  uint amountInMax, // The maximum amount of input tokens that can be required before the transaction reverts

  address() calldata path, // An array of token addresses

  address to, // Destination address

  uint deadline // Unix timestamp, after which the transaction will revert

) external returns (uint() memory amounts); //

The ‘swapExactETHForTokens’ function is also useful for swapping token on Uniswap with code. It is applicable in use cases where you have to swap the exact number of ETH tokens as the number of output tokens along the route defined by the path. In addition, the function also wraps ETH in the form of WETH. Here is an example of using the ‘swapExactETHForTokens’ function in the router contract.

function swapExactETHForTokens(

  uint amountOutMin, // The minimum amount of output tokens that must be received for the transaction not to revert

  address() calldata path, //An array of token addresses

  address to, // Destination address

  uint deadline) // Unix timestamp, after which the transaction will revert

  external payable returns (uint() memory amounts);

Get familiar with common Ethereum terms with the Ethereum Flashcards

How Can You Set Up the Ethereum Endpoint?

The working of Uniswap and different swapping techniques provide a clear impression of how you can use code for swapping tokens. However, you would have to start by setting up a Rinkeby test node. You could also set up your own node. However, you can also rely on node service providers such as QuickNode to fire up blockchain nodes quickly. Once you have booted up a node, you can retrieve the HTTP URL and prepare to use ether.js for swapping tokens.

How Can You Use Ether.js for Swapping Tokens on Uniswap?

After setting up the Rinkeby test node, you can start the token swap on ether.js with Uniswap. First of all, you must create a pair with liquidity when the token you want to swap does not have liquidity. Let us assume the example of swapping ETH with DAI. You can begin the project by opening the terminal window and creating your project directory alongside the essential files. In addition, you must also install the required dependencies. Now, you should complete the following steps before moving to the next stage.

  • Importing the private key into a .secret file.
  • Navigating to the source code for the concerned Router address on Etherscan. You should also copy the ABI in the ‘./abis/router.json’ file. You can find the ABI in the ‘Contract’ tab. 
  • Retrieving test ETH on Rinkeby. You should configure the wallet to the Rinkeby Testnet and obtain free test ETH from crypto faucets. 

Learn about how cryptocurrencies work, and the significance of crypto in the changing finance industry with Cryptocurrency E-Book

Creating the Program for Swapping Tokens 

You can create the program for swapping token with ether.js on Uniswap after completing the essential steps. You should open the ‘swapTokensWithEthers’ directory in a specific code editor of your choice. In the subsequent step, you should navigate to the index.js file and then use the following code snippets for independent functionalities required to complete the token swap script.

Import the Dependencies

First of all, you should include the required dependencies for the project. You have to import the ethers.js library for interacting with the smart contract alongside the Uniswap SDK for fetching and creating the swap structure. It is important to use version 5.7 or more. The utils and fs libraries are useful for reading and modifications in data. 

const  ethers  = require("ethers")

const UNISWAP = require("@uniswap/sdk")

const fs = require('fs');

const  Token, WETH, Fetcher, Route, Trade, TokenAmount, TradeType, Percent = require("@uniswap/sdk");

const  getAddress  = require("ethers/lib/utils");

Excited to learn about the basic concepts of Ethereum, such as transactions, addresses, consensus, blocks, and important tools, Enroll now in the Ethereum Technology Course

Configuration of Infrastructure Provider

You could utilize the HTTP URL from the node service provider and Ethers for instantiating a ‘Provider’ object that represents interactions with the blockchain. 

const QUICKNODE_HTTP_ENDPOINT = "YOUR_QUICKNODE_HTTP_URL"

let provider = new ethers.providers.getDefaultProvider(QUICKNODE_HTTP_ENDPOINT)

Importing the Wallet 

The answers to ‘How do you swap coins on Uniswap?’ would also focus on the snippets for importing the wallet. You can import the account that you would rely on for swapping tokens. The process would involve the ‘fs’ module for reading from the ‘.secret’ file, followed by instantiating a ‘Wallet’ object by utilizing Ethers.

const privateKey = fs.readFileSync(".secret").toString().trim()

const wallet = new ethers.Wallet(privateKey, provider)

Instantiation of Router Contract

The ether.js library features a ‘Contract’ module that can help in instantiating different instances of smart contracts. You can swap tokens on Uniswap with ether.js by creating an instance of the ‘Router’ contract by providing a smart contract address, a Provider object, and an ABI. Here is the code snippet for instantiation of Router contract.

UNISWAP_ROUTER_ADDRESS = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"

UNISWAP_ROUTER_ABI = fs.readFileSync("./abis/router.json").toString()

UNISWAP_ROUTER_CONTRACT = new ethers.Contract(UNISWAP_ROUTER_ADDRESS, UNISWAP_ROUTER_ABI, provider)

Certified Enterprise Blockchain Professional Certification

Importing the Token Data

You have to import token data by creating an instance of ‘Token’ class, followed by passing the required inputs like chain ID, decimal places, and smart contract address. It is important to note that the decimal figures and contract addresses could vary significantly according to the type of token.

Swap ETH for Tokens 

The core logic would be present in the ‘swapTokens()’ function that could assume both the tokens as arguments alongside the amount that should be swapped. You could also set the slippage amount. After compiling the code in the ‘index.js’ file, you should call the function to ensure execution of the swap logic. Finally, you can save the file and run the ‘node index.js’ command in a terminal window.

Familiarize yourself with the popular blockchain network, Ethereum, and ensure overall, comprehensive skill development with Ethereum Skill Path

Conclusion 

The review of the method for swapping token on Uniswap by using ether.js shows that you should understand the functionalities of Uniswap. It is important to understand that swapping tokens through ether.js would involve a programmatic approach. Users who don’t want to interact with the front-end interface could create their own custom code for swapping tokens. However, you should develop a clear understanding of the fundamentals of ether.js to use the library for swapping tokens. Learn more about Uniswap and ether.js alongside the best practices for using them right now.

Unlock your career with 101 Blockchains' Learning Programs

*Disclaimer: The article should not be taken as, and is not intended to provide any investment advice. Claims made in this article do not constitute investment advice and should not be taken as such. 101 Blockchains shall not be responsible for any loss sustained by any person who relies on this article. Do your own research!

Related Articles

Back to top button