0

I have a question about mapping.

mapping(uint => address) public id;

function setMapping() public {
    id[1] = msg.sender;
}

As in the code above, if you put a key and a value in the mapping and save the data, does the data i put in the key incur a gas fee?

Where is the mapping key stored in the smart contract?

3 Answers 3

1

Mappings are kept in storage. Cost of storing in a mapping is approximately the cost of an SSTORE operation, which varies depending on if you're writing an entirely new value or if you're overwriting an old value. Check out evm.codes for more information about the cost of an SSTORE operation.

Every smart contract on Ethereum has its own key/value storage where keys and values are both 32 bytes. Solidity mapping values are placed into this key/value storage according to the logic defined in the Solidity documentation regarding state variable layout in storage. For mappings, this is:

storage_key = keccak256(concat(uint256(mapping_key), uint256(mapping_variable_position)))

Where mapping_key is the key in the mapping that you're updating and mapping_variable_position is the position of the mapping within your contract. mapping_variable_position literally is just the order in which your mapping was defined -- if the mapping is the very first variable in the contract then mapping_variable_position will be 0. Second variable will be 1, etc etc.

For your example, assuming the id mapping is the first variable defined in the contract, id[1] is found at:

mapping_key = 1
mapping_variable_position = 0

storage_key = keccak256(concat(uint256(mapping_key), uint256(mapping_variable_position)))
            = keccak256(
                concat(
                  0x0000000000000000000000000000000000000000000000000000000000000001,
                  0x0000000000000000000000000000000000000000000000000000000000000000
                )
              )
            = 0xada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d
1

Yes, it costs gas. Mappings are stored on the storage level. When you initialize a mapping, the key and value are set to default (in this case 0 & 0x0). So when you call setMapping you are changing that data and updating/changing data on blockchain costs

1

When you create themapping the main thing that happens is the compiler reserves a storage slot which is used to organize storage. The effect is entirely in the bytecode for the contract.

public makes it create a function to return key values.

Unset values are initially binary zero because nothing has been written and all keys "exist".

Setting a value causes an SSTORE. The cost varies. Writing to a previously zero key is more expensive than overwriting a non-zero value.

Hope it helps.

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.