Truffle Payable – Testing Payable Functions from Truffle

payabletruffle

I'm trying to test a payable function from Truffle my function looks like so:

function recordOrder(bytes32 orderNumber) payable returns(bool success) {
    if(msg.value==0)
    {
        return false;
    }

    if(!orderStructs[orderNumber].exists) {
        orderStructs[orderNumber].sender = msg.sender;
        orderStructs[orderNumber].amountReceived = msg.value;
        orderStructs[orderNumber].exists = true;
    }
    else {
        orderStructs[orderNumber].amountReceived += msg.value;
    }

    LogOrder(msg.sender, orderNumber, msg.value);
    withdrawFee(msg.value, orderNumber);
    return true;
}

I'm trying to figure out how to send payments to a function but I'm confused on how. If I call the function like so:

var facilitator;
OrdersFacilitator.deployed().then(x => facilitator = x);

var orderNumber = '33075588-8408-484b-8a53-e9c7f61bcb12';
facilitator.recordOrder.call(orderNumber);

I get a return value of false which make sense considering I don't think I've specified an amount to send. However when I call the function directly:

facilitator.recordOrder(orderNumber);

I'm returned some json with a reciept:

{ tx: '0x5e38d5bb4f933a58e56620e8b0ae9ae0acb191b92ce0fef2f8fe784c9d40ef2c',
  receipt:
   { transactionHash: '0x5e38d5bb4f933a58e56620e8b0ae9ae0acb191b92ce0fef2f8fe784c9d40ef2c',
     transactionIndex: 0,
     blockHash: '0x038a57ce4a73efc59d57403d652119d3114602311756251be74e75cbe4d06e39',
     blockNumber: 5,
     gasUsed: 24150,
     cumulativeGasUsed: 24150,
     contractAddress: null,
     logs: [],
     status: 1 },
  logs: [] }

Which I have no idea what is going on here, because I never specified an amount, and I'm calling from the truffle console, So I don't even know how gas when I'm not connected to an account (that I know of).

How can I send value to my payable function from truffle?

Best Answer

Web3 offers a number of optional parameters which you can add to a function call:

  • from - The address transactions should be made from.
  • gasPrice - The gas price in wei to use for transactions.
  • gas - The maximum gas provided for a transaction (gas limit).
  • value - The value transferred for the transaction in Wei, also the endowment if it's a contract-creation transaction.

etc...

To use them, simply include them as an object as the last parameter in your function call:

facilitator.recordOrder(orderNumber, {value: web3.toWei(2, 'ether')});
Related Topic