1

I'm trying to create a function that will take as argument the name of a contract method with web3.js. This is the original function:

async function estimateGas() {
  const w3 = await new Web3(window.ethereum);
  window.contract = await new w3.eth.Contract(myContr.abi, myContr.addr);
  window.contract.methods.buy().estimateGas({from: ethereum.selectedAddress});
}

THis function works fine like this, but I would like to modifiy it so that I may be able to use all the other methods on the contract (like for example .claim(), .transfer(), etc) as an argument, like so:

async function estimateGas(argumentName) {
  const w3 = await new Web3(window.ethereum);
  window.contract = await new w3.eth.Contract(myContr.abi, myContr.addr);    
  // I want to change here below what was the ".buy()" method with my argument as if it would have been ".argumentName()"
  window.contract.methods.argumentName().estimateGas({from: ethereum.selectedAddress});
}

How can I do that?

1 Answer 1

1

You can definetelly do that with Javascript. Take a look at another way to access the properties of a js object, with the obj["property"] syntax:

async function estimateGas(argumentName) {
  const w3 = await new Web3(window.ethereum);
  window.contract = await new w3.eth.Contract(myContr.abi, myContr.addr);    
  // I want to change here below what was the ".buy()" method with my argument as if it would have been ".argumentName()"
  window.contract.methods[argumentName]().estimateGas({from: ethereum.selectedAddress});
}

As an example, take a look at this answer where I use this approach to dynamically call a function of a js web3 object: Is there a way to extract functions from an ABI and show it in the front end?

const result = await counter.methods[functionName](...args).call();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.