Skip to content

Commit

Permalink
[Contract] - Credit the remainder to the sender's balance when split …
Browse files Browse the repository at this point in the history
…odd number of ether.
  • Loading branch information
JakeLin committed Aug 17, 2019
1 parent 33829d0 commit d5854bb
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
4 changes: 3 additions & 1 deletion contracts/Splitter.sol
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ contract Splitter is Pausable, Killable {
function split(address _beneficiary1, address _beneficiary2) external payable whenRunning whenAlive {
require(_beneficiary1 != address(0) && _beneficiary2 != address(0), "Beneficiary's address must not be zero!");
require(msg.value > 0, "Must split more than zero ether!");
require(msg.value.mod(2) == 0, "The ether to be splitted must be even!");

if (msg.value.mod(2) == 1) {
balances[msg.sender] = balances[msg.sender].add(1);
}
uint256 half = msg.value.div(2);
balances[_beneficiary1] = balances[_beneficiary1].add(half);
balances[_beneficiary2] = balances[_beneficiary2].add(half);
Expand Down
34 changes: 28 additions & 6 deletions test/splitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,34 @@ contract('Splitter', accounts => {
});

context('When owner splits 3 wei (the number is odd)', () => {
it('should fail', async () => {
// Act & Assert
await truffleAssert.reverts(
contract.methods.split(bob, carol).send({from: owner, value: 3}),
'The ether to be splitted must be even!'
);
beforeEach(async () => {
// Act
tx = await contract.methods.split(bob, carol).send({from: owner, value: 3});
});

it('should split the ether to Bob and Carol\'s balance evenly', async () => {
// Assert
assert.strictEqual((await contract.methods.balances(bob).call()), '1');
assert.strictEqual((await contract.methods.balances(carol).call()), '1');
});

it('should credit the remainder (1 wei) to the sender\'s balance', async () => {
// Assert
assert.strictEqual((await contract.methods.balances(owner).call()), '1');
});

it('the contract balance should increase 3 wei', async () => {
// Assert
assert.strictEqual(await web3.eth.getBalance(contract.options.address), '3');
});

it('should emit the LogSplitted event', async () => {
// Assert
assert.strictEqual(tx.events.LogSplitted.event, 'LogSplitted');
assert.strictEqual(tx.events.LogSplitted.returnValues.sender, owner);
assert.strictEqual(tx.events.LogSplitted.returnValues.amount, '3');
assert.strictEqual(tx.events.LogSplitted.returnValues.beneficiary1, bob);
assert.strictEqual(tx.events.LogSplitted.returnValues.beneficiary2, carol);
});
});

Expand Down

0 comments on commit d5854bb

Please sign in to comment.