Internal json rpc error что это

I am using getWeb3() to instantiate a contract and make calls with, the transaction says that is confirmed but when I open up developer tools there is the following error MetaMask - RPC Error: Inte...

I am using getWeb3() to instantiate a contract and make calls with, the transaction says that is confirmed but when I open up developer tools there is the following error MetaMask - RPC Error: Internal JSON-RPC error.

I am not sure what is wrong with my code.. (it is mostly from the Truffle react-box)

import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./utils/getWeb3";

import "./App.css";

class App extends Component {
  state = { storageValue: 0, web3: null, accounts: null, contract: null };

  componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();
      // Use web3 to get the user's accounts.
      const accounts = await web3.eth.getAccounts();

      // Get the contract instance.
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = SimpleStorageContract.networks[networkId];
      const instance = new web3.eth.Contract(
        SimpleStorageContract.abi,
        deployedNetwork && deployedNetwork.address,
      );

      // Set web3, accounts, and contract to the state, and then proceed with an
      // example of interacting with the contract's methods.
      this.setState({ web3, accounts, contract: instance }, this.runExample);
    } catch (error) {
      // Catch any errors for any of the above operations.
      alert(
        `Failed to load web3, accounts, or contract. Check console for details.`,
      );
      console.error(error);
    }
  };

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.    
    getWeb3()
    .then(results => {
      this.setState({
        web3: results
      })

      // Instantiate contract once web3 provided.
      this.instantiateContract()
    })
    .catch((error) => {      
      console.log(error);
      console.log('Error finding web3.')
    })
  }

  instantiateContract() {
    /*
     * SMART CONTRACT EXAMPLE
     *
     * Normally these functions would be called in the context of a
     * state management library, but for convenience I've placed them here.
     */

    const contract = require('truffle-contract')
    const simpleStorage = contract(SimpleStorageContract)
    simpleStorage.setProvider(this.state.web3.currentProvider)

    // Declaring this for later so we can chain functions on SimpleStorage.
    var simpleStorageInstance

    // Get accounts.
    this.state.web3.eth.getAccounts((error, accounts) => {
      simpleStorage.deployed().then((instance) => {
        simpleStorageInstance = instance

        this.setState(prevState => ({
          ...prevState,
          accounts,
          simpleStorageInstance
        }));

        // Stores a given value, 5 by default.
        return simpleStorageInstance.set(5, {from: accounts[0]})
      }).then((result) => {
        // Get the value from the contract to prove it worked.
        return simpleStorageInstance.get.call(accounts[0])
      }).then((result) => {
        // Update state with the result.
        return this.setState(prevState => ({
          ...prevState,
          storageValue: result.c[0]
        }))
      })
    })
  }

  runExample = async () => {
    const { accounts, contract } = this.state;

    // Stores a given value, 5 by default.
    await contract.methods.set(5).send({ from: accounts[0], gas: 100000 });

    // Get the value from the contract to prove it worked.
    const response = await contract.methods.get().call();

    // Update state with the result.
    this.setState({ storageValue: response });
  };

  addToSimpleStorage() {
    console.log("RUNNING");
    if (this.state.simpleStorageInstance && this.state.accounts) {
      const value = this.storageAmountInput.value;
      this.state.simpleStorageInstance.set(value, {from: this.state.accounts[0]})
        .then((result) => {
          return this.state.simpleStorageInstance.get.call(this.state.accounts[0])
        }).then((result) => {
          this.setState(prevState => ({
            ...prevState,
            storageValue: result.c[0]
          }));
        }).catch((err) => {
          console.log('error');
          console.log(err);
        });
    } else {
      this.setState(prevState => ({
        ...prevState,
        error: new Error('simple storage instance not loaded')
      }))
    }
  }

  render() {
    if (!this.state.web3) {
      return <div>Loading Web3, accounts, and contract...</div>;
    }
    return (
      <div className="App">
        <h1>Good to Go!</h1>
        <p>Your Truffle Box is installed and ready.</p>
        <h2>Smart Contract Example</h2>
        <p>
          If your contracts compiled and migrated successfully, below will show
          a stored value of 5 (by default).
        </p>
        <p>
          Try changing the value stored on <strong>line 40</strong> of App.js.
        </p>
        <div>The stored value is: {this.state.storageValue}</div>
        <form className="pure-form pure-form-stacked">
          <fieldset>
            <label htmlFor="storage">Storage Amount</label>
            <input id="storage" type="number" ref={c => { this.storageAmountInput = c }} />
            <button
              className="pure-button"
              onClick={(e) => {
                e.preventDefault();
                this.addToSimpleStorage()
              }}
            >
              Set Storage
            </button>
          </fieldset>
        </form>
      </div>
    );
  }
}

