Payable Function – How to Pass Arguments to Deployed Contract via Web3/JavaScript/Truffle

javascriptpayablesoliditytruffle

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!

Best Answer

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

Related Topic