'How to create a staking smart contract?

I'm a novice in a smartcontracts but want to create a simple stake contract in Solana. But can't understand when I need to update a reward counter per user? Because contracts interact with accounts for write, only when user paid for this. But in all staking protocols, we can see rewards count after staking. How this can work? And how I can change APY in a time?

I invented only one method - save counters in off chain program but think it's not right way



Solution 1:[1]

Smart contract doesn't have such a timer so it's impossible to update the states automatically. In other words, reward states should be updated by triggering a function manually. In staking contract, users can call a function for updating or claiming rewards by signing with his private keys. The best example is the orca.so github repo(https://github.com/orgs/orca-so). Orca is one of the successful AMM exchange on solana and you can get all necessary code snippets there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dev Topaz