window.web3.currentProvider & ethereum.enable deprecated

Metamask has deprecated window.web3.currentProvider as well as ethereum.enable()
ethEnabledeprecated
Does anyone know what is the new best practice and can provider a boiler-plate?
I did check Metamask documentation, and other resources, but can’t yet find out how to connect the frontend to the smart contract in the new way?

For now I am still going with:

const web3 = new Web3(Web3.givenProvider);

var tokenContractAddress = "0x3F0.....22";
var mtnt;

$(document).ready(function() {
    window.ethereum.enable().then(function (accounts) {
        mtnt = new web3.eth.Contract(abi, tokenContractAddress, {from: accounts[0]});

        console.log(mtnt);
    })
})

Any help much appreciated :pray:

You have to install metamask Legacy Web3 Extension. For me at least solve that problem. Try it and let me know.

3 Likes

thanks @kenn.eth, As I can see, this will help to keep deprecated code alive. Nice find. But how do we actually use the new implementation?

Check out new implementation at https://web3js.readthedocs.io/en/v1.2.6/

2 Likes

That’s cool thanks. Also, I found this one just today, and I really like it:

if (window.ethereum) {
  App.web3Provider = window.ethereum;
  try {
    // Request account access
    await window.ethereum.enable();
  } catch (error) {
    // User denied account access...
    console.error("User denied account access")
  }
}
// Legacy dapp browsers...
else if (window.web3) {
  App.web3Provider = window.web3.currentProvider;
}
// If no injected web3 instance is detected, fall back to Ganache
else {
  App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);
3 Likes

Hello I have a question.
What is the App from App.web3Provider ?
Did you import it like this?:

const App= require("web3");

If so, how did you use require in JS?

require is not available in the browser. It is used in Node.js.
In the browser you just include the scripts calling the file in the HTML. Like :

 <script src"..."></script>

When we include it like that, you can just call the object class directly.
For example.

const App = new Web3()
2 Likes

@filip , @dan-i

Hello Devs

I would like to know what is the best way to proceed. I am trying to start using web3 but is has been depreciated " Web3.js Start Coding" lesson 2 of 4.

I have been trying to read the docs and implement the new way but no luck yet. Any suggestions?

1 Like

Hey @bjamRez ! Can you share your code. Share a github repo or just paste it here.

https://github.com/brlojam4932/bl_crytpKittiesProj.git

above, the link to my Github project.
Also, I began implementing the new eth methods from here:

https://docs.metamask.io/guide/create-dapp.html#project-setup

youTube tutorial
https://youtu.be/NseL8v9EH_Q

in the index.js file, I managed to link my Ganache account to my kitty website but I am having trouble accessing the abi.

here is just the index.js file with the new eth methods from metamask and another tutorial I followed which It can print back my eth address from Metamask but not my balance

// 1 Basic Action(Part 1)

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

const initialize = () => {
  //You will start here
  
  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();
  };
  */

  // I just managed to get the abi with this code =================
  $(document).ready(async () => {
    const accounts = await ethereum.request({ method: 'eth_accounts' });
    const instance = ethereum.request({method: 'eth_requestAccounts', params: [accounts[0]] }, window.abi, 0x51d9aD5C5EB7FDBB444D78ADE2a194f87dcEf735);

      console.log(instance);

      instance.methods
  });
  //================================================================ 


  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);

I just watched a Moralis video with Filip and changed the code and it seems to be giving e access to the windoe.abi

…this is what I changed:

// I just managed to get the abi with this code =================
  $(document).ready(async () => {
    const accounts = await ethereum.request({ method: 'eth_accounts' });
    const instance = ethereum.request({method: 'eth_requestAccounts', params: [accounts[0]] }, window.abi, 0x51d9aD5C5EB7FDBB444D78ADE2a194f87dcEf735);

      console.log(instance);

      instance.methods
  });
  //================================================================ 

…but I may have spoken too soon, I don’t see Methods in the console so this might not be the code yet

1 Like

@kenn.eth
hey Kenn, I just figured out a way to retrieve the abi in the console. I have part of the code here and the rest, follow the link to the my Github files
— I spoke too soon - it’s not right

2 Likes

@kenn.eth, @REGO350
sorry - the code is not right - spoke too soon

I re-edited my code but it’s still not working

 $(async () => {

      try {
        // Request account access if needed
        const accounts = await ethereum.request('eth_requestAccounts');
        // Accounts now exposed, use them
        const instance = ethereum.request('eth_sendTransaction', {from: accounts[0], abi: "0x51d9aD5C5EB7FDBB444D78ADE2a194f87dcEf735"});

        console.log(instance);
        
        instance.methods.createKittyGen0(dnaStr).send({}, function(error, txHash)

        {
          if(error)
          console.log(error); 
          else{
            console.log(txHash);
            }
        });
        
      } catch (error) {
          // User denied account access
      }
       
  });

Hello

I think this part:

const instance = ethereum.request('eth_sendTransaction', {from: accounts[0], abi: "0x51d9aD5C5EB7FDBB444D78ADE2a194f87dcEf735"});

is not correct because abi should be a json file.

Here, I am using the latest web3js version but try this:

web3 = new Web3(Web3.givenProvider);
const accounts = await window.ethereum.request({method: "eth_requestAccounts"});
const instance = new web3.eth.Contract(abi, address, { from: accounts[0] });
1 Like

thanks, I was trying to use the new eth window since web3 gives me all of these errors and it looks like it’s not being used anymore. - thanks I’ll try to go back to this

1 Like

sorry, I see you have changed some things - it’s not the same - I started to implement it and it did something but I have change the code so much - i’ll have to go back to what i had prviously and retry your code

1 Like

I am all over the place now - but here is how I tried to implement your code. it’s doing something but not quite there yet with this code set up

$(async () => {

    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });

    // window.ethereum
    try {
      const transactionHash = await ethereum.request({
        method:  'eth_sendTransaction',
        params: [
          {
            abi,
            address: "0x51d9aD5C5EB7FDBB444D78ADE2a194f87dcEf735",
            from: accounts[0]

          },
        ],
      });
      // Handle the result
      console.log(transactionHash);
    } catch (error) {
      console.error(error);
    }  
        
  });
4 Likes

Read up on web3 implementation here
although a little tricky in the beginning, it is very good practice to get accustomed to reading the docs. Once you get the hang of that, lot’s of things will literally become an open book.

3 Likes

Hello Bhujanga,

I am trying to use the new way of doing this with the Ethereum window
https://docs.metamask.io/guide/#why-metamask
…since web3 has been deprecated, I would like to learn the latest methods but I have not heard from the devs so far so I may follow your advise and install web3 since the link of the file that Filip supplied is also not working

1 Like

yea it is good to stay up to date to best practices. check out this link here

1 Like

nice, this looks promising

1 Like