0

i am trying to write a contract in which there is a function to divide the amount into equal parts and then deposit it into multiple accounts in one transaction. The problem is that, i want function to reverse or fail the transaction if some error is produced during deposit of any address from the given addresses. And is it possible to make it more dynamic? Thanks

contract amountSplit {

  mapping(address => uint) public toAccountBalance;
  address[2] public beneficiaryList;

  event LogReceived(address sender, uint amount);
  function addAddresses(address addressOne, address addressTwo) {
    beneficiaryList[0]=addressOne;
    beneficiaryList[1]=addressTwo;
  }

  function pay(uint amount) public payable returns(bool success)
  {
    if(amount==0) throw;
    uint forth = amount / 2;

    toAccountBalance[beneficiaryList[0]] += forth;
    toAccountBalance[beneficiaryList[1]] += forth;
    emit LogReceived(msg.sender, msg.value);
    return true;
  }
}
0

In your code, there only possible errors are:

Amount is zero. increasing the balance of any of the beneficiaries causes overflow.

The first is taking care by you, but I suggest this instead:

require(ammount>0)

The second is that you need to check for overflow when doing mathematical operations. For this, you can use safeMath library or just to check for overflow. The last case gives you something like this:

function pay(uint amount) public payable returns(bool success)
  {
    require(amount>0);
    uint forth = amount / 2;
    require(toAccountBalance[beneficiaryList[0]] + forth > forth);
    require(toAccountBalance[beneficiaryList[1]] + forth > forth);

    toAccountBalance[beneficiaryList[0]] += forth;
    toAccountBalance[beneficiaryList[1]] += forth;
    emit LogReceived(msg.sender, msg.value);
    return true;
  }

This function will throw if the amount is zero or if the sum produces overflow.

hope this helps.

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.