I’ve just watched the latest youtube tutorial on Ethereum Gas Programming and Estimation and am looking at the logic.js code that handles the functionality for interacting with the contract and estimating gas fees:
const serverUrl = "";
const appId = "";
Moralis.start({ serverUrl, appId });
const storeSecretAddress = "";
const storeSecretABI = [...];
login();
async function login(){
Moralis.Web3.enableWeb3().then(async function (){
const chainIdHex = await Moralis.switchNetwork("0x2A");
});
}
async function storeSecret() {
const web3 = await Moralis.enableWeb3();
const secretNumber = document.getElementById("secretNumber").value;
const options = {
contractAddress: storeSecretAddress,
functionName: "storeSecret",
abi: storeSecretABI,
params: {
_newSecret: secretNumber
},
};
const receipt = await Moralis.executeFunction(options);
window.alert("operation concluded with hash " + receipt["transactionHash"]);
};
async function estimate() {
const web3 = await Moralis.enableWeb3();
const secretNumber = document.getElementById("secretNumber").value;
const storeContract = await new web3.eth.Contract(storeSecretABI,storeSecretAddress)
const estimatedGas = await storeContract.methods.storeSecret(secretNumber).estimateGas({from:ethereum.selectedAddress})
document.getElementById("estimatedGas").value = estimatedGas;
}
In this code, the call Moralis.enableWeb3();
occurs in three different places - within each of the three functions - login()
, storeSecret()
, and estimate()
.
My question is, why is the code written in a way that includes this call within each function?
Is it possible to set a global let web3
variable at the beginning of the script that gets populated one time during the login()
function, and not again? For example:
let web3;
login();
async function login(){
web3 = await Moralis.Web3.enableWeb3();
const chainIdHex = await Moralis.switchNetwork("0x2A");
}
Or, is it a regular practice to define a new Moralis.enableWeb3()
instance within each function?