window.web3.currentProvider & ethereum.enable deprecated

Hey @bjamRez, hope you are ok.

As @Bhujanga as suggested, maybe this links could also help you to go indeep with this:

Carlos Z

thanks Carlos but the web3 stuff is just not working at all for me. Now is ethereum.window.
I installed web3 package like @Bhujanga suggested and tried the code but the local host rejects web3, anything with web3.js

I followed a tutorial from Metamask and combined it from a youTube guy and It works but I can only get my account to show but not balance since some of the code is old but I cannot get it read the abi so I can start creating the crypto cats

https://docs.metamask.io/guide/create-dapp.html#project-setup
this is the tutorial but I still need to access the abi

// 1 Basic Action(Part 1)


const forwarderOrigin = 'http://localhost:7545';

const initialize = () => {
  //You will start here
  //const { ethers } = require("ethers");
  //import { ethers } from "ethers";
  
  const onboardButton = document.getElementById('connectButton');
  const getAccountsButton = document.getElementById('getAccounts');
  const getAccountsResult = document.getElementById('getAccountsResult');
  const showBalance = document.getElementById('showbalance')

  //Created check function to see if the MetaMask extension is installed
  const isMetaMaskInstalled = () => {
    //Have to check the ethereum binding on the window object to see if it's installed
    const { ethereum } = window;
    return Boolean(ethereum && ethereum.isMetaMask);
  };

  

  //We create a new MetaMask onboarding object to use in our app
  //import MetaMaskOnboarding from '@metamask/onboarding';
 /*
  import MetaMaskOnboarding from '@metamask/onboarding';
  const onboarding = new MetaMaskOnboarding({ forwarderOrigin });

  //This will start the onboarding proccess
  const onClickInstall = () => {
    onboardButton.innerText = 'Onboarding in progress';
    onboardButton.disabled = true;
    //On this object we have startOnboarding which will start the onboarding process for our end user
    onboarding.startOnboarding();
  };
  */


  const onClickConnect = async () => {
    try {
      // Will open the MetaMask UI
      // You should disable this button while the request is pending!
      await ethereum.request({ method: 'eth_requestAccounts' });
    } catch (error) {
      console.error(error);
    }
  };

  //------Inserted Code------\\
  const MetaMaskClientCheck = () => {
    //Now we check to see if Metmask is installed
    if (!isMetaMaskInstalled()) {
      //If it isn't installed we ask the user to click to install it
      onboardButton.innerText = 'Click here to install MetaMask!';
      //When the button is clicked we call this function
      onboardButton.onclick = onClickInstall;
      
      //The button is now disabled
      onboardButton.disabled = false;
    } else {
      //If it is installed we change our button text
      onboardButton.innerText = 'Connect';
       //When the button is clicked we call this function to connect the users MetaMask Wallet
      onboardButton.onclick = onClickConnect;
      //The button is now disabled
      onboardButton.disabled = false;
    }
  };
  MetaMaskClientCheck();
  //------/Inserted Code------\\

  // last step, grab data
  //Eth_Accounts-getAccountsButton
    getAccountsButton.addEventListener('click', async () => {
    //we use eth_accounts because it returns a list of addresses owned by us.
    const accounts = await ethereum.request({ method: 'eth_accounts' });
    //We take the first address in the array of addresses and display it
    getAccountsResult.innerHTML = accounts[0] || 'Not able to get accounts';

    const balance = await ethereum.request({ method: 'eth_getBalance', params: [accounts, 'latest']});
    const read = parseInt[balance] / 10**18; // ten to the 18th power
    //console.log((read.toFixed(5)));
    showBalance.innerHTML = read.toFixed(5) || 'Not able to get accounts'

  });


};
window.addEventListener('DOMContentLoaded', initialize);

try to console.log(window.web3)
what do you get?
If you get undefined, your window object does not have any web3 injected. if so, make sure to install web3 either with npm i web3 or get web3.min.js and import it inside your html file.

I’ve done all of that but I keep getting errors - - I’ll keep trying –

<script typ="module" src="https://unpkg.com/@metamask/detect-provider/dist/detect-provider.min.js"></script>
  <script type="text/javascript">
  (async () => {
    const provider = await detectEthereumProvider()
   
    if (provider) {
      // handle provider
      options.mustBeMetaMask
    } else {
      // handle no provider
      options.silent
    }

  })
    
  </script>  
 
  <script type="text/javascript" src="assets/js/jquery-3.4.1.js"></script>
    
 
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <!--<script src="assets/bootstrap/js/popper.js"></script>-->
  
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script type="module" src="assets/node_modules/web3/dist/web3.min.js"></script>
  
  <script type="text/javascript"src="./abi.js" ></script>

  <!--<script src="./metamask-onboarding-main.bundle.js"></script>-->
  
  <script src="https://cdn.ethers.io/lib/ethers-5.0.umd.min.js" type="text/javascript">
  </script>

  <script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
    type="application/javascript"></script>

Here are two files from an older project of mine were I build an ERC20 Token contract and build a frontend to it. It is deployed on Mumbai Testnet (Polygon Testnet). You can check it out here. Make sure to set up your metamask to run on Mumbai testnet to use the dapp.

So these two files can serve you as a example/template. I hope this helps you out :slight_smile: I know how hard it can be to get everything working when you are starting out on this journey. Keep going! You will get there!

exampleHTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossorigin="anonymous"></script>
    <script src="jquery-ui.js"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <link rel="stylesheet" href="style.css" />
    <script src="web3.min.js"></script>
    <script src="abi.js"></script>
    <script src="main.js"></script>
    <title>My TestNet Token</title>
</head>
<body>
    <div class="tokenHeader">
        <table>
            <tbody>
                <tr>
                    <td><h1>Welcome to MyTestNetToken</h1>
                        <p>An ERC20 Token dApp for educational purposes</p>
                    </td>
                    <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                    <td>
                        <div class="contractBalances">
                            <h4>Name:</h4><span style="align: center" id="tokenName"></span><br/>
                            <h4>Symbol:</h4><span style="align: center" id="tokenSymbol"></span><br/>
                        </div>
                    </td>
                    <td>
                        <div class="contractBalances">
                            <h4>Supply:</h4><span style="align: center" id="tokenTotalSupply"></span>
                            <h4>Decimals:</h4><span style="align: center" id="tokenDecimals"></span>
                        </div>
                    </td>
                    <td>
                        <div class="contractBalances">
                            <h4>Contract ETH Balance:</h4><span id="contractEthBalance"></span><br/>
                            <h4>Contract Token Balance:</h4><span id="contractTokenBalance"></span><br/>
                        </div>    
                    </td>
                </tr>
            </tbody>
        </table>    
    </div>
<br/>   
    
<div class="container">
    <div class="userData">
        <p>Your ETH Balance is: </p><span id="userEthBalance"></span><br/>
        <p>Your Token Balance is: </p><span id="userTokenBalance"></span><br/>
        <button class="btn-primary" id="requestTokens" style="border-radius: 10px;">Request 1000 FREE MTNT Tokens! (One time only)</button>
    </div>
    <div class="randomNumber">
        <img src="https://media.giphy.com/media/kbhgFU6739Zh3wZrn9/source.gif" alt="GuessNumber" width="200px" class="images" />
        <label for="userGuess">Guess a number between <br/>0 and 10 and WIN 0.1 ETH!</label>
        <input type="number" id="userGuess" placeholder="0 - 10" style="border-radius: 10px;" required></input>
        <button class="btn-primary" id="randomNumberBtn" style="border-radius: 10px;">Guess!</button>
    </div>
    
</div>

<br/>   


<div class="container">  
    <div class="makeTransaction">
        <p>Transfer Token:</p>
        <label for="transferRecipient">Recipient Address</label><br/>
        <input type="text" id="transferRecipient" style="border-radius: 10px;"></input><br/>
        <label for="transferTokenAmount">Amount of MTNT to Transfer in Wei</label><br/>
        <input type="number" id="transferTokenAmount" style="border-radius: 10px;"></input><br/>
        <button class="btn-primary" id="transferTokenBtn" style="border-radius: 10px;">Transfer Token(s)</button><br/>
    </div> 
    <div class="flipCoin" id="tokenFlip">
        <img src="https://media.giphy.com/media/6jqfXikz9yzhS/source.gif" alt="coinflipGIPHY" width="200px" class="images" />
        <p>Flip and WIN 100 MTNT Tokens</p>
        <input type="radio" id="heads" name="headTail" checked>Heads</button>
        <input type="radio" id="tails" name="headTail">Tails</button>
        <button class="btn-primary" id="flipToken" style="border-radius: 10px;">Flip Coin</button>
    </div>
  
</div>

<br/>   
<br/>

<div class="container">
    <div class="funding" id="fundingDiv">
        <p>Funding for Contract Owner:</p>
        <label for="fundingAmount">Amount in ETH to Fund the contract</label><br/>
        <input type="number" id="fundingAmount" style="border-radius: 10px;"></input><br/>
        <button class="btn-primary" id="fundContractBtn" style="border-radius: 10px;">Fund Contract!</button><br/>
    </div>
</div>
 
</body>
</html>
exampleJS
const web3 = new Web3(Web3.givenProvider);

var tokenContractAddress = "0x54956E74cb8bF3974A7a03Aef313287956E4c254";
var mtnt;
var x;
var y;
var didRequestToken;
var rewardGranted = false;

$(document).ready(function() {
    window.ethereum.enable().then(async function (accounts) {
        mtnt = new web3.eth.Contract(abi, tokenContractAddress, {from: accounts[0]});
        let user = ethereum.selectedAddress;
        console.log(user);
        userData();
        contractData();
        contractBalance();
        $("#transferTokenBtn").click(transferToken);
        $("#fundContractBtn").click(fundContract);
        $("#randomNumberBtn").click(getRandomNumber);
        $("#requestTokens").click(payToken);
        $("#grantRewardBtn").click(grantReward);
        $("#flipToken").click(flipCoin);
        
        x = document.getElementById("fundingDiv");
        y = document.getElementById("requestTokens");
        didRequestToken = await mtnt.methods.tokenRequested(user).call();
        console.log(didRequestToken);
        if(user != 0xE7D693e35fe25a6776523e1dE04F877A18f33B08) {
            x.style.display = "none";
        }
        if(didRequestToken){
            y.style.display = "none";
        }
    })
})

