Examples
Uniswap Widget Example
This example will walk you through how to integrate @web3-onboard with the
Uniswap Widget! Add this Web3 Onboard enabled Uniswap widget to your site to provide users with token swap capabilities quickly.
Step 1: Install
To start, we'll install the widgets library and the Web3 Onboard react library using npm or Yarn.
- Yarn
- Npm
Step 2: Import + Configure
Import the libraries and any wallets you would like to use. For this example, we are going to use the injected wallets module. You can easily add more wallet support to your dapp via our other wallet modules. Additionally, we'll setup Web3 Onboard to support 2 chains: Ethereum mainnet and Polygon mainnet.
We'll create a file called web3-onboard.ts and then export the initialized web3-onboard instance and use this throughout our dapp.
Step 3: Add the react hooks
In our main App component we'll setup our Web3 Onboard react hooks. For this example we'll be using the useConnectWallet react hook. This will give us access to the currently connected wallets, as well as, methods for us to facilitate connecting and disconnecting a wallet.
Step 4: Add the Uniswap widget
To begin, we'll import the SwapWidget along with the corresponding fonts. We'll define a few constants that will be passed to the swap widget:
- The json rpc endpoint that will be used to provide trade quotes prior to the user connecting a wallet
- The token list url used to provide a list of tokens for the user to select from
- The Uniswap token address which will be used as the default selected token
To learn more about all of the SwapWidget props, check out
the api reference.
We will take the connectWallet function that we previously defined and pass it to the onConnectWallet prop on the SwapWidget. This will allow us to initiate the web3-onboard connect wallet modal once the user clicks the on the connect wallet button within the SwapWidget. Finally, we'll also pass the provider to the SwapWidget such that once the provider is defined, the SwapWidget will be able to use the wallet's provider to facilitate the swap.
Step 5: Wrap the context provider
Finally, we'll wrap our main App component with the web3-onboard context provider in order for us to access the web3-onboard instance throughout our app.
See in action!
Live Example 🚀
Check out the live example on StackBlitz! StackBlitz will install and build the package in the below container