How to get balance of liquidity approve uniswap token

Hello i have been having trouble getting the balance of the submitted uniswap token pair address in the approve on metamask, it is detecting the overall balance of the token address instead of the uniswap liquidity token address balance i submitted
here is my code below

import React, { useState, useEffect } from 'react';
import { utils as Web3Utils } from 'web3';
import pairABI from './pairABI.json';
import ERC20ABI from './ERC20ABI.json';
import Web3 from 'web3';

const LockTokensForm = ({ contract, accounts }) => {
  const [tokenPairAddress, setTokenPairAddress] = useState('');
  const [tokenSymbol, setTokenSymbol] = useState('');
  const [amount, setAmount] = useState('');
  const [unlockTime, setUnlockTime] = useState('');
  const [errorMessage, setErrorMessage] = useState('');
  const [transactionHash, setTransactionHash] = useState('');
  const [tokenBalance, setTokenBalance] = useState(null);
  const [lockFee, setLockFee] = useState('');
  const [tokenContracts, setTokenContracts] = useState([]);
  const [pairApproved, setPairApproved] = useState(false);

  useEffect(() => {
    const fetchTokenData = async () => {
      try {
        if (tokenPairAddress) {
          const web3 = new Web3(window.ethereum);
          const pairContract = new web3.eth.Contract(pairABI, tokenPairAddress);
          const [token0, token1] = await Promise.all([
            pairContract.methods.token0().call(),
            pairContract.methods.token1().call(),
          ]);

          const token0Contract = new web3.eth.Contract(ERC20ABI, token0);
          const token1Contract = new web3.eth.Contract(ERC20ABI, token1);

          const [token0Symbol, token1Symbol] = await Promise.all([
            token0Contract.methods.symbol().call(),
            token1Contract.methods.symbol().call(),
          ]);

          const symbol = `${token0Symbol}-${token1Symbol}`;
          setTokenSymbol(symbol);
          setTokenContracts([token0Contract, token1Contract]); // Store the token contract instances
        }
      } catch (error) {
        console.error('Failed to fetch token data:', error);
      }
    };

    fetchTokenData();
  }, [tokenPairAddress]);

  useEffect(() => {
    const fetchTokenBalance = async (pairContract) => {
      try {
        if (pairContract && accounts[0]) {
          const balance = await pairContract.methods.balanceOf(accounts[0]).call();
          setTokenBalance(balance);
        }
      } catch (error) {
        console.error('Failed to fetch token balance:', error);
      }
    };

    if (tokenPairAddress) {
      const web3 = new Web3(window.ethereum);
      const pairContract = new web3.eth.Contract(pairABI, tokenPairAddress);

      fetchTokenBalance(pairContract);
    }
  }, [tokenPairAddress, accounts]);

  useEffect(() => {
    const fetchLockFee = async () => {
      try {
        if (contract) {
          const fee = await contract.methods.lockFee().call();
          setLockFee(Web3.utils.fromWei(fee)); // Convert lock fee to Ether
        }
      } catch (error) {
        console.error('Failed to fetch lock fee:', error);
      }
    };

    fetchLockFee();
  }, [contract]);

  const handleLockTokens = async (event) => {
    event.preventDefault();

    // Validate inputs
    if (!amount || !unlockTime) {
      setErrorMessage('Please enter both the amount and unlock time.');
      return;
    }

    const parsedAmount = parseFloat(amount);

    if (isNaN(parsedAmount) || parsedAmount <= 0) {
      setErrorMessage('Please enter a valid amount.');
      return;
    }

    try {
      setErrorMessage('');

      // Check if the token pair is approved
      if (!pairApproved) {
        setErrorMessage('Please approve the token pair before locking the tokens.');
        return;
      }

      // Get the token symbols
      const web3 = new Web3(window.ethereum);
      const pairContract = new web3.eth.Contract(pairABI, tokenPairAddress);
      const [token0, token1] = await Promise.all([
        pairContract.methods.token0().call(),
        pairContract.methods.token1().call(),
      ]);

      const token0Contract = new web3.eth.Contract(ERC20ABI, token0);
      const token1Contract = new web3.eth.Contract(ERC20ABI, token1);
      const [token0Symbol, token1Symbol] = await Promise.all([
        token0Contract.methods.symbol().call(),
        token1Contract.methods.symbol().call(),
      ]);

      const symbol = `${token0Symbol}-${token1Symbol}`;
      setTokenSymbol(symbol);

      // Get the current time from the user's computer
      const currentTime = Math.floor(Date.now() / 1000);

      // Calculate the unlock time as the current time plus the specified unlock time in seconds
      const unlockTimestamp = currentTime + parseInt(unlockTime);

      const tx = await contract.methods
        .lockLiquidityTokens(Web3.utils.toWei(amount), unlockTimestamp)
        .send({ from: accounts[0] });

      setTransactionHash(tx.transactionHash);
      // Handle transaction success
    } catch (error) {
      setErrorMessage('Transaction failed. Please try again.');
      // Handle transaction failure
    }
  };

  const handleMaxButtonClick = () => {
    if (tokenBalance !== null) {
      const maxAmount = Web3Utils.fromWei(tokenBalance);
      setAmount(maxAmount);
    }
  };

  const handleApproveTokens = async () => {
    try {
      const web3 = new Web3(window.ethereum);
      const pairContract = new web3.eth.Contract(pairABI, tokenPairAddress);

      for (let i = 0; i < tokenContracts.length; i++) {
        const tokenContractInstance = tokenContracts[i];

        const maxApproval = '115792089237316195423570985008687907853269984665640564039457584007913129639935'; // Max uint256 value
        const tx = await tokenContractInstance.methods.approve(pairContract.options.address, maxApproval).send({
          from: accounts[0],
        });

        console.log('Approval transaction successful:', tx);
        // Perform additional actions or update state as needed
      }

      // Check the token pair balance after approval
      const balance = await pairContract.methods.balanceOf(accounts[0]).call();
      setTokenBalance(balance);

      // Mark the token pair as approved
      setPairApproved(true);
    } catch (error) {
      console.error('Approval transaction failed:', error);
      // Perform additional actions or update state as needed
    }
  };

  return (
    <div>
      <h3>Lock Tokens</h3>
      <form onSubmit={handleLockTokens}>
        <label>
          LP Token Address:
          <input
            type="text"
            value={tokenPairAddress}
            onChange={(e) => setTokenPairAddress(e.target.value)}
          />
        </label>
        <br />
        <label>
          Pair: <span>{tokenSymbol}</span>
        </label>
        <br />
        <label>
          LP Token Amount to Lock:
          <div className="token-amount-container">
            <input
              type="number"
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              min="0"
              step="any"
              required
            />
            <button type="button" onClick={handleMaxButtonClick}>
              Max
            </button>
          </div>
        </label>
        <br />
        <label>
          Unlock Time (in seconds):
          <input
            type="number"
            value={unlockTime}
            onChange={(e) => setUnlockTime(e.target.value)}
            min="0"
            required
          />
        </label>
        <br />
        {errorMessage && <div className="error-message">{errorMessage}</div>}
        {transactionHash && (
          <div className="success-message">
            Transaction successful! Transaction hash: {transactionHash}
          </div>
        )}
        <button type="submit">Lock Tokens</button>
      </form>
      {!pairApproved && (
        <button type="button" onClick={handleApproveTokens}>
          Approve Tokens
        </button>
      )}
      {lockFee && (
        <div>
          Lock Fee: {lockFee} ETH
        </div>
      )}
      {tokenBalance !== null && (
        <div>
          Token Balance: {Web3.utils.fromWei(tokenBalance)} {tokenSymbol}
        </div>
      )}
    </div>
  );
};

export default LockTokensForm;

@cryptokid please help

@alex please help with this

@YosephKS please check this for me

Hey @Cyberhot,

what do you mean by uniswap liquidity token address here?

I am trying to approve the uniswap LP pair address submitted on the frontend but it is approving the 2 tokens present in the pair address @YosephKS

Can I know why you are trying to approve the uniswap LP address here? Is your use case to take back the tokens and burn the LP address?

I am building a LP token locker and I want my Lock Contract to be the spender of the LP address submitted on the frontend and approve it for spending so that it will lock the LP token, that’s what am doing but the approve button is not working as expected, if I try to click the approve button, it will pop up Metamask and show the first token e.g USDT and after clicking confirm, then another pop up will show telling me to approve WETH which is not exactly what I expected to do on the frontend.
I wanted the approve to detect the balance of the LP token address which is e.g USDT/WETH and it will show as USDT/WETH LP balance will look like this 458.089778889565301876 USDT/WETH @YosephKS

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.