3

I'm wondering how to pass argument to a payable function of a contract that has already been deployed, via web3 / javascript / truffle. For instance, I see the following piece of code at: http://solidity.readthedocs.io/en/develop/contracts.html

pragma solidity ^0.4.0;

contract ClientReceipt {
    event Deposit(
        address indexed _from,
        bytes32 indexed _id,
        uint _value
    );

    function deposit(bytes32 _id) payable {
        // Any call to this function (even deeply nested) can
        // be detected from the JavaScript API by filtering
        // for `Deposit` to be called.
        Deposit(msg.sender, _id, msg.value);
    }
}

But then if I were to interact with this contract via javascript, how would I pass bytes32 _id to function deposit as I send (say) 100 wei to the contract address?? So far, I have tried:

// bytes32 data for "test"
var myData = "0x7465737400000000000000000000000000000000000000000000000000000000"; 

ClientReceipt.deployed().then(function(instance) {
    instance.deposit.sendTransaction(myData, {value: 100, from: myAccount, to: instance.address});
    ...

ClientReceipt.deployed().then(function(instance) {
    instance.deposit(myData, {value: 100, from: myAccount, to: instance.address});
    ...

ClientReceipt.deployed().then(function(instance) {
    instance.sendTransaction(myData, {value: 100, from: myAccount, to: instance.address});
    ...

Is this where {data: myData} might be relevant perhaps?? If so, then how do things change if the function took multiple parameters, e.g. if it were function deposit(bytes32 _id, uint n, bool m)?? How would you be passing parameters while simultaneously sending 100 wei to the contract?? Thanks a lot!

4

As you're using truffle, you can check out how to interact with contracts via javascript here https://truffle.readthedocs.io/en/beta/getting_started/contracts/ basically this should work

instance.deposit(myData, {value: 100, from: myAccount});

if the function had a second parameter you wanted to pass in you could do:

instance.deposit(myData, myOtherData, {value: 100, from: myAccount});

you don't need to specify a "to" parameter, you're already calling the contract instance which is deployed at a specific address

  • Aha! So my second approach was the correct one, but I realized what was going on was that Rinkeby Etherscan has not been in sync properly for the past 9 hours for some reason (is it just my PC? I'm not sure...), so I couldn't verify if the transaction took place as desired. I ended up running my local node and finally verified it works via above method. Thanks! – Kevin Choi Oct 28 '17 at 23:23

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.