Skip to content

Instantly share code, notes, and snippets.

@frangio
Created September 23, 2022 16:06
Show Gist options
  • Save frangio/79eb6f6a0a115d08537751bf21ce52fe to your computer and use it in GitHub Desktop.
Save frangio/79eb6f6a0a115d08537751bf21ce52fe to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/Math.sol";
struct Accumulator {
uint concrete;
uint virtualRate;
uint virtualSince;
}
function getValue(Accumulator storage acc) view returns (uint) {
return acc.concrete + acc.virtualRate * (block.timestamp - acc.virtualSince);
}
function addRate(Accumulator storage acc, uint rate) {
setRate(acc, acc.virtualRate + rate);
}
function subRate(Accumulator storage acc, uint rate) {
setRate(acc, acc.virtualRate - rate);
}
function setRate(Accumulator storage acc, uint rate) {
acc.concrete = getValue(acc);
acc.virtualRate = rate;
acc.virtualSince = block.timestamp;
}
struct Stakes {
Accumulator total;
mapping (address => Accumulator) accounts;
}
function getTotal(Stakes storage st) view returns (uint) {
return getValue(st.total);
}
function getDividend(Stakes storage st, address account) view returns (uint) {
return getValue(st.accounts[account]);
}
function addStake(Stakes storage st, address account, uint stake) {
addRate(st.total, stake);
addRate(st.accounts[account], stake);
}
function subStake(Stakes storage st, address account, uint stake) {
subRate(st.total, stake);
subRate(st.accounts[account], stake);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment