Search code examples
ethereumsoliditydecentralized-applications

How to make a smart contract only executable when called by specific verified addresses?


I am trying to make a decentralized web application where if a condition is met a contract would be executed and could send eth to an address. for example, if my website were to have a list of users who have registered accounts and each user has an ethereum address associated with their account, how could I make it so that my smart contract can only be executed by the specific addresses that have registered an account on my website?

When a users clicks a button on my website like (get eth) that would call a smart contract function, how can I make it so that only registered users can use my smart contract?

I have been looking into message signing and ecrecover as well as off chain whitelisting. My thought process for solving this problem has been to use these in some fashion to verify if an address is valid to execute a contract. I would think of this problem as essentially creating a basic faucet smart contract but limiting the addresses that can use it to a select few.


Solution

  • I think we just simple add the users to our smartcontract. Then we verify it like this:

    contract MyContract {
        mapping(address=>bool) public registerUsers;
        address owner;
    
        modifier onlyOwner(){
            require(msg.sender==owner);
            _;
        }
        modifier onlyUser(){
            require(registerUsers[msg.sender] == true);
            _;
        }
    
        function() external payable { }
        constructor() public{
            owner = msg.sender;
        }
    
        function  addUser(address userAddr) onlyOwner() public{
            registerUsers[userAddr] = true;
        }
        // User calls this function to claim some eth
        function claimEth(uint amount) onlyUser() public{
            msg.sender.transfer(amount);
        }
    }