async function contractData() {
    let tokenName = await mtnt.methods.name().call();
    let tokenSymbol = await mtnt.methods.symbol().call();
    let tokenTotalSupply = await mtnt.methods.totalSupply().call();
    let tokenDecimals = await mtnt.methods.decimals().call();

    $("#tokenName").append(tokenName);
    $("#tokenSymbol").append(tokenSymbol);
    $("#tokenTotalSupply").append(tokenTotalSupply);
    $("#tokenDecimals").append(tokenDecimals);

    
}

async function userData() {
    let user = ethereum.selectedAddress;
    let userEthBalance = await web3.eth.getBalance(user);
    let userTokenBalance = await mtnt.methods.balanceOf(user).call();
    if(userTokenBalance == 0){
     console.log("Request Tokens!");
    }
    $("#userEthBalance").append(web3.utils.fromWei(userEthBalance)  + " ETH");
    $("#userTokenBalance").append(web3.utils.fromWei(userTokenBalance) + " MTNT");
}

async function transferToken () {
    let user = ethereum.selectedAddress;
    let recipient = $("#transferRecipient").val();
    let isAddress = web3.utils.isAddress(recipient);
    let transferAmount = $("#transferTokenAmount").val();
    if(isAddress){
        try{
            await mtnt.methods.transfer(recipient, transferAmount).send({from: user});
            location.reload();
        } catch(error){
            console.log(error);
        }
    } else {
        alert("Please enter a valid Ethereum address!");
    }

}

async function getRandomNumber() {
    let user = ethereum.selectedAddress;
    let userGuess = parseInt($("#userGuess").val());
    let randomNumber = Math.floor(Math.random() * 11);
    if(isNaN(userGuess)){
        alert("Please insert a valid number!");
    }
    else if(userGuess === randomNumber){
        alert("Correct! You WIN! Sign Transanction to receive 0.1 ETH! Page will reload after TX has been approved, please stand by...");
        let amount = web3.utils.toWei("0.1", "ether");
         await mtnt.methods.payout(amount).send({from: user});
         location.reload();
        } else{
        alert("You Loose! Your Guess: " + userGuess + " Correct number: " + randomNumber + " Try Again!");
    }
    
}

async function contractBalance() {
    let contractBalance = await web3.eth.getBalance(tokenContractAddress);
    $("#contractEthBalance").append(web3.utils.fromWei(contractBalance) + " ETH");
    let contractTokenBalance = await mtnt.methods.balanceOf(tokenContractAddress).call();
    $("#contractTokenBalance").append(web3.utils.fromWei(contractTokenBalance) + " MTNT");
}

async function fundContract() {
    let fundingAmount = parseInt(web3.utils.toWei($("#fundingAmount").val()));
    try{
        await web3.eth.sendTransaction({from: ethereum.selectedAddress, to: tokenContractAddress, value: fundingAmount});
        location.reload();
    } catch (error) {
        console.log(error);
    }
}

async function payToken(){
    let user = ethereum.selectedAddress;
    if(didRequestToken == true){
        alert("You already did request Tokens once!");
    } else{
        try{
            await mtnt.methods.payToken().send({from: user});
            location.reload();
        } catch (error) {
            console.log(error.reason);
        }
    }
  
}

async function grantReward() {
    let user = ethereum.selectedAddress;
    await mtnt.methods.setRewardGranted().send();
    let isGranted = await mtnt.methods.rewardGranted(user).call();
    console.log(isGranted);
    rewardGranted = true;
    payTokenReward();
}

async function payTokenReward(){
    if(rewardGranted == true){
        try{
            await mtnt.methods.tokenReward().send();
            rewardGranted = false;
            location.reload();
        } catch (error) {
            console.log(error);
        }
    } else {
        alert("You have not been granted any rewards!");
    }    
}

async function flipCoin(){
    var heads = $("#heads").is(':checked');
    var tails = $("#tails").is(':checked');
    var bet;
    var flip = Math.floor(Math.random() * 2);
    if (flip == 0 && heads || flip == 1 && tails){
        alert("You win! 100 MTNT Tokens go to your Account!");
        grantReward();
    } else {
        alert ("You loose!");
    }
}

2 Likes

thanks , I appreciated it

1 Like

I stared over - following Filip’s tutorial and for some reason, injected web3 worked and did not get deprecated errors, strange…well, it’s working, thanks for your support

2 Likes

keep pushing :grin: it is not too far away

3 Likes

Wwo thanks for this info I able to solve my issue for my Metamask :wink:

Great! Thanks for this able to solve my issue on Metamask :wink: