Loading...
Lets define compiler version and smart contract
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract toptenusers {
. . .
}
We will add a user struct to save invested amount by user in it and map it to user address.
struct User{
uint256 total_invested_amount;
}
mapping(address => User) public user_info;
mapping(uint8 => address) public top_10_investors;
Our algorithm will assign top ten users who send token to contract in mapping created before from 1 to 10 position.
function top_10() public{
for(uint8 i=0; i<10; i++){
if(top_10_investors[i] == msg.sender){
for(uint8 j=i ; j<11;j++){
top_10_investors[j] = top_10_investors[j+1];
}
}
}
for(uint8 i=0;i<10;i++){
if(user_info[top_10_investors[i]].total_invested_amount < user_info[msg.sender].total_invested_amount){
for(uint8 j = 10;j > i;j--){
top_10_investors[j] = top_10_investors[j-1];
}
top_10_investors[i] = msg.sender;
return;
}
}
}
We will need a function to trigger our top_10 function and add user amount.
function store() public payable {
user_info[msg.sender].total_invested_amount += msg.value;
top_10();
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract toptenusers {
struct User{
uint256 total_invested_amount;
}
mapping(address => User) public user_info;
mapping(uint8 => address) public top_10_investors;
function top_10() public{
for(uint8 i=0; i<10; i++){
if(top_10_investors[i] == msg.sender){
for(uint8 j=i ; j<11;j++){
top_10_investors[j] = top_10_investors[j+1];
}
}
}
for(uint8 i=0;i<10;i++){
if(user_info[top_10_investors[i]].total_invested_amount < user_info[msg.sender].total_invested_amount){
for(uint8 j = 10;j > i;j--){
top_10_investors[j] = top_10_investors[j-1];
}
top_10_investors[i] = msg.sender;
return;
}
}
}
function store() public payable {
user_info[msg.sender].total_invested_amount += msg.value;
top_10();
}
}