Let's say I have a BEP-20 token, where holders can optionally stake their own tokens in a pool. I want a smart contract that can assess

1.) The percentage of tokens they have staked relative to the total number of tokens in the pool.

2.) A way to efficiently distribute "dividends" based on the percentage of tokens they have relative to the pool (see 1).

Can anyone give me some starting ideas for this? I want to avoid arrays and large loops if possible due to gas concerns.

Thank you

1 Answer 1


I am pretty sure you can find stuff like this. Look up the rough lines of Proof-of-Stake protocols.

I never did that but my first ideas are:

  • Use epochs. For instance, you could say that an epoch is 1,000 blocks.
  • When someone stakes tokens, the user's total and the global total are saved for the next epoch.
  • When someone unstakes tokens, the user's total and the global total of the current epoch are reduced.
  • Dividends can be claimed after the epoch has ended. Dividends are calculated on the total that was left at the end of the epoch.

In terms of data structure, for each user, you want to be able to keep a total per epoch, but not keep all epochs. Essentially, you store the total for another epoch only if the total has changed. Sparse array?

uint[] globalEpochs;
mapping(uint => uint) globalTotals;

struct User {
    uint[] epochs; // epoch ids
    mapping(uint => uint) totals; // epoch id -> total
    uint latestClaimedEpochId;

On each action, you find what is the latest epoch that has a value, at epochs[epochs.length - 1]. Whether this is a past or the current epoch, you act differently.

When the user claims, the user has to provide accurate values, that the contract checks, instead of the contract searching for them.

Gotta go

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.