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?
loadWeb3
attaches a function to 'load' event so it is likelyloadBlockchainData
runs beforeloadWeb3
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.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!