Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting mapping from mapping in Solidity

I have something like this:

mapping (address => mapping(string => uint)) m_Map;

It can be accessed as m_Map[strCampaignName][addrRecipient], campaign can have multiple recipients...

Now at some point (ICO failed), I need to remove that campaign with all recipients. I don't think a simple delete m_Map[strCampaignName] will work. If I use m_Map[strCampaignName] = null, I think data will not be deleted. If I iterate through a list of all recipients, I will run out of gas.

How should this situation be handled? Min: I want m_Map[strCampaignName] to be empty, Max: I want to stop wasting memory on it.

like image 777
Steve Brown Avatar asked Jan 30 '18 06:01

Steve Brown


People also ask

How is mapping stored Solidity?

Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type.

How do you clear an array in Solidity?

We can create a function remove() that will take an array's index as an argument. Then the function will set the index argument to the last element in the array. Simply, we will shift the index argument over the last element of the array. Then we will remove the last element by using the pop() method.


1 Answers

As you stated, you can't delete a mapping in Solidity. The only way to "clear" the data is to iterate through the keys (using a separate array that stores the keys) and delete the individual elements. However, you're correct to be concerned about the cost...Depending on the size of the mapping, you could run into gas consumption issues.

A common approach to work around this is to use a struct in your mapping with a soft delete:

struct DataStruct {
  mapping(string => uint) _data;
  bool _isDeleted;
}

mapping(address => DataStruct) m_Map;

Now, deleting an entry just requires you to set the flag: m_Map[someAddr]._isDeleted = true;

like image 126
Adam Kipnis Avatar answered Oct 21 '22 21:10

Adam Kipnis