Search code examples
ethereumblockchainsolidityremix

For/If Loop has no errors but does not push the value to the array


I am trying to create a whitelist. I've used a for and if loop to check if the msg.sender already exists in the array. When the whitelist() function is run, no errors are returned, but when I run check(), it tells me the address doesn't exist in the array, same thing with directing fetching the array.

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SelfWhitelist {

    address[] public addressWhitelist;

    function whitelist() public returns(string memory) {
        for(uint i = 0; i < addressWhitelist.length; i++) {
            if(addressWhitelist[i] != msg.sender) {
                addressWhitelist.push(msg.sender);
                return "Whitelisted!";
            }
        }
        return "Already whitelisted!";
    }

    function check() public view returns (bool){
        for(uint i = 0; i < addressWhitelist.length; i++){
            if(addressWhitelist[i] == msg.sender)
                return true;
        }
        return false;
    }

}

I added this block of code to check for duplicate entries in the array.

for(uint i = 0; i < addressWhitelist.length; i++) {
            if(addressWhitelist[i] != msg.sender) {
                addressWhitelist.push(msg.sender);
                return "Whitelisted!";
            }

Expected for no errors and my address being pushed to the array.

The code ran without errors, but nothing was added to the array.


Solution

  • I would use mapping type to hold the whitelisted addresses, then you don't have to loop over the array

    contract SelfWhitelist {
    
        mapping(address => bool) public addressWhitelist;
    
        function whitelist() public returns(string memory) {
            if (check()) {
                return "Already whitelisted!";
            }
            addressWhitelist[msg.sender] = true;
            return "Whitelisted!";
        }
    
        function check() public view returns (bool) {
    
            return addressWhitelist[msg.sender];
        }
    }
    

    And in your code, seems you have logical issues:

     for(uint i = 0; i < addressWhitelist.length; i++) {
        if(addressWhitelist[i] != msg.sender) {
            addressWhitelist.push(msg.sender);
            return "Whitelisted!";
        }
    }
    
    • if the array is empty, the loop never executes, so nothing will be added
    • if the first item is not msg.sender, msg.sender will be whitelisted, even though it might be already whitelisted.