1

Inside Remix I'm using one address (addr1) to deploy the contract, and another (addr2) to call a function within the contract. The function is a simple transfer function. I'm transferring 1000000000000000000 Wei (1 ether) from addr2 to addr1. However it's unable to transfer and my output keeps returning false. What is wrong here?

Also I'm using SafeMath library for the sub, it's the same thing as subtract.

function transferToOwner() payable returns (bool) {
    owner.transfer(msg.value.sub(1000000000000000000));
    return true;
}
1

The correct way to do this would be like this:

function transferToOwner() payable returns (bool) {
    owner.transfer(msg.value);
    return true;
}

This will forward any amount of eth the person calling this function sent.

If you just want to send 1 eth regardless of what they sent when they called the function, then it would look like this:

function transferToOwner() payable returns (bool) {
    //Sender should forward at least 1 ether.
    require(msg.value > 1 ether);
    uint amountToSend = 1 ether;
    uint change = msg.value - amountToSend; // Do something with the change. Return it to sender, maybe?
    //If you don't do anything with the change, it will be stuck on this contract
    owner.transfer(1 ether);
    return true;
}
  • How do you pass in msg.value though? Currently it returns 0. – JorahFriendzone Nov 15 '17 at 22:18
  • @JorahFriendzone if you are using Remix there's a field in the top that says "value" you can enter how much ether to send to a payable function like the one you wrote above. – pabloruiz55 Nov 15 '17 at 22:19
  • Ah thanks! The reason I was trying to test was ultimately to have web3 call the function transferToOwner. However, right now using Remix I'm manually inputting the value. How would I do this via web3, since I'm not passing in a variable to the function? – JorahFriendzone Nov 15 '17 at 22:34
  • You can pass an object alongside any function call containing among other things the value of eth you want to send or gas supplied. – pabloruiz55 Nov 15 '17 at 22:46
  • Normally when I do a function call in web3 I do contractInstance.functionName(data passed here), but I'm trying to forgo passing data, through the function and just having the function handle everything internally, hence why my transferToOwner doesn't have any parameters. I'm trying to figure out how I can run transferToOwner without passing parameters via web3 if that makes sense – JorahFriendzone Nov 15 '17 at 23:16

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.