export default App;

I am using getWeb3() to instantiate a contract and make calls with, the transaction says that is confirmed but when I open up developer tools there is the following error MetaMask - RPC Error: Internal JSON-RPC error.

I am not sure what is wrong with my code.. (it is mostly from the Truffle react-box)

import React, { Component } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./utils/getWeb3";

import "./App.css";

class App extends Component {
  state = { storageValue: 0, web3: null, accounts: null, contract: null };

  componentDidMount = async () => {
    try {
      // Get network provider and web3 instance.
      const web3 = await getWeb3();
      // Use web3 to get the user's accounts.
      const accounts = await web3.eth.getAccounts();

      // Get the contract instance.
      const networkId = await web3.eth.net.getId();
      const deployedNetwork = SimpleStorageContract.networks[networkId];
      const instance = new web3.eth.Contract(
        SimpleStorageContract.abi,
        deployedNetwork && deployedNetwork.address,
      );

      // Set web3, accounts, and contract to the state, and then proceed with an
      // example of interacting with the contract's methods.
      this.setState({ web3, accounts, contract: instance }, this.runExample);
    } catch (error) {
      // Catch any errors for any of the above operations.
      alert(
        `Failed to load web3, accounts, or contract. Check console for details.`,
      );
      console.error(error);
    }
  };

  componentWillMount() {
    // Get network provider and web3 instance.
    // See utils/getWeb3 for more info.    
    getWeb3()
    .then(results => {
      this.setState({
        web3: results
      })

      // Instantiate contract once web3 provided.
      this.instantiateContract()
    })
    .catch((error) => {      
      console.log(error);
      console.log('Error finding web3.')
    })
  }

  instantiateContract() {
    /*
     * SMART CONTRACT EXAMPLE
     *
     * Normally these functions would be called in the context of a
     * state management library, but for convenience I've placed them here.
     */

    const contract = require('truffle-contract')
    const simpleStorage = contract(SimpleStorageContract)
    simpleStorage.setProvider(this.state.web3.currentProvider)

    // Declaring this for later so we can chain functions on SimpleStorage.
    var simpleStorageInstance

    // Get accounts.
    this.state.web3.eth.getAccounts((error, accounts) => {
      simpleStorage.deployed().then((instance) => {
        simpleStorageInstance = instance

        this.setState(prevState => ({
          ...prevState,
          accounts,
          simpleStorageInstance
        }));

        // Stores a given value, 5 by default.
        return simpleStorageInstance.set(5, {from: accounts[0]})
      }).then((result) => {
        // Get the value from the contract to prove it worked.
        return simpleStorageInstance.get.call(accounts[0])
      }).then((result) => {
        // Update state with the result.
        return this.setState(prevState => ({
          ...prevState,
          storageValue: result.c[0]
        }))
      })
    })
  }

  runExample = async () => {
    const { accounts, contract } = this.state;

    // Stores a given value, 5 by default.
    await contract.methods.set(5).send({ from: accounts[0], gas: 100000 });

    // Get the value from the contract to prove it worked.
    const response = await contract.methods.get().call();

    // Update state with the result.
    this.setState({ storageValue: response });
  };

  addToSimpleStorage() {
    console.log("RUNNING");
    if (this.state.simpleStorageInstance && this.state.accounts) {
      const value = this.storageAmountInput.value;
      this.state.simpleStorageInstance.set(value, {from: this.state.accounts[0]})
        .then((result) => {
          return this.state.simpleStorageInstance.get.call(this.state.accounts[0])
        }).then((result) => {
          this.setState(prevState => ({
            ...prevState,
            storageValue: result.c[0]
          }));
        }).catch((err) => {
          console.log('error');
          console.log(err);
        });
    } else {
      this.setState(prevState => ({
        ...prevState,
        error: new Error('simple storage instance not loaded')
      }))
    }
  }

  render() {
    if (!this.state.web3) {
      return <div>Loading Web3, accounts, and contract...</div>;
    }
    return (
      <div className="App">
        <h1>Good to Go!</h1>
        <p>Your Truffle Box is installed and ready.</p>
        <h2>Smart Contract Example</h2>
        <p>
          If your contracts compiled and migrated successfully, below will show
          a stored value of 5 (by default).
        </p>
        <p>
          Try changing the value stored on <strong>line 40</strong> of App.js.
        </p>
        <div>The stored value is: {this.state.storageValue}</div>
        <form className="pure-form pure-form-stacked">
          <fieldset>
            <label htmlFor="storage">Storage Amount</label>
            <input id="storage" type="number" ref={c => { this.storageAmountInput = c }} />
            <button
              className="pure-button"
              onClick={(e) => {
                e.preventDefault();
                this.addToSimpleStorage()
              }}
            >
              Set Storage
            </button>
          </fieldset>
        </form>
      </div>
    );
  }
}

export default App;

Welcome to this guide, where we will see how to fix the internal json-rpc error that you may have encountered sometime using Metamask and you can’t fix the problem.

Let’s take a look at the solution we have found, and you can use to bypass this problem.

To do this:

If you see the error “Internal JSON-RPC error” when trying to interact with another network, I recommend you try the following:

  • Make sure that the network you are using has been added correctly. You can use Chainlist to add custom networks/tokens.
  • Make sure you have enough tokens native to that network (e.g. Etheruem on the Ethereum network, BNB on the BSC, etc.) to pay the gas transaction fee.
  • Make sure you have the Metamask extension or mobile app updated.

The problem usually comes from the network configuration. To do this, I recommend you check that you have the correct information, and try to add the network again with other information. Because many times, there are different RPC points, or what we indicate in the second box of new rpc url. Sometimes, the network is congested and some RPC points work worse than others, and adding the network with a different url in new RPC URL can solve this problem. To find out about the different RPCs, search for the network and RPC in Google or you can search this list to find the documentation listing all the urls you can use for that network. For example, in the case of polygon, we have: https://polygon-rpc.com/, https://rpc-mainnet.matic.network, https://rpc-mainnet.maticvigil.com and many more.

In the list, simply enter the network name with control+f and you will see the RPCs for each network that are listed in Chainlist and can be used in your metamask.

Another solution that sometimes works is to restart the app or uninstall the app or extension and reinstall it. But always do this if you have the recovery phrase and can import your Metamask account again.

I hope this has helped you to find out how you can fix this annoying metamask problem. Remember, if you don’t have an account with Binance, you can create one just below.

Содержание

  1. Exceptions¶
  2. JSON-RPC Errors¶
  3. JSON-RPC Exceptions¶
  4. Solution Metamask RPC Error Internal json-rpc
  5. Understanding and resolving MetaMask error codes
  6. 32700
  7. 32600
  8. 32601
  9. 32602
  10. 32603
  11. 32000
  12. Over 200k developers use LogRocket to create better digital experiences
  13. 32001
  14. 32002
  15. 32003
  16. 32004
  17. 32005
  18. Conclusion
  19. Join organizations like Bitso and Coinsquare who use LogRocket to proactively monitor their Web3 apps
  20. Name already in use
  21. json-rpc / docs / source / exceptions.rst

Exceptions¶

According to specification, error code should be in response message. Http server should respond with status code 200, even if there is an error.

JSON-RPC Errors¶

Error is an object which represent any kind of erros in JSON-RPC specification. It is not python Exception and could not be raised.

Errors (Error messages) are members of JSONRPCError class. Any custom error messages should be inherited from it. The class is responsible for specification following and creates response string based on error’s attributes.

JSON-RPC has several predefined errors, each of them has reserved code, which should not be used for custom errors.

Code Message Meaning
-32700 Parse error Invalid JSON was received by the server.An error occurred on the server while parsing the JSON text.
-32600 Invalid Request The JSON sent is not a valid Request object.
-32601 Method not found The method does not exist / is not available.
-32602 Invalid params Invalid method parameter(s).
-32603 Internal error Internal JSON-RPC error.
-32000 to -32099 Server error Reserved for implementation-defined server-errors.

JSONRPCResponseManager handles common errors. If you do not plan to implement own manager, you do not need to write custom errors. To controll error messages and codes, json-rpc has exceptions, covered in next paragraph.

JSON-RPC Exceptions¶

Exception here a json-rpc library object and not related to specification. They are inherited from python Exception and could be raised.

JSON-RPC manager handles dispatcher method’s exceptions, anything you raise would be catched. There are two ways to generate error message in manager:

First is to simply raise exception in your method. Manager will catch it and return JSONRPCServerError message with description. Advantage of this mehtod is that everything is already implemented, just add method to dispatcher and manager will do the job.

If you need custom message code or error management, you might need to raise exception, inherited from JSONRPCDispatchException . Make sure, your exception class has error code.

New in version 1.9.0: Fix Invalid params error false generated if method raises TypeError. Now in this case manager introspects the code and returns proper exception.

© Copyright 2013-2015, Kirill Pavlov. Revision f1b4e5e9 .

Источник

Welcome to this guide, where we will see how to fix the internal json-rpc error that you may have encountered sometime using Metamask and you can’t fix the problem.

Let’s take a look at the solution we have found, and you can use to bypass this problem.

If you see the error “Internal JSON-RPC error” when trying to interact with another network, I recommend you try the following:

  • Make sure that the network you are using has been added correctly. You can use Chainlist to add custom networks/tokens.
  • Make sure you have enough tokens native to that network (e.g. Etheruem on the Ethereum network, BNB on the BSC, etc.) to pay the gas transaction fee.
  • Make sure you have the Metamask extension or mobile app updated.

The problem usually comes from the network configuration. To do this, I recommend you check that you have the correct information, and try to add the network again with other information. Because many times, there are different RPC points, or what we indicate in the second box of new rpc url. Sometimes, the network is congested and some RPC points work worse than others, and adding the network with a different url in new RPC URL can solve this problem. To find out about the different RPCs, search for the network and RPC in Google or you can search this list to find the documentation listing all the urls you can use for that network. For example, in the case of polygon, we have: https://polygon-rpc.com/, https://rpc-mainnet.matic.network, https://rpc-mainnet.maticvigil.com and many more.

In the list, simply enter the network name with control+f and you will see the RPCs for each network that are listed in Chainlist and can be used in your metamask.

Another solution that sometimes works is to restart the app or uninstall the app or extension and reinstall it. But always do this if you have the recovery phrase and can import your Metamask account again.

I hope this has helped you to find out how you can fix this annoying metamask problem. Remember, if you don’t have an account with Binance, you can create one just below.

Источник

May 6, 2022 6 min read 1737

MetaMask gives us the ability to access decentralized applications (dApps) while offering a form of authentication using the MetaMask wallet. It provides a one-click secure login flow that allows us to access the blockchain resources using ethers on the front end. MetaMask abstracts delicate processes like signing transactions while interacting with the blockchain, and provides your MetaMask’s public address to the application.

Thus, as developers, when building these dApps, there are bound to be errors, and these errors should be handled appropriately so both the developers and users can know what is wrong. Because the MetaMask documentation does not have a comprehensive and clear guide to the many types of errors that might come up while working with MetaMask, I have compiled a list here of the most common errors and what they mean.

You can jump to the error codes outlined in this article with the following links:

When trying to connect to the wallet, if a user clicks “Cancel” at any point on this interface and terminates the process, it returns a 4001 error.

Here’s the JSON structure of the error:

This error occurs when the dApp wants to take action concerning an account that is not authorized.

For instance, to do certain actions like signing a message, you need to first get account permission from MetaMask, using the eth_requestAccounts method:

Similarly, to switch the chain of your wallet, you need to use the wallet_switchEthereumChain method, which in turn asks for permission through MetaMask extension:

If the permission is denied, the wallet returns this error:

MetaMask enables two methods: restricted and unrestricted. These methods allow the dApp to take actions like connecting to the wallet, signing transactions, and adding or switching networks.

This error is returned for the methods that aren’t supported on MetaMask:

This error is returned when the user’s MetaMask wallet is not connected to any chain:

It has to do with the disconnect event. This event is triggered when the wallet is disconnected and it becomes unable to submit requests to a chain. Besides disconnection, this can also happen due to network connectivity issues.

Once we emit disconnect , the provider will not accept any new requests until the connection to the chain has been reestablished, which requires reloading the page. You can also use the ethereum.isConnected() method to determine if the provider is disconnected.

Here’s the error’s JSON response:

This error means the user is not connected to the appropriate chain for that transaction. For example, if a transaction requires the user to be on the Polygon chain, and they’re on Harmony or Ethereum blockchain.

One thing to note is that the MetaMask provider allows us to listen to the chainChanged event that listens and acts if the currently connected chain changes:

We submit our RPC requests to the currently connected chain, which makes it important to keep track of the current chain ID by listening for changes. Every chain has its unique chainID, which you can find on Chainlist.

It returns the error if it becomes unable to submit RPC requests to that specific chain:

32700

This error is returned if the user sends an incomplete request object to the contract. It can occur if the object sent to the contract does not contain all the data that it requires.

Here’s the JSON response:

32600

Here, the object is valid, but the structure or properties aren’t correct. It’s somewhat similar to 32700, but in this case, it’s the internal structure that’s not correct.

Here’s the JSON response:

32601

This error is returned if the method specified does not exist at all:

32602

We get this error if the arguments passed into an RPC method is incorrect. For instance, when defining the transactionParameters , the from property references accounts[0] .

Ordinarily, accounts[0] is supposed to be the user’s wallet address, but in this case, we assign it to an empty array:

The Mint function will return this particular error because the parameter is clearly invalid:

32603

This is a blanket error caused by several things. It might be because you’re trying to add a new chain to your wallet (manually or through the dApp) but added the wrong chain data. Or, you’re trying to complete a transaction, but you don’t have enough tokens to pay the gas fee. For instance, if you’re transacting on the Ethereum mainnet, you have to pay gas fees in ETH regardless of whether you’re transacting using other tokens.

