Deleting Data From A Smart Contract

With Ethereum we can create a stateful system, and where we can add and remove data from data stored in a smart contact. This is a stateful…

Photo by Leon Seibert on Unsplash

Deleting Data From A Smart Contract

With Ethereum we can create a stateful system, and where we can add and remove data from data stored in a smart contact. This is a stateful system, and where we change the state of the smart contact, and which will require the payment of some case to the miners. But how do we delete data?

So here’s a smart contract to add and remove strings into myArray:

The add() function is fairly simple, and where we basically just use a push() method. With this contact we can have “Edinburgh”, “Glasgow” and “London” added [here]:

Now we will delete “London” using this method:

function del(string x) public {                                       
for (uint j = 0; j < myArray.length; j++) {
if (keccak256(abi.encodePacked(myArray[j])) ==
keccak256(abi.encodePacked(x))) {
delete myArray[j];
}
} }

For this the keccak256() method is used to compare two strings, and will match the string in myArray with a string entered by the user into the smart contract (x):

if (keccak256(abi.encodePacked(myArray[j])) == 
keccak256(abi.encodePacked(x)))

Once a match is found, we can then delete the data element with [here]:

delete myArray[j];

Now, we can try it by selecting the delete function from the smart contact:

This will cost us some gas, and then it will go to a pending state:

Once complete we get:

Now, we can go back to the smart contract and see if the data has been deleted:

And success!

Here are a few other examples of using smart contacts in Ethereum:

  • Math functions on Test Network. Go.
  • zkSnarks, Smart Contracts and Ethereum. Go.
  • Creating ERC20 tokens on the Ethereum Test Network. Go.
  • Storing State in a Smart Contract. Go.