0

I'm building a UI that talks to a smart contract and I'm using contract methods.

const data = await contract.methods.buyCredits().send({
        from: account,
        gas: 233000,
        value: choice.value,
      });

But noticed in several questions, the usage of sendTransaction.

Is the difference that sendTransaction is just a raw wallet to contract, wallet to wallet sending of Ether — not a contract method call? web3.eth.sendTransaction or contract methods

What is the difference?

0

Well, you can technically call a contract function also via sendTransaction, by specifying the encoded function-call in the data field (as explained in the official documentation).

For example:

const transaction = contract.methods.func(arg1, arg2, arg3);
const receipt = await web3.eth.sendTransaction({
    value: someValue,
    from: accountAddress,
    to: transaction._parent._address,
    gas: transaction.estimateGas({from: accountAddress, value: someValue}),
    data: transaction.encodeABI()
});

Of course, as shown in your question, you can just as well execute the function directly with send.

3
  • Is there any reason to use sendTransaction over calling a contract methods directly? Is it just a matter of taste? – GN. Dec 15 '20 at 5:03
  • @GN.: See the bottom line that I added a second before your comment. – goodvibration Dec 15 '20 at 5:04
  • @GN.: There is a reason though. Typically, you cannot really use send, unless your account is unlocked on the node that you're communicating with (like, when you use Truffle & Ganache). However, since this is not desirable (for security reasons), in order to sign transactions, you need to use web3.eth.accounts.signTransaction followed by web3.eth.sendSignedTransaction, where the former is called in a similar manner shown in my answer above. – goodvibration Dec 15 '20 at 5:07

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.