Finally, it could be as trivial as not having the latest version of MetaMask.

Here’s the error JSON response:

32000

One scenario that can trigger this error is when the contract address used in production is the contract you deployed to the testnet. This is a simple error that we can correct.

Similar to Web2 where we have a dev environment and a production environment, when building dApps, we use testnet to deploy our contract, so we can test it while building without using real ETH on mainnet. As such, the same contract deployed on testnet and mainnet will have different addresses. If you use the wrong address for the chain you’re on, this error is returned.

Over 200k developers use LogRocket to create better digital experiences

In general, when dealing with smart contracts, you need params like the contract address, the ABI file, and your signer:

If any of these params are wrong, you’ll most likely get his error, also referred to as a “user input error”:

32001

In this case, the resource we’re requesting does not exist on the blockchain. It’s possibly a typo from the client side.

Imagine you’re trying to get info about a non-existent block number on the ETH chain:

You would get this JSON response:

32002

This error means the requested resource does exist, but it’s currently unavailable at the time of the request. This can occur when we are trying to access a resource that’s currently in use. It can happen on the MetaMask extension when you’re trying to use a particular resource/method, like switching chains when the MetaMask is currently in the process of doing the same.

When building your dApp, you should learn to disable your button once that method has been successfully initiated, so user is not clicking in quick succession.

Here’s this error’s JSON response:

32003

This error could be a result of many things. It could be because the sender’s address doesn’t exist, insufficient funds, the account is locked, or we can’t sign the transaction. To fix this, make sure everything in your transaction is correct.

The transaction can be rejected if the conditions needed to complete the transaction aren’t satisfied:

32004

The method is not supported at all. Possibly, it doesn’t exist or there’s just a typographical error:

32005

This error means the RPC provider has a rate limit that has been exceeded. This issue can occur if the RPC provider endpoint has a rate limit for the number of requests:

Also, there’s a fairly common error with the error message “intrinsic gas too low.” It’s simply because the gas limit that’s assigned when initiating the transaction is less than what is required.

This occurs most often in cases where there’s a complex transaction, which can make the gas fee unpredictable:

Conclusion

Congratulations if you’ve made it to the end! We covered a bunch of possible errors and how to deal with them. Now, when building your next dApp, you can easily interpret these errors and fix them without being confused about what caused them in the first place. This can help improve your developer experience dealing with these Web3 technologies.

You can check out more about MetaMask errors from the official resource.

Join organizations like Bitso and Coinsquare who use LogRocket to proactively monitor their Web3 apps

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — Start monitoring for free.

Источник

Name already in use

json-rpc / docs / source / exceptions.rst

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

According to specification, error code should be in response message. Http server should respond with status code 200, even if there is an error.

Error is an object which represent any kind of erros in JSON-RPC specification. It is not python Exception and could not be raised.

Errors (Error messages) are members of :class:`

jsonrpc.exceptions.JSONRPCError` class. Any custom error messages should be inherited from it. The class is responsible for specification following and creates response string based on error’s attributes.

JSON-RPC has several predefined errors, each of them has reserved code, which should not be used for custom errors.

Code Message Meaning
-32700 Parse error Invalid JSON was received by the server.An error occurred on the server while parsing the JSON text.
-32600 Invalid Request The JSON sent is not a valid Request object.
-32601 Method not found The method does not exist / is not available.
-32602 Invalid params Invalid method parameter(s).
-32603 Internal error Internal JSON-RPC error.
-32000 to -32099 Server error Reserved for implementation-defined server-errors.

jsonrpc.manager.JSONRPCResponseManager` handles common errors. If you do not plan to implement own manager, you do not need to write custom errors. To controll error messages and codes, json-rpc has exceptions, covered in next paragraph.

Exception here a json-rpc library object and not related to specification. They are inherited from python Exception and could be raised.

JSON-RPC manager handles dispatcher method’s exceptions, anything you raise would be catched. There are two ways to generate error message in manager:

First is to simply raise exception in your method. Manager will catch it and return :class:`

jsonrpc.exceptions.JSONRPCServerError` message with description. Advantage of this mehtod is that everything is already implemented, just add method to dispatcher and manager will do the job.

If you need custom message code or error management, you might need to raise exception, inherited from :class:`

Источник

According to specification, error code should be in response message. Http
server should respond with status code 200, even if there is an error.

JSON-RPC Errors¶

Note

Error is an object which represent any kind of erros in JSON-RPC specification. It is not python Exception and could not be raised.

