struct Payment {
 uint amount;
 uint timestamp;

 struct Balance {
 uint totalBalance;
 uint numPayments;
 mapping(uint => Payment) payments;

 mapping(address => Balance) public balanceReceived;

function sendMoney() public payable {
 balanceReceived[msg.sender].totalBalance += msg.value;

 Payment memory payment = Payment(msg.value, now);
yments] = payment;

In the above smart contract, why is this the definition used to add to the payments mapping inside the Balance struct:

balanceReceived[msg.sender].payments[balanceReceived[msg.sender].numPayments] = payment;

and not:

balanceReceived[msg.sender].payments[_index] = payment;

Where is the connection with numPayments in the balance struct with obtaining the key


The numPayments is essentially acting as an index as you would have expected.

A key thing to notice is that it is an index per address. The balanceReceived mapping maps an address to a balance struct where initially the numPayments will be set to zero. This will be true for every address that interacts with this contract. Each time they make a payment this numPayments will increase only for the balance of that particular address.

You could certainly keep a global _index for all user balances and increment that each time. That would work fine, the only difference is that this index would be incremented for all payments across all addresses. In this case you would lose the information about how many payments were made by that particular address.

  • So in a mapping such the payments above with the uint as a key, we use the key as a counter, such that if 5 people transacted with the smart contract the mapping will automatically enumerate assign them the values 0,1,2,3,4 in the order that they came? and it can only store as many fields as 2^256. Similarly if we used uint8, then it would only store 256 fields?
    – HallonDev
    Nov 15 '20 at 20:30
  • 1
    Sounds about right! Thanks to balanceReceived, each address would have their own Balance struct, which would have a Payment in the payments mapping for every payment made with the index being the current payment they're on.
    – Dan-Nolan
    Nov 15 '20 at 21:06

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.