- Create a mapping variable to store the address as a key and whitelisting status as the value. Marking the mapping as a public variable will create a getter function that can be used to verify the whitelist status:
mapping(address => bool) public whitelist;
- Create a function to add users to the whitelisting contract. This function should be restricted to the owner or admin:
function addToWhitelist(address _investor) external
onlyOwner {
whitelist[_investor] = true;
}
- For easy whitelisting, you can have another function that accepts an array of addresses:
function addMultipleToWhitelist(address[] _investors)
external onlyOwner {
for (uint256 i = 0; i < _investors.length; i++) {
whitelist[_investors[i]] = true;
}
}
- Create a function to remove a user from the whitelist. It can come in handy if an address is added by mistake, or the user is no longer invited to the function:
function removeFromWhitelist(address _beneficiary) external
onlyOwner {
whitelist[_beneficiary] = false;
}
- Create a modifier to prevent non-whitelisted users from accessing the functions:
modifier isWhitelisted(address _investor) {
require(whitelist[_investor]);
_;
}
- Apply the modifier to the token buying function. It will allow only whitelisted users to buy tokens through this crowdsale. The final contract should look like the following example:
contract WhitelistContract {
mapping(address => bool) public whitelist;
/**
* @dev Check if investor is whitelisted.
*/
modifier isWhitelisted(address _investor) {
require(whitelist[_investor]);
_;
}
/**
* @dev Adds an address to whitelist.
* @param _investor Address to whitelist
*/
function addToWhitelist(address _investor) external
onlyOwner {
whitelist[_investor] = true;
}
/**
* @dev Adds list of addresses to whitelist.
* @param _investors Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _investors) external
onlyOwner {
for (uint256 i = 0; i < _investors.length; i++) {
whitelist[_investors[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _investor Address to be removed to the whitelist
*/
function removeFromWhitelist(address _investor) external
onlyOwner {
whitelist[_investor] = false;
}
// Add isWhitelisted modifier to token buying function
function buyTokens(address _investor, uint256 _weiAmount)
public isWhitelisted(_investor) {
// ..
}
}