Errors (Error messages) are members of JSONRPCError class. Any custom error messages should be inherited from it.
The class is responsible for specification following and creates response string based on error’s attributes.

JSON-RPC has several predefined errors, each of them has reserved code, which should not be used for custom errors.

Code Message Meaning
-32700 Parse error Invalid JSON was received by the server.An error occurred on the server while parsing the JSON text.
-32600 Invalid Request The JSON sent is not a valid Request object.
-32601 Method not found The method does not exist / is not available.
-32602 Invalid params Invalid method parameter(s).
-32603 Internal error Internal JSON-RPC error.
-32000 to -32099 Server error Reserved for implementation-defined server-errors.

JSONRPCResponseManager handles common errors. If you do not plan to implement own manager, you do not need to write custom errors. To controll error messages and codes, json-rpc has exceptions, covered in next paragraph.

JSON-RPC Exceptions¶

Note

Exception here a json-rpc library object and not related to specification. They are inherited from python Exception and could be raised.

JSON-RPC manager handles dispatcher method’s exceptions, anything you raise would be catched.
There are two ways to generate error message in manager:

First is to simply raise exception in your method. Manager will catch it and return JSONRPCServerError message with description. Advantage of this mehtod is that everything is already implemented, just add method to dispatcher and manager will do the job.

If you need custom message code or error management, you might need to raise exception, inherited from JSONRPCDispatchException. Make sure, your exception class has error code.

New in version 1.9.0: Fix Invalid params error false generated if method raises TypeError. Now in this case manager introspects the code and returns proper exception.

MetaMask gives us the ability to access decentralized applications (dApps) while offering a form of authentication using the MetaMask wallet. It provides a one-click secure login flow that allows us to access the blockchain resources using ethers on the front end. MetaMask abstracts delicate processes like signing transactions while interacting with the blockchain, and provides your MetaMask’s public address to the application.

Thus, as developers, when building these dApps, there are bound to be errors, and these errors should be handled appropriately so both the developers and users can know what is wrong. Because the MetaMask documentation does not have a comprehensive and clear guide to the many types of errors that might come up while working with MetaMask, I have compiled a list here of the most common errors and what they mean.

You can jump to the error codes outlined in this article with the following links:

  • 4001
  • 4100
  • 4200
  • 4900
  • 4901
  • 32700
  • 32600
  • 32601
  • 32602
  • 32603
  • 32000
  • 32001
  • 32002
  • 32003
  • 32004
  • 32005

4001

When trying to connect to the wallet, if a user clicks “Cancel” at any point on this interface and terminates the process, it returns a 4001 error.

Cancel button metamask error

Here’s the JSON structure of the error:

'4001': {
  standard: 'EIP-1193',
  message: 'User rejected the request.',
},

4100

This error occurs when the dApp wants to take action concerning an account that is not authorized.

For instance, to do certain actions like signing a message, you need to first get account permission from MetaMask, using the eth_requestAccounts method:

import { ethers } from "ethers";

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

const address = accounts[0];
const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();
const signature = await signer.signMessage(address);
console.log(signer);

Similarly, to switch the chain of your wallet, you need to use the wallet_switchEthereumChain method, which in turn asks for permission through MetaMask extension:

// switching the chain for MetaMask wallet

await provider.request({
  method: "wallet_switchEthereumChain",
  params: [{ chainId: "0x89" }],
});

If the permission is denied, the wallet returns this error:

'4100': {
  standard: 'EIP-1193',
  message: 'The requested account and/or method has not been authorized by the user.',
},

4200

MetaMask enables two methods: restricted and unrestricted. These methods allow the dApp to take actions like connecting to the wallet, signing transactions, and adding or switching networks.

This error is returned for the methods that aren’t supported on MetaMask:

'4200': {
  standard: 'EIP-1193',
  message: 'The requested method is not supported by this Ethereum provider.',
},

You can find a link to existing methods here.

4900

This error is returned when the user’s MetaMask wallet is not connected to any chain:

ethereum.on('disconnect', (error) => console.log(error));

It has to do with the disconnect event. This event is triggered when the wallet is disconnected and it becomes unable to submit requests to a chain. Besides disconnection, this can also happen due to network connectivity issues.

Once we emit disconnect, the provider will not accept any new requests until the connection to the chain has been reestablished, which requires reloading the page. You can also use the ethereum.isConnected() method to determine if the provider is disconnected.

Here’s the error’s JSON response:

'4900': {
  standard: 'EIP-1193',
  message: 'The provider is disconnected from all chains.',
},

4901

This error means the user is not connected to the appropriate chain for that transaction. For example, if a transaction requires the user to be on the Polygon chain, and they’re on Harmony or Ethereum blockchain.

