I want to keep a track of top 5 token holders inside the contract in terms of their token balances, is there any efficient way to do that in solidity?
-
You can just keep an array with the top five in it, in sorted order. When someone's balance increases, see if it's better than the #5 slot. If so, find the right place to insert it and move the others down.– user19510Commented Sep 9, 2019 at 2:41
-
That's fine if balances only increase, but won't work when balances decrease. If one of the top 5 transfers, say, their entire balance - not to another address, but to many addresses - who do you add to the top 5?– ZakalweCommented Sep 9, 2019 at 8:55
1 Answer
You could store data in a heap which would approximately double your storage requirements (or less if you're willing to do some extra computation for indirection) for balances but gives you O(log n)
changes and you can get the top 5 holders in O(log n)
. You might also consider a sorted list for the entirety of the list (not just the top 5); insertions/deletions are O(log n)
and lookups are O(1)
. In all cases here, n
is the number of token holders.