0

Below is the code which I saw on Solidity official site

pragma solidity >=0.4.0 <0.9.0;

contract MappingExample {
    mapping(address => uint) public balances;

    function update(uint newBalance) public {
        balances[msg.sender] = newBalance;
    }
}

contract MappingUser {
    function f() public returns (uint) {
        MappingExample m = new MappingExample();
        m.update(100);            //       **LINE 1**
        return m.balances(address(this));         **LINE 2**
    }
}

What is m.update(100) is doing in contract ? I thought that it will be passing value 100 in the paramter newBalance in function update of contract MappingExample. But it is taking value from user.

Secondly , please explain to me what role does line 2 i.e m.balances(address(this)) have in here.

1 Answer 1

0

mapping(address => uint) public balances;

is a Map from an address to a number

address1 -> number
address2 -> number
...

Because it is public, Solidity will create a hidden function for you called balances, and will look like this function balances(address addr) view returns (uint) this function will return the stored value (number) for a given key (address)

The function function update(uint newBalance) public update this map by updating the value (number) for the key which is the caller (address)

NOW

MappingUser is a new contract that has a function function f() public returns (uint)

This function do the following:

  • MappingExample m = new MappingExample(); Deploy a new MappingExample Contract

  • m.update(100); It sends a request to the new contract and calls the update function. WARNING the update function has msg.sender and in this case the caller of the update function is the MappingUser contract and not the user. so it basically changes the value in the map address-of-MappingUser-contract -> 100

  • return m.balances(address(this)); it calls hidden balances function and it gives its address (the address of MappingUser contract) as an argument. address(this) is the address of the MappingUser contract

2
  • Thank you very very much .So basically , does it mean that MappingUser contract is just creating a entry in the mapping table and not doi ng anything else. Is it so ?
    – Brijesh
    Commented Aug 20, 2022 at 5:02
  • It deploy a new contract each time ‚f()‘ is called and add an entry to the map in the new deployed contract. This entry is <mapping-user-contract-address> to 100 @Brijesh
    – Majd TL
    Commented Aug 20, 2022 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.