What is the best way to store users data on smart contract? Suppose we have n number of users and we want to store each username and his other details, should we have to create a smart contract individually for every user?
1 Answer
Create a struct like so:
struct User {
uint256 id;
bytes32 name;
// other stuff
bool set; // This boolean is used to differentiate between unset and zero struct values
}
And create a mapping:
mapping(address => User) public users;
You could also use other values as index, but this is just for demonstration.
Now, to create a user, use a function like this:
function createUser(address _userAddress, uint256 _userId, bytes32 _userName) public {
User storage user = users[_userAddress];
// Check that the user did not already exist:
require(!user.set);
//Store the user
users[_userAddress] = User({
id: _userId,
name: _userName,
set: true
});
}
And done!
EDIT As you stated in the comments, you want to store the hash of user information in a smart contract. That is even simpler: just store the hashes in a mapping.
This is the mapping you use to store the hashes in:
mapping(uint256 => bytes32) public userDataHashes;
Now, the function to set a hash for a user id becomes:
function storeUserDataHash(uint256 _userId, bytes32 _dataHash) public {
userDataHashes[_userId] = _dataHash;
}
-
1I'm not sure if the OP asked about contract users, could be just any users in general. So a mapping to address may not be appropriate. But, your guess is as good as mine. Apr 13, 2018 at 8:49
-
1
-
1Thank you for the quick response @henkiedoodle. Here's my application model. There are N general users who don't know anything about smart contracts. They will login to a portal, submit their documents, there will be a function in backend that will convert file content to hash using keccak256 and will store the file hash in smart contract. I am confused in should every time we have to create a new smart contract when a new user will login to portal? Apr 13, 2018 at 9:40
-
1No, you should store the information in a mapping. They are perfect for this application.– HenkApr 13, 2018 at 10:00
-
1But in that case contract address would be same for each user, how a user would be identified individually? Apr 13, 2018 at 10:12