Uniswap V2 Get Price Quote Code Full Stack Step by Step Tutorial

Uniswap V2 Get Price Quote Code Full Stack Step by Step Tutorial

In this tutorial, you'll learn how to:

  • Set up a Node.js backend using Express and Ethers.js to interact with the Ethereum network
  • Build a React frontend that makes requests to the backend using Axios
  • Display the price of WETH in USDC

Part 1: Setting up the backend

1.Open your terminal and navigate to the directory where you want to create the backend.

2.Run the following command to create a new Node.js project:

mkdir backend
cd backend
yarn init -y        

3.Install the necessary dependencies:

yarn add express ethers dotenv cors        

4.Create a new file called index.js in the root of the project with the following code:

const express = require('express');
const { ethers } = require('ethers')
const cors = require('cors');
require('dotenv').config();

const app = express();

app.use(cors());
app.use(express.json());

//from https://docs.uniswap.org/contracts/v2/reference/smart-contracts/router-02
const ADDRESS = '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D';

const ABI = ['function getAmountsOut(uint amountIn, address[] memory path) public view returns (uint[] memory amounts)'];

const provider = new ethers.WebSocketProvider(`wss://eth-mainnet.g.alchemy.com/v2/${process.env.ALCHEMY_API_KEY}`);

const router = new ethers.Contract(ADDRESS, ABI, provider);

app.get('/weth-price', async (req, res) => {
? const amountIn = ethers.parseUnits('1', 18);
? const path = [
? ? '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', //Wrapped Ether (WETH) https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2
? ? '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' ?//USD Coin (USDC) https://etherscan.io/address/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48
? ];
? const amounts = await router.getAmountsOut(amountIn, path);
? const price = ethers.formatUnits(amounts[1].toString(), 6);
? res.send(price);
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
? console.log(`Server running on port ${port}`);
});        

5.Create a new file called .env in the root of the project with the following content:

ALCHEMY_API_KEY=<your-alchemy-api-key>        

You can find <your-alchemy-api-key> for Ethereum Mainnet from https://alchemy.com/

6.Start the server by running the following command:

node index.js        

Your backend is now ready to serve requests.

No alt text provided for this image

Part 2: Setting up the frontend

Navigate to root directory where you have backend folder.

1.Create a new React app

npx create-react-app frontend        

2.Install dependencies

Next, let's install the necessary dependencies for our frontend. Run the following command in your terminal to install axios:

cd frontend
yarn add axios        

3.Update src/App.js

Now, let's update the src/App.js file in our React app. Replace the existing code with the following:

import React, { useState, useEffect } from 'react'
import axios from 'axios';

function App() {
? const [price, setPrice] = useState('');

? useEffect(() => {
? ? async function fetchData() {
? ? ? const result = await axios('https://localhost:5000/weth-price');
? ? ? setPrice(result.data);
? ? }
? ? fetchData();
? }, []);

? return (
? ? <div className="App">
? ? ? <h1 style={{textAlign: "center", fontSize: "3em"}}>{price}</h1>
? ? </div>
? );
}

export default App;        

This code sets up a state variable called price, which will hold the price of 1 WETH in USDC. It also makes a request to the /weth-price endpoint using axios and sets the price state variable with the returned data. Finally, it displays the price in an h1 tag that is centered both horizontally and vertically.

Step 4: Start the app

Now that we've updated App.js, let's start the app by running the following command in your terminal:

yarn start        

This will start the app and open it in your default browser.

No alt text provided for this image

And that's it! You should now see the price of 1 WETH in USDC displayed in the center of the screen.

要查看或添加评论,请登录

Aghasi Gasparyan的更多文章

社区洞察

其他会员也浏览了