2

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.

2 Answers 2

3

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).

0

No need to set the data manually. You can use the web3 contract methods function. In your case, you can call the setValue(123,'ABC') like this:

myContract = new web3.eth.Contract(abi,contractAddress);
myContract.methods.setValue(123,'ABC')
.send({
     from: youraccount.address,
     to: myContract.options.address,
     value: 0, // Don't send ETH, this is a contract transaction
})

See the web3 docs for more information.

Keep in mind that this is not a "call". Your function changes the state of the smart contract. You can use methods.myMethod.call for executing EVM functions that do not create a transaction.

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

1
  • I don't want to use Metamask. I am using my account directly in my javascript code. Commented Sep 24, 2019 at 13:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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