React dApp that enables swapping ETH for UNI tokens via Uniswap's smart contracts. It leverages the Uniswap SDK to interact with these contracts and develop a custom frontend for executing token swaps.
Before starting, make sure you have the following knowledge and tools:
- npm
- React
- ethers.js
- wagmi.sh
-
Create a new React dApp project using TypeScript template:
npx create-react-app Swap-dapp --template typescript
-
Change the directory to the project folder:
cd Swap-dapp
- Install the required dependencies:
npm install ethers wagmi @uniswap/v3-sdk @uniswap/sdk-core
- Start the development server:
npm start
To connect the dApp with an Ethereum node and enable wallet integration with MetaMask, follow these steps:
-
Open the
App.tsx
file and wrap the entire application with theWagmiConfig
provider, providing the necessary configuration options. -
Implement the wallet connection button and logic in the header of the dApp by creating a new
Header
component.
To fetch token prices and interact with the Uniswap contracts, create a custom hook called useSwap
:
-
Obtain a reference to the contract of the desired token pool (e.g., WETH-UNI).
-
Define the interfaces (
Immutables
andState
) representing the on-chain pool data. -
Create functions (
getPoolImmutables
andgetPoolState
) to fetch the required data from the pool contract. -
Implement the
getQuote
function to calculate the amount of UNI tokens for a given amount of ETH. -
Build the UI components (
SwapCard
) that call thegetQuote
function and display the quote accordingly.
Before executing the token swap, it's necessary to convert ETH to WETH and approve the router contract to use WETH on behalf of the user. Follow these steps:
-
Create a new file called
useWETH.tsx
and implement a custom React hook similar touseSwap
. -
Instantiate the contract instance for the WETH token and define the necessary functions (
deposit
andapprove
) to convert ETH to WETH and grant permission for router contract access.
To execute the token swap using the Uniswap router contract, follow these steps:
-
Add the required import statements to the
useSwap.tsx
file. -
Update the hook to use a signer instead of a provider for the router contract and import the functions from the
useWETH
hook. -
Implement the
swap
function that executes the swap by converting ETH to WETH, approving router access, and calling theexactInputSingle
function on the router contract. -
Integrate the
swap
function into the UI by adding the necessary logic and a button in theSwapCard.tsx
component.
To display the current ETH and UNI token balances, follow these steps:
-
Add the required constant at the top of the
SwapCard.tsx
file. -
Implement the
useAccount
hook to fetch and watch the account balance for both tokens. -
Update the template to display the current balance for each token.