One thing to note is that the MetaMask provider allows us to listen to the chainChanged event that listens and acts if the currently connected chain changes:

ethereum.on('chainChanged', (chainId) => {console.log(chainId)});

We submit our RPC requests to the currently connected chain, which makes it important to keep track of the current chain ID by listening for changes. Every chain has its unique chainID, which you can find on Chainlist.

It returns the error if it becomes unable to submit RPC requests to that specific chain:

'4901': {
  standard: 'EIP-1193',
  message: 'The provider is disconnected from the specified chain.',
}

32700

This error is returned if the user sends an incomplete request object to the contract. It can occur if the object sent to the contract does not contain all the data that it requires.

Here’s the JSON response:

 '-32700': {
    standard: 'JSON RPC 2.0',
    message: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',
  },

32600

Here, the object is valid, but the structure or properties aren’t correct. It’s somewhat similar to 32700, but in this case, it’s the internal structure that’s not correct.

Here’s the JSON response:

  '-32600': {
    standard: 'JSON RPC 2.0',
    message: 'The JSON sent is not a valid Request object.',
  },

32601

This error is returned if the method specified does not exist at all:

'-32601': {
    standard: 'JSON RPC 2.0',
    message: 'The method does not exist / is not available.',
  },

You can find a link to existing methods here.

32602

We get this error if the arguments passed into an RPC method is incorrect. For instance, when defining the transactionParameters, the from property references accounts[0].

Ordinarily, accounts[0] is supposed to be the user’s wallet address, but in this case, we assign it to an empty array:

 let accounts = [];
  const amountEth = 1
   const paymentAddress = '0x71C7656EC7ab88b098defB751B7401B5f6d8976F'
  const transactionParameters = { from: accounts[0], to: paymentAddress, value: web3.toWei(amountEth, 'ether') };

  function Mint(){
  ethereum.request({ method: 'eth_sendTransaction',  params: [transactionParameters] });

  }

The Mint function will return this particular error because the parameter is clearly invalid:

'-32602': {
    standard: 'JSON RPC 2.0',
    message: 'Invalid method parameter(s).',
  },

32603

This is a blanket error caused by several things. It might be because you’re trying to add a new chain to your wallet (manually or through the dApp) but added the wrong chain data. Or, you’re trying to complete a transaction, but you don’t have enough tokens to pay the gas fee. For instance, if you’re transacting on the Ethereum mainnet, you have to pay gas fees in ETH regardless of whether you’re transacting using other tokens.

Finally, it could be as trivial as not having the latest version of MetaMask.

Here’s the error JSON response:

'-32603': {
    standard: 'JSON RPC 2.0',
    message: 'Internal JSON-RPC error.',
  },

32000

One scenario that can trigger this error is when the contract address used in production is the contract you deployed to the testnet. This is a simple error that we can correct.

Similar to Web2 where we have a dev environment and a production environment, when building dApps, we use testnet to deploy our contract, so we can test it while building without using real ETH on mainnet. As such, the same contract deployed on testnet and mainnet will have different addresses. If you use the wrong address for the chain you’re on, this error is returned.

In general, when dealing with smart contracts, you need params like the contract address, the ABI file, and your signer:

const provider = new ethers.providers.Web3Provider(ethereum);
const signer = provider.getSigner();

const countContract = new ethers.Contract(contractAddress, contractABI, signer);

/*
 * Call the getAllCount method from your Smart Contract
 */
const count = await countContract.getAllCount()

If any of these params are wrong, you’ll most likely get his error, also referred to as a “user input error”:

  '-32000': {
    standard: 'EIP-1474',
    message: 'Invalid input.',
  },

32001

In this case, the resource we’re requesting does not exist on the blockchain. It’s possibly a typo from the client side.

Imagine you’re trying to get info about a non-existent block number on the ETH chain:

import Web3 from 'web3';

const web3 = new Web3(web3Provider);
var block = await web3.eth.getBlock({invalid block number})

You would get this JSON response:

'-32001': {
    standard: 'EIP-1474',
    message: 'Resource not found.',
  },

32002

This error means the requested resource does exist, but it’s currently unavailable at the time of the request. This can occur when we are trying to access a resource that’s currently in use. It can happen on the MetaMask extension when you’re trying to use a particular resource/method, like switching chains when the MetaMask is currently in the process of doing the same.

When building your dApp, you should learn to disable your button once that method has been successfully initiated, so user is not clicking in quick succession.

Here’s this error’s JSON response:

  '-32002': {
    standard: 'EIP-1474',
    message: 'Resource unavailable.',
  },

32003

This error could be a result of many things. It could be because the sender’s address doesn’t exist, insufficient funds, the account is locked, or we can’t sign the transaction. To fix this, make sure everything in your transaction is correct.

