2

I'm trying to call different functions of a contract with a single function that has the function name passed to it as an argument.

var Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io'));
var myContract = new web3.eth.Contract(JSON.parse(data.abi), data.address);

var method = data.method // 'getWord'
myContract.methods.getWord().call().then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

Above I have created a variable called method and its value has been set to getWord on the line below I am calling getWord()

What I'm trying to do is call whatever function is named in data.method like this...

    myContract.methods.[data.method].call().then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

but of course it breaks and id prefer to not use eval() like this

    var myContract = new web3.eth.Contract(JSON.parse(data.abi), data.address);
    eval('myContract.methods.'+data.method+'().call()')  
    .then(function(value) {
        console.log(value)
    }, function(error) {
        console.log(error)
    });

Is there another way?

Bill
  • 439
  • 6
  • 18

1 Answers1

2

It should just be:

myContract.methods[data.method]().call()

(You had an extra dot in there.)

user19510
  • 27,999
  • 2
  • 30
  • 48