MetaMask / metamask-extension

:globe_with_meridians: :electric_plug: The MetaMask browser extension enables browsing Ethereum blockchain enabled websites
https://metamask.io
Other
12.01k stars 4.91k forks source link

TypeError: NetworkError when attempting to fetch resource #6095

Closed mwaeckerlin closed 5 years ago

mwaeckerlin commented 5 years ago

This issue seems to exists in #1779 (and #2301), but both have been closed long ago, even though the problem is not solved, at least not for me. Since I cannot reopen it and get no answer to my comments there, I open a new bug and provide all the information I have. Unfortunately the whole source code is too huge to append, so I provide the snippets where the problem occurs.

Describe the bug

Using:

Without Metamask the exactly same code works (using the fallback to localhost, connecting to canache-cli). In a nodejs / express environment without react, it works. So I suppose, it is something about Metamask and React in combination.

startup of canache:

ganache-cli -d --db ${HOME}/tmp/ganache/db -i 123456

first error message is TypeError: NetworkError when attempting to fetch resource on line await window.ethereum.enable(); in the following Initiatlization code:

import Web3 from "web3";

const getWeb3 = new Promise((resolve, reject) => {
  // Wait for loading completion to avoid race conditions with web3 injection timing.
  window.addEventListener("load", async () => {
    // Modern dapp browsers...
    if (window.ethereum) {
      const web3 = new Web3(window.ethereum);
      try {
        // Request account access if needed
        await window.ethereum.enable();
        // Acccounts now exposed
        resolve(web3);
      } catch (error) {
        reject(error);
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      // Use Mist/MetaMask's provider.
      const web3 = window.web3;
      console.log("Injected web3 detected.");
      resolve(web3);
    }
    // Fallback to localhost; use dev console port by default...
    else {
      const provider = new Web3.providers.WebsocketProvider(
        "ws://127.0.0.1:8545"
      );
      const web3 = new Web3(provider);
      console.log("No web3 instance injected, using Local web3.");
      resolve(web3);
    }
  });
});

export default getWeb3;

Using Web3 0.20.7

On line await window.ethereum.enable();, I always get an error:

Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource.
Ressourcen-Adresse: moz-extension://b18341ab-dfc3-4aa4-b3a8-c6b259c38e56/contentscript.js
Source-Map-Adresse: ../sourcemaps/contentscript.js.map[Weitere Informationen] 

At the end, creating a contract, web3 fails with silly error messages without a useful context, such as:

Error: invalid address
formatters.js:268
inputAddressFormatter
formatters.js:268
inputTransactionFormatter
formatters.js:104
./node_modules/web3/lib/web3/method.js/Method.prototype.formatInput/<
method.js:94
map self-hosted:286:17 ./node_modules/web3/lib/web3/method.js/Method.prototype.formatInput
method.js:93
./node_modules/web3/lib/web3/method.js/Method.prototype.toPayload
method.js:121
send
method.js:148
ContractFactory/this.new
contract.js:196
deploy
deploy.js:44
deploy self-hosted:975:17 callCallback
react-dom.development.js:147
invokeGuardedCallbackDev
react-dom.development.js:196
invokeGuardedCallback
react-dom.development.js:250
invokeGuardedCallbackAndCatchFirstError
react-dom.development.js:265
executeDispatch
react-dom.development.js:571
executeDispatchesInOrder
react-dom.development.js:596
executeDispatchesAndRelease
react-dom.development.js:695
executeDispatchesAndReleaseTopLevel
react-dom.development.js:704
forEachAccumulated
react-dom.development.js:676
runEventsInBatch
react-dom.development.js:844
runExtractedEventsInBatch
react-dom.development.js:852
handleTopLevel
react-dom.development.js:5027
batchedUpdates$1
react-dom.development.js:20269
batchedUpdates
react-dom.development.js:2246
dispatchEvent
react-dom.development.js:5107
interactiveUpdates$1
react-dom.development.js:20331
interactiveUpdates
react-dom.development.js:2267
dispatchInteractiveEvent
react-dom.development.js:5083
dispatchInteractiveEvent self-hosted:1019:17

Using Web3 1.0.0-beta41

Same in web3 1.0.0-beta41:

Source-Map-Fehler: TypeError: NetworkError when attempting to fetch resource.
Ressourcen-Adresse: moz-extension://b18341ab-dfc3-4aa4-b3a8-c6b259c38e56/contentscript.js
Source-Map-Adresse: ../sourcemaps/contentscript.js.map

The message Weitere Informationen links to a Firefox page.

When I try to deploy a contract in Web3 1.0.0-beta41, I get no more information than:

DataCloneError: The object could not be cloned. inpage.js:1 

To Reproduce Steps to reproduce the behavior:

  1. Setup a react app
  2. Use the above initialisation code
  3. Use Metamask in Firefox
  4. See error in console
  5. Try to deploy a contract
  6. See the second error message

Expected behavior Web3 should be correctly initialized, a contract should be deployed.

Browser details (please complete the following information):

Additional context

The code, where the contract is deployed:

    web3.eth.Contract(contractjson.abi).deploy({
      data: contractjson.bytecode,
      arguments: [this.state.arg1, this.state.arg2 this.state.arg3]
    }).send({
        from: this.state.account,
        gas: this.state.gas,
        gasPrice: this.state.gasprice
      })
      .then(newContractInstance => {
        this.setState({
          result: "success: " + newContractInstance.options.address
        });
        this.updateAccounts();
      })
      .catch(err => {
        this.setState({ result: "cannot create contract: " + err });
      });
tmashuang commented 5 years ago

How are you setting this.state.account.

mwaeckerlin commented 5 years ago

@tmashuang, here:

  updateAccounts(cb = null) {
    this.state.web3.eth
      .getAccounts()
      .then(
        accounts => {
          this.setState(prev => ({
            accounts: [],
            account: prev.account || accounts[0] || ""
          }));
          accounts.forEach(account => {
            this.state.web3.eth.getBalance(account).then(balance => {
              this.setState(prev => ({
                accounts: [
                  ...prev.accounts,
                  {
                    account: account,
                    balance: balance
                  }
                ]
              }));
            });
          });
          if (cb) cb();
        }
      )
  }

BTW, I have at exactly this position a really strange behavior with web3.js and my attempts to add a proper error handling:

This works:

 updateAccounts(cb = null) {
    this.state.web3.eth
      .getAccounts()
      .then(
        [… same as above …]
      )
      .once("transactionHash", console.log)
      .once("receipt", console.log)
      .on("confirmation", console.log)
      .on("error", console.log);
  }

But this, which is exactly according to the documentation fails and nothing is called:

 updateAccounts(cb = null) {
    this.state.web3.eth
      .getAccounts()
      .once("transactionHash", console.log)
      .once("receipt", console.log)
      .on("confirmation", console.log)
      .on("error", console.log)
      .then(
        [… same as above …]
      );
  }

Any idea, what's wrong here and how to implement a proper error handling?

EDIT: Only the following works to get a correct result in case error and in case of success:

 updateAccounts(cb = null) {
    this.state.web3.eth
      .getAccounts((error, accounts) => {…})
  }

Unfortunately, with Metamask, I still get an error.

So the new promises from Web3 1.0.0 do not work at all… :-1:

mwaeckerlin commented 5 years ago

BTW: It makes a difference on the kind of error whether i access the react webpage in development environment through the built-in react server or as production deployment in webpack through a nodejs/express server (running in a docker image). But: Both fail, and both get TypeError: NetworkError when attempting to fetch resource.

tmashuang commented 5 years ago

Unfortunately, my reproduction has not produced these errors, if you could provide a repo that has these errors I would gladly take a look. Your code snippet reminded me to Truffle, so I used their package to try to reproduce your issue here. I noticed that when I upgraded the default web3 package from 1.0.0-beta.37 to 1.0.0-beta.41 it did break.

mwaeckerlin commented 5 years ago

@tmashuang, I can reproduce the problem with a simple react-metamask-test demo:

git clone https://github.com/mwaeckerlin/react-metamask-test
cd react-metamask-test
npm install
solc --overwrite --combined-json abi,bin -o src/contracts/json src/contracts/test.sol
ganache-cli -d --db ${HOME}/tmp/ganache/db -i 123456
BROWSER=none npm start
  1. Start Firefox, disable Metamask, head to http://localhost:3000, create a contract (chose a local account, add some text, press the button) → It works without MetaMask!
  2. Enable Metamask, reload the page, try again → ERROR: DataCloneError: The object could not be cloned
mwaeckerlin commented 5 years ago

YES, @tmashuang, you are 100% right: Setting "web3": "1.0.0-beta.37" in package.json fixes the problem! Thank you very much!

Now: On which side is the problem, in web3.js or in MetaMask? And is there already an open ticket to fix this?

Please add a link to the the ticket in web3.js or in MetaMask, then close this one.

tmashuang commented 5 years ago

I would assume web3.js since downgrading solved it, but maybe they are experimenting with something we haven't adjusted for yet.

mwaeckerlin commented 5 years ago

@tmashuang, since the problem seems to be known, there is probably an open ticket? Or where did you get this information from?

Could you please add a link to the ticket?

AchinthyaBhat commented 3 years ago

I am getting the same error when using metamask on polygon network on ff browser

lxhyl commented 2 years ago

i getting the error in Firefox too. How did you resolve this?

luismasuelli commented 5 months ago

Getting the same error here. I'm using a local hardhat.

It is NOT a network error since I'm getting no errors when making many static calls or invoking the getPastEvents function, but as of today it happens when trying to send a transaction (which is not the same error when a transaction is reverted). This error is not consistent, however: perhaps in 1h it stops happening.

This happens in Firefox 126.0 with Metamask on Ubuntu. Assume all the other packages (project-related things, even Hardhat) as stable as possible.