1

I am working on an HTML page to connect to an Ethereum wallet and initiate transactions using ethers.js. However, when I attempt to connect to the wallet by clicking the 'Connect Wallet' button, I encounter a specific error. Here's the relevant part of my code:

 <script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js" type="application/javascript"></script>
    <script>
    let PreSaleContract = undefined;
    let signer = undefined;
    const contractAddress = '0x3616D3D8b0fdcdA7a9069dF97508d6b5905790d6';
    const abi = []; //I have my abi pasted here
    async function connectWallet() {
     
      const provider = new ethers.providers.Web3Provider(window.ethereum, "sepolia");
      
      try {
        console.log("provider", provider);
        await provider.send("eth_requestAccounts", []);
        const accounts = await provider.listAccounts();
        signer = provider.getSigner(accounts[0]);
        console.log("signer", signer)
        PreSaleContract = new ethers.Contract(
          contractAddress,
          abi,
          signer
        );
      } catch (error) {
        console.error("Error connecting to wallet:", error);
      }
    }

    async function buyReflectNFT() {
      console.log(PreSaleContract, signer);
      const nftAmount = document.getElementById("numberInput").value;
      const price = await PreSaleContract.getCurrentNFTPrice();
      console.log(price);
      const buyTransaction = await PreSaleContract.getCurrentNFTPrice(nftAmount, { value: price * nftAmount });
      console.log(buyTransaction);
    }
  </script>

this is html code

<button onclick="connectWallet()">Connect Wallet</button>
<button onclick="buyReflectNFT()">Buy Reflect NFT</button>

but when i click connect wallet button i get this error enter image description here

4
  • Can you check the output of console.log(window.ethereum)? Is it logging the proper object ? Commented Apr 23 at 22:35
  • @SYEDASADKAZMI I tried doing it, it says undefined. I even tried different browsers but still metamask is not being detected. I tried code from the official documentation too Commented Apr 24 at 10:47
  • Which of your browsers (that you tried) has MetaMask installed? Commented Apr 24 at 10:57
  • I tried both chrome and firefox. and in both cases metamask is installed and working. Working fine with React Project but not here Commented Apr 24 at 11:09

1 Answer 1

1

Your connectWallet() function is not implemented correctly, due to which the provider is not getting initialised. Here's how it should be done:

Connect Wallet:

const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
console.log(`Wallet connected: ${accounts[0]}`);

Initialise provider and getting signer:

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
console.log(signer.address);

Here's a simple HTML code having connectWallet() and sendTransaction() functions, in which sendTransaction() is basically sending 0.001 ether from the connected wallet to the RECIPIENT_ADDRESS:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connect Wallet and Send Transaction with ethers.js</title>
    <script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js" type="application/javascript"></script>
</head>

<body>
    <h1>Connect Wallet and Send Transaction with ethers.js</h1>

    <button id="connectButton">Connect Wallet</button>
    <button id="sendTransactionButton" style="display: none;">Send Transaction</button>

    <script>
        async function connectWallet() {
            if (window.ethereum) {
                try {
                    const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                    alert(`Wallet connected: ${accounts[0]}`);
                    document.getElementById('connectButton').style.display = 'none';
                    document.getElementById('sendTransactionButton').style.display = 'block';
                } catch (error) {
                    console.error('Wallet connection error:', error);
                    alert('Wallet connection error: ' + error.message);
                }
            } else {
                alert('Please install MetaMask or another Ethereum wallet to use this feature.');
            }
        }

        async function sendTransaction() {
            const provider = new ethers.providers.Web3Provider(window.ethereum);
            const signer = provider.getSigner();

            try {
                // Example: Prepare a transaction
                const transaction = {
                    from: signer.address,
                    to: 'RECIPIENT_ADDRESS', // Replace with recipient address
                    value: ethers.utils.parseUnits('0.001') // Example: Send 0.001 ether (ETH/MATIC depending on the network you're connected to)
                };
                const transferTx = await signer.sendTransaction(transaction);
                await transferTx.wait();
                alert(`Transaction successful: ${transferTx.hash}`);
            } catch (error) {
                console.error('Transaction failed:', error);
                alert('Transaction failed: ' + error.message);
            }
        }

        document.getElementById('connectButton').addEventListener('click', connectWallet);
        document.getElementById('sendTransactionButton').addEventListener('click', sendTransaction);
    </script>
</body>

</html>
3
  • I copy pasted your code and when i ran it using chrome, it said "Please Intsall Metamask" Even though wallet is installed Commented Apr 28 at 16:08
  • @TalhaSajidChaudhary, I think you should uninstall your MetaMask and try reinstalling. Let me know if the problem still persists after reinstallation. Commented Apr 28 at 16:10
  • 2
    Issue is fixed, it was issue on my side. I was not running HTML code on the live server. Instead, I was opening HTML files directly on Chrome Commented Apr 29 at 10:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.