Step 1: Define the Enum
Start by defining an enum. An enum is a user-defined type that consists of a series of named constants. In this case, we’ll create an enum called UserType
.
enum UserType { Admin, User, Guest }
- Admin: Represents a user with administrative privileges.
- User: Represents a regular user.
- Guest: Represents a user with minimal permissions.
Step 2: Map Address to Enum
Next, create a mapping that associates Ethereum addresses to your enum values. This map will allow you to keep track of user types based on their address.
mapping(address => UserType) public userTypes;
- This line creates a public mapping called
userTypes
where each address maps to aUserType
.
Step 3: Create a Function to Set User Type
You need a function to assign a user type to a specific address. This function will accept an address and a corresponding UserType
.
function setUserType(address user, UserType userType) public {
userTypes[user] = userType;
}
- user: The Ethereum address of the user.
- userType: The enum value you want to assign to that address.
Step 4: Create a Function to Retrieve User Type
To access the user type associated with an address, you’ll want to create a function that retrieves this information.
function getUserType(address user) public view returns (UserType) {
return userTypes[user];
}
- This function takes an address as input and returns the corresponding
UserType
.
Example Usage
Here’s how you might use the above components together in a contract.
pragma solidity ^0.8.0;
contract UserManagement {
enum UserType { Admin, User, Guest }
mapping(address => UserType) public userTypes;
function setUserType(address user, UserType userType) public {
userTypes[user] = userType;
}
function getUserType(address user) public view returns (UserType) {
return userTypes[user];
}
}
Explanation of Example Code
- Contract Declaration: The contract name is
UserManagement
. - Enum Declaration: The three user types (Admin, User, Guest) are defined in the
UserType
enum. - Mapping Setup: The mapping
userTypes
is established to link addresses to user types. - setUserType Function: This function allows anyone to set the user type for any address (it can be restricted with access control if needed).
- getUserType Function: This reads and returns the user type for the given address.
Final Notes
- Make sure you’re careful with who can set user types; consider adding access controls (like
onlyAdmin
) if needed. - Always test your smart contract thoroughly to avoid any security issues.