1

I have this mapping

  mapping(bytes32 => address[]) public authorisation;

This maps a hash with a list of authorised users.

I have a function to add, and confirm - these work and its not an issue. But now I need to add a delete funciton, where given a hash and an address, that address is revoked access/permission

function deletePermission(bytes32 hash, address user) public {// get index of element with the address = user, then delete this element from the array.}

I already looked over here but didn't find any solutions where the index isn't known. I know you can loop through the array until you find the element matching the address but that would be very costly( in terms of gas). Is there any more efficient way to do it? Thanks

2 Answers 2

2

When adding to the array, you can also store the index you added it to. You can use a second mapping to do that:

mapping(bytes32 => mapping(address => uint256)) public authorisation_arrayIndex;

When adding to the authorisation mapping:

authorisation_arrayIndex[hash][addr] = authorisation[hash].length;
authorisation[hash].push(addr);

Also, maybe you should consider using one mapping directly instead of an array and array index mapping. For example:

mapping(bytes32 => mapping(address => bool)) public authorisation;

That way you can easily add and remove:

authorisation[hash][addr] = true;
authorisation[hash][addr] = false;

... with the disadvantage that you can't loop over them.

2

I agree with @Jesse.

"without knowing the index?"

It will work out better with the question reframed as "How can I organize storage so deletes are efficient?"

There is a process to delete from an indexed mapping (where you have implemented with an array and a mapping. In summary, move the last item of the unordered list into the row to delete and then index.length--; Full example with explanation: https://medium.com/@robhitchens/solidity-crud-part-2-ed8d8b4f74ec

There are variations on the pattern, e.g. using a simple bool instead of a struct if it will suffice.

As a general rule, In Solidity, most such challenges are best solved by putting the focus on storage organization rather than looking for ways to deal with sub-optimal organization.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.