The transaction can be rejected if the conditions needed to complete the transaction aren’t satisfied:

  '-32003': {
    standard: 'EIP-1474',
    message: 'Transaction rejected.',
  },

32004

The method is not supported at all. Possibly, it doesn’t exist or there’s just a typographical error:

'-32004': {
    standard: 'EIP-1474',
    message: 'Method not supported.',
  },

32005

This error means the RPC provider has a rate limit that has been exceeded. This issue can occur if the RPC provider endpoint has a rate limit for the number of requests:

  '-32005': {
    standard: 'EIP-1474',
    message: 'Request limit exceeded.',
  },

Also, there’s a fairly common error with the error message “intrinsic gas too low.” It’s simply because the gas limit that’s assigned when initiating the transaction is less than what is required.

This occurs most often in cases where there’s a complex transaction, which can make the gas fee unpredictable:

ethereum
.request({
  method: 'eth_sendTransaction',
  params: [
    {
      from: accounts[0],
      to: '0xbCfDCCDbE7B3D681A1144D25a31e0D4BE869079a',
      value: '0x293434x341af62c0000',
      gasPrice: '0x09184e242',
      gas: '0x2709',
      gasLimit: '0x2723'
    },
  ],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);

Conclusion

Congratulations if you’ve made it to the end! We covered a bunch of possible errors and how to deal with them. Now, when building your next dApp, you can easily interpret these errors and fix them without being confused about what caused them in the first place. This can help improve your developer experience dealing with these Web3 technologies.

You can check out more about MetaMask errors from the official resource.

Join organizations like Bitso and Coinsquare who use LogRocket to proactively monitor their Web3 apps

Client-side issues that impact users’ ability to activate and transact in your apps can drastically affect your bottom line. If you’re interested in monitoring UX issues, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.LogRocket Dashboard Free Trial Bannerhttps://logrocket.com/signup/

LogRocket is like a DVR for web and mobile apps, recording everything that happens in your web app or site. Instead of guessing why problems happen, you can aggregate and report on key frontend performance metrics, replay user sessions along with application state, log network requests, and automatically surface all errors.

Modernize how you debug web and mobile apps — Start monitoring for free.

I’m developing the front-end to an application that I’m trying to test. However, MetaMask keeps giving me this error? I tried changing the gas limit like previously suggested and nothing. Any ideas?

Error:
MetaMask — RPC Error: Internal JSON-RPC error.

code: -32603
data: {code: -32000, message: «gas required exceeds allowance (30000000) or always failing transaction»}
message: «Internal JSON-RPC error.»

asked Apr 2, 2021 at 20:18

ChefMari's user avatar

4

Without seeing the code, it’s hard to say for sure but you could try:

  1. Check any code you changed in the front end, specifically in your code you may have something like this:
const contractInstance = new state.web3.eth.Contract(
    MyContract.abi,
    "0x.....",            // contract address
    {
        from: state.accounts[0],
        gasPrice: 1000,
        gas: 100000
    }
);

Make sure the gas prices are similar to those, you may have to adjust for your case.

  1. Re-compile and redeploy —> for truffle, run truffle develop first, then compile then migrate --reset for local deployment.

  2. In Metamask, reset your test account. Metamask > Select Account > Settings > Advanced > Reset account. Only do this for testing accounts

answered Apr 5, 2021 at 22:36

ttoshev's user avatar

Previously it used to happen in older versions due to a gas specification issue which was fixed. rpcErrors.internal` expects a string as the first argument, with arbitrary data being the optional second argument. Passing in a non-
string first argument results in the error being shadowed by an error
from eth-json-rpc-errors.

Please check what you are passing to Metamask.

answered Aug 11, 2021 at 10:50

Aurobindo Nayak's user avatar

In my case, after trying so many options I have restarted Ganache and re-imported new account from Ganache to Metamask.
I connected this new account with localhost application.

This resoles my issue.

Dharman's user avatar

Dharman

29.3k21 gold badges80 silver badges131 bronze badges

answered Mar 20, 2022 at 18:43

Murali krishna Konduru's user avatar

Before performing any transaction the sending ETH address must be connected to your own site or UI. So it can get the address of sending account and goes towards the further transaction in the metamask.

Make sure Your sending account address must be connected to your UI.

answered Jun 27, 2022 at 15:48

Prabin Baral's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Internal json rpc error metamask ошибка
  • Internal exception java net sockettimeoutexception read timed out как исправить
  • Internal exception java net socketexception connection reset майнкрафт как исправить ошибку
  • Internal exception java lang index out of bounds exception майнкрафт как исправить
  • Internal exception java lang illegalstateexception invalid characters in username как исправить