Open In App

How To Fix the Error “Metamask stopped injecting Web3”?

Last Updated : 30 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s see some basic terminologies first as follows:

  • Metamask: Metamask is a cryptocurrency software wallet that interacts with the Ethereum network.
  • web3.js: web3.js is a collection of libraries that allow you to interact with a local or remote Ethereum node using HTTP, IPC, or WebSocket. 
  • Blockchain: A blockchain is a digitally distributed, decentralized, public ledger that exists across a network. Almost all of the cryptocurrencies, dApps, Defi, and NFT are based on blockchain technology.
  • Ethereum: Ethereum is the most popular decentralized, open-source blockchain technology in the world. Smart contracts are deployed on the Ethereum blockchain.
  • dApps: Decentralized apps or dApps are applications that run on peer-to-peer networks based on the distributed nature of blockchain.

Setting up web3 project: To set up a web3 project please refer to the following:

  1. How to Set up Ganache with Metamask? 
  2. Creating dApps using the Truffle Framework.  

Project Structure: In the end, the folder structure should look like:

 

The problem: It may happen that you were either working on some project or following some tutorial that was using a legacy version of web3.js. Now, will/can give the following errors:

  1. Metamask stopped injecting Web3.
  2. Web3 is not a constructor.
  3. The send transactions “from” field must be defined.
  4. (intermediate value).toBigNumber is not a function.
  5. Cannot read property ‘accounts’ of undefined.
  6. You are accessing the MetaMask window.web3.currentProvider shim. This property is deprecated.

It is because MetaMask stopped injecting web3.js, somewhere in 2021. In a blog post they wrote:

Web3@0.20.x is currently used by MetaMask, however it is no longer receiving patches or updates. Some safety validations were also missing in 0.20.x, which caused issues for our users.
The removal of web3.js is part of a larger effort to simplify MetaMask’s API and provide the most secure and stable experience possible. 
If dapps want to use a convenience library in early 2021, they’ll have to bring their own. 

The solution: Fixing these errors includes a series of steps.

Step 1: Update the development environment and testing frameworks( “devDependencies”) like truffle, ganache, etc. to the latest version.

Step 2: Install and import web3.js on the client-side of the application.

via npm

npm install web3

via CDN

<script src=”https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js”></script>

Note: Import web3 before calling any development framework(like truffle-contract).

Step 3: Follow Metamask’s migration guide and update any legacy code. Some common examples are:

Loading web3

window.addEventListener(‘load’, async () => {

// Modern dapp browsers…

if (window.ethereum) {

    window.web3 = new Web3(ethereum);

    try {

        // Request account access if needed

        await ethereum.enable();

        // Accounts now exposed

        web3.eth.sendTransaction({/* … */});

    } catch (error) {

        // User denied account access…

    }

}

// Legacy dapp browsers…

else if (window.web3) {

    window.web3 = new Web3(web3.currentProvider);

    // Accounts always exposed

    web3.eth.sendTransaction({/* … */});

}

// Non-dapp browsers…

else {

    console.log(‘Non-Ethereum browser detected. You should consider trying MetaMask!’);

}

Connecting to an Ethereum Node

const web3 = new Web3(new Web3.providers.HttpProvider(‘http://localhost:8545’));

Fetching Accounts 

const accounts = await ethereum.request({ method: ‘eth_accounts’ });

Sending a Transaction

try {

 const transactionHash = await ethereum.request({

   method: ‘eth_sendTransaction’,

   params: [

     {

      to: address,

      from: window.web3.currentProvider.selectedAddress,

      value: amount,

      gasPrice: ‘20000000000’ 

     },

   ],

 });

 // Handle the result

 console.log(transactionHash);

} catch (error) {

 console.error(error);

}

After updating the legacy code: After updating the legacy code, deploy your smart contract with truffle and run your web server. Verify the changes by logging into your metamask account or by visiting the transactions on ganache blockchain.

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads