0

I have two functions, called one after another. The first one called creates a new Web3 object and sets it to window.web3:

  async loadWeb3() {
    window.addEventListener('load', async () => {
      if (window.ethereum) {
        window.web3 = new Web3(window.ethereum);
        console.log(window.web3);
        await window.ethereum.enable();
       }
    });
  }

Next, my program calls another function, which tries to access the web3 object which is set to window.web3. Here it is:

  async loadBlockchainData() {
    console.log(window.web3);
  }

So to sum it up, I create a new Web3 object and set it to window.web3 in one function, log it to the console and then in a different function, I log this same object. Here's the catch, you can't do any of the typical things like window.web3.eth.getAccounts() within the loadBlockchainData() function. This is because in the loadBlockchainData() function, window.web3 becomes a proxy object, and is different from the same window.web3 that is defined in the loadWeb3() method. You can try it out yourself.

My question is, why does window.web3 become a proxy object, what makes it a proxy object (metamask? web3.js?), and how do we interact with this proxy object using the web3.js library?

3
  • It is a normal javascript behavior, both are async function so one of them may run while the other hasn't finished. loadWeb3 attaches a function to 'load' event so it is likely loadBlockchainData runs before loadWeb3 has finished. The proxy is created by metamask when injecting into the pages. Since several iterations using 'load' event is no longer the recommended procedure. Read their Getting started guide.
    – Ismael
    Commented Apr 13, 2021 at 23:57
  • Ah I see. You are right, the loadBlockchainData runs before the other function has finished. Does JS automatically make anything returned from an async function a proxy? Is that what is happening? Or is the proxy created by metamask? I'm confused since you say it is normal JS behavior but also created by metamask. Thanks! Commented Apr 14, 2021 at 1:56
  • The normal js behavior relates how async function are executed. The proxy is metamask way of dealing with web3 deprecation, it is in their blog announcement.
    – Ismael
    Commented Apr 14, 2021 at 5:20

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.