2

I have this mapping:

mapping (uint256 => string ) private storedData;

I am trying to do this:

modifier dataNotStored(uint256 _index) {
        require( keccak256(abi.encodePacked(storedData[_index])) == keccak256(abi.encodePacked('')) );
        _;
    }

    function set(uint _index, string calldata _data_to_store) external dataNotStored(_index) {
        storedData[_index] = _data_to_store;
    }

My goal is to allow only one write for each entry of the mapping.

I think it is working, because from Remix IDE I get error only when trying a rewrite.

Is there a more efficient and intelligent way to avoid to overwrite a mapping?

Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82
realtebo
  • 333
  • 5
  • 15

1 Answers1

2

You can avoid the modifier and the hashing. It is simpler to do:

function set(uint _index, string calldata _data_to_store) external {
    require(bytes(storedData[_index]).length == 0);
    storedData[_index] = _data_to_store;
}

Checking the length of the bytes was inspired by this answer.

Shane Fontaine
  • 18,036
  • 20
  • 54
  • 82