Created
January 2, 2022 19:15
-
-
Save jakep84/53664a13c2d52258b47f72950dca5e29 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pragma solidity >=0.8.0; | |
contract Leaderboard { | |
// person who deploys contract is the owner | |
address owner; | |
// lists top 100 users | |
uint leaderboardLength = 100; | |
// 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