0

This question already has an answer here:

I'm trying to return sender address and value in truffle under private blockchain. When function is called from truffle console I'm not getting proper msg.sender address.

Contract code

pragma solidity ^0.4.13;

contract Sample {

mapping (address => uint) Id;
event log(address sender, uint value);

function getSender() payable returns (uint,address) {

    Id[msg.sender] = msg.value;
    log(msg.sender,msg.value);
    return (Id[msg.sender],msg.sender);
}

}

Truffle console function code

Sample.deployed().then(function(i) {i.getSender(web3.eth.coinbase,2,{from : web3.eth.coinbase, value : web3.toWei(1, "ether")}).then(function(f) {console.log(f)})});

Sample.deployed().then(function(i) {i.getSender.call(web3.eth.coinbase,2,{from : web3.eth.coinbase, value : web3.toWei(1, "ether")}).then(function(f) {console.log(f)})});

Output

truffle(development)> [ BigNumber { s: 1, e: 0, c: [ 0 ] }, '0x' ]

This contracts fine in remix.

marked as duplicate by Ismael, Richard Horrocks, Achala Dissanayake, Crema, Malone Nov 8 '17 at 11:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

The problem is that you are trying to have this function both modify an state variable AND return a value, which is not possible.

When calling a function from outside the contract, if the function is marked as view/constant it will return whatever data you want, BUT said function can't modify any state variables.

If the function is not view/constant, then it is a transaction that modifies a state variable. Therefore, you can't return a value, it will return the tx hash.

With truffle you can get the transaction logs in the callback/promise as soon as the transaction has been mined, without having to watch for events.

Search for "Processing transaction results": https://github.com/trufflesuite/truffle-contract

So, what you will have to do is break this function in two: setSender() which mostly does what you are doing now, except it doesn't return anything and getSender() which will return Id[msg.sender].

In JS you would be able to call setSender to set the value and then either use the logs to display the result.logs OR in the callback, call getSender to retrieve the new value you just updated.

Not the answer you're looking for? Browse other questions tagged or ask your own question.