Skip to content

Instantly share code, notes, and snippets.

@leon-do
Last active July 12, 2022 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leon-do/d5850bf39fd7710bc365764d1c0d1c8d to your computer and use it in GitHub Desktop.
Save leon-do/d5850bf39fd7710bc365764d1c0d1c8d to your computer and use it in GitHub Desktop.
Leaderboard in Solidity
pragma solidity >=0.6.6;
contract Leaderboard {
// person who deploys contract is the owner
address owner;
// lists top 10 users
uint leaderboardLength = 10;
// create an array of Users
mapping (uint => User) public leaderboard;
// each user has a username and score
struct User {
string user;
uint score;
}
constructor() public{
owner = msg.sender;
}
// allows owner only
modifier onlyOwner(){
require(owner == msg.sender, "Sender not authorized");
_;
}
// owner calls to update leaderboard
function addScore(string memory user, uint score) onlyOwner() public returns (bool) {
// if the score is too low, don't update
if (leaderboard[leaderboardLength-1].score >= score) return false;
// loop through the leaderboard
for (uint i=0; i<leaderboardLength; i++) {
// find where to insert the new score
if (leaderboard[i].score < score) {
// shift leaderboard
User memory currentUser = leaderboard[i];
for (uint j=i+1; j<leaderboardLength+1; j++) {
User memory nextUser = leaderboard[j];
leaderboard[j] = currentUser;
currentUser = nextUser;
}
// insert
leaderboard[i] = User({
user: user,
score: score
});
// delete last from list
delete leaderboard[leaderboardLength];
return true;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment