test included; contract refactored

This commit is contained in:
oho 2019-05-21 05:49:22 +02:00
parent 2e2c5ebdce
commit c308fa9b0b
3 changed files with 48 additions and 15 deletions

View file

@ -1,24 +1,25 @@
pragma solidity >=0.4.25 <0.6.0;
contract Splitter {
mapping (address => uint) public balances;
event LogSplit(address indexed sender, address indexed bob, address indexed carol, uint amount);
event LogWithdrawn(address indexed who, uint amount);
event Transfer(address indexed _from, address indexed _to1, address indexed _to2, uint256 _value);
mapping (address => uint) public balances;
constructor() public {
balances[msg.sender] = 10000;
}
function sendSplitCoin(address receiver1, address receiver2, uint amount) public returns(bool sufficient) {
if (balances[msg.sender] < amount) return false;
balances[msg.sender] -= amount;
balances[receiver1] += amount/2;
balances[receiver2] += amount/2;
emit Transfer(msg.sender, receiver1, receiver2, amount);
return true;
}
function split(address bob, address carol) payable public {
function getBalance(address addr) public view returns(uint) {
return balances[addr];
}
require(bob != address(0));
require(carol != address(0));
uint half = msg.value / 2;
require(half > 0);
balances[bob] += half;
balances[carol] += msg.value - half;
// We do not log the balance, only the change.
emit LogSplit(msg.sender, bob, carol, msg.value);
}
}

32
test/TestSplitter.sol Normal file
View file

@ -0,0 +1,32 @@
pragma solidity >=0.5.0 <0.6.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Splitter.sol";
contract TestSplitter {
uint public initialBalance = 101 finney;
address bob = 0x0123456789012345678901234567890123456789;
address carol = 0x1234567890123456789012345678901234567890;
function testSplitEqualBobCarol() public {
Splitter splitter = new Splitter();
splitter.split.value(100 finney)(bob, carol);
Assert.equal(address(splitter).balance, 100 finney, "Splitter contract should have the Ether");
Assert.equal(splitter.balances(bob), 50 finney, "Bob should be owed the exact half");
Assert.equal(splitter.balances(carol), 50 finney, "Carol should be owed the exact half");
}
function testSplitUnequalBobCarol() public {
Splitter splitter = new Splitter();
splitter.split.value(200003)(bob, carol);
Assert.equal(address(splitter).balance, 200003, "Splitter contract should have the Ether");
Assert.equal(splitter.balances(bob), 100001, "Bob should be owed the smaller half");
Assert.equal(splitter.balances(carol), 100002, "Carol should be owed the larger half");
}
}

View file

@ -1,5 +1,5 @@
module.exports = {
/*
networks: {
development: { // this one is optional and reduces "failing fast" dummerweise
host: "127.0.0.1",
@ -22,5 +22,5 @@ module.exports = {
network_id: "3"
}
}
*/
};