0

If you are building a program where users stake tokens into a vault, which gets compounded every week, how do you keep track of how much token each user has?

A naive approach would be to create a Stake { amount: u64 } account per user. But then to compound, you would have to go through each user's account and multiply by the compounding factor.

Is there a more scalable solution?

2
  • please add context to the title. "compounding" can mean a lot of thing in a lot of contexts
    – trent.sol
    Commented Jul 18, 2022 at 19:30
  • @trent.sol fixed
    – itsfarseen
    Commented Jul 18, 2022 at 19:36

2 Answers 2

3

I support oscarb.sol's approach.

I had the same challenge with my app. And after some thought, I ended up letting users claim on their own. This has the added advantage that the users pay the transaction fees, not me. So they can decide in what frequency they claim, to keep fees low.

Also, in my case, I have implemented a two-level approach of "collect" and "claim". Collect will do the math (compounded interest in this case), advance the last_collection timestamp, and collect the amount into a field in their account, e.g. collected_yet_unclaimed: u64. After they've collected, they can claim any amount from 0 up to collected_yet_unclaimed into their wallet.

That way, doing the math (which is way more complicated in my case than compounded interest) is decoupled from the actual withdrawal.

This is great because often, the user just wants to know how much they've earned so far ("collect") rather than being forced to withdraw every time they check earnings.

2
  • This approach is not feasible if the compounding rate varies every week right?
    – itsfarseen
    Commented Jul 21, 2022 at 4:33
  • 2
    It should still be feasible as log as the compounding is deterministic. Even if it varies every week, you can save the rate for each week in some global state (PDA), and then do the calculation for each individual user only when they come back, using the global data that was stored before. Commented Jul 21, 2022 at 13:28
2

If you run the compound calculation lazily, then you don't have to update accounts. When a user tries to claim their tokens, compound during that instruction.

This way, your on-chain state will look something like:

Stake {
   last_withdrawl: UnixTimestamp,
   amount: u64,
}
1
  • What if the compounding rate varies every week?
    – itsfarseen
    Commented Jul 20, 2022 at 9:42

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.