0

Suppose In a banking system many people are enrolled (managed through mapping ) mapping (address => bool) enrolled;

And only those can deposit who are enrolled in the bank.

Can I check if the msg.sender exists as a key in the above mapping?

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
CryptoScroller
  • 825
  • 1
  • 9
  • 18

3 Answers3

1

The default value of a bool in a mapping is false. If you also use false as a part of your tracking system, then no, you will not be able to tell whether a value has been set to false or has not been set at all.

For that, you may need a second mapping which tracks whether the value has been set before.

mapping (address => bool) enrolledSet;
Shawn Tabrizi
  • 8,008
  • 4
  • 19
  • 38
  • Means for tracking a new mapping is needed we cant check or iterate through the mapping right ? – CryptoScroller Nov 30 '18 at 20:20
  • You cannot iterate through a mapping. You will need to create an array to do any sort of practical iterations since they have a measurable length and order. Otherwise, as I suggested in my answer, a mapping works to simply check whether the value has been set – Shawn Tabrizi Nov 30 '18 at 20:21
1

Here is a minimal way to cover random access, counting uniques and iterating over the list.

pragma solidity 0.5.0;

contract InterableMapping {

    address[] public addressList;
    mapping(address => bool) public isAddress;

    function insertAddress(address customer) public {
        require(!isAddress[customer]);
        addressList.push(customer);
        isAddress[customer] = true;
    }

    function getAddressCount() public view returns(uint count) {
        return addressList.length;
    }
}

You could add a soft delete by setting the bool to false.

function disableCustomer(address customer) public {
  require(isAddress[customer]);
  isAddress[customer] = false;
}

Have a look over here for different patterns: Are there well-solved and simple storage patterns for Solidity?

Hope it helps.

Rob Hitchens
  • 55,151
  • 11
  • 89
  • 145
0

Yes, with your example, you can just do the following:

require(enrolled[msg.sender]);
user19510
  • 27,999
  • 2
  • 30
  • 48