0

This should be really easy but I can't seem to find the way to do it, thanks to the great documentation. I'm thinking I'm missing something big.

I have a function that buys ownership of something. I want to remove amount ether to msg.sender (user a) and give them to owner (user b) (minus fees).

Can I do it directly? Do I have to first let a send ether to the contract and then send b the same amount, or is there a function to transfer directly?

I assume owner.transfer(amount) (or .send(amount)) sends ether from the contract to the owner, but then how do I get ether from a?

I'm using Solidity by Example as a model, but in the Blind Auction example I can't seem to find what function actually sends ether from the bidder to the contract.

1

You can't just take somebody's ether, so yes, they need to send it to the contract first, but this can all be done in a single contract call. E.g.

// "payable" means ether can be sent to this function
function buyIt() public payable {
    // msg.value is how much ether was sent
    require(msg.value == price);

    // send the ether to "owner"
    owner.transfer(msg.value);

    // msg.sender is the new "owner"
    owner = msg.sender;
}

When calling this function, the caller must attach price ether. This means setting the "value" field of the transaction.

I think this blog post will help: https://programtheblockchain.com/posts/2017/12/15/writing-a-contract-that-handles-ether/.

EDIT

You linked to a very old version of the Solidity documentation, before payable was required to allow ether to be sent. The current version shows a payable bid function. That's where ether is transferred to the contract.

  • Thanks, I didn't know that you could change the version on readthedocs! With this function, the price is chosen by the buyer, right? If the price is fixed, do I have to check that he sent more than price and then refund all the exceeding ether, or can something handle that automatically? – Teleporting Goat Mar 1 '18 at 9:53
  • I just made up price. I assumed a fixed price. The code I shared requires that the caller send exactly the right amount. If you want to allow overpayment and refund the excess, you could do require(msg.value >= price); if (msg.value > price) { msg.sender.transfer(msg.value - price); }. – smarx Mar 1 '18 at 9:57
  • Oh my bad, I missed the part with require. It's crystal clear now! :) – Teleporting Goat Mar 1 '18 at 10:01
0

How about web3 sendTransaction method? it has "to" option.

https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsendtransaction

  • It needs to be inside the contract, I can't do this just at JavaScript level. – Teleporting Goat Jul 12 '18 at 9:19
  • I got it! exactly! We need to go through contract – Kosuke Yoshimura Jul 12 '18 at 9:22

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.