Solidity – How to Manage Deposits and Withdrawals from Multiple Accounts

blockchaingo-ethereumremixsolidity

I have a scenario of deposit the amount on a particular address and keep the record of the total amount deposited at this address. The same way one can also withdraw the amount from this address and total should be deducted the withdrawn amount for that particular address.

Here, twick is there can be multiple accounts so there can be multiple addresses and we need to store final amount(deposit/withdraw) account wise. Here we are storing just random amount, not ether.

So my questions are

  1. To store the accounts we need to use the mapping but how to calculate the amount(deposit/withdraw) by using mapping?

  2. can we use the array here?

Thanks

Edit the below part

My program

pragma solidity ^0.4.18;

contract Banking {     
  uint deposit;       
  uint amount;       
  mapping(address => uint) accountBalance;       

  function setDeposit(uint amt)
  {
   uint new_deposit = deposit + amt;
   accountBalance[msg.sender] = new_deposit;
   deposit += amount;
  }
  function getAmount() constant returns (uint)
  {
    return(accountBalance[msg.sender]);
  }
  function withdraw(uint amt)
  {
    uint withdrawAmount = amt;
    uint newBalance = accountBalance[msg.sender] - withdrawAmount;
    accountBalance[msg.sender] = newBalance;
  }
}

Best Answer

  1. Use mapping (address => uint256) accountBalance; where an address is obviously the users' address and uint256 is the amount that the users has as balance. When a user sends ether to your contract update the amount by uint256 oldBalance = accountBalance[msg.sender]; uint256 newBalance = msg.value + oldBalance; accountBalance[msg.sender] = newBalance; Note that I have not thought about re-entrancy or over/underflow of the uint values.

  2. Using an array is not optimal but you could indeed use an array for this. For instance, you could create an array of structs which have the address and balance of the user. But again, this isn't optimal.

Related Topic