0

I'm using the truffle console to test my contract, but I'm having a trouble passing an argument. For example, I have a method like this

function sendEtherTo(address addr) public payable {
   require(addr != 0x0);
   require(msg.value > 0);
   addr.transfer(msg.value);
}

I'm trying to use sendTransaction but can't figure out how to pass in the argument.

This:

 web3.eth.sendTransaction({from: web3.eth.accounts[1], to: myContract.address, data: myContract.sendEtherTo.sendTransaction(web3.eth.accounts[2]), value: web3.toWei(10, "finney")})

Results in my testrpc crashing with an error in truffle saying

Error: Invalid JSON RPC response: undefined

I've tried the following which I've done in web3 successfully

web3.eth.sendTransaction({from: web3.eth.accounts[1], to: myContract.address, data: myContract['sendEtherTo'].getData(web3.eth.accounts[2]), value: web3.toWei(10, "finney")})

but this tells me that getData is undefined

  • How do you create myContract? If you call myContract.sendEtherTo() directly does it work? – Ismael Mar 17 '18 at 15:27
  • AFAIK sendTransaction can't invoke a method, it can invoke a contract. Then this contract may send message (i.e. call a method) to another contract, – Nulik Mar 19 '18 at 1:57
  • @Nulik You are wrong. To use sendTransaction you need to encode the function call inside the data field. – Ismael Mar 19 '18 at 2:56
1

Truffle wraps contracts with a custom object that doesn't provide getData, but we can use the request method to obtain the parameters for sendTransaction.

const MyContract = artifacts.require('MyContract');

contract('MyContract', function(accounts) {
  it('Call with sendTransaction', async () => {
    const myContract = await MyContract.deployed();

    // We want to call foo(23) on myContract
    const data = myContract.foo.request(23);

    // Here data.params[0].data contains the parameters to the call

    const txhash = web3.eth.sendTransaction({ 
      from: accounts[0], 
      to: myContract.address, 
      value: 1, 
      data: data.params[0].data
    });
  });
});
  • Thanks, I'll try this out tonight to see how it works. What's the JS framework this example is using? I've been out of the loop in the JS world for a while – Chris Mar 19 '18 at 15:32
  • This is a unit test for Truffle. – Ismael Mar 19 '18 at 17:36

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.