Blockchain Development — Day 4
Mapping
In the last article, “Sending ether to a contract and withdrawing” we looked at a working example for using the address variable and msg object. In this article, we are going to extend our contract to store the balance for each addres sending money to the contract using the mapping variable.
Mappings Explained
Mappings act as hash tables which consist of key corresponding to value pairs. In our example, we will map an address to a balance.
mapping (address => uint)
This is the same code as the last contract with the new variable, balanceReceived that maps addresses to balances.
We modify the sendMoneyToContract
function to increment the amount the address that sent money to the contract and
Lets now add a getBalanceForAddress
function that gets the balance for a specified address
Finally, lets create a functionwithdrawMoney
passing the address we want to send the money too and the amount to send.
Line 34 : Checks that the msg sender has enough to send, otherwise it will send a message that there is not enough funds to transfer
Line 36: Updates the balance
Line 38: Sends the amount to the specified address
That’s covers extended smart contract to record each addresses balance sent to the smart contract using mapping.
If you found this article helpful, please give me a Clap, as this brightens my day knowing I may have helped someone in their journey in making stuff! Also if you want to be notified for future releases in this series, “Follow” me. You may also send me a message if you need any further help.