TransWikia.com

What storage is assigned to mappings in solidity?

Ethereum Asked by Trevor Lee Oakley on February 27, 2021

I based some code on this – https://solidity.readthedocs.io/en/develop/types.html

When I run the code below –

pragma solidity ^0.4.18;

contract CA2 {

  mapping (uint => Student) public students;

  struct Student {
        address studentAccount;
        uint age;
        uint income;
        uint score;
        uint attendance;
  }
  uint public studentCount;

  function setStudent (uint age, uint income, uint score, uint attendance) public {
    studentCount++;
    students[studentCount]=Student(msg.sender,age,income, score,attendance);
  }

}

I get this –

con.setStudent(10,15000, 4, 96) “0x5c23079797c41856010185fbf633bb9ffa64c363c282e4adda120b4e3af1c29c”

eth.pendingTransactions []
eth.getStorageAt(con.address,0) “0x0000000000000000000000000000000000000000000000000000000000000000”
eth.getStorageAt(con.address,1) “0x0000000000000000000000000000000000000000000000000000000000000000”
eth.getStorageAt(con.address,2) “0x0000000000000000000000000000000000000000000000000000000000000000”

con is set to the deployed contract using eth.contract(abi).at(addr).

I have two questions –

  1. students appears to be an implicit array somehow. What dimensions are allocated in getStorageAt()?
  2. After it runs the storage is all zero.

I had expected to explicitly define the array but I followed the code example.

One Answer

The storage position for mappings is:

keccak256(k . p)

where k is the mapping key, . is concatenation, p is the position of the field as defined in your Solidity code:

students[].studentAccount: p=0
students[].age: p=1
students[].income: p=2

You can find more details in the documentation http://solidity.readthedocs.io/en/develop/miscellaneous.html#layout-of-state-variables-in-storage

Answered by medvedev1088 on February 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP