Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A contract to split funds between addresses. Demostrates pushing vs pulling transfers
pragma solidity ^0.4.6;
contract Splitter {
mapping(address => uint) public balances;
function unsafeSplit(address address1, address address2)
public
payable
returns(bool success)
{
require(msg.value > 1);
require(address1 != address(0));
require(address2 != address(0));
uint amount = (msg.value - (msg.value % 2)) / 2;
address1.transfer(amount); // if either transfer fails, the function stops executing
address2.transfer(amount); //
msg.sender.transfer(msg.value % 2);
return true;
}
function split(address address1, address address2) // no external calls, so it will not fail
public
payable
returns(bool success)
{
require(msg.value > 1);
require(address1 != address(0));
require(address2 != address(0));
uint amount = (msg.value - (msg.value % 2)) / 2;
balances[address1] += amount;
balances[address2] += amount;
balances[msg.sender] += msg.value % 2;
return true;
}
function withdraw()
public
returns(bool success)
{
require(balances[msg.sender] > 0);
uint amount = balances[msg.sender];
balances[msg.sender] = 0;
msg.sender.transfer(amount);
return true;
}
}
@dwardu
Copy link

dwardu commented Jun 21, 2018

In withdraw(), since balances[msg.sender] is first set to 0, the subsequent msg.sender.transfer(balances[msg.sender]) is equivalent to msg.sender.transfer(0), so no ether ends up being withdrawn. It could be fixed as follows:

+ uint256 amountToTransfer = balances[msg.sender];
  balances[msg.sender] = 0;
- msg.sender.transfer(balances[msg.sender]);
+ msg.sender.transfer(amountToTransfer);

P.S. Cool idea for the splitter to get the extra 1 wei back, although it might take some to save up enough weis to make it worth the gas to withdraw them 😃 Maybe a simpler strategy could be for the split() function to reject odd msg.values in the first place.

Loading

@critesjosh
Copy link
Author

critesjosh commented Jun 21, 2018

thanks for pointing that out. gist updated

Loading

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment