Design gas-efficient staking with accurate, manipulation-resistant reward accounting.
## CONTEXT A team is building a staking contract in 2026 and needs O(1) reward accounting that stays accurate as users stake, unstake, and claim. They want resistance to reward gaming and dust attacks. Solidity 0.8.28+ assumed. ## ROLE Act as a rewards-systems engineer who has implemented the accumulated-reward-per-token pattern and knows its precision pitfalls. ## RESPONSE GUIDELINES - Provide the core accounting formula and update sequence. - Emphasize correct ordering of updates relative to user actions. - Address precision and dust at every step. - Recommend tests proving conservation of rewards. ## TASK CRITERIA ### Reward Accounting Model - Implement accumulated reward-per-token with rewardPerTokenStored. - Define userRewardPerTokenPaid and earned() correctly. - Update accounting before any stake/unstake/claim mutation. - Handle the zero-total-supply division case. ### Reward Sources & Rates - Support fixed-rate, duration-based, or fee-funded rewards. - Handle reward-rate changes and unfinished periods safely. - Prevent reward overfunding or underfunding edge cases. - Address multiple reward tokens if required. ### Manipulation Resistance - Prevent flash-stake-then-claim gaming within a block. - Handle dust stakes that bloat storage or skew math. - Address sandwiching of reward-rate updates. - Consider lock periods or claim cooldowns. ### Precision & Dust - Choose a precision multiplier to minimize rounding loss. - Ensure rounding never lets total claimed exceed funded rewards. - Sweep or socialize residual dust deterministically. - Test cumulative rounding over many small operations. ### Safety & Edge Cases - Use SafeERC20 and handle fee-on-transfer stake tokens. - Add pause and emergency-withdraw without losing accounting. - Guard against reentrancy in claim paths. - Provide invariant tests for sum-of-earned consistency. ## ASK THE USER FOR - The stake token and reward token(s). - The reward funding model and rate schedule. - Whether lock periods or cooldowns are desired. - Expected user count and dust tolerance.
Or press ⌘C to copy