Last active
April 6, 2022 20:00
-
-
Save critesjosh/80d41928db2310684bc7660aa45873da to your computer and use it in GitHub Desktop.
A contract to split funds between addresses. Demostrates pushing vs pulling transfers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
thanks for pointing that out. gist updated
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In
withdraw()
, sincebalances[msg.sender]
is first set to 0, the subsequentmsg.sender.transfer(balances[msg.sender])
is equivalent tomsg.sender.transfer(0)
, so no ether ends up being withdrawn. It could be fixed as follows: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 oddmsg.value
s in the first place.