contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
SmarcToken
SmarcToken.sol
0x5ae655088e79fa0ced7b472d3bacd215ef796ccc
Solidity
SmarcToken
contract SmarcToken is ERC677, Ownable { // mapping for locking certain addresses mapping(address => uint256) public lockups; event LockedTokens(address indexed _holder, uint256 _lockup); // burnable address address public burnable; /** * @dev Smarc constructor just parametrizes the ERC677 -> MiniMeToken constructor */ constructor() public ERC677( 0x0, // no parent token 0, // no parent token - no snapshot block number "SmarcToken", // Token name 18, // Decimals "SMARC", // Symbol false // Disable transfers for time of minting ) {} uint256 public constant maxSupply = 150 * 1000 * 1000 * 10**uint256(decimals); // use the smallest denomination unit to operate with token amounts /** * @notice Sets the locks of an array of addresses. * @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same. * @param _holders The array of investor addresses * @param _lockups The array of timestamps until which corresponding address must be locked */ function setLocks(address[] _holders, uint256[] _lockups) public onlyController { require(_holders.length == _lockups.length); require(_holders.length < 256); require(transfersEnabled == false); for (uint8 i = 0; i < _holders.length; i++) { address holder = _holders[i]; uint256 lockup = _lockups[i]; // make sure lockup period can not be overwritten once set require(lockups[holder] == 0); lockups[holder] = lockup; emit LockedTokens(holder, lockup); } } /** * @notice Finishes minting process and throws out the controller. * @dev Owner can not finish minting without setting up address for burning tokens. * @param _burnable The address to burn tokens from */ function finishMinting(address _burnable) public onlyController() { require(_burnable != address(0x0)); // burnable address must be set assert(totalSupply() <= maxSupply); // ensure hard cap enableTransfers(true); // turn-on transfers changeController(address(0x0)); // ensure no new tokens will be created burnable = _burnable; // set burnable address } modifier notLocked(address _addr) { require(now >= lockups[_addr]); _; } /** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @dev We override transfer function to add lockup check * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _amount) public notLocked(msg.sender) returns (bool success) { return super.transfer(_to, _amount); } /** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` * @dev We override transfer function to add lockup check * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public notLocked(_from) returns (bool success) { return super.transferFrom(_from, _to, _amount); } /** * @notice Burns `_amount` tokens from pre-defined "burnable" address. * @param _amount The amount of tokens to burn * @return True if the tokens are burned correctly */ function burn(uint256 _amount) public onlyOwner returns (bool) { require(burnable != address(0x0)); // burnable address must be set uint256 currTotalSupply = totalSupply(); uint256 previousBalance = balanceOf(burnable); require(currTotalSupply >= _amount); require(previousBalance >= _amount); updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount); updateValueAtNow(balances[burnable], previousBalance - _amount); emit Transfer(burnable, 0, _amount); return true; } }
finishMinting
function finishMinting(address _burnable) public onlyController() { require(_burnable != address(0x0)); // burnable address must be set assert(totalSupply() <= maxSupply); // ensure hard cap enableTransfers(true); // turn-on transfers changeController(address(0x0)); // ensure no new tokens will be created burnable = _burnable; // set burnable address }
/** * @notice Finishes minting process and throws out the controller. * @dev Owner can not finish minting without setting up address for burning tokens. * @param _burnable The address to burn tokens from */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://bc5b66ddafec8d21bbbed131eef8898516da669ea8eb0f2115329fd071c2783e
{ "func_code_index": [ 2108, 2517 ] }
3,000
SmarcToken
SmarcToken.sol
0x5ae655088e79fa0ced7b472d3bacd215ef796ccc
Solidity
SmarcToken
contract SmarcToken is ERC677, Ownable { // mapping for locking certain addresses mapping(address => uint256) public lockups; event LockedTokens(address indexed _holder, uint256 _lockup); // burnable address address public burnable; /** * @dev Smarc constructor just parametrizes the ERC677 -> MiniMeToken constructor */ constructor() public ERC677( 0x0, // no parent token 0, // no parent token - no snapshot block number "SmarcToken", // Token name 18, // Decimals "SMARC", // Symbol false // Disable transfers for time of minting ) {} uint256 public constant maxSupply = 150 * 1000 * 1000 * 10**uint256(decimals); // use the smallest denomination unit to operate with token amounts /** * @notice Sets the locks of an array of addresses. * @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same. * @param _holders The array of investor addresses * @param _lockups The array of timestamps until which corresponding address must be locked */ function setLocks(address[] _holders, uint256[] _lockups) public onlyController { require(_holders.length == _lockups.length); require(_holders.length < 256); require(transfersEnabled == false); for (uint8 i = 0; i < _holders.length; i++) { address holder = _holders[i]; uint256 lockup = _lockups[i]; // make sure lockup period can not be overwritten once set require(lockups[holder] == 0); lockups[holder] = lockup; emit LockedTokens(holder, lockup); } } /** * @notice Finishes minting process and throws out the controller. * @dev Owner can not finish minting without setting up address for burning tokens. * @param _burnable The address to burn tokens from */ function finishMinting(address _burnable) public onlyController() { require(_burnable != address(0x0)); // burnable address must be set assert(totalSupply() <= maxSupply); // ensure hard cap enableTransfers(true); // turn-on transfers changeController(address(0x0)); // ensure no new tokens will be created burnable = _burnable; // set burnable address } modifier notLocked(address _addr) { require(now >= lockups[_addr]); _; } /** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @dev We override transfer function to add lockup check * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _amount) public notLocked(msg.sender) returns (bool success) { return super.transfer(_to, _amount); } /** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` * @dev We override transfer function to add lockup check * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public notLocked(_from) returns (bool success) { return super.transferFrom(_from, _to, _amount); } /** * @notice Burns `_amount` tokens from pre-defined "burnable" address. * @param _amount The amount of tokens to burn * @return True if the tokens are burned correctly */ function burn(uint256 _amount) public onlyOwner returns (bool) { require(burnable != address(0x0)); // burnable address must be set uint256 currTotalSupply = totalSupply(); uint256 previousBalance = balanceOf(burnable); require(currTotalSupply >= _amount); require(previousBalance >= _amount); updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount); updateValueAtNow(balances[burnable], previousBalance - _amount); emit Transfer(burnable, 0, _amount); return true; } }
transfer
function transfer(address _to, uint256 _amount) public notLocked(msg.sender) returns (bool success) { return super.transfer(_to, _amount); }
/** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @dev We override transfer function to add lockup check * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://bc5b66ddafec8d21bbbed131eef8898516da669ea8eb0f2115329fd071c2783e
{ "func_code_index": [ 2938, 3097 ] }
3,001
SmarcToken
SmarcToken.sol
0x5ae655088e79fa0ced7b472d3bacd215ef796ccc
Solidity
SmarcToken
contract SmarcToken is ERC677, Ownable { // mapping for locking certain addresses mapping(address => uint256) public lockups; event LockedTokens(address indexed _holder, uint256 _lockup); // burnable address address public burnable; /** * @dev Smarc constructor just parametrizes the ERC677 -> MiniMeToken constructor */ constructor() public ERC677( 0x0, // no parent token 0, // no parent token - no snapshot block number "SmarcToken", // Token name 18, // Decimals "SMARC", // Symbol false // Disable transfers for time of minting ) {} uint256 public constant maxSupply = 150 * 1000 * 1000 * 10**uint256(decimals); // use the smallest denomination unit to operate with token amounts /** * @notice Sets the locks of an array of addresses. * @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same. * @param _holders The array of investor addresses * @param _lockups The array of timestamps until which corresponding address must be locked */ function setLocks(address[] _holders, uint256[] _lockups) public onlyController { require(_holders.length == _lockups.length); require(_holders.length < 256); require(transfersEnabled == false); for (uint8 i = 0; i < _holders.length; i++) { address holder = _holders[i]; uint256 lockup = _lockups[i]; // make sure lockup period can not be overwritten once set require(lockups[holder] == 0); lockups[holder] = lockup; emit LockedTokens(holder, lockup); } } /** * @notice Finishes minting process and throws out the controller. * @dev Owner can not finish minting without setting up address for burning tokens. * @param _burnable The address to burn tokens from */ function finishMinting(address _burnable) public onlyController() { require(_burnable != address(0x0)); // burnable address must be set assert(totalSupply() <= maxSupply); // ensure hard cap enableTransfers(true); // turn-on transfers changeController(address(0x0)); // ensure no new tokens will be created burnable = _burnable; // set burnable address } modifier notLocked(address _addr) { require(now >= lockups[_addr]); _; } /** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @dev We override transfer function to add lockup check * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _amount) public notLocked(msg.sender) returns (bool success) { return super.transfer(_to, _amount); } /** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` * @dev We override transfer function to add lockup check * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public notLocked(_from) returns (bool success) { return super.transferFrom(_from, _to, _amount); } /** * @notice Burns `_amount` tokens from pre-defined "burnable" address. * @param _amount The amount of tokens to burn * @return True if the tokens are burned correctly */ function burn(uint256 _amount) public onlyOwner returns (bool) { require(burnable != address(0x0)); // burnable address must be set uint256 currTotalSupply = totalSupply(); uint256 previousBalance = balanceOf(burnable); require(currTotalSupply >= _amount); require(previousBalance >= _amount); updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount); updateValueAtNow(balances[burnable], previousBalance - _amount); emit Transfer(burnable, 0, _amount); return true; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _amount) public notLocked(_from) returns (bool success) { return super.transferFrom(_from, _to, _amount); }
/** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` * @dev We override transfer function to add lockup check * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://bc5b66ddafec8d21bbbed131eef8898516da669ea8eb0f2115329fd071c2783e
{ "func_code_index": [ 3516, 3700 ] }
3,002
SmarcToken
SmarcToken.sol
0x5ae655088e79fa0ced7b472d3bacd215ef796ccc
Solidity
SmarcToken
contract SmarcToken is ERC677, Ownable { // mapping for locking certain addresses mapping(address => uint256) public lockups; event LockedTokens(address indexed _holder, uint256 _lockup); // burnable address address public burnable; /** * @dev Smarc constructor just parametrizes the ERC677 -> MiniMeToken constructor */ constructor() public ERC677( 0x0, // no parent token 0, // no parent token - no snapshot block number "SmarcToken", // Token name 18, // Decimals "SMARC", // Symbol false // Disable transfers for time of minting ) {} uint256 public constant maxSupply = 150 * 1000 * 1000 * 10**uint256(decimals); // use the smallest denomination unit to operate with token amounts /** * @notice Sets the locks of an array of addresses. * @dev Must be called while minting (enableTransfers = false). Sizes of `_holder` and `_lockups` must be the same. * @param _holders The array of investor addresses * @param _lockups The array of timestamps until which corresponding address must be locked */ function setLocks(address[] _holders, uint256[] _lockups) public onlyController { require(_holders.length == _lockups.length); require(_holders.length < 256); require(transfersEnabled == false); for (uint8 i = 0; i < _holders.length; i++) { address holder = _holders[i]; uint256 lockup = _lockups[i]; // make sure lockup period can not be overwritten once set require(lockups[holder] == 0); lockups[holder] = lockup; emit LockedTokens(holder, lockup); } } /** * @notice Finishes minting process and throws out the controller. * @dev Owner can not finish minting without setting up address for burning tokens. * @param _burnable The address to burn tokens from */ function finishMinting(address _burnable) public onlyController() { require(_burnable != address(0x0)); // burnable address must be set assert(totalSupply() <= maxSupply); // ensure hard cap enableTransfers(true); // turn-on transfers changeController(address(0x0)); // ensure no new tokens will be created burnable = _burnable; // set burnable address } modifier notLocked(address _addr) { require(now >= lockups[_addr]); _; } /** * @notice Send `_amount` tokens to `_to` from `msg.sender` * @dev We override transfer function to add lockup check * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return Whether the transfer was successful or not */ function transfer(address _to, uint256 _amount) public notLocked(msg.sender) returns (bool success) { return super.transfer(_to, _amount); } /** * @notice Send `_amount` tokens to `_to` from `_from` on the condition it is approved by `_from` * @dev We override transfer function to add lockup check * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(address _from, address _to, uint256 _amount) public notLocked(_from) returns (bool success) { return super.transferFrom(_from, _to, _amount); } /** * @notice Burns `_amount` tokens from pre-defined "burnable" address. * @param _amount The amount of tokens to burn * @return True if the tokens are burned correctly */ function burn(uint256 _amount) public onlyOwner returns (bool) { require(burnable != address(0x0)); // burnable address must be set uint256 currTotalSupply = totalSupply(); uint256 previousBalance = balanceOf(burnable); require(currTotalSupply >= _amount); require(previousBalance >= _amount); updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount); updateValueAtNow(balances[burnable], previousBalance - _amount); emit Transfer(burnable, 0, _amount); return true; } }
burn
function burn(uint256 _amount) public onlyOwner returns (bool) { require(burnable != address(0x0)); // burnable address must be set uint256 currTotalSupply = totalSupply(); uint256 previousBalance = balanceOf(burnable); require(currTotalSupply >= _amount); require(previousBalance >= _amount); updateValueAtNow(totalSupplyHistory, currTotalSupply - _amount); updateValueAtNow(balances[burnable], previousBalance - _amount); emit Transfer(burnable, 0, _amount); return true; }
/** * @notice Burns `_amount` tokens from pre-defined "burnable" address. * @param _amount The amount of tokens to burn * @return True if the tokens are burned correctly */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://bc5b66ddafec8d21bbbed131eef8898516da669ea8eb0f2115329fd071c2783e
{ "func_code_index": [ 3905, 4489 ] }
3,003
OptionsPool
contracts/TimeLock.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Timelock
contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event VoteCast(address indexed voter, bytes32 indexed txHash, bool support, uint votes); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; CheckToken chk; /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint256 votes; } struct QueuedTransaction { mapping (address => Receipt) receipts; uint256 queuedBlock; uint256 againstVotes; uint256 totalSupply; bool queued; } mapping (bytes32 => QueuedTransaction) public queuedTransactions; constructor(address admin_, uint delay_, address chk_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; chk = CheckToken(chk_); } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); QueuedTransaction storage queuedTx = queuedTransactions[txHash]; queuedTx.queued = true; queuedTx.queuedBlock = block.number; queuedTx.totalSupply = chk.totalSupply(); emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash].queued = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash].queued, "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); QueuedTransaction storage queuedTrans = queuedTransactions[txHash]; if (queuedTrans.againstVotes > 0) { // console.log("against votes: ", queuedTrans.againstVotes); require(queuedTrans.againstVotes.mul(100).div(queuedTrans.totalSupply) < 51, "TimeLock::executeTransaction: Community rejected"); } queuedTrans.queued = false; queuedTrans.queuedBlock = 0; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value: value}(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } function veto(bytes32 txHash) public { // console.logBytes32(txHash); address voter = msg.sender; QueuedTransaction storage queuedTrans = queuedTransactions[txHash]; require(queuedTrans.queued, "TimeLock::veto: tx is not queued"); Receipt storage receipt = queuedTrans.receipts[voter]; require(receipt.hasVoted == false, "TimeLock::veto: voter already voted"); uint256 votes = chk.getPriorVotes(voter, queuedTrans.queuedBlock); // console.log("votes: ", votes, "block: ", queuedTrans.queuedBlock); queuedTrans.againstVotes = queuedTrans.againstVotes.add(votes); receipt.hasVoted = true; receipt.votes = votes; emit VoteCast(voter, txHash, false, votes); } }
// import "hardhat/console.sol";
LineComment
// XXX: function() external payable { }
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 2019, 2053 ] }
3,004
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
add
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); }
// Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 2629, 3133 ] }
3,005
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
set
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; }
// Update the given pool's CHK allocation point. Can only be called by the owner.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 3221, 3523 ] }
3,006
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
pendingChk
function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); }
// View function to see pending CHKs on frontend.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 3724, 5011 ] }
3,007
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
massUpdatePools
function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } }
// Update reward variables for all pools. Be careful of gas spending!
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 5087, 5266 ] }
3,008
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
updatePool
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; }
// Update reward variables of the given pool to be up-to-date.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 5335, 6098 ] }
3,009
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
deposit
function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
// Deposit LP tokens to MasterChef for Chk allocation.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 6159, 7139 ] }
3,010
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
withdraw
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); }
// Withdraw LP tokens from MasterChef.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 7184, 7910 ] }
3,011
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
emergencyWithdraw
function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
// Withdraw without caring about rewards. EMERGENCY ONLY.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 7974, 8327 ] }
3,012
OptionsPool
contracts/rewards/Queen.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
Queen
contract Queen is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of CHKs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accChkPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accChkPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. CHKs to distribute per block. uint256 lastRewardBlock; // Last block number that CHKs distribution occurs. uint256 accChkPerShare; // Accumulated CHKs per share, times 1e18. See below. } // The CHK TOKEN! CheckToken public chk; // The block number when CHK mining starts. uint256 public startBlock; uint256 public endBlock; // CHK tokens created per block. uint256 public chkPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _chk, uint256 _chkPerBlock, uint256 _startBlock, uint256 _endBlock ) public { chk = CheckToken(_chk); chkPerBlock = _chkPerBlock; startBlock = _startBlock; endBlock = _endBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accChkPerShare: 0 })); } // Update the given pool's CHK allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return Math.min(_to, endBlock).sub(_from); } // View function to see pending CHKs on frontend. function pendingChk(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accChkPerShare = pool.accChkPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); // console.log("lpSupply: ", lpSupply); // console.log("pool.lastRewardBlock: ", pool.lastRewardBlock); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); // console.log("multiplier: ", multiplier ); // console.log("chkPerBlock: ", chkPerBlock); // console.log("pool.allocPoint: ", pool.allocPoint); // console.log("totalAlloc: ", totalAllocPoint); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // console.log("accChkPerShare: ", accChkPerShare); // console.log("chkReward: ", chkReward); accChkPerShare = accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); // console.log("accChkPerShare: ", accChkPerShare); } return user.amount.mul(accChkPerShare).div(1e18).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 chkReward = multiplier.mul(chkPerBlock.mul(pool.allocPoint).div(totalAllocPoint)); // chk.mint(devaddr, chkReward.div(10)); chk.mint(address(this), chkReward); pool.accChkPerShare = pool.accChkPerShare.add(chkReward.mul(1e18).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Chk allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); // console.log("user.amount: ", user.amount); if (user.amount > 0) { // console.log("pool.accChkPerShare: ", pool.accChkPerShare); // console.log("userRewardDebt: ", user.rewardDebt); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); // console.log("pending: ", pending); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accChkPerShare).div(1e18).sub(user.rewardDebt); if(pending > 0) { chkSafeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accChkPerShare).div(1e18); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs. function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } } }
/** Queen is Masterchef but without the migrate, without the dev addr without the multiplier. But adds in an end block. to minting. */
NatSpecMultiLine
chkSafeTransfer
function chkSafeTransfer(address _to, uint256 _amount) internal { uint256 chkBal = chk.balanceOf(address(this)); // console.log("bal: ", chkBal); if (_amount > chkBal) { chk.transfer(_to, chkBal); } else { chk.transfer(_to, _amount); } }
// Safe chk transfer function, just in case if rounding error causes pool to not have enough CHKs.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 8432, 8741 ] }
3,013
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() internal { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() internal { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 257, 319 ] }
3,014
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
Ownable
contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() internal { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 642, 818 ] }
3,015
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
pause
function pause() onlyOwner whenNotPaused public { paused = true; Pause(); }
/** * @dev called by the owner to pause, triggers stopped state */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 513, 604 ] }
3,016
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
Pausable
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } }
/** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */
NatSpecMultiLine
unpause
function unpause() onlyOwner whenPaused public { paused = false; Unpause(); }
/** * @dev called by the owner to unpause, returns to normal state */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 688, 781 ] }
3,017
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0x0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0x0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 268, 615 ] }
3,018
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0x0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 821, 937 ] }
3,019
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken, Pausable { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0x0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant whenNotPaused returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0x0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 402, 967 ] }
3,020
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
JubsICO
contract JubsICO is StandardToken { using SafeMath for uint256; //Information coin string public name = "Honor"; string public symbol = "HNR"; uint256 public decimals = 18; uint256 public totalSupply = 100000000 * (10 ** decimals); //100 000 000 HNR //Adress informated in white paper address public walletETH; //Wallet ETH address public icoWallet; //63% address public preIcoWallet; //7% address public teamWallet; //10% address public bountyMktWallet; //7% address public arbitrationWallet; //5% address public rewardsWallet; //5% address public advisorsWallet; //2% address public operationWallet; //1% //Utils ICO uint256 public icoStage = 0; uint256 public tokensSold = 0; // total number of tokens sold uint256 public totalRaised = 0; // total amount of money raised in wei uint256 public totalTokenToSale = 0; uint256 public rate = 8500; // HNR/ETH rate / initial 50% bool public pauseEmergence = false; //the owner address can set this to true to halt the crowdsale due to emergency //Time Start and Time end //Stage pre sale uint256 public icoStartTimestampStage = 1515974400; //15/01/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage = 1518998399; //18/02/2018 @ 11:59pm (UTC) //Stage 1 //25% uint256 public icoStartTimestampStage1 = 1518998400; //19/02/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage1 = 1519603199; //25/02/2018 @ 11:59pm (UTC) //Stage 2 //20% uint256 public icoStartTimestampStage2 = 1519603200; //26/02/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage2 = 1520207999; //04/03/2018 @ 11:59pm (UTC) //Stage 3 //15% uint256 public icoStartTimestampStage3 = 1520208000; //05/03/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage3 = 1520812799; //11/03/2018 @ 11:59pm (UTC) //Stage 4 //10% uint256 public icoStartTimestampStage4 = 1520812800; //12/03/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage4 = 1521417599; //18/03/2018 @ 11:59pm (UTC) //end of the waiting time for the team to withdraw uint256 public teamEndTimestamp = 1579046400; //01/15/2020 @ 12:00am (UTC) // =================================== Events ================================================ event Burn(address indexed burner, uint256 value); // =================================== Constructor ============================================= function JubsICO ()public { //Address walletETH = 0x6eA3ec9339839924a520ff57a0B44211450A8910; icoWallet = 0x357ace6312BF8B519424cD3FfdBB9990634B8d3E; preIcoWallet = 0x7c54dC4F3328197AC89a53d4b8cDbE35a56656f7; teamWallet = 0x06BC5305016E9972F4cB3F6a3Ef2C734D417788a; bountyMktWallet = 0x6f67b977859deE77fE85cBCAD5b5bd5aD58bF068; arbitrationWallet = 0xdE9DE3267Cbd21cd64B40516fD2Aaeb5D77fb001; rewardsWallet = 0x232f7CaA500DCAd6598cAE4D90548a009dd49e6f; advisorsWallet = 0xA6B898B2Ab02C277Ae7242b244FB5FD55cAfB2B7; operationWallet = 0x96819778cC853488D3e37D630d94A337aBd527A8; //Distribution Token balances[icoWallet] = totalSupply.mul(63).div(100); //totalSupply * 63% balances[preIcoWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[teamWallet] = totalSupply.mul(10).div(100); //totalSupply * 10% balances[bountyMktWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[arbitrationWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[rewardsWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[advisorsWallet] = totalSupply.mul(2).div(100); //totalSupply * 2% balances[operationWallet] = totalSupply.mul(1).div(100); //totalSupply * 1% //set pause pause(); //set token to sale totalTokenToSale = balances[icoWallet].add(balances[preIcoWallet]); } // ======================================== Modifier ================================================== modifier acceptsFunds() { if (icoStage == 0) { require(msg.value >= 1 ether); require(now >= icoStartTimestampStage); require(now <= icoEndTimestampStage); } if (icoStage == 1) { require(now >= icoStartTimestampStage1); require(now <= icoEndTimestampStage1); } if (icoStage == 2) { require(now >= icoStartTimestampStage2); require(now <= icoEndTimestampStage2); } if (icoStage == 3) { require(now >= icoStartTimestampStage3); require(now <= icoEndTimestampStage3); } if (icoStage == 4) { require(now >= icoStartTimestampStage4); require(now <= icoEndTimestampStage4); } _; } modifier nonZeroBuy() { require(msg.value > 0); _; } modifier PauseEmergence { require(!pauseEmergence); _; } //========================================== Functions =========================================================================== /// fallback function to buy tokens function () PauseEmergence nonZeroBuy acceptsFunds payable public { uint256 amount = msg.value.mul(rate); assignTokens(msg.sender, amount); totalRaised = totalRaised.add(msg.value); forwardFundsToWallet(); } function forwardFundsToWallet() internal { walletETH.transfer(msg.value); // immediately send Ether to wallet address, propagates exception if execution fails } function assignTokens(address recipient, uint256 amount) internal { if (icoStage == 0) { balances[preIcoWallet] = balances[preIcoWallet].sub(amount); } if (icoStage > 0) { balances[icoWallet] = balances[icoWallet].sub(amount); } balances[recipient] = balances[recipient].add(amount); tokensSold = tokensSold.add(amount); //test token sold, if it was sold more than the total available right total token total if (tokensSold > totalTokenToSale) { uint256 diferenceTotalSale = totalTokenToSale.sub(tokensSold); totalTokenToSale = tokensSold; totalSupply = tokensSold.add(diferenceTotalSale); } Transfer(0x0, recipient, amount); } function manuallyAssignTokens(address recipient, uint256 amount) public onlyOwner { require(tokensSold < totalSupply); assignTokens(recipient, amount); } function setRate(uint256 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } function setIcoStage(uint256 _icoStage) public onlyOwner { require(_icoStage >= 0); require(_icoStage <= 4); icoStage = _icoStage; } function setPauseEmergence() public onlyOwner { pauseEmergence = true; } function setUnPauseEmergence() public onlyOwner { pauseEmergence = false; } function sendTokenTeam(address _to, uint256 amount) public onlyOwner { require(_to != 0x0); //test deadline to request token require(now >= teamEndTimestamp); assignTokens(_to, amount); } function burn(uint256 _value) public whenNotPaused { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
JubsICO
function JubsICO ()public { //Address walletETH = 0x6eA3ec9339839924a520ff57a0B44211450A8910; icoWallet = 0x357ace6312BF8B519424cD3FfdBB9990634B8d3E; preIcoWallet = 0x7c54dC4F3328197AC89a53d4b8cDbE35a56656f7; teamWallet = 0x06BC5305016E9972F4cB3F6a3Ef2C734D417788a; bountyMktWallet = 0x6f67b977859deE77fE85cBCAD5b5bd5aD58bF068; arbitrationWallet = 0xdE9DE3267Cbd21cd64B40516fD2Aaeb5D77fb001; rewardsWallet = 0x232f7CaA500DCAd6598cAE4D90548a009dd49e6f; advisorsWallet = 0xA6B898B2Ab02C277Ae7242b244FB5FD55cAfB2B7; operationWallet = 0x96819778cC853488D3e37D630d94A337aBd527A8; //Distribution Token balances[icoWallet] = totalSupply.mul(63).div(100); //totalSupply * 63% balances[preIcoWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[teamWallet] = totalSupply.mul(10).div(100); //totalSupply * 10% balances[bountyMktWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[arbitrationWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[rewardsWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[advisorsWallet] = totalSupply.mul(2).div(100); //totalSupply * 2% balances[operationWallet] = totalSupply.mul(1).div(100); //totalSupply * 1% //set pause pause(); //set token to sale totalTokenToSale = balances[icoWallet].add(balances[preIcoWallet]); }
// =================================== Constructor =============================================
LineComment
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 3267, 4884 ] }
3,021
JubsICO
JubsICO.sol
0x108116d36907223e13ba244b5bde5893cd5e730b
Solidity
JubsICO
contract JubsICO is StandardToken { using SafeMath for uint256; //Information coin string public name = "Honor"; string public symbol = "HNR"; uint256 public decimals = 18; uint256 public totalSupply = 100000000 * (10 ** decimals); //100 000 000 HNR //Adress informated in white paper address public walletETH; //Wallet ETH address public icoWallet; //63% address public preIcoWallet; //7% address public teamWallet; //10% address public bountyMktWallet; //7% address public arbitrationWallet; //5% address public rewardsWallet; //5% address public advisorsWallet; //2% address public operationWallet; //1% //Utils ICO uint256 public icoStage = 0; uint256 public tokensSold = 0; // total number of tokens sold uint256 public totalRaised = 0; // total amount of money raised in wei uint256 public totalTokenToSale = 0; uint256 public rate = 8500; // HNR/ETH rate / initial 50% bool public pauseEmergence = false; //the owner address can set this to true to halt the crowdsale due to emergency //Time Start and Time end //Stage pre sale uint256 public icoStartTimestampStage = 1515974400; //15/01/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage = 1518998399; //18/02/2018 @ 11:59pm (UTC) //Stage 1 //25% uint256 public icoStartTimestampStage1 = 1518998400; //19/02/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage1 = 1519603199; //25/02/2018 @ 11:59pm (UTC) //Stage 2 //20% uint256 public icoStartTimestampStage2 = 1519603200; //26/02/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage2 = 1520207999; //04/03/2018 @ 11:59pm (UTC) //Stage 3 //15% uint256 public icoStartTimestampStage3 = 1520208000; //05/03/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage3 = 1520812799; //11/03/2018 @ 11:59pm (UTC) //Stage 4 //10% uint256 public icoStartTimestampStage4 = 1520812800; //12/03/2018 @ 00:00am (UTC) uint256 public icoEndTimestampStage4 = 1521417599; //18/03/2018 @ 11:59pm (UTC) //end of the waiting time for the team to withdraw uint256 public teamEndTimestamp = 1579046400; //01/15/2020 @ 12:00am (UTC) // =================================== Events ================================================ event Burn(address indexed burner, uint256 value); // =================================== Constructor ============================================= function JubsICO ()public { //Address walletETH = 0x6eA3ec9339839924a520ff57a0B44211450A8910; icoWallet = 0x357ace6312BF8B519424cD3FfdBB9990634B8d3E; preIcoWallet = 0x7c54dC4F3328197AC89a53d4b8cDbE35a56656f7; teamWallet = 0x06BC5305016E9972F4cB3F6a3Ef2C734D417788a; bountyMktWallet = 0x6f67b977859deE77fE85cBCAD5b5bd5aD58bF068; arbitrationWallet = 0xdE9DE3267Cbd21cd64B40516fD2Aaeb5D77fb001; rewardsWallet = 0x232f7CaA500DCAd6598cAE4D90548a009dd49e6f; advisorsWallet = 0xA6B898B2Ab02C277Ae7242b244FB5FD55cAfB2B7; operationWallet = 0x96819778cC853488D3e37D630d94A337aBd527A8; //Distribution Token balances[icoWallet] = totalSupply.mul(63).div(100); //totalSupply * 63% balances[preIcoWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[teamWallet] = totalSupply.mul(10).div(100); //totalSupply * 10% balances[bountyMktWallet] = totalSupply.mul(7).div(100); //totalSupply * 7% balances[arbitrationWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[rewardsWallet] = totalSupply.mul(5).div(100); //totalSupply * 5% balances[advisorsWallet] = totalSupply.mul(2).div(100); //totalSupply * 2% balances[operationWallet] = totalSupply.mul(1).div(100); //totalSupply * 1% //set pause pause(); //set token to sale totalTokenToSale = balances[icoWallet].add(balances[preIcoWallet]); } // ======================================== Modifier ================================================== modifier acceptsFunds() { if (icoStage == 0) { require(msg.value >= 1 ether); require(now >= icoStartTimestampStage); require(now <= icoEndTimestampStage); } if (icoStage == 1) { require(now >= icoStartTimestampStage1); require(now <= icoEndTimestampStage1); } if (icoStage == 2) { require(now >= icoStartTimestampStage2); require(now <= icoEndTimestampStage2); } if (icoStage == 3) { require(now >= icoStartTimestampStage3); require(now <= icoEndTimestampStage3); } if (icoStage == 4) { require(now >= icoStartTimestampStage4); require(now <= icoEndTimestampStage4); } _; } modifier nonZeroBuy() { require(msg.value > 0); _; } modifier PauseEmergence { require(!pauseEmergence); _; } //========================================== Functions =========================================================================== /// fallback function to buy tokens function () PauseEmergence nonZeroBuy acceptsFunds payable public { uint256 amount = msg.value.mul(rate); assignTokens(msg.sender, amount); totalRaised = totalRaised.add(msg.value); forwardFundsToWallet(); } function forwardFundsToWallet() internal { walletETH.transfer(msg.value); // immediately send Ether to wallet address, propagates exception if execution fails } function assignTokens(address recipient, uint256 amount) internal { if (icoStage == 0) { balances[preIcoWallet] = balances[preIcoWallet].sub(amount); } if (icoStage > 0) { balances[icoWallet] = balances[icoWallet].sub(amount); } balances[recipient] = balances[recipient].add(amount); tokensSold = tokensSold.add(amount); //test token sold, if it was sold more than the total available right total token total if (tokensSold > totalTokenToSale) { uint256 diferenceTotalSale = totalTokenToSale.sub(tokensSold); totalTokenToSale = tokensSold; totalSupply = tokensSold.add(diferenceTotalSale); } Transfer(0x0, recipient, amount); } function manuallyAssignTokens(address recipient, uint256 amount) public onlyOwner { require(tokensSold < totalSupply); assignTokens(recipient, amount); } function setRate(uint256 _rate) public onlyOwner { require(_rate > 0); rate = _rate; } function setIcoStage(uint256 _icoStage) public onlyOwner { require(_icoStage >= 0); require(_icoStage <= 4); icoStage = _icoStage; } function setPauseEmergence() public onlyOwner { pauseEmergence = true; } function setUnPauseEmergence() public onlyOwner { pauseEmergence = false; } function sendTokenTeam(address _to, uint256 amount) public onlyOwner { require(_to != 0x0); //test deadline to request token require(now >= teamEndTimestamp); assignTokens(_to, amount); } function burn(uint256 _value) public whenNotPaused { require(_value > 0); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } }
function () PauseEmergence nonZeroBuy acceptsFunds payable public { uint256 amount = msg.value.mul(rate); assignTokens(msg.sender, amount); totalRaised = totalRaised.add(msg.value); forwardFundsToWallet(); }
/// fallback function to buy tokens
NatSpecSingleLine
v0.4.19+commit.c4cbbb05
bzzr://9d90d728973c5a4ea720eb7ae7fafc49fe5cfc954a98e65af75fd6c7761d0423
{ "func_code_index": [ 6317, 6577 ] }
3,022
IiinoCoin
contracts/BasicToken.sol
0x48c71990d24f18a441b881e13983e4621fcd812f
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferInternal(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
totalSupply
function totalSupply() public view returns (uint256) { return totalSupply_; }
/** * @dev total number of tokens in existence */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://6743e49142cb6d45b5afd276952c40d63d4477401d2a03306bb949f6d6477ef6
{ "func_code_index": [ 205, 301 ] }
3,023
IiinoCoin
contracts/BasicToken.sol
0x48c71990d24f18a441b881e13983e4621fcd812f
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferInternal(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transferInternal
function transferInternal(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://6743e49142cb6d45b5afd276952c40d63d4477401d2a03306bb949f6d6477ef6
{ "func_code_index": [ 459, 897 ] }
3,024
IiinoCoin
contracts/BasicToken.sol
0x48c71990d24f18a441b881e13983e4621fcd812f
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transferInternal(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://6743e49142cb6d45b5afd276952c40d63d4477401d2a03306bb949f6d6477ef6
{ "func_code_index": [ 1103, 1223 ] }
3,025
IiinoCoin
contracts/MintableToken.sol
0x48c71990d24f18a441b881e13983e4621fcd812f
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; address public icoContractAddress; modifier canMint() { require(!mintingFinished); _; } /** * @dev Throws if called by any account other than the icoContract. */ modifier onlyIcoContract() { require(msg.sender == icoContractAddress); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyIcoContract canMint external returns (bool) { //return true; totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint external returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
mint
function mint(address _to, uint256 _amount) onlyIcoContract canMint external returns (bool) { //return true; totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; }
/** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://6743e49142cb6d45b5afd276952c40d63d4477401d2a03306bb949f6d6477ef6
{ "func_code_index": [ 744, 1083 ] }
3,026
IiinoCoin
contracts/MintableToken.sol
0x48c71990d24f18a441b881e13983e4621fcd812f
Solidity
MintableToken
contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; address public icoContractAddress; modifier canMint() { require(!mintingFinished); _; } /** * @dev Throws if called by any account other than the icoContract. */ modifier onlyIcoContract() { require(msg.sender == icoContractAddress); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyIcoContract canMint external returns (bool) { //return true; totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint external returns (bool) { mintingFinished = true; emit MintFinished(); return true; } }
/** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */
NatSpecMultiLine
finishMinting
function finishMinting() onlyOwner canMint external returns (bool) { mintingFinished = true; emit MintFinished(); return true; }
/** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */
NatSpecMultiLine
v0.4.21+commit.dfe3193c
bzzr://6743e49142cb6d45b5afd276952c40d63d4477401d2a03306bb949f6d6477ef6
{ "func_code_index": [ 1208, 1373 ] }
3,027
Ping
Ping.sol
0x86b1431988ce038589d96fb462e5c96d3b482ae0
Solidity
Ping
contract Ping is ReserveRetriever { int8 ZZZinLP; ReserveRetriever ZZZETH; /********* Step 2: Deploy Ping, giving it the address of Pong. *********/ constructor (ReserveRetriever _ZZZETHAddress) { ZZZinLP = -1; ZZZETH = _ZZZETHAddress; } /********* Step 3: Transactionally retrieve pongval from Pong. *********/ function getZZZinPool() { (reserve0, reserve1, blockTimestampLast) = ZZZETH.getReserves(); } /********* Step 5: Get pongval (which was previously retrieved from Pong via transaction) *********/ function getPongvalConstant() constant returns (uint112) { return reserve0; } // ----------------------------------------------------------------------------------------------------------------- /********* Functions to get and set pongAddress just in case *********/ function setZZZETHAddress(ReserveRetriever _ZZZETHAddress) { ZZZETH = _ZZZETHAddress; } function getPongAddress() constant returns (address) { return ZZZETH; } }
getZZZinPool
function getZZZinPool() { (reserve0, reserve1, blockTimestampLast) = ZZZETH.getReserves(); }
/********* Step 3: Transactionally retrieve pongval from Pong. *********/
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://f462742911980ea6e17f2dc465c75b94480d9ad20495f192d9401a15a542e535
{ "func_code_index": [ 394, 496 ] }
3,028
Ping
Ping.sol
0x86b1431988ce038589d96fb462e5c96d3b482ae0
Solidity
Ping
contract Ping is ReserveRetriever { int8 ZZZinLP; ReserveRetriever ZZZETH; /********* Step 2: Deploy Ping, giving it the address of Pong. *********/ constructor (ReserveRetriever _ZZZETHAddress) { ZZZinLP = -1; ZZZETH = _ZZZETHAddress; } /********* Step 3: Transactionally retrieve pongval from Pong. *********/ function getZZZinPool() { (reserve0, reserve1, blockTimestampLast) = ZZZETH.getReserves(); } /********* Step 5: Get pongval (which was previously retrieved from Pong via transaction) *********/ function getPongvalConstant() constant returns (uint112) { return reserve0; } // ----------------------------------------------------------------------------------------------------------------- /********* Functions to get and set pongAddress just in case *********/ function setZZZETHAddress(ReserveRetriever _ZZZETHAddress) { ZZZETH = _ZZZETHAddress; } function getPongAddress() constant returns (address) { return ZZZETH; } }
getPongvalConstant
function getPongvalConstant() constant returns (uint112) { return reserve0; }
/********* Step 5: Get pongval (which was previously retrieved from Pong via transaction) *********/
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://f462742911980ea6e17f2dc465c75b94480d9ad20495f192d9401a15a542e535
{ "func_code_index": [ 622, 720 ] }
3,029
Ping
Ping.sol
0x86b1431988ce038589d96fb462e5c96d3b482ae0
Solidity
Ping
contract Ping is ReserveRetriever { int8 ZZZinLP; ReserveRetriever ZZZETH; /********* Step 2: Deploy Ping, giving it the address of Pong. *********/ constructor (ReserveRetriever _ZZZETHAddress) { ZZZinLP = -1; ZZZETH = _ZZZETHAddress; } /********* Step 3: Transactionally retrieve pongval from Pong. *********/ function getZZZinPool() { (reserve0, reserve1, blockTimestampLast) = ZZZETH.getReserves(); } /********* Step 5: Get pongval (which was previously retrieved from Pong via transaction) *********/ function getPongvalConstant() constant returns (uint112) { return reserve0; } // ----------------------------------------------------------------------------------------------------------------- /********* Functions to get and set pongAddress just in case *********/ function setZZZETHAddress(ReserveRetriever _ZZZETHAddress) { ZZZETH = _ZZZETHAddress; } function getPongAddress() constant returns (address) { return ZZZETH; } }
setZZZETHAddress
function setZZZETHAddress(ReserveRetriever _ZZZETHAddress) ZETH = _ZZZETHAddress;
/********* Functions to get and set pongAddress just in case *********/
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://f462742911980ea6e17f2dc465c75b94480d9ad20495f192d9401a15a542e535
{ "func_code_index": [ 942, 1041 ] }
3,030
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
svb
function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; }
// if supply provided is 0, then default assigned
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 1766, 2082 ] }
3,031
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
chargeDemurringFee
function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } }
// charge demurring fee for previuos period // fee is not applied to owners
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 2489, 3234 ] }
3,032
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
chargeTransferFee
function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; }
// fee is not applied to owners
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 3274, 3953 ] }
3,033
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
issue
function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } }
// issue new coins
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 7176, 7368 ] }
3,034
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
destroy
function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; }
// destroy existing coins
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 7402, 7584 ] }
3,035
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
kill
function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); }
// kill contract only if all wallets are empty
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 7639, 7745 ] }
3,036
svb
svb.sol
0x0fcf5c6b20577d48ba209e077975b9f2eac55798
Solidity
svb
contract svb { // totalSupply is zero by default, owner can issue and destroy coins any amount any time uint constant totalSupplyDefault = 0; string public constant symbol = "SVB"; string public constant name = "Silver"; uint8 public constant decimals = 5; // minimum fee is 0.00001 uint32 public constant minFee = 1; uint32 public constant minTransfer = 10; uint public totalSupply = 0; // transfer fee default = 0.17% (0.0017) uint32 public transferFeeNum = 17; uint32 public transferFeeDenum = 10000; // demurring fee default = 0,7 % per year // 0.007 per year = 0.007 / 365 per day = 0.000019178 per day // 0.000019178 / (24*60) per minute = 0.000000013 per minute uint32 public demurringFeeNum = 13; uint32 public demurringFeeDenum = 1000000000; // Owner of this contract address public owner; modifier onlyOwner() { if (msg.sender != owner) { revert(); } _; } address public demurringFeeOwner; address public transferFeeOwner; // Balances for each account mapping(address => uint) balances; // demurring fee deposit payed date for each account mapping(address => uint64) timestamps; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from , address indexed to , uint256 value); event DemurringFee(address indexed to , uint256 value); event TransferFee(address indexed to , uint256 value); // if supply provided is 0, then default assigned function svb(uint supply) { if (supply > 0) { totalSupply = supply; } else { totalSupply = totalSupplyDefault; } owner = msg.sender; demurringFeeOwner = owner; transferFeeOwner = owner; balances[this] = totalSupply; } function changeDemurringFeeOwner(address addr) onlyOwner { demurringFeeOwner = addr; } function changeTransferFeeOwner(address addr) onlyOwner { transferFeeOwner = addr; } function balanceOf(address addr) constant returns (uint) { return balances[addr]; } // charge demurring fee for previuos period // fee is not applied to owners function chargeDemurringFee(address addr) internal { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0 && now > timestamps[addr] + 60) { var mins = (now - timestamps[addr]) / 60; var fee = balances[addr] * mins * demurringFeeNum / demurringFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } balances[addr] -= fee; balances[demurringFeeOwner] += fee; Transfer(addr, demurringFeeOwner, fee); DemurringFee(addr, fee); timestamps[addr] = uint64(now); } } // fee is not applied to owners function chargeTransferFee(address addr, uint amount) internal returns (uint) { if (addr != owner && addr != transferFeeOwner && addr != demurringFeeOwner && balances[addr] > 0) { var fee = amount * transferFeeNum / transferFeeDenum; if (fee < minFee) { fee = minFee; } else if (fee > balances[addr]) { fee = balances[addr]; } amount = amount - fee; balances[addr] -= fee; balances[transferFeeOwner] += fee; Transfer(addr, transferFeeOwner, fee); TransferFee(addr, fee); } return amount; } function transfer(address to, uint amount) returns (bool) { if (amount >= minTransfer && balances[msg.sender] >= amount && balances[to] + amount > balances[to] ) { chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function transferFrom(address from, address to, uint amount) returns (bool) { if ( amount >= minTransfer && allowed[from][msg.sender] >= amount && balances[from] >= amount && balances[to] + amount > balances[to] ) { allowed[from][msg.sender] -= amount; chargeDemurringFee(msg.sender); if (balances[msg.sender] >= amount) { amount = chargeTransferFee(msg.sender, amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[msg.sender] -= amount; balances[to] += amount; Transfer(msg.sender, to, amount); } return true; } else { return false; } } function approve(address spender, uint amount) returns (bool) { allowed[msg.sender][spender] = amount; Approval(msg.sender, spender, amount); return true; } function allowance(address addr, address spender) constant returns (uint) { return allowed[addr][spender]; } function setTransferFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); transferFeeNum = numinator; transferFeeDenum = denuminator; } function setDemurringFee(uint32 numinator, uint32 denuminator) onlyOwner { require(denuminator > 0 && numinator < denuminator); demurringFeeNum = numinator; demurringFeeDenum = denuminator; } function sell(address to, uint amount) onlyOwner { require(amount > minTransfer && balances[this] >= amount); // charge recepient with demurring fee if (balances[to] > 0) { chargeDemurringFee(to); } else { timestamps[to] = uint64(now); } balances[this] -= amount; balances[to] += amount; Transfer(this, to, amount); } // issue new coins function issue(uint amount) onlyOwner { if (totalSupply + amount > totalSupply) { totalSupply += amount; balances[this] += amount; } } // destroy existing coins function destroy(uint amount) onlyOwner { require(amount>0 && balances[this] >= amount); balances[this] -= amount; totalSupply -= amount; } // kill contract only if all wallets are empty function kill() onlyOwner { require (totalSupply == 0); selfdestruct(owner); } // payments ar reverted back function () payable { revert(); } }
//contract svb is svb_ {
LineComment
function () payable { revert(); }
// payments ar reverted back
LineComment
v0.4.15+commit.bbb8e64f
bzzr://0478f2575bea87511e4ddc553e292146a9d87bb776cafd843d185838d1e66766
{ "func_code_index": [ 7782, 7834 ] }
3,037
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
transfer
function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 268, 507 ] }
3,038
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } }
/** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */
NatSpecMultiLine
balanceOf
function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 714, 823 ] }
3,039
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
transferFrom
function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 392, 895 ] }
3,040
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
approve
function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 1131, 1314 ] }
3,041
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
allowance
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
/** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 1638, 1776 ] }
3,042
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
/** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */
NatSpecMultiLine
increaseApproval
function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
/* * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */
Comment
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 2025, 2297 ] }
3,043
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
ERC677Token
contract ERC677Token is ERC677 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public returns (bool success) { super.transfer(_to, _value); Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } // PRIVATE function contractFallback(address _to, uint _value, bytes _data) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private returns (bool hasCode) { uint length; assembly { length := extcodesize(_addr) } return length > 0; } }
transferAndCall
function transferAndCall(address _to, uint _value, bytes _data) public returns (bool success) { super.transfer(_to, _value); Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; }
/** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 314, 609 ] }
3,044
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
ERC677Token
contract ERC677Token is ERC677 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public returns (bool success) { super.transfer(_to, _value); Transfer(msg.sender, _to, _value, _data); if (isContract(_to)) { contractFallback(_to, _value, _data); } return true; } // PRIVATE function contractFallback(address _to, uint _value, bytes _data) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); } function isContract(address _addr) private returns (bool hasCode) { uint length; assembly { length := extcodesize(_addr) } return length > 0; } }
contractFallback
function contractFallback(address _to, uint _value, bytes _data) private { ERC677Receiver receiver = ERC677Receiver(_to); receiver.onTokenTransfer(msg.sender, _value, _data); }
// PRIVATE
LineComment
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 630, 830 ] }
3,045
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
GYBToken
contract GYBToken is StandardToken, ERC677Token { uint public constant totalSupply = 2100000000000000000000000000; string public constant name = 'GYB'; uint8 public constant decimals = 18; string public constant symbol = 'GYB'; function GYBToken() public { balances[msg.sender] = totalSupply; } /** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); } /** * @dev transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } // MODIFIERS modifier validRecipient(address _recipient) { require(_recipient != address(0) && _recipient != address(this)); _; } }
transferAndCall
function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); }
/** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 613, 809 ] }
3,046
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
GYBToken
contract GYBToken is StandardToken, ERC677Token { uint public constant totalSupply = 2100000000000000000000000000; string public constant name = 'GYB'; uint8 public constant decimals = 18; string public constant symbol = 'GYB'; function GYBToken() public { balances[msg.sender] = totalSupply; } /** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); } /** * @dev transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } // MODIFIERS modifier validRecipient(address _recipient) { require(_recipient != address(0) && _recipient != address(this)); _; } }
transfer
function transfer(address _to, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); }
/** * @dev transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 967, 1129 ] }
3,047
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
GYBToken
contract GYBToken is StandardToken, ERC677Token { uint public constant totalSupply = 2100000000000000000000000000; string public constant name = 'GYB'; uint8 public constant decimals = 18; string public constant symbol = 'GYB'; function GYBToken() public { balances[msg.sender] = totalSupply; } /** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); } /** * @dev transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } // MODIFIERS modifier validRecipient(address _recipient) { require(_recipient != address(0) && _recipient != address(this)); _; } }
approve
function approve(address _spender, uint256 _value) public validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 1365, 1536 ] }
3,048
GYBToken
GYBToken.sol
0x8a5c9d88c03a9722be267614b0c0004acc43ff21
Solidity
GYBToken
contract GYBToken is StandardToken, ERC677Token { uint public constant totalSupply = 2100000000000000000000000000; string public constant name = 'GYB'; uint8 public constant decimals = 18; string public constant symbol = 'GYB'; function GYBToken() public { balances[msg.sender] = totalSupply; } /** * @dev transfer token to a specified address with additional data if the recipient is a contract. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall(address _to, uint _value, bytes _data) public validRecipient(_to) returns (bool success) { return super.transferAndCall(_to, _value, _data); } /** * @dev transfer token to a specified address. * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public validRecipient(_to) returns (bool success) { return super.transfer(_to, _value); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public validRecipient(_spender) returns (bool) { return super.approve(_spender, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } // MODIFIERS modifier validRecipient(address _recipient) { require(_recipient != address(0) && _recipient != address(this)); _; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public validRecipient(_to) returns (bool) { return super.transferFrom(_from, _to, _value); }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.19+commit.c4cbbb05
None
bzzr://1532c37a9c54cfc4fc7961ddd20a4299bd0367e269513036df92d55963c80f3f
{ "func_code_index": [ 1816, 2003 ] }
3,049
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
rebase
function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; }
/** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 3024, 4397 ] }
3,050
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
name
function name() public view override returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 6370, 6464 ] }
3,051
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
symbol
function symbol() public view override returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 6660, 6758 ] }
3,052
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
decimals
function decimals() public view override returns (uint8) { return _decimals; }
/** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 7377, 7471 ] }
3,053
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
totalSupply
function totalSupply() public view override returns (uint256) { return _totalSupply; }
/** * @return The total number of fragments. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 7535, 7673 ] }
3,054
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
balanceOf
function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); }
/** * @param who The address to query. * @return The balance of the specified address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 7784, 7977 ] }
3,055
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
transfer
function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; }
/** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 8191, 8767 ] }
3,056
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
allowance
function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; }
/** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 9062, 9251 ] }
3,057
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
transferFrom
function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); }
/** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 9501, 9828 ] }
3,058
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
approve
function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
/** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 10889, 11136 ] }
3,059
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; }
/** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 11496, 11835 ] }
3,060
OptionsPool
contracts/RebaseableToken.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
RebaseableToken
contract RebaseableToken is IERC20Nameable, Ownable { // PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH // Anytime there is division, there is a risk of numerical instability from rounding errors. In // order to minimize this risk, we adhere to the following guidelines: // 1) The conversion rate adopted is the number of gons that equals 1 fragment. // The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is // always the denominator. (i.e. If you want to convert gons to fragments instead of // multiplying by the inverse rate, you should divide by the normal rate) // 2) Gon balances converted into Fragments are always rounded down (truncated). // // We make the following guarantees: // - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will // be decreased by precisely x Fragments, and B's external balance will be precisely // increased by x Fragments. // // We do not guarantee that the sum of all balances equals the result of calling totalSupply(). // This is because, for any conversion function 'f()' that has non-zero rounding error, // f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn). using SafeMath for uint256; using SafeMathInt for int256; event LogRebase(uint256 indexed epoch, uint256 totalSupply); modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); require(settledAt[to] == 0); _; } modifier notSettling(address addr) { require(settledAt[addr] == 0); _; } string private _name; string private _symbol; uint8 private _decimals = 18; uint256 private constant MAX_UINT256 = ~uint256(0); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 private _totalGons; uint256 public _gonsPerFragment = 10**24; // when _totalSupply goes to zero we reset all balances to zero (ignoring old balances) // this is an optimization as otherwise the _gonsPerFragment gets out of hand // and we have multiplication overflow errors on deposit. mapping(uint256 => mapping(address => uint256)) private _gonBalances; uint256 private _currentBalances = 0; uint256 public epoch = 1; // This is denominated in Fragments, because the gons-fragments conversion might change before // it's fully paid. mapping (address => mapping (address => uint256)) private _allowedFragments; // When the users account was locked for a settlement // this is the epoch + 1 to handle the epoch 0 case. mapping (address => uint256) public settledAt; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch_, int256 supplyDelta) external onlyOwner returns (uint256) { // console.log(symbol(), ": starting total supply ", epoch, _totalSupply.div(10**18)); // console.log("gonsPerFragment: ", epoch, _gonsPerFragment); epoch = epoch_; if (supplyDelta == 0) { emit LogRebase(epoch, _totalSupply); return _totalSupply; } if (supplyDelta < 0) { // console.log(symbol(), ": supply delta / _totalSupply -", uint256(supplyDelta.abs()), _totalSupply); _totalSupply = _totalSupply.sub(uint256(supplyDelta.abs())); } else { // console.log(symbol(), ": supply delta +", uint256(supplyDelta.abs())); _totalSupply = _totalSupply.add(uint256(supplyDelta)); } if (_totalSupply > MAX_SUPPLY) { _totalSupply = MAX_SUPPLY; } if (_totalSupply > 0) { _gonsPerFragment = _totalGons.div(_totalSupply); if (_gonsPerFragment == 0) { _gonsPerFragment = 10**24; //TODO: is this right? } } else if (_totalGons > 0) { _currentBalances++; _gonsPerFragment = 10**24; _totalGons = 0; } emit LogRebase(epoch, _totalSupply); return _totalSupply; } function mint(address who, uint256 value) public onlyOwner notSettling(who) returns (bool) { _totalSupply = _totalSupply.add(value); uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][who] = _gonBalances[_currentBalances][who].add(gonValue); _totalGons = _totalGons.add(gonValue); return true; } function liquidate(address who) public onlyOwner returns (bool) { // console.log("settling", epoch, settledAt[who]); require(epoch > settledAt[who]); uint256 gonValue = _gonBalances[_currentBalances][who]; _gonBalances[_currentBalances][who] = 0; uint256 bal = gonValue.div(_gonsPerFragment); // console.log(symbol(), "burn", who); // console.log("-", bal, gonValue, _totalSupply); _totalGons = _totalGons.sub(gonValue); if (_totalSupply > bal) { _totalSupply = _totalSupply.sub(bal); } else { _totalSupply = 0; } delete settledAt[who]; return true; } function settle(address who) public onlyOwner notSettling(who) returns (bool) { // console.log(symbol(), "settling: ", who); settledAt[who] = epoch; return true; } function initialize(string memory name, string memory symbol, address operator_) onlyOwner public { setName(name); setSymbol(symbol); uint256 balance = _gonBalances[_currentBalances][owner()]; _gonBalances[_currentBalances][owner()] = 0; _gonBalances[_currentBalances][operator_] = _gonBalances[_currentBalances][operator_].add(balance); transferOwnership(operator_); } constructor() Ownable() public { _totalSupply = 0; } function setName(string memory name) public { _name = name; } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } function setSymbol(string memory symbol) public { _symbol = symbol; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view override returns (uint8) { return _decimals; } /** * @return The total number of fragments. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) public view override returns (uint256) { return _gonBalances[_currentBalances][who].div(_gonsPerFragment); } /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) public override validRecipient(to) returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][msg.sender] = _gonBalances[_currentBalances][msg.sender].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(msg.sender, to, value); // console.log("transfer", symbol(), msg.sender); // console.log(to, value.div(10**18)); return true; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) public view override returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) public validRecipient(to) notSettling(from) override returns (bool) { _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); return _transferFrom(from, to, value); } function _transferFrom(address from, address to, uint256 value) private returns (bool) { uint256 gonValue = value.mul(_gonsPerFragment); _gonBalances[_currentBalances][from] = _gonBalances[_currentBalances][from].sub(gonValue); _gonBalances[_currentBalances][to] = _gonBalances[_currentBalances][to].add(gonValue); emit Transfer(from, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } }
/** * @title uFragments ERC20 token * @dev This is part of an implementation of the uFragments Ideal Money protocol. * uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and * combining tokens proportionally across all wallets. * * uFragment balances are internally represented with a hidden denomination, 'gons'. * We support splitting the currency in expansion and combining the currency on contraction by * changing the exchange rate between the hidden 'gons' and the public 'fragments'. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; }
/** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 12085, 12589 ] }
3,061
ZNCoin
ZNCoin.sol
0x7aeace15f7d9a8e0ae3a1418d8360c6f41927552
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
Ownable
function Ownable() { owner = msg.sender; }
/** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */
NatSpecMultiLine
v0.4.13+commit.fb4cb1a
bzzr://f14ccdcc204b1692d159a19f1dedc5a5ef0500237a1c0db4cadb988a96a4adfb
{ "func_code_index": [ 179, 240 ] }
3,062
ZNCoin
ZNCoin.sol
0x7aeace15f7d9a8e0ae3a1418d8360c6f41927552
Solidity
Ownable
contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; } }
/** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */
NatSpecMultiLine
transferOwnership
function transferOwnership(address newOwner) onlyOwner { require(newOwner != address(0)); owner = newOwner; }
/** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */
NatSpecMultiLine
v0.4.13+commit.fb4cb1a
bzzr://f14ccdcc204b1692d159a19f1dedc5a5ef0500237a1c0db4cadb988a96a4adfb
{ "func_code_index": [ 589, 726 ] }
3,063
ZNCoin
ZNCoin.sol
0x7aeace15f7d9a8e0ae3a1418d8360c6f41927552
Solidity
ZNCoin
contract ZNCoin is ERC20,ZNCoinStandard,Ownable { using SafeMath for uint256; string public name = "ZNCoin"; string public symbol = "ZNC"; uint public decimals = 18; uint public chainStartTime; //chain start time uint public chainStartBlockNumber; //chain start block number uint public stakeStartTime; //stake start time uint public stakeMinAge = 1 days; // minimum age for coin age: 1D uint public stakeMaxAge = 365 days; // stake age of full weight: 90D uint public maxMintProofOfStake = 10**17; // default 10% annual interest uint public totalSupply; uint public maxTotalSupply; uint public totalInitialSupply; struct transferInStruct{ uint128 amount; uint64 time; } mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => transferInStruct[]) transferIns; event Burn(address indexed burner, uint256 value); /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier canZNCMint() { require(totalSupply < maxTotalSupply); _; } function ZNCoin() { maxTotalSupply = 21000000000000000000000000000; // 21b. totalInitialSupply = 500000000000000000000000000; // 500m. chainStartTime = now; chainStartBlockNumber = block.number; balances[msg.sender] = totalInitialSupply; totalSupply = totalInitialSupply; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) returns (bool) { if(msg.sender == _to) return mint(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; uint64 _now = uint64(now); transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) returns (bool) { require(_to != address(0)); var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); if(transferIns[_from].length > 0) delete transferIns[_from]; uint64 _now = uint64(now); transferIns[_from].push(transferInStruct(uint128(balances[_from]),_now)); transferIns[_to].push(transferInStruct(uint128(_value),_now)); return true; } function approve(address _spender, uint256 _value) returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function mint() canZNCMint returns (bool) { if(balances[msg.sender] <= 0) return false; if(transferIns[msg.sender].length <= 0) return false; uint reward = getProofOfStakeReward(msg.sender); if(reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now))); Mint(msg.sender, reward); return true; } function getBlockNumber() returns (uint blockNumber) { blockNumber = block.number.sub(chainStartBlockNumber); } function coinAge() constant returns (uint myCoinAge) { myCoinAge = getCoinAge(msg.sender,now); } function annualInterest() constant returns(uint interest) { uint _now = now; interest = maxMintProofOfStake; if((_now.sub(stakeStartTime)).div(1 years) == 0) { interest = (770 * maxMintProofOfStake).div(100); } else if((_now.sub(stakeStartTime)).div(1 years) == 1){ interest = (435 * maxMintProofOfStake).div(100); } } function getProofOfStakeReward(address _address) internal returns (uint) { require( (now >= stakeStartTime) && (stakeStartTime > 0) ); uint _now = now; uint _coinAge = getCoinAge(_address, _now); if(_coinAge <= 0) return 0; uint interest = maxMintProofOfStake; //77% interest first year if((_now.sub(stakeStartTime)).div(1 years) == 0) { interest = (770 * maxMintProofOfStake).div(100); } else if((_now.sub(stakeStartTime)).div(1 years) == 1){ // 2nd year effective annual interest rate is 43.5% interest = (435 * maxMintProofOfStake).div(100); } //10% interest rest return (_coinAge * interest).div(365 * (10**decimals)); } function getCoinAge(address _address, uint _now) internal returns (uint _coinAge) { if(transferIns[_address].length <= 0) return 0; for (uint i = 0; i < transferIns[_address].length; i++){ if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue; uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time)); if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge; _coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days)); } } function ownerSetStakeStartTime(uint timestamp) onlyOwner { require((stakeStartTime <= 0) && (timestamp >= chainStartTime)); stakeStartTime = timestamp; } function ownerBurnToken(uint _value) onlyOwner { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),uint64(now))); totalSupply = totalSupply.sub(_value); totalInitialSupply = totalInitialSupply.sub(_value); maxTotalSupply = maxTotalSupply.sub(_value*10); Burn(msg.sender, _value); } /* Batch token transfer. Used by contract creator to distribute initial tokens to holders */ function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now)); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); return true; } }
batchTransfer
function batchTransfer(address[] _recipients, uint[] _values) onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint128(_values[j]),_now)); Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint128(balances[msg.sender]),_now)); return true; }
/* Batch token transfer. Used by contract creator to distribute initial tokens to holders */
Comment
v0.4.13+commit.fb4cb1a
bzzr://f14ccdcc204b1692d159a19f1dedc5a5ef0500237a1c0db4cadb988a96a4adfb
{ "func_code_index": [ 7035, 8033 ] }
3,064
OptionsPool
contracts/OptionsPool.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
OptionsPool
contract OptionsPool { using SafeMath for uint256; using SafeMathInt for int256; uint256 public upsLiquidated; uint256 public downsLiquidated; RebaseableToken public up; RebaseableToken public down; address private owner; IPriceOracleGetter public oracle; /** This is the price returned by the oracle at the beginning of thise epoch. */ uint256 public epochStartPrice; /** This is the blockNumber of the start of this epoch */ uint256 public epochStart; /** The current epoch */ uint256 public epoch = 1; // 1 index the epoch as we often check for epoch + 1 and also "epoch not defined" for liquidations, etc - and 0 is the same as undefined /** How many blocks should this epoch last? */ uint256 public epochLength; IERC20 public underlying; /** The token which ups and downs convert into */ IERC20 public payoutToken; IMinimalBPool public espool; uint8 public multiplier; // uint256 public rake = 0; // the amount this pool charges for in percentage as 18 decimal precision integer modifier isOwner { require(msg.sender == owner); _; } modifier checkEpoch { if (block.number >= epochStart.add(epochLength)) { endEpoch(); } _; } constructor() public { owner = msg.sender; } function testForEnd() public checkEpoch {} function createUpAndDown() internal returns (address upAddr, address downAddr) { bytes memory bytecode = type(RebaseableToken).creationCode; bytes32 upSalt = keccak256(abi.encodePacked(address(this), int8(0))); // console.logBytes32(upSalt); bytes32 downSalt = keccak256(abi.encodePacked(address(this), int8(1))); upAddr = Create2.deploy(0, upSalt, bytecode); downAddr = Create2.deploy(0, downSalt, bytecode); RebaseableToken(upAddr).initialize("UpDownUp", "udUp", address(this)); RebaseableToken(downAddr).initialize( "UpDownDown", "udDn", address(this) ); setTokens(upAddr, downAddr); return (upAddr, downAddr); } // following the pattern of uniswap so there can be a pool factory function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); } function setESPool(address espool_) public isOwner { espool = IMinimalBPool(espool_); } function setTokens(address up_, address down_) internal isOwner { up = RebaseableToken(up_); down = RebaseableToken(down_); } function setOwner(address newOwner) public isOwner { owner = newOwner; } /** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */ function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; } function endEpoch() internal { updatePrice(oracle.getAssetPrice(address(underlying))); } // function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // } function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); } function updatePrice(uint256 newPrice_) internal { // console.log( // "--------> ending epoch: ", // epoch, // epochStartPrice, // newPrice_ // ); uint256 pool_ = payoutToken.balanceOf(address(this)); // logPool(); uint newEpoch = epoch + 1; if (pool_ == 0) { up.rebase(newEpoch, int256(up.totalSupply()) * -1); down.rebase(newEpoch, int256(down.totalSupply()) * -1); epochStartPrice = newPrice_; epochStart = block.number; epoch = newEpoch; upsLiquidated = 0; downsLiquidated = 0; updateEsPool(); return; } uint256 upTotal = up.totalSupply(); uint256 downTotal = down.totalSupply(); (uint256 adjustedUp, uint256 adjustedDown) = liquidationAdjustments(pool_, upTotal, downTotal); upsLiquidated = 0; downsLiquidated = 0; // console.log("---- real rebase begins ---"); uint256 currentPrice = epochStartPrice; uint256 diff; if (newPrice_ > currentPrice) { diff = newPrice_.sub(currentPrice); } else { diff = currentPrice.sub(newPrice_); } uint256 percent = percentChangeMax100(diff, currentPrice); int256 baseUp = int256(adjustedUp).sub(int256(upTotal)); int256 baseDown = int256(adjustedDown).sub(int256(downTotal)); if (newPrice_ > currentPrice) { int256 take = int256(adjustedDown.mul(percent).div(10**18)); up.rebase(newEpoch, baseUp.add(take)); down.rebase(newEpoch, baseDown.sub(take)); } else { int256 take = int256(adjustedUp.mul(percent).div(10**18)); down.rebase(newEpoch, baseDown.add(take)); up.rebase(newEpoch, baseUp.sub(take)); } // logPool(); updateEsPool(); epochStartPrice = newPrice_; epoch = newEpoch; epochStart = block.number; } function updateEsPool() internal { if (address(espool) != address(0)) { espool.resyncWeights(address(up), address(down)); } } /** The user wants out of the pool and so at the end of this epoch we will let them cash out. */ function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); } // TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup. function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); } function deposit(uint256 amount) public checkEpoch { require(payoutToken.transferFrom(msg.sender, address(this), amount)); // console.log( // "at deposit time: ", // up.totalSupply().div(10**18), // down.totalSupply().div(10**18) // ); require(up.mint(msg.sender, amount.mul(100))); require(down.mint(msg.sender, amount.mul(100))); } }
// import "hardhat/console.sol";
LineComment
initialize
function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); }
// following the pattern of uniswap so there can be a pool factory
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 2325, 2891 ] }
3,065
OptionsPool
contracts/OptionsPool.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
OptionsPool
contract OptionsPool { using SafeMath for uint256; using SafeMathInt for int256; uint256 public upsLiquidated; uint256 public downsLiquidated; RebaseableToken public up; RebaseableToken public down; address private owner; IPriceOracleGetter public oracle; /** This is the price returned by the oracle at the beginning of thise epoch. */ uint256 public epochStartPrice; /** This is the blockNumber of the start of this epoch */ uint256 public epochStart; /** The current epoch */ uint256 public epoch = 1; // 1 index the epoch as we often check for epoch + 1 and also "epoch not defined" for liquidations, etc - and 0 is the same as undefined /** How many blocks should this epoch last? */ uint256 public epochLength; IERC20 public underlying; /** The token which ups and downs convert into */ IERC20 public payoutToken; IMinimalBPool public espool; uint8 public multiplier; // uint256 public rake = 0; // the amount this pool charges for in percentage as 18 decimal precision integer modifier isOwner { require(msg.sender == owner); _; } modifier checkEpoch { if (block.number >= epochStart.add(epochLength)) { endEpoch(); } _; } constructor() public { owner = msg.sender; } function testForEnd() public checkEpoch {} function createUpAndDown() internal returns (address upAddr, address downAddr) { bytes memory bytecode = type(RebaseableToken).creationCode; bytes32 upSalt = keccak256(abi.encodePacked(address(this), int8(0))); // console.logBytes32(upSalt); bytes32 downSalt = keccak256(abi.encodePacked(address(this), int8(1))); upAddr = Create2.deploy(0, upSalt, bytecode); downAddr = Create2.deploy(0, downSalt, bytecode); RebaseableToken(upAddr).initialize("UpDownUp", "udUp", address(this)); RebaseableToken(downAddr).initialize( "UpDownDown", "udDn", address(this) ); setTokens(upAddr, downAddr); return (upAddr, downAddr); } // following the pattern of uniswap so there can be a pool factory function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); } function setESPool(address espool_) public isOwner { espool = IMinimalBPool(espool_); } function setTokens(address up_, address down_) internal isOwner { up = RebaseableToken(up_); down = RebaseableToken(down_); } function setOwner(address newOwner) public isOwner { owner = newOwner; } /** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */ function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; } function endEpoch() internal { updatePrice(oracle.getAssetPrice(address(underlying))); } // function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // } function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); } function updatePrice(uint256 newPrice_) internal { // console.log( // "--------> ending epoch: ", // epoch, // epochStartPrice, // newPrice_ // ); uint256 pool_ = payoutToken.balanceOf(address(this)); // logPool(); uint newEpoch = epoch + 1; if (pool_ == 0) { up.rebase(newEpoch, int256(up.totalSupply()) * -1); down.rebase(newEpoch, int256(down.totalSupply()) * -1); epochStartPrice = newPrice_; epochStart = block.number; epoch = newEpoch; upsLiquidated = 0; downsLiquidated = 0; updateEsPool(); return; } uint256 upTotal = up.totalSupply(); uint256 downTotal = down.totalSupply(); (uint256 adjustedUp, uint256 adjustedDown) = liquidationAdjustments(pool_, upTotal, downTotal); upsLiquidated = 0; downsLiquidated = 0; // console.log("---- real rebase begins ---"); uint256 currentPrice = epochStartPrice; uint256 diff; if (newPrice_ > currentPrice) { diff = newPrice_.sub(currentPrice); } else { diff = currentPrice.sub(newPrice_); } uint256 percent = percentChangeMax100(diff, currentPrice); int256 baseUp = int256(adjustedUp).sub(int256(upTotal)); int256 baseDown = int256(adjustedDown).sub(int256(downTotal)); if (newPrice_ > currentPrice) { int256 take = int256(adjustedDown.mul(percent).div(10**18)); up.rebase(newEpoch, baseUp.add(take)); down.rebase(newEpoch, baseDown.sub(take)); } else { int256 take = int256(adjustedUp.mul(percent).div(10**18)); down.rebase(newEpoch, baseDown.add(take)); up.rebase(newEpoch, baseUp.sub(take)); } // logPool(); updateEsPool(); epochStartPrice = newPrice_; epoch = newEpoch; epochStart = block.number; } function updateEsPool() internal { if (address(espool) != address(0)) { espool.resyncWeights(address(up), address(down)); } } /** The user wants out of the pool and so at the end of this epoch we will let them cash out. */ function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); } // TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup. function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); } function deposit(uint256 amount) public checkEpoch { require(payoutToken.transferFrom(msg.sender, address(this), amount)); // console.log( // "at deposit time: ", // up.totalSupply().div(10**18), // down.totalSupply().div(10**18) // ); require(up.mint(msg.sender, amount.mul(100))); require(down.mint(msg.sender, amount.mul(100))); } }
// import "hardhat/console.sol";
LineComment
percentChangeMax100
function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; }
/** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 3342, 3763 ] }
3,066
OptionsPool
contracts/OptionsPool.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
OptionsPool
contract OptionsPool { using SafeMath for uint256; using SafeMathInt for int256; uint256 public upsLiquidated; uint256 public downsLiquidated; RebaseableToken public up; RebaseableToken public down; address private owner; IPriceOracleGetter public oracle; /** This is the price returned by the oracle at the beginning of thise epoch. */ uint256 public epochStartPrice; /** This is the blockNumber of the start of this epoch */ uint256 public epochStart; /** The current epoch */ uint256 public epoch = 1; // 1 index the epoch as we often check for epoch + 1 and also "epoch not defined" for liquidations, etc - and 0 is the same as undefined /** How many blocks should this epoch last? */ uint256 public epochLength; IERC20 public underlying; /** The token which ups and downs convert into */ IERC20 public payoutToken; IMinimalBPool public espool; uint8 public multiplier; // uint256 public rake = 0; // the amount this pool charges for in percentage as 18 decimal precision integer modifier isOwner { require(msg.sender == owner); _; } modifier checkEpoch { if (block.number >= epochStart.add(epochLength)) { endEpoch(); } _; } constructor() public { owner = msg.sender; } function testForEnd() public checkEpoch {} function createUpAndDown() internal returns (address upAddr, address downAddr) { bytes memory bytecode = type(RebaseableToken).creationCode; bytes32 upSalt = keccak256(abi.encodePacked(address(this), int8(0))); // console.logBytes32(upSalt); bytes32 downSalt = keccak256(abi.encodePacked(address(this), int8(1))); upAddr = Create2.deploy(0, upSalt, bytecode); downAddr = Create2.deploy(0, downSalt, bytecode); RebaseableToken(upAddr).initialize("UpDownUp", "udUp", address(this)); RebaseableToken(downAddr).initialize( "UpDownDown", "udDn", address(this) ); setTokens(upAddr, downAddr); return (upAddr, downAddr); } // following the pattern of uniswap so there can be a pool factory function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); } function setESPool(address espool_) public isOwner { espool = IMinimalBPool(espool_); } function setTokens(address up_, address down_) internal isOwner { up = RebaseableToken(up_); down = RebaseableToken(down_); } function setOwner(address newOwner) public isOwner { owner = newOwner; } /** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */ function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; } function endEpoch() internal { updatePrice(oracle.getAssetPrice(address(underlying))); } // function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // } function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); } function updatePrice(uint256 newPrice_) internal { // console.log( // "--------> ending epoch: ", // epoch, // epochStartPrice, // newPrice_ // ); uint256 pool_ = payoutToken.balanceOf(address(this)); // logPool(); uint newEpoch = epoch + 1; if (pool_ == 0) { up.rebase(newEpoch, int256(up.totalSupply()) * -1); down.rebase(newEpoch, int256(down.totalSupply()) * -1); epochStartPrice = newPrice_; epochStart = block.number; epoch = newEpoch; upsLiquidated = 0; downsLiquidated = 0; updateEsPool(); return; } uint256 upTotal = up.totalSupply(); uint256 downTotal = down.totalSupply(); (uint256 adjustedUp, uint256 adjustedDown) = liquidationAdjustments(pool_, upTotal, downTotal); upsLiquidated = 0; downsLiquidated = 0; // console.log("---- real rebase begins ---"); uint256 currentPrice = epochStartPrice; uint256 diff; if (newPrice_ > currentPrice) { diff = newPrice_.sub(currentPrice); } else { diff = currentPrice.sub(newPrice_); } uint256 percent = percentChangeMax100(diff, currentPrice); int256 baseUp = int256(adjustedUp).sub(int256(upTotal)); int256 baseDown = int256(adjustedDown).sub(int256(downTotal)); if (newPrice_ > currentPrice) { int256 take = int256(adjustedDown.mul(percent).div(10**18)); up.rebase(newEpoch, baseUp.add(take)); down.rebase(newEpoch, baseDown.sub(take)); } else { int256 take = int256(adjustedUp.mul(percent).div(10**18)); down.rebase(newEpoch, baseDown.add(take)); up.rebase(newEpoch, baseUp.sub(take)); } // logPool(); updateEsPool(); epochStartPrice = newPrice_; epoch = newEpoch; epochStart = block.number; } function updateEsPool() internal { if (address(espool) != address(0)) { espool.resyncWeights(address(up), address(down)); } } /** The user wants out of the pool and so at the end of this epoch we will let them cash out. */ function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); } // TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup. function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); } function deposit(uint256 amount) public checkEpoch { require(payoutToken.transferFrom(msg.sender, address(this), amount)); // console.log( // "at deposit time: ", // up.totalSupply().div(10**18), // down.totalSupply().div(10**18) // ); require(up.mint(msg.sender, amount.mul(100))); require(down.mint(msg.sender, amount.mul(100))); } }
// import "hardhat/console.sol";
LineComment
liquidationAdjustments
function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); }
// function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // }
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 4377, 5957 ] }
3,067
OptionsPool
contracts/OptionsPool.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
OptionsPool
contract OptionsPool { using SafeMath for uint256; using SafeMathInt for int256; uint256 public upsLiquidated; uint256 public downsLiquidated; RebaseableToken public up; RebaseableToken public down; address private owner; IPriceOracleGetter public oracle; /** This is the price returned by the oracle at the beginning of thise epoch. */ uint256 public epochStartPrice; /** This is the blockNumber of the start of this epoch */ uint256 public epochStart; /** The current epoch */ uint256 public epoch = 1; // 1 index the epoch as we often check for epoch + 1 and also "epoch not defined" for liquidations, etc - and 0 is the same as undefined /** How many blocks should this epoch last? */ uint256 public epochLength; IERC20 public underlying; /** The token which ups and downs convert into */ IERC20 public payoutToken; IMinimalBPool public espool; uint8 public multiplier; // uint256 public rake = 0; // the amount this pool charges for in percentage as 18 decimal precision integer modifier isOwner { require(msg.sender == owner); _; } modifier checkEpoch { if (block.number >= epochStart.add(epochLength)) { endEpoch(); } _; } constructor() public { owner = msg.sender; } function testForEnd() public checkEpoch {} function createUpAndDown() internal returns (address upAddr, address downAddr) { bytes memory bytecode = type(RebaseableToken).creationCode; bytes32 upSalt = keccak256(abi.encodePacked(address(this), int8(0))); // console.logBytes32(upSalt); bytes32 downSalt = keccak256(abi.encodePacked(address(this), int8(1))); upAddr = Create2.deploy(0, upSalt, bytecode); downAddr = Create2.deploy(0, downSalt, bytecode); RebaseableToken(upAddr).initialize("UpDownUp", "udUp", address(this)); RebaseableToken(downAddr).initialize( "UpDownDown", "udDn", address(this) ); setTokens(upAddr, downAddr); return (upAddr, downAddr); } // following the pattern of uniswap so there can be a pool factory function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); } function setESPool(address espool_) public isOwner { espool = IMinimalBPool(espool_); } function setTokens(address up_, address down_) internal isOwner { up = RebaseableToken(up_); down = RebaseableToken(down_); } function setOwner(address newOwner) public isOwner { owner = newOwner; } /** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */ function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; } function endEpoch() internal { updatePrice(oracle.getAssetPrice(address(underlying))); } // function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // } function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); } function updatePrice(uint256 newPrice_) internal { // console.log( // "--------> ending epoch: ", // epoch, // epochStartPrice, // newPrice_ // ); uint256 pool_ = payoutToken.balanceOf(address(this)); // logPool(); uint newEpoch = epoch + 1; if (pool_ == 0) { up.rebase(newEpoch, int256(up.totalSupply()) * -1); down.rebase(newEpoch, int256(down.totalSupply()) * -1); epochStartPrice = newPrice_; epochStart = block.number; epoch = newEpoch; upsLiquidated = 0; downsLiquidated = 0; updateEsPool(); return; } uint256 upTotal = up.totalSupply(); uint256 downTotal = down.totalSupply(); (uint256 adjustedUp, uint256 adjustedDown) = liquidationAdjustments(pool_, upTotal, downTotal); upsLiquidated = 0; downsLiquidated = 0; // console.log("---- real rebase begins ---"); uint256 currentPrice = epochStartPrice; uint256 diff; if (newPrice_ > currentPrice) { diff = newPrice_.sub(currentPrice); } else { diff = currentPrice.sub(newPrice_); } uint256 percent = percentChangeMax100(diff, currentPrice); int256 baseUp = int256(adjustedUp).sub(int256(upTotal)); int256 baseDown = int256(adjustedDown).sub(int256(downTotal)); if (newPrice_ > currentPrice) { int256 take = int256(adjustedDown.mul(percent).div(10**18)); up.rebase(newEpoch, baseUp.add(take)); down.rebase(newEpoch, baseDown.sub(take)); } else { int256 take = int256(adjustedUp.mul(percent).div(10**18)); down.rebase(newEpoch, baseDown.add(take)); up.rebase(newEpoch, baseUp.sub(take)); } // logPool(); updateEsPool(); epochStartPrice = newPrice_; epoch = newEpoch; epochStart = block.number; } function updateEsPool() internal { if (address(espool) != address(0)) { espool.resyncWeights(address(up), address(down)); } } /** The user wants out of the pool and so at the end of this epoch we will let them cash out. */ function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); } // TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup. function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); } function deposit(uint256 amount) public checkEpoch { require(payoutToken.transferFrom(msg.sender, address(this), amount)); // console.log( // "at deposit time: ", // up.totalSupply().div(10**18), // down.totalSupply().div(10**18) // ); require(up.mint(msg.sender, amount.mul(100))); require(down.mint(msg.sender, amount.mul(100))); } }
// import "hardhat/console.sol";
LineComment
settle
function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); }
/** The user wants out of the pool and so at the end of this epoch we will let them cash out. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 8293, 8466 ] }
3,068
OptionsPool
contracts/OptionsPool.sol
0xfd6c25608c05c85dd4e7f798eb8893a6a8a5624c
Solidity
OptionsPool
contract OptionsPool { using SafeMath for uint256; using SafeMathInt for int256; uint256 public upsLiquidated; uint256 public downsLiquidated; RebaseableToken public up; RebaseableToken public down; address private owner; IPriceOracleGetter public oracle; /** This is the price returned by the oracle at the beginning of thise epoch. */ uint256 public epochStartPrice; /** This is the blockNumber of the start of this epoch */ uint256 public epochStart; /** The current epoch */ uint256 public epoch = 1; // 1 index the epoch as we often check for epoch + 1 and also "epoch not defined" for liquidations, etc - and 0 is the same as undefined /** How many blocks should this epoch last? */ uint256 public epochLength; IERC20 public underlying; /** The token which ups and downs convert into */ IERC20 public payoutToken; IMinimalBPool public espool; uint8 public multiplier; // uint256 public rake = 0; // the amount this pool charges for in percentage as 18 decimal precision integer modifier isOwner { require(msg.sender == owner); _; } modifier checkEpoch { if (block.number >= epochStart.add(epochLength)) { endEpoch(); } _; } constructor() public { owner = msg.sender; } function testForEnd() public checkEpoch {} function createUpAndDown() internal returns (address upAddr, address downAddr) { bytes memory bytecode = type(RebaseableToken).creationCode; bytes32 upSalt = keccak256(abi.encodePacked(address(this), int8(0))); // console.logBytes32(upSalt); bytes32 downSalt = keccak256(abi.encodePacked(address(this), int8(1))); upAddr = Create2.deploy(0, upSalt, bytecode); downAddr = Create2.deploy(0, downSalt, bytecode); RebaseableToken(upAddr).initialize("UpDownUp", "udUp", address(this)); RebaseableToken(downAddr).initialize( "UpDownDown", "udDn", address(this) ); setTokens(upAddr, downAddr); return (upAddr, downAddr); } // following the pattern of uniswap so there can be a pool factory function initialize( address owner_, address payoutToken_, uint256 epochLength_, uint8 multiplier_, address oracle_, address underlying_ ) public isOwner { owner = owner_; payoutToken = IERC20(payoutToken_); oracle = IPriceOracleGetter(oracle_); epochStart = block.number; epochLength = epochLength_; multiplier = multiplier_; underlying = IERC20(underlying_); epochStartPrice = oracle.getAssetPrice(underlying_); createUpAndDown(); } function setESPool(address espool_) public isOwner { espool = IMinimalBPool(espool_); } function setTokens(address up_, address down_) internal isOwner { up = RebaseableToken(up_); down = RebaseableToken(down_); } function setOwner(address newOwner) public isOwner { owner = newOwner; } /** calculate the percent change defined as an 18 precision decimal (1e18 is 100%) */ function percentChangeMax100(uint256 diff, uint256 base) internal view returns (uint256) { if (base == 0) { return 0; // ignore zero price } uint256 percent = (diff * 10**18).mul(10**18).div(base.mul(10**18)).mul(uint256(multiplier)); if (percent >= 10**18) { percent = uint256(10**18).sub(1); } return percent; } function endEpoch() internal { updatePrice(oracle.getAssetPrice(address(underlying))); } // function logPool() internal view { // uint256 pool_ = payoutToken.balanceOf(address(this)); // console.log("pool: ", pool_, pool_.div(10**18)); // console.log("ups: ", up.totalSupply()); // console.log("downs: ", down.totalSupply()); // int256 upDownDiff = int256(pool_.mul(200)) // .sub(int256(up.totalSupply())) // .sub(int256(down.totalSupply())); // console.log("Diff : "); // console.logInt(upDownDiff); // } function liquidationAdjustments( uint256 pool_, uint256 upBal, uint256 downBal ) internal view returns (uint256 adjustedUp, uint256 adjustedDown) { if (upsLiquidated == 0 && downsLiquidated == 0) { return (upBal, downBal); } if (upBal == 0 && downBal == 0) { return (0,0); } // console.log("ups liquidated ", upsLiquidated); // console.log("downs liquidated ", downsLiquidated); // first add back in the liquidated adjustedUp = upBal + upsLiquidated; adjustedDown = downBal + downsLiquidated; uint256 diff = adjustedUp.add(adjustedDown).sub(pool_.mul(200)); uint256 halfDiff = diff.div(2); // console.log("diff from pool to remove equally: ", halfDiff.div(10**18)); // but now we will rebase down to the current pool size uint256 upToRemove = halfDiff; uint256 downToRemove = diff.sub(halfDiff); if (upToRemove > adjustedUp) { downToRemove += upToRemove.sub(adjustedUp); upToRemove = adjustedUp; } if (downToRemove > adjustedDown) { upToRemove += downToRemove.sub(adjustedDown); downToRemove = adjustedDown; } if (upToRemove > adjustedUp) { upToRemove = adjustedUp; // console.log("hit edge case :", downToRemove); } adjustedUp = adjustedUp.sub(upToRemove); adjustedDown = adjustedDown.sub(downToRemove); return (adjustedUp, adjustedDown); } function updatePrice(uint256 newPrice_) internal { // console.log( // "--------> ending epoch: ", // epoch, // epochStartPrice, // newPrice_ // ); uint256 pool_ = payoutToken.balanceOf(address(this)); // logPool(); uint newEpoch = epoch + 1; if (pool_ == 0) { up.rebase(newEpoch, int256(up.totalSupply()) * -1); down.rebase(newEpoch, int256(down.totalSupply()) * -1); epochStartPrice = newPrice_; epochStart = block.number; epoch = newEpoch; upsLiquidated = 0; downsLiquidated = 0; updateEsPool(); return; } uint256 upTotal = up.totalSupply(); uint256 downTotal = down.totalSupply(); (uint256 adjustedUp, uint256 adjustedDown) = liquidationAdjustments(pool_, upTotal, downTotal); upsLiquidated = 0; downsLiquidated = 0; // console.log("---- real rebase begins ---"); uint256 currentPrice = epochStartPrice; uint256 diff; if (newPrice_ > currentPrice) { diff = newPrice_.sub(currentPrice); } else { diff = currentPrice.sub(newPrice_); } uint256 percent = percentChangeMax100(diff, currentPrice); int256 baseUp = int256(adjustedUp).sub(int256(upTotal)); int256 baseDown = int256(adjustedDown).sub(int256(downTotal)); if (newPrice_ > currentPrice) { int256 take = int256(adjustedDown.mul(percent).div(10**18)); up.rebase(newEpoch, baseUp.add(take)); down.rebase(newEpoch, baseDown.sub(take)); } else { int256 take = int256(adjustedUp.mul(percent).div(10**18)); down.rebase(newEpoch, baseDown.add(take)); up.rebase(newEpoch, baseUp.sub(take)); } // logPool(); updateEsPool(); epochStartPrice = newPrice_; epoch = newEpoch; epochStart = block.number; } function updateEsPool() internal { if (address(espool) != address(0)) { espool.resyncWeights(address(up), address(down)); } } /** The user wants out of the pool and so at the end of this epoch we will let them cash out. */ function settle() public checkEpoch { // TODO: set lockedAt and only allow a liquidate then up.settle(msg.sender); down.settle(msg.sender); } // TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup. function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); } function deposit(uint256 amount) public checkEpoch { require(payoutToken.transferFrom(msg.sender, address(this), amount)); // console.log( // "at deposit time: ", // up.totalSupply().div(10**18), // down.totalSupply().div(10**18) // ); require(up.mint(msg.sender, amount.mul(100))); require(down.mint(msg.sender, amount.mul(100))); } }
// import "hardhat/console.sol";
LineComment
liquidate
function liquidate() public checkEpoch { // TODO: only allow this after the lockout period address user_ = msg.sender; uint256 upBal = up.balanceOf(user_); uint256 downBal = down.balanceOf(user_); up.liquidate(address(user_)); down.liquidate(address(user_)); upsLiquidated += upBal; downsLiquidated += downBal; // console.log( // "liquidating (ups/downs): ", // upBal.div(10**18), // downBal.div(10**18) // ); uint256 totalPayout = upBal.add(downBal).div(200); // console.log( // "liquidate payout to ", // msg.sender, // totalPayout.div(10**18) // ); uint256 fee = totalPayout.div(1000); // 10 basis points fee uint256 toUser = totalPayout.sub(fee); require(payoutToken.transfer(user_, toUser)); uint poolBal = payoutToken.balanceOf(address(this)); if (fee > poolBal) { payoutToken.transfer(owner, poolBal); return; } require(payoutToken.transfer(owner, fee)); }
// TODO: this provides an arbitrage opportunity to withdraw // before the end of a period. This should be a lockup.
LineComment
v0.6.12+commit.27d51765
{ "func_code_index": [ 8592, 9723 ] }
3,069
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
committeeMembershipWillChange
function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); }
/// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 3306, 3690 ] }
3,070
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getFeesAndBootstrapBalance
function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); }
/// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 3952, 4314 ] }
3,071
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
estimateFutureFeesAndBootstrapRewards
function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); }
/// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 4852, 5547 ] }
3,072
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
withdrawFees
function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); }
/// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 5713, 6288 ] }
3,073
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
withdrawBootstrapFunds
function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); }
/// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 6459, 7106 ] }
3,074
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getFeesAndBootstrapState
function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; }
/// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time)
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 7870, 8944 ] }
3,075
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getFeesAndBootstrapData
function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); }
/// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 9474, 10365 ] }
3,076
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
activateRewardDistribution
function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); }
/// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 10692, 11064 ] }
3,077
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
deactivateRewardDistribution
function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); }
/// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 11272, 11604 ] }
3,078
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
isRewardAllocationActive
function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; }
/// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 11730, 11866 ] }
3,079
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
setGeneralCommitteeAnnualBootstrap
function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); }
/// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 12160, 12379 ] }
3,080
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getGeneralCommitteeAnnualBootstrap
function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; }
/// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 12535, 12693 ] }
3,081
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
setCertifiedCommitteeAnnualBootstrap
function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); }
/// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 12991, 13214 ] }
3,082
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getCertifiedCommitteeAnnualBootstrap
function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; }
/// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 13388, 13550 ] }
3,083
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
migrateRewardsBalance
function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } }
/// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 13940, 15804 ] }
3,084
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
acceptRewardsBalanceMigration
function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } }
/// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list.
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 16479, 18082 ] }
3,085
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
emergencyWithdraw
function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); }
/// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 18377, 18703 ] }
3,086
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getSettings
function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; }
/// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 19035, 19535 ] }
3,087
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_getFeesAndBootstrapState
function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } }
/// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 20316, 22242 ] }
3,088
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_updateFeesAndBootstrapState
function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); }
/// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 22677, 24017 ] }
3,089
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
updateFeesAndBootstrapState
function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); }
/// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 24230, 24553 ] }
3,090
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_getGuardianFeesAndBootstrap
function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; }
/// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 25435, 26835 ] }
3,091
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_updateGuardianFeesAndBootstrap
function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); }
/// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 27626, 28766 ] }
3,092
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
getGuardianFeesAndBootstrap
function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); }
/// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 29368, 30232 ] }
3,093
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
updateGuardianFeesAndBootstrap
function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); }
/// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 30491, 30972 ] }
3,094
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_setGeneralCommitteeAnnualBootstrap
function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); }
/// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 31149, 31481 ] }
3,095
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
_setCertifiedCommitteeAnnualBootstrap
function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); }
/// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 31631, 31969 ] }
3,096
FeesAndBootstrapRewards
contracts/FeesAndBootstrapRewards.sol
0xda7e381544fc73cad7d9e63c86e561452b9b9e9c
Solidity
FeesAndBootstrapRewards
contract FeesAndBootstrapRewards is IFeesAndBootstrapRewards, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; uint256 constant PERCENT_MILLIE_BASE = 100000; uint256 constant TOKEN_BASE = 1e18; struct Settings { uint96 generalCommitteeAnnualBootstrap; uint96 certifiedCommitteeAnnualBootstrap; bool rewardAllocationActive; } Settings settings; IERC20 public bootstrapToken; IERC20 public feesToken; struct FeesAndBootstrapState { uint96 certifiedFeesPerMember; uint96 generalFeesPerMember; uint96 certifiedBootstrapPerMember; uint96 generalBootstrapPerMember; uint32 lastAssigned; } FeesAndBootstrapState public feesAndBootstrapState; struct FeesAndBootstrap { uint96 feeBalance; uint96 bootstrapBalance; uint96 lastFeesPerMember; uint96 lastBootstrapPerMember; uint96 withdrawnFees; uint96 withdrawnBootstrap; } mapping(address => FeesAndBootstrap) public feesAndBootstrap; /// Constructor /// @param _contractRegistry is the contract registry address /// @param _registryAdmin is the registry admin address /// @param _feesToken is the token used for virtual chains fees /// @param _bootstrapToken is the token used for the bootstrap reward /// @param generalCommitteeAnnualBootstrap is the general committee annual bootstrap reward /// @param certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap reward constructor( IContractRegistry _contractRegistry, address _registryAdmin, IERC20 _feesToken, IERC20 _bootstrapToken, uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap ) ManagedContract(_contractRegistry, _registryAdmin) public { require(address(_bootstrapToken) != address(0), "bootstrapToken must not be 0"); require(address(_feesToken) != address(0), "feeToken must not be 0"); _setGeneralCommitteeAnnualBootstrap(generalCommitteeAnnualBootstrap); _setCertifiedCommitteeAnnualBootstrap(certifiedCommitteeAnnualBootstrap); feesToken = _feesToken; bootstrapToken = _bootstrapToken; } modifier onlyCommitteeContract() { require(msg.sender == address(committeeContract), "caller is not the elections contract"); _; } /* * External functions */ /// Triggers update of the guardian rewards /// @dev Called by: the Committee contract /// @dev called upon expected change in the committee membership of the guardian /// @param guardian is the guardian who's committee membership is updated /// @param inCommittee indicates whether the guardian is in the committee prior to the change /// @param isCertified indicates whether the guardian is certified prior to the change /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function committeeMembershipWillChange(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) external override onlyWhenActive onlyCommitteeContract { _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, generalCommitteeSize, certifiedCommitteeSize); } /// Returns the fees and bootstrap balances of a guardian /// @dev calculates the up to date balances (differ from the state) /// @return feeBalance the guardian's fees balance /// @return bootstrapBalance the guardian's bootstrap balance function getFeesAndBootstrapBalance(address guardian) external override view returns (uint256 feeBalance, uint256 bootstrapBalance) { (FeesAndBootstrap memory guardianFeesAndBootstrap,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return (guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.bootstrapBalance); } /// Returns an estimation of the fees and bootstrap a guardian will be entitled to for a duration of time /// The estimation is based on the current system state and there for only provides an estimation /// @param guardian is the guardian address /// @param duration is the amount of time in seconds for which the estimation is calculated /// @return estimatedFees is the estimated received fees for the duration /// @return estimatedBootstrapRewards is the estimated received bootstrap for the duration function estimateFutureFeesAndBootstrapRewards(address guardian, uint256 duration) external override view returns (uint256 estimatedFees, uint256 estimatedBootstrapRewards) { (FeesAndBootstrap memory guardianFeesAndBootstrapNow,) = getGuardianFeesAndBootstrap(guardian, block.timestamp); (FeesAndBootstrap memory guardianFeesAndBootstrapFuture,) = getGuardianFeesAndBootstrap(guardian, block.timestamp.add(duration)); estimatedFees = guardianFeesAndBootstrapFuture.feeBalance.sub(guardianFeesAndBootstrapNow.feeBalance); estimatedBootstrapRewards = guardianFeesAndBootstrapFuture.bootstrapBalance.sub(guardianFeesAndBootstrapNow.bootstrapBalance); } /// Transfers the guardian Fees balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawFees(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].feeBalance; feesAndBootstrap[guardian].feeBalance = 0; uint96 withdrawnFees = feesAndBootstrap[guardian].withdrawnFees.add(amount); feesAndBootstrap[guardian].withdrawnFees = withdrawnFees; emit FeesWithdrawn(guardian, amount, withdrawnFees); require(feesToken.transfer(guardian, amount), "Rewards::withdrawFees - insufficient funds"); } /// Transfers the guardian bootstrap balance to their account /// @dev One may withdraw for another guardian /// @param guardian is the guardian address function withdrawBootstrapFunds(address guardian) external override onlyWhenActive { updateGuardianFeesAndBootstrap(guardian); uint256 amount = feesAndBootstrap[guardian].bootstrapBalance; feesAndBootstrap[guardian].bootstrapBalance = 0; uint96 withdrawnBootstrap = feesAndBootstrap[guardian].withdrawnBootstrap.add(amount); feesAndBootstrap[guardian].withdrawnBootstrap = withdrawnBootstrap; emit BootstrapRewardsWithdrawn(guardian, amount, withdrawnBootstrap); require(bootstrapToken.transfer(guardian, amount), "Rewards::withdrawBootstrapFunds - insufficient funds"); } /// Returns the current global Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return certifiedFeesPerMember represents the fees a certified committee member from day 0 would have receive /// @return generalFeesPerMember represents the fees a non-certified committee member from day 0 would have receive /// @return certifiedBootstrapPerMember represents the bootstrap fund a certified committee member from day 0 would have receive /// @return generalBootstrapPerMember represents the bootstrap fund a non-certified committee member from day 0 would have receive /// @return lastAssigned is the time the calculation was done to (typically the latest block time) function getFeesAndBootstrapState() external override view returns ( uint256 certifiedFeesPerMember, uint256 generalFeesPerMember, uint256 certifiedBootstrapPerMember, uint256 generalBootstrapPerMember, uint256 lastAssigned ) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(block.timestamp), certifiedFeesWallet.getOutstandingFees(block.timestamp), block.timestamp, settings); certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember; generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember; certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember; generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember; lastAssigned = _feesAndBootstrapState.lastAssigned; } /// Returns the current guardian Fees and Bootstrap rewards state /// @dev calculated to the latest block, may differ from the state read /// @return feeBalance is the guardian fees balance /// @return lastFeesPerMember is the FeesPerMember on the last update based on the guardian certification state /// @return bootstrapBalance is the guardian bootstrap balance /// @return lastBootstrapPerMember is the FeesPerMember on the last BootstrapPerMember based on the guardian certification state function getFeesAndBootstrapData(address guardian) external override view returns ( uint256 feeBalance, uint256 lastFeesPerMember, uint256 bootstrapBalance, uint256 lastBootstrapPerMember, uint256 withdrawnFees, uint256 withdrawnBootstrap, bool certified ) { FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, certified) = getGuardianFeesAndBootstrap(guardian, block.timestamp); return ( guardianFeesAndBootstrap.feeBalance, guardianFeesAndBootstrap.lastFeesPerMember, guardianFeesAndBootstrap.bootstrapBalance, guardianFeesAndBootstrap.lastBootstrapPerMember, guardianFeesAndBootstrap.withdrawnFees, guardianFeesAndBootstrap.withdrawnBootstrap, certified ); } /* * Governance functions */ /// Activates fees and bootstrap allocation /// @dev governance function called only by the initialization admin /// @dev On migrations, startTime should be set as the previous contract deactivation time. /// @param startTime sets the last assignment time function activateRewardDistribution(uint startTime) external override onlyMigrationManager { require(!settings.rewardAllocationActive, "reward distribution is already activated"); feesAndBootstrapState.lastAssigned = uint32(startTime); settings.rewardAllocationActive = true; emit RewardDistributionActivated(startTime); } /// Deactivates fees and bootstrap allocation /// @dev governance function called only by the migration manager /// @dev guardians updates remain active based on the current perMember value function deactivateRewardDistribution() external override onlyMigrationManager { require(settings.rewardAllocationActive, "reward distribution is already deactivated"); updateFeesAndBootstrapState(); settings.rewardAllocationActive = false; emit RewardDistributionDeactivated(); } /// Returns the rewards allocation activation status /// @return rewardAllocationActive is the activation status function isRewardAllocationActive() external override view returns (bool) { return settings.rewardAllocationActive; } /// Sets the annual rate for the general committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual general committee bootstrap award function setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setGeneralCommitteeAnnualBootstrap(annualAmount); } /// Returns the general committee annual bootstrap award /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap function getGeneralCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.generalCommitteeAnnualBootstrap; } /// Sets the annual rate for the certified committee bootstrap /// @dev governance function called only by the functional manager /// @dev updates the global bootstrap and fees state before updating /// @param annualAmount is the annual certified committee bootstrap award function setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) external override onlyFunctionalManager { updateFeesAndBootstrapState(); _setCertifiedCommitteeAnnualBootstrap(annualAmount); } /// Returns the certified committee annual bootstrap reward /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap function getCertifiedCommitteeAnnualBootstrap() external override view returns (uint256) { return settings.certifiedCommitteeAnnualBootstrap; } /// Migrates the rewards balance to a new FeesAndBootstrap contract /// @dev The new rewards contract is determined according to the contracts registry /// @dev No impact of the calling contract if the currently configured contract in the registry /// @dev may be called also while the contract is locked /// @param guardians is the list of guardians to migrate function migrateRewardsBalance(address[] calldata guardians) external override { require(!settings.rewardAllocationActive, "Reward distribution must be deactivated for migration"); IFeesAndBootstrapRewards currentRewardsContract = IFeesAndBootstrapRewards(getFeesAndBootstrapRewardsContract()); require(address(currentRewardsContract) != address(this), "New rewards contract is not set"); uint256 totalFees = 0; uint256 totalBootstrap = 0; uint256[] memory fees = new uint256[](guardians.length); uint256[] memory bootstrap = new uint256[](guardians.length); for (uint i = 0; i < guardians.length; i++) { updateGuardianFeesAndBootstrap(guardians[i]); FeesAndBootstrap memory guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; fees[i] = guardianFeesAndBootstrap.feeBalance; totalFees = totalFees.add(fees[i]); bootstrap[i] = guardianFeesAndBootstrap.bootstrapBalance; totalBootstrap = totalBootstrap.add(bootstrap[i]); guardianFeesAndBootstrap.feeBalance = 0; guardianFeesAndBootstrap.bootstrapBalance = 0; feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; } require(feesToken.approve(address(currentRewardsContract), totalFees), "migrateRewardsBalance: approve failed"); require(bootstrapToken.approve(address(currentRewardsContract), totalBootstrap), "migrateRewardsBalance: approve failed"); currentRewardsContract.acceptRewardsBalanceMigration(guardians, fees, totalFees, bootstrap, totalBootstrap); for (uint i = 0; i < guardians.length; i++) { emit FeesAndBootstrapRewardsBalanceMigrated(guardians[i], fees[i], bootstrap[i], address(currentRewardsContract)); } } /// Accepts guardian's balance migration from a previous rewards contract /// @dev the function may be called by any caller that approves the amounts provided for transfer /// @param guardians is the list of migrated guardians /// @param fees is the list of received guardian fees balance /// @param totalFees is the total amount of fees migrated for all guardians in the list. Must match the sum of the fees list. /// @param bootstrap is the list of received guardian bootstrap balance. /// @param totalBootstrap is the total amount of bootstrap rewards migrated for all guardians in the list. Must match the sum of the bootstrap list. function acceptRewardsBalanceMigration(address[] memory guardians, uint256[] memory fees, uint256 totalFees, uint256[] memory bootstrap, uint256 totalBootstrap) external override { uint256 _totalFees = 0; uint256 _totalBootstrap = 0; for (uint i = 0; i < guardians.length; i++) { _totalFees = _totalFees.add(fees[i]); _totalBootstrap = _totalBootstrap.add(bootstrap[i]); } require(totalFees == _totalFees, "totalFees does not match fees sum"); require(totalBootstrap == _totalBootstrap, "totalBootstrap does not match bootstrap sum"); if (totalFees > 0) { require(feesToken.transferFrom(msg.sender, address(this), totalFees), "acceptRewardBalanceMigration: transfer failed"); } if (totalBootstrap > 0) { require(bootstrapToken.transferFrom(msg.sender, address(this), totalBootstrap), "acceptRewardBalanceMigration: transfer failed"); } FeesAndBootstrap memory guardianFeesAndBootstrap; for (uint i = 0; i < guardians.length; i++) { guardianFeesAndBootstrap = feesAndBootstrap[guardians[i]]; guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(fees[i]); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(bootstrap[i]); feesAndBootstrap[guardians[i]] = guardianFeesAndBootstrap; emit FeesAndBootstrapRewardsBalanceMigrationAccepted(msg.sender, guardians[i], fees[i], bootstrap[i]); } } /// Performs emergency withdrawal of the contract balance /// @dev called with a token to withdraw, should be called twice with the fees and bootstrap tokens /// @dev governance function called only by the migration manager /// @param erc20 is the ERC20 token to withdraw function emergencyWithdraw(address erc20) external override onlyMigrationManager { IERC20 _token = IERC20(erc20); emit EmergencyWithdrawal(msg.sender, address(_token)); require(_token.transfer(msg.sender, _token.balanceOf(address(this))), "Rewards::emergencyWithdraw - transfer failed"); } /// Returns the contract's settings /// @return generalCommitteeAnnualBootstrap is the general committee annual bootstrap /// @return certifiedCommitteeAnnualBootstrap is the certified committee additional annual bootstrap /// @return rewardAllocationActive indicates the rewards allocation activation state function getSettings() external override view returns ( uint generalCommitteeAnnualBootstrap, uint certifiedCommitteeAnnualBootstrap, bool rewardAllocationActive ) { Settings memory _settings = settings; generalCommitteeAnnualBootstrap = _settings.generalCommitteeAnnualBootstrap; certifiedCommitteeAnnualBootstrap = _settings.certifiedCommitteeAnnualBootstrap; rewardAllocationActive = _settings.rewardAllocationActive; } /* * Private functions */ // Global state /// Returns the current global Fees and Bootstrap rewards state /// @dev receives the relevant committee and general state data /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @param collectedGeneralFees is the amount of fees collected from general virtual chains for the calculated period /// @param collectedCertifiedFees is the amount of fees collected from general virtual chains for the calculated period /// @param currentTime is the time to calculate the fees and bootstrap for /// @param _settings is the contract settings function _getFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize, uint256 collectedGeneralFees, uint256 collectedCertifiedFees, uint256 currentTime, Settings memory _settings) private view returns (FeesAndBootstrapState memory _feesAndBootstrapState, uint256 allocatedGeneralBootstrap, uint256 allocatedCertifiedBootstrap) { _feesAndBootstrapState = feesAndBootstrapState; if (_settings.rewardAllocationActive) { uint256 generalFeesDelta = generalCommitteeSize == 0 ? 0 : collectedGeneralFees.div(generalCommitteeSize); uint256 certifiedFeesDelta = certifiedCommitteeSize == 0 ? 0 : generalFeesDelta.add(collectedCertifiedFees.div(certifiedCommitteeSize)); _feesAndBootstrapState.generalFeesPerMember = _feesAndBootstrapState.generalFeesPerMember.add(generalFeesDelta); _feesAndBootstrapState.certifiedFeesPerMember = _feesAndBootstrapState.certifiedFeesPerMember.add(certifiedFeesDelta); uint duration = currentTime.sub(_feesAndBootstrapState.lastAssigned); uint256 generalBootstrapDelta = uint256(_settings.generalCommitteeAnnualBootstrap).mul(duration).div(365 days); uint256 certifiedBootstrapDelta = generalBootstrapDelta.add(uint256(_settings.certifiedCommitteeAnnualBootstrap).mul(duration).div(365 days)); _feesAndBootstrapState.generalBootstrapPerMember = _feesAndBootstrapState.generalBootstrapPerMember.add(generalBootstrapDelta); _feesAndBootstrapState.certifiedBootstrapPerMember = _feesAndBootstrapState.certifiedBootstrapPerMember.add(certifiedBootstrapDelta); _feesAndBootstrapState.lastAssigned = uint32(currentTime); allocatedGeneralBootstrap = generalBootstrapDelta.mul(generalCommitteeSize); allocatedCertifiedBootstrap = certifiedBootstrapDelta.mul(certifiedCommitteeSize); } } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _getFeesAndBootstrapState to calculate the global state /// @param generalCommitteeSize is the current number of members in the certified committee /// @param certifiedCommitteeSize is the current number of members in the general committee /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function _updateFeesAndBootstrapState(uint generalCommitteeSize, uint certifiedCommitteeSize) private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { Settings memory _settings = settings; if (!_settings.rewardAllocationActive) { return feesAndBootstrapState; } uint256 collectedGeneralFees = generalFeesWallet.collectFees(); uint256 collectedCertifiedFees = certifiedFeesWallet.collectFees(); uint256 allocatedGeneralBootstrap; uint256 allocatedCertifiedBootstrap; (_feesAndBootstrapState, allocatedGeneralBootstrap, allocatedCertifiedBootstrap) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, collectedGeneralFees, collectedCertifiedFees, block.timestamp, _settings); bootstrapRewardsWallet.withdraw(allocatedGeneralBootstrap.add(allocatedCertifiedBootstrap)); feesAndBootstrapState = _feesAndBootstrapState; emit FeesAllocated(collectedGeneralFees, _feesAndBootstrapState.generalFeesPerMember, collectedCertifiedFees, _feesAndBootstrapState.certifiedFeesPerMember); emit BootstrapRewardsAllocated(allocatedGeneralBootstrap, _feesAndBootstrapState.generalBootstrapPerMember, allocatedCertifiedBootstrap, _feesAndBootstrapState.certifiedBootstrapPerMember); } /// Updates the global Fees and Bootstrap rewards state /// @dev utilizes _updateFeesAndBootstrapState /// @return _feesAndBootstrapState is a FeesAndBootstrapState struct with the updated state function updateFeesAndBootstrapState() private returns (FeesAndBootstrapState memory _feesAndBootstrapState) { (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = committeeContract.getCommitteeStats(); return _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); } // Guardian state /// Returns the current guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data and the global state /// @param guardian is the guardian to query /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param _feesAndBootstrapState is the current updated global fees and bootstrap state /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return addedBootstrapAmount is the amount added to the guardian bootstrap balance /// @return addedFeesAmount is the amount added to the guardian fees balance function _getGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, FeesAndBootstrapState memory _feesAndBootstrapState) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, uint256 addedBootstrapAmount, uint256 addedFeesAmount) { guardianFeesAndBootstrap = feesAndBootstrap[guardian]; if (inCommittee) { addedBootstrapAmount = (isCertified ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember).sub(guardianFeesAndBootstrap.lastBootstrapPerMember); guardianFeesAndBootstrap.bootstrapBalance = guardianFeesAndBootstrap.bootstrapBalance.add(addedBootstrapAmount); addedFeesAmount = (isCertified ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember).sub(guardianFeesAndBootstrap.lastFeesPerMember); guardianFeesAndBootstrap.feeBalance = guardianFeesAndBootstrap.feeBalance.add(addedFeesAmount); } guardianFeesAndBootstrap.lastBootstrapPerMember = nextCertification ? _feesAndBootstrapState.certifiedBootstrapPerMember : _feesAndBootstrapState.generalBootstrapPerMember; guardianFeesAndBootstrap.lastFeesPerMember = nextCertification ? _feesAndBootstrapState.certifiedFeesPerMember : _feesAndBootstrapState.generalFeesPerMember; } /// Updates a guardian Fees and Bootstrap rewards state /// @dev receives the relevant guardian committee membership data /// @dev updates the global Fees and Bootstrap state prior to calculating the guardian's /// @dev utilizes _getGuardianFeesAndBootstrap /// @param guardian is the guardian to update /// @param inCommittee indicates whether the guardian is currently in the committee /// @param isCertified indicates whether the guardian is currently certified /// @param nextCertification indicates whether after the change, the guardian is certified /// @param generalCommitteeSize indicates the general committee size prior to the change /// @param certifiedCommitteeSize indicates the certified committee size prior to the change function _updateGuardianFeesAndBootstrap(address guardian, bool inCommittee, bool isCertified, bool nextCertification, uint generalCommitteeSize, uint certifiedCommitteeSize) private { uint256 addedBootstrapAmount; uint256 addedFeesAmount; FeesAndBootstrapState memory _feesAndBootstrapState = _updateFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize); FeesAndBootstrap memory guardianFeesAndBootstrap; (guardianFeesAndBootstrap, addedBootstrapAmount, addedFeesAmount) = _getGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, nextCertification, _feesAndBootstrapState); feesAndBootstrap[guardian] = guardianFeesAndBootstrap; emit BootstrapRewardsAssigned(guardian, addedBootstrapAmount, guardianFeesAndBootstrap.withdrawnBootstrap.add(guardianFeesAndBootstrap.bootstrapBalance), isCertified, guardianFeesAndBootstrap.lastBootstrapPerMember); emit FeesAssigned(guardian, addedFeesAmount, guardianFeesAndBootstrap.withdrawnFees.add(guardianFeesAndBootstrap.feeBalance), isCertified, guardianFeesAndBootstrap.lastFeesPerMember); } /// Returns the guardian Fees and Bootstrap rewards state for a given time /// @dev if the time to estimate is in the future, estimates the fees and rewards for the given time /// @dev for future time estimation assumes no change in the guardian committee membership and certification /// @param guardian is the guardian to query /// @param currentTime is the time to calculate the fees and bootstrap for /// @return guardianFeesAndBootstrap is a struct with the guardian updated fees and bootstrap state /// @return certified is the guardian certification status function getGuardianFeesAndBootstrap(address guardian, uint256 currentTime) private view returns (FeesAndBootstrap memory guardianFeesAndBootstrap, bool certified) { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (FeesAndBootstrapState memory _feesAndBootstrapState,,) = _getFeesAndBootstrapState(generalCommitteeSize, certifiedCommitteeSize, generalFeesWallet.getOutstandingFees(currentTime), certifiedFeesWallet.getOutstandingFees(currentTime), currentTime, settings); bool inCommittee; (inCommittee, , certified,) = _committeeContract.getMemberInfo(guardian); (guardianFeesAndBootstrap, ,) = _getGuardianFeesAndBootstrap(guardian, inCommittee, certified, certified, _feesAndBootstrapState); } /// Updates a guardian Fees and Bootstrap rewards state /// @dev query the relevant guardian and committee data from the committee contract /// @dev utilizes _updateGuardianFeesAndBootstrap /// @param guardian is the guardian to update function updateGuardianFeesAndBootstrap(address guardian) private { ICommittee _committeeContract = committeeContract; (uint generalCommitteeSize, uint certifiedCommitteeSize, ) = _committeeContract.getCommitteeStats(); (bool inCommittee, , bool isCertified,) = _committeeContract.getMemberInfo(guardian); _updateGuardianFeesAndBootstrap(guardian, inCommittee, isCertified, isCertified, generalCommitteeSize, certifiedCommitteeSize); } // Governance and misc. /// Sets the annual rate for the general committee bootstrap /// @param annualAmount is the annual general committee bootstrap award function _setGeneralCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.generalCommitteeAnnualBootstrap = uint96(annualAmount); emit GeneralCommitteeAnnualBootstrapChanged(annualAmount); } /// Sets the annual rate for the certified committee bootstrap /// @param annualAmount is the annual certified committee bootstrap award function _setCertifiedCommitteeAnnualBootstrap(uint256 annualAmount) private { require(uint256(uint96(annualAmount)) == annualAmount, "annualAmount must fit in uint96"); settings.certifiedCommitteeAnnualBootstrap = uint96(annualAmount); emit CertifiedCommitteeAnnualBootstrapChanged(annualAmount); } /* * Contracts topology / registry interface */ ICommittee committeeContract; IFeesWallet generalFeesWallet; IFeesWallet certifiedFeesWallet; IProtocolWallet bootstrapRewardsWallet; /// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); } }
refreshContracts
function refreshContracts() external override { committeeContract = ICommittee(getCommitteeContract()); generalFeesWallet = IFeesWallet(getGeneralFeesWallet()); certifiedFeesWallet = IFeesWallet(getCertifiedFeesWallet()); bootstrapRewardsWallet = IProtocolWallet(getBootstrapRewardsWallet()); }
/// Refreshes the address of the other contracts the contract interacts with /// @dev called by the registry contract upon an update of a contract in the registry
NatSpecSingleLine
v0.6.12+commit.27d51765
MIT
ipfs://ca7f2529f56054280eeeb86b39c30e8c839f5ddb6846120be619df37eaa803e8
{ "func_code_index": [ 32368, 32708 ] }
3,097
maddencoin
maddencoin.sol
0x84ad9b68533e5eefac045c39f306fd3fcc6bc440
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; }
/** * @dev Multiplies two numbers, throws on overflow. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://216fdb4c2b24239b5f5b98721f0615109947591774c3c60bec2a7b4ff002bfad
{ "func_code_index": [ 89, 476 ] }
3,098
maddencoin
maddencoin.sol
0x84ad9b68533e5eefac045c39f306fd3fcc6bc440
Solidity
SafeMath
library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } }
/** * @title SafeMath * @dev Math operations with safety checks that throw on error */
NatSpecMultiLine
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; }
/** * @dev Integer division of two numbers, truncating the quotient. */
NatSpecMultiLine
v0.4.24+commit.e67f0147
bzzr://216fdb4c2b24239b5f5b98721f0615109947591774c3c60bec2a7b4ff002bfad
{ "func_code_index": [ 560, 840 ] }
3,099