Deleting Data From A Smart ContractWith 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: pragma solidity ^0.4.18; contract ExampleApp { string[] myArray; function add(string x) public { myArray.push(x); } 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]; } } } function show() public view returns (uint256, string) { string memory str; for (uint j = 0; j < myArray.length; j++) { str = string(abi.encodePacked(str, myArray[j])); } return(myArray.length,str); } } 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! The new contract is [here]. Update for compilerThe memory extension was added in 0.5.0 onwards, so we have to add it for later compilers: pragma solidity ^0.8.13; contract ExampleApp { string[] myArray; function add(string memory x) public { myArray.push(x); } function del(string memory x) public { for (uint j = 0; j < myArray.length; j++) { if (keccak256(abi.encodePacked(myArray[j])) == keccak256(abi.encodePacked(x))) { delete myArray[j]; } } } function show() public view returns (uint256, string memory) { string memory str; for (uint j = 0; j < myArray.length; j++) { str = string(abi.encodePacked(str, myArray[j])); } return(myArray.length,str); } } |