Geek Culture
Published in

Geek Culture

How to Add the Uniswap Swap Widget to your React dApp

Swap widget state

A few weeks ago, I attended the Polygon Guild Lagos event where Teju gave a talk on People Over Protocols and how we can improve the User Experience in Web3 by anticipating users’ needs.

She spoke about her experience trying to stake on a dApp, but couldn’t do so because she didn’t have the required token. In addition to expressing her dissatisfaction, she touched on how we can make this experience better by making it easy for users to access the required token in-app.

This stuck with me, and I’ve since made it a thing to consider token accessibility when building any web3 product. Therefore, I decided to try my hands on the Uniswap Labs Swap Widget so that users can swap tokens on the Uniswap Protocol without leaving my dApp.

While working on this, I came across some minor roadblocks and also got to learn of the common issues others faced by combing the Uniswap discord server. So I decided to write a beginner-friendly guide so you don’t have to face the same issues we did.

The Swap Widget

In cases whereby you need your users to carry out transactions in a native token (e.g. ENS), you need to make it easy for them to get the token without leaving your dApp. Doing this will help improve your user experience and also reduce drop-off due to the inaccessibility of a native token.

Adding the Swap widget to your dApp is pretty straightforward, and can be done in just a few lines of code. But before we go into the implementation, here are a few things you need to get started.

JSON-RPC Endpoint

The JSON-RPC Endpoint is required to fetch on-chain data and submit transactions. If you already have one in your DApp, you can skip this step. But if you don’t, you can easily create one on services like Infura or Alchemy.

Here is a simple guide on how to create one on Infura:

Step 1: Go to the Infura website, then sign up or log in to your account if you already have one.

Step 2: Navigate to your Dashboard and click on CREATE NEW PROJECT

Step 3: Select an applicable product, give your project a name and click on CREATE.

Step 4: Scroll down to Keys and copy your endpoint URL or Project ID.

Great job! You’ve successfully generated a JSON-RPC Endpoint.

Web3 Provider

The Swap widget also needs a web3 provider to fetch balances and submit transactions through the user’s connected wallet. If you’re creating a DApp, then you’ll need a web3 provider.

There are various providers you can choose from. But in this article, we’ll be using ethers.

//install the ethers librarynpm install --save ethers

Wallet Connect Flow

You also need a wallet connect flow in your app so that users can connect their wallets to carry out transactions. There are various libraries you can use (e.g. web3-react, wagmi, etc.). For simplicity, we will be connecting to a user-installed browser wallet like metamask.

However, we can only do this if the user has a wallet installed. So, we will be checking for wallet installation using metamask’s, detect-provider library.

//install metamask detect-providernpm install --save @metamask/detect-provider

Now that we’ve gotten our requirements ready, let’s get started.

Adding the Widgets Library

To get started, install the widgets library and react-redux if you don’t already have it installed.

//install the swap widgetnpm install --save @uniswap/widgets react-redux oryarn add @uniswap/widgets react-redux

Import App Dependencies

//Store some state variables.
import { useState } from 'react';
//connect to our infura endpoint
import { providers, ethers } from 'ethers';
//check if metamask is installed in the browser.
import detectEthereumProvider from '@metamask/detect-provider';
//uniswap widgets library
import { SwapWidget } from '@uniswap/widgets';

Define Constants

const infuraId = process.env.REACT_APP_INFURA_ID;
const jsonRpcEndpoint = `https://mainnet.infura.io/v3/${infuraId}`;
const jsonRpcProvider = new providers.JsonRpcProvider(jsonRpcEndpoint);
const provider = new ethers.providers.Web3Provider(jsonRpcProvider);

Define State Variables

function App() {  const [account, setAccount] = useState({
address: '',
provider: provider,
})

Create connectWallet function

async function connectWallet() {//check if Metamask is installed in the browser
const ethereumProvider = await detectEthereumProvider();
if (ethereumProvider) { //prompt user to connect their wallet
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts',
})
const address = accounts[0]; setAccount({
address: address,
provider: ethereumProvider
})
}
}

You might be wondering why we added a provider at all when it was going to be updated anyways. Here’s why 👇

If we don’t define a provider from the start, our widget is going to show up this way when we load our app.

Add Return Elements

Finally, we add our return elements. You can see here that the “Connect wallet” button calls the connectWallet function onClick. The SwapWidget also takes in 2 parameters; the provider and JsonRpcEndpoint.

return (
<div className="App">
<div>
<button onClick={connectWallet}>Connect Wallet</button>
</div>
<div className="Uniswap">
<SwapWidget
provider={account.provider}
JsonRpcEndpoint={jsonRpcEndpoint} />
</div>
</div>
);
}

Great job! You’ve successfully added the Swap Widget to your dApp. Now, you can run npm start to view your dApp.

You can check out the full code on GitHub.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store