Web3.js – How to Provide Data for sendTransaction Using Web3.js 1.0?

sendtransactionweb3js-v1.x

I'm using web3.js 1.0. I want to use sendTransaction method to call a contract method, but I don't know how to provide data parameter for it.
For example suppose we have a contract named myContract and the method setValue in it, then we want to call the method with two parameters: 123 as uint and 'ABC' as string. so we have:

nodeUrl='...';
abi=...;
contractAddress='0x...';
web3 = new Web3(new Web3.providers.HttpProvider(nodeUrl));
myContract = new web3.eth.Contract(abi,contractAddress);
web3.eth.sendTransaction({
    from: '0x...',
    data: data
}, function(error, hash){
    ...
});

And we want to use the method as follows:

setValue(123,'ABC');

How can we set the data value for sendTransaction method?

P.S: I don't want to use Metamask. I am using my account directly in my javascript code.

Best Answer

Try this:

data: myContract.methods.setValue(123,'ABC').encodeABI()

BTW, you'll first need to unlock on your node the account that you specify in the from field (otherwise, you'll need to use web3.eth.sendSignedTransaction instead).